Mock Open

1.4.0 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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!")

view raw JSON →