pyfakefs
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.
Warnings
- breaking pyfakefs version 6.0.0 and above dropped support for Python versions older than 3.10. Ensure your project runs on Python 3.10+ when upgrading.
- breaking Support for patching legacy modules `scandir` and `pathlib2` was removed in pyfakefs version 6.0.0. If your tests relied on these, they will break.
- gotcha pyfakefs cannot mock file system access that uses C libraries directly, rather than Python's standard `os`, `io`, or `pathlib` modules. Libraries like `lxml` fall into this category.
- gotcha Using `unittest.mock.patch` on file system functions concurrently with pyfakefs can lead to incorrect behavior or conflicts, as both attempt to modify the same system modules.
- gotcha pyfakefs does not retain the Method Resolution Order (MRO) for its fake file objects. This means `isinstance()` checks against original file types (e.g., `io.TextIOBase`) may fail unexpectedly.
- gotcha pyfakefs is not guaranteed to work correctly in multi-threading environments, especially concerning concurrent write access to a single file from different threads.
Install
-
pip install pyfakefs
Imports
- pytest_fixture
import pytest def test_something(fs):
- TestCase
from pyfakefs.fake_filesystem_unittest import TestCase
- Patcher
from pyfakefs.fake_filesystem_unittest import Patcher
- FakeFilesystem
from pyfakefs.fake_filesystem import FakeFilesystem
Quickstart
import os
import pytest
def test_file_operations(fs):
# The 'fs' fixture provides a fake file system
# All os.path and file operations will use this fake system
assert not os.path.exists("/test_dir")
os.mkdir("/test_dir")
assert os.path.exists("/test_dir")
file_path = "/test_dir/my_file.txt"
with open(file_path, "w") as f:
f.write("Hello, pyfakefs!")
assert os.path.exists(file_path)
with open(file_path, "r") as f:
content = f.read()
assert content == "Hello, pyfakefs!"
os.remove(file_path)
assert not os.path.exists(file_path)