The `mock-open` library (current version 1.4.0) provides an enhanced mock object for testing file I/O operations in Python. It extends `unittest.mock.mock_open` to offer more realistic behavior for file-like objects, including robust handling of `with` statements, `read`, `write`, `seek`, and binary modes. It is actively maintained with releases addressing compatibility and feature enhancements.
pip install mock-openVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `mock-open` to patch `builtins.open` for both reading and writing operations. It shows how to initialize `MockOpen` with `read_data` and how to inspect written content via `mock_handle.write` calls.
Update tests to use `MockOpen(read_data='...')` for reading, or access `mo.mock_handle.write.assert_called_with(...)` for writing, rather than setting `side_effect` on the `MockOpen` instance itself for content.
Ensure tests account for the file pointer being reset for each new `open` call when patching. If sequential reads from the *same* `open` call are needed, configure `read_data` or `side_effect` appropriately. If you relied on position persistence across *multiple* `open` calls, re-evaluate your test logic.
Use `b'your binary data'` for `read_data` and assert against `bytes` objects when testing binary file modes. For text modes, use `str`.
After patching `builtins.open` with a `MockOpen` instance (`mo`), you must interact with the file object returned by `open` (e.g., `with open(...) as f: f.read()`) or directly access `mo.mock_handle` for assertions (e.g., `mo.mock_handle.read.assert_called_once()`).
When initializing `MockOpen`, pass the expected content as a string (or bytes for binary mode) to the `read_data` parameter: `mo = MockOpen(read_data='Expected file content')`.
Ensure `read_data` and any data passed to `f.write()` match the expected type for the file mode. For binary modes (`'rb'`, `'wb'`), use `b"..."` for bytes. For text modes (`'r'`, `'w'`), use `"..."` for strings.
No dependency data recorded yet.