Registry / testing / mock-open

mock-open

JSON →
library1.4.0pypypi✓ verified 85d ago

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-open
INSTALL
IMPORT
SIG · MOCK-OPEN
M
mock-open
testingpythonv1.4.0
Install
2.6s avg
Import
358ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.4.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.385s · 19.3MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 2.6s · import 0.331s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

MockOpen
from mock_open import MockOpen
patch
from unittest.mock import patch
Commonly used with MockOpen for patching 'builtins.open'.

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.

from unittest.mock import patch from mock_open import MockOpen # Scenario 1: Mocking file reading mock_data_to_read = "Line 1\nLine 2\nLine 3" mo_read = MockOpen(read_data=mock_data_to_read) with patch("builtins.open", mo_read): with open("my_input.txt", "r") as f: content = f.read() lines = f.readlines() assert content == mock_data_to_read assert lines == ["Line 1\n", "Line 2\n", "Line 3"] mo_read.assert_called_with("my_input.txt", "r") # Scenario 2: Mocking file writing mo_write = MockOpen() with patch("builtins.open", mo_write): with open("my_output.txt", "w") as f: f.write("Hello, world!") f.write("Python is great.") # Access the mock handle to verify writes mo_write.mock_handle.write.assert_any_call("Hello, world!") mo_write.mock_handle.write.assert_any_call("Python is great.") mo_write.assert_called_with("my_output.txt", "w") # You can get the content written to the mock written_content = "".join(call.args[0] for call in mo_write.mock_handle.write.call_args_list) assert written_content == "Hello, world!Python is great." print("Mocking successful!")
Debug
Known issues
breakingPrior to v1.3.0, `mock-open` often required contrived `side_effect` workarounds for file operations (`read`, `write`, `seek`). V1.3.0 changed this to use direct mock wrapping, making `return_value` and direct attribute access (`.mock_handle.read`) the correct way to interact. Code relying on `side_effect` for content might break.
fix
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.
affects: <1.3.0
gotchaIn `mock-open` v1.4.0+, consecutive calls to a patched `open` function will reset the file-like mock's internal position (like `seek(0)`). In previous versions, the position might have persisted across different `with open(...)` blocks using the same mock, leading to unexpected behavior in subsequent reads.
fix
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.
affects: <1.4.0
gotchaWhen mocking binary file operations (`'rb'`, `'wb'`, etc.) with `mock-open` (v1.3.0+), the underlying content storage uses `io.BytesIO`. Ensure that `read_data` provided for binary modes is a `bytes` object, not a `str`, and that assertions check for `bytes` content.
fix
Use `b'your binary data'` for `read_data` and assert against `bytes` objects when testing binary file modes. For text modes, use `str`.
affects: >=1.3.0
Errors
Common errors & fixes
AttributeError: 'MockOpen' object has no attribute 'read'
Attempting to call file-like methods (like `read()`, `write()`, `seek()`) directly on the `MockOpen` instance instead of on the mock file handle returned by `open()` or accessed via `mo.mock_handle`.
fix
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()`).
AssertionError: Expected 'some_data', but received '' (empty string) or 'None'
Forgetting to provide initial data to `MockOpen` via the `read_data` argument when mocking a file read operation.
fix
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')`.
TypeError: a bytes-like object is required, not 'str'
Mismatch between the file mode (e.g., 'rb' for binary, 'r' for text) and the type of data provided (`read_data`) or written to the mock file. For binary modes, `read_data` and `write` arguments must be `bytes`; for text modes, they must be `str`.
fix
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.
Upgrade
Version history
1.4.0latest on PyPI · released Apr 15, 2020
Audit
Dependencies

No dependency data recorded yet.

Agent activity
6 hits · last 30 days
node
4
Resources
mock-open — pip install mock-open · libregistry