Skip to main content

A better mock for file I/O

Project description


PyPI version Build Status GitHub license Maintenance PRs Welcome

A better mock for file I/O.


$ pip install mock-open

class MockOpen

The MockOpen class should work as a stand-in replacement for mock.mock_open with some added features (though it tries to conform to how the builtin open works where the two differ):

  • Multiple file support, including a mapping-like access to file mocks by path:

    from mock_open import MockOpen
    mock_open = MockOpen()
    mock_open["/path/to/file"].read_data = "Data from a fake file-like object"
    mock_open["/path/to/bad_file"].side_effect = IOError()

    You can also configure behavior via the regular mock library API:

    mock_open = MockOpen()
    mock_open.return_value.write.side_effect = IOError()
  • Persistent file contents between calls to open:

    with patch("", MockOpen()):
        with open("/path/to/file", "w") as handle:
            handle.write("Some text")
        with open("/path/to/file", "r") as handle:
            assert "Some text" ==
  • All the regular file operations: read, readline, readlines, write, writelines, seek, tell.


This library uses modified versions of tests from the CPython source code as part of its test suite. The original tests are licensed under the PSF license agreement and are copyright of the Python Software Foundation.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for mock-open, version 1.4.0
Filename, size File type Python version Upload date Hashes
Filename, size mock-open-1.4.0.tar.gz (12.1 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page