[issue37669] Make mock_open return per-file content

Damien Nadé report at bugs.python.org
Mon Jul 29 08:09:33 EDT 2019


Damien Nadé <bugzilla-python at livna.org> added the comment:

To summarize the change I'm proposing, I'd say that instead of having mock_open creating closures (functions inside a specific context), mock_open now creates objects that will hold the contexts. Each context would be filename-dedicated and would include specific 'read_data' and linked MagikMock object.

So the change is fully transparent compared to the currently-existing mock_open. It just brings a little extra something, in the way of an extra parameter to mock_open : 

mock_open(mock, read_data, data)

While the name 'data' obviously can (and should) be replaced before merge (I dont have a "good" name in mind ATM, feel free to suggest), I'm suggesting in my PR that it could be a {<file name>: <read data>} mapping.

e.g: If i call

mock_open(read_data="default read data", data={"/foo": "abc", "/asdf/bar": "xyz"})

Then, after mock.patching open, I can assert the following:

assert open("random file").read() == "default read data"
assert open("/foo").read() == "abc"
assert open("/bar").read() == "xyz"

And so far, that's all I'm proposing... But I'm really open to suggestion on that.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue37669>
_______________________________________


More information about the Python-bugs-list mailing list