pyfakefs implements a fake file system that mocks the Python file system modules. It allows tests to operate on an in-memory file system without touching the real disk, requiring no modification to the software under test. pyfakefs supports pytest, unittest, and can be used as a context manager. It is actively maintained with frequent releases to support new Python versions and fix bugs.
pip install pyfakefsVerified import paths — ran on the pinned version, not inferred.
This example demonstrates basic file operations using the `fs` pytest fixture, which automatically sets up and tears down an in-memory fake filesystem for your test. Simply run `pytest your_test_file.py`.
Upgrade your Python environment to 3.10 or newer, or pin pyfakefs to a version prior to 6.0.0 (e.g., `pyfakefs<6.0.0`).
Migrate your code to use the standard `os.scandir` and `pathlib.Path` modules, which pyfakefs continues to patch.
Avoid using C-backed libraries for file I/O in code under test with pyfakefs, or patch them separately if possible. Consider using pure Python alternatives where applicable.
Prefer using pyfakefs's native patching mechanisms (e.g., `fs` fixture, `TestCase` inheritance, `Patcher`) for file system related mocks. Avoid `unittest.mock.patch` for `os`, `io`, or `pathlib` when pyfakefs is active.
Avoid using `isinstance()` checks to differentiate file object types when using pyfakefs. Focus on duck typing or attribute checks if necessary.
If testing multi-threaded code with file I/O, exercise caution. Consider restructuring tests to isolate file operations or to avoid concurrent access to the same fake files.