How to Mock open() in Python for Reading File Data
This example shows how to mock Python's built-in open() function using unittest.mock to simulate file reading without touching the disk.
Python code
28 linesimport builtins
from unittest.mock import patch
def read_file_data(filename):
with open(filename, 'r') as f:
return f.read()
def mock_read_data():
fake_data = "This is mocked file content"
class FakeFile:
def __enter__(self):
return self
def __exit__(self, *args):
pass
def read(self):
return fake_data
def __iter__(self):
return iter([fake_data])
with patch('builtins.open', return_value=FakeFile()) as mock_open:
content = read_file_data("nonexistent.txt")
mock_open.assert_called_once_with("nonexistent.txt", 'r')
return content
if __name__ == "__main__":
result = mock_read_data()
print(result)
Output
This is mocked file content
How it works
The patch('builtins.open') context manager temporarily replaces Python's built-in open function with a mock. When read_file_data() calls open(), it receives a FakeFile instance whose read() method returns the predetermined fake data. The mock also tracks the call, allowing assertions against its arguments. This approach lets you test code that reads files without depending on the file system, making tests fast and deterministic.
Common mistakes
- Patching 'builtins.open' instead of the import in your module namespace when the code uses `from builtins import open`
- Forgetting that `patch` restores the original behavior only within the context manager block
- Creating the FakeFile instance outside the patch call, causing all calls to share the same read state
- Testing file reads without verifying that open is called with the expected filename and mode
Variations
- Use `mock_open` from unittest.mock instead of a custom FakeFile class for simpler setups
- Use `side_effect` with a list of fake file handles to mock multiple open calls in sequence
Real-world use cases
- Testing a config loader that parses JSON from a file during unit tests on a CI runner without disk artifacts.
- Verifying that a service retries or logs correctly when file read failures occur, by simulating empty or malformed content.
- Validating that a CLI tool reads from a named file path correctly while keeping the test suite hermetic and fast.
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.