PyDocs

Nav

Development Tools

mock_open

  • mock_open(mock=None, read_data='')
A helper function to create a mock to replace the use of `open`. It works
for `open` called directly or used as a context manager.

The `mock` argument is the mock object to configure. If `None` (the
default) then a `MagicMock` will be created for you, with the API limited
to methods or attributes available on standard file handles.

`read_data` is a string for the `read`, `readline` and `readlines` of the
file handle to return.  This is an empty string by default.
Changed in 3.4, 3.5, 3.8
  • 3.4: Added readline() and readlines() support. The mock of read() changed to consume read_data rather than returning it on each call.
  • 3.5: read_data is now reset on each call to the mock.
  • 3.8: Added __iter__() to implementation so that iteration (such as in for loops) correctly consumes read_data.
1 Example
>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
...     with open('foo') as h:
...         result = h.read()
...
>>> m.assert_called_once_with('foo')
>>> assert result == 'bibble'
from the Python docs
See Also
No see-alsos for unittest.mock/mock_open
0 Notes
No notes for mock_open