Implements a fake file system that mocks the Python file system modules.
npx @tessl/cli install tessl/pypi-pyfakefs@5.9.0A comprehensive Python library that implements a fake file system for mocking Python file system modules during testing. pyfakefs creates an in-memory file system that replaces the real filesystem during tests, allowing software to be tested without touching the real disk.
pip install pyfakefs# Core filesystem
from pyfakefs.fake_filesystem import FakeFilesystem, OSType, PatchMode
# unittest integration
from pyfakefs.fake_filesystem_unittest import TestCase, TestCaseMixin, patchfs, Patcher, Pause, load_doctests
# Helper functions
from pyfakefs.helpers import set_uid, set_gid, reset_ids, get_uid, get_gid, is_root, reload_cleanup_handlerdef test_file_operations(fs):
"""The fs fixture automatically provides a fake filesystem."""
# Create a fake file
fs.create_file('/fake/file.txt', contents='Hello World')
# Test file operations
with open('/fake/file.txt', 'r') as f:
content = f.read()
assert content == 'Hello World'
assert os.path.exists('/fake/file.txt')import unittest
from pyfakefs.fake_filesystem_unittest import TestCase
class MyTest(TestCase):
def setUp(self):
self.setUpPyfakefs()
def test_file_operations(self):
# Create a fake file
self.fs.create_file('/fake/file.txt', contents='Hello World')
# Test file operations
with open('/fake/file.txt', 'r') as f:
content = f.read()
self.assertEqual(content, 'Hello World')
self.assertTrue(os.path.exists('/fake/file.txt'))from pyfakefs.fake_filesystem_unittest import Patcher
def test_with_patcher():
with Patcher() as patcher:
# Create a fake file
patcher.fs.create_file('/fake/file.txt', contents='Hello World')
# Test file operations
with open('/fake/file.txt', 'r') as f:
content = f.read()
assert content == 'Hello World'pyfakefs works by patching Python's built-in file system modules during test execution:
The library automatically handles all standard file operations, path manipulations, and filesystem queries through the fake filesystem, providing complete isolation from the real disk.
Basic filesystem operations for creating, modifying, and querying files and directories in the fake filesystem.
class FakeFilesystem:
def create_file(self, file_path: str, contents: str = '', **kwargs) -> FakeFile: ...
def create_dir(self, directory_path: str, **kwargs) -> FakeDirectory: ...
def remove(self, path: str, shutil_rmtree: bool = False) -> None: ...
def exists(self, path: str) -> bool: ...
def is_file(self, path: str) -> bool: ...
def is_dir(self, path: str) -> bool: ...Integration with popular Python testing frameworks including unittest and pytest, with decorators, mixins, and fixtures.
class TestCase(unittest.TestCase):
fs: FakeFilesystem
def setUpPyfakefs(self, **kwargs) -> None: ...
def patchfs(func: Callable) -> Callable: ...
# pytest fixture
def fs() -> FakeFilesystem: ...Advanced functionality including real filesystem mapping, pause/resume operations, OS emulation, and filesystem size tracking.
class FakeFilesystem:
def add_real_file(self, source_path: str, target_path: str = None, **kwargs) -> FakeFile: ...
def add_real_directory(self, source_path: str, target_path: str = None, **kwargs) -> FakeDirectory: ...
def pause(self) -> None: ...
def resume(self) -> None: ...
def set_total_size(self, total_size: int) -> None: ...from typing import Union, Optional, Any, Dict, List, Callable, Tuple
from enum import Enum
import os
class OSType(Enum):
LINUX = "linux"
MACOS = "macos"
WINDOWS = "windows"
class PatchMode(Enum):
OFF = "off"
ON = "on"
class FakeFile:
name: str
contents: bytes
size: int
st_mode: int
st_uid: int
st_gid: int
st_atime: float
st_mtime: float
st_ctime: float
def set_contents(self, contents: Union[str, bytes], encoding: str = None) -> None: ...
def copy(self) -> 'FakeFile': ...
class FakeDirectory:
name: str
entries: Dict[str, Union[FakeFile, 'FakeDirectory']]
size: int
st_mode: int
st_uid: int
st_gid: int
st_atime: float
st_mtime: float
st_ctime: float
def add_entry(self, entry: Union[FakeFile, 'FakeDirectory']) -> None: ...
def get_entry(self, name: str) -> Union[FakeFile, 'FakeDirectory']: ...
def remove_entry(self, name: str) -> Union[FakeFile, 'FakeDirectory']: ...
def get_entries(self) -> Dict[str, Union[FakeFile, 'FakeDirectory']]: ...
# Helper types
AnyString = Union[str, bytes]
AnyPath = Union[str, bytes, os.PathLike]
AnyFileWrapper = Union[FakeFile, FakeDirectory]
ModulesToPatch = Dict[str, str]
ModulesToReload = List[str]
SkipNames = List[str]
PatchfsDecorator = Callable[[Callable], Callable]
DiskUsage = Tuple[int, int, int] # (total, used, available)