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.

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

Python code

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

stdout
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

  1. Use `mock_open` from unittest.mock instead of a custom FakeFile class for simpler setups
  2. 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

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.