How to Mock pathlib Path.read_text with mock_open in Python
Mock pathlib.Path.read_text using patch and mock_open to test file-reading code without touching the filesystem.
Python code
14 linesimport pathlib
from unittest.mock import mock_open, patch
def read_config(filepath: pathlib.Path) -> str:
"""Read file content with pathlib."""
return filepath.read_text()
if __name__ == "__main__":
mock_data = "version: 1.0\nname: demo-app"
with patch("pathlib.Path.open", mock_open(read_data=mock_data)):
path = pathlib.Path("/fake/config.yaml")
content = read_config(path)
print(content)
Output
version: 1.0
name: demo-app
How it works
The patch context manager replaces Path.open with a mock that returns a file object pre-loaded with mock_data. Since read_text() internally calls open(), the patch intercepts that call and returns the fake content without any real I/O. The test can then assert against the returned string, verifying the logic that consumes the file content.
Common mistakes
- Patching `pathlib.Path.read_text` directly instead of `pathlib.Path.open` – the latter is what `read_text` uses.
- Forgetting to pass `mock_open(read_data=...)` – without it, the mock file returns empty bytes.
- Using the wrong patch target when the file is opened elsewhere in the codebase.
Variations
- Patch `builtins.open` when the code uses the standard `open()` instead of `pathlib.Path.read_text`.
- Use `unittest.mock.patch` with a custom `MagicMock` that has a `read_text` method returning a fixed string.
Real-world use cases
- Unit-testing a configuration loader that uses pathlib to read YAML or JSON settings files.
- Testing a script that reads template files at startup to avoid filesystem dependencies in CI.
- Validating error handling when a file is missing, without creating or deleting actual test fixtures.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.