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.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 14 views 0 copies

Python code

14 lines
Python 3.9+
import 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

stdout
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

  1. Patch `builtins.open` when the code uses the standard `open()` instead of `pathlib.Path.read_text`.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.