or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-features.mdcore-filesystem.mdindex.mdtesting-integration.md
tile.json

tessl/pypi-pyfakefs

Implements a fake file system that mocks the Python file system modules.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pyfakefs@5.9.x

To install, run

npx @tessl/cli install tessl/pypi-pyfakefs@5.9.0

index.mddocs/

pyfakefs

A 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.

Package Information

  • Package Name: pyfakefs
  • Package Type: pypi
  • Language: Python
  • Installation: pip install pyfakefs

Core Imports

# 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_handler

Basic Usage

With pytest (recommended)

def 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')

With unittest

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'))

With context manager

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'

Architecture

pyfakefs works by patching Python's built-in file system modules during test execution:

  • FakeFilesystem: Core in-memory filesystem implementation that stores files and directories
  • Module Patchers: Replace real filesystem modules (os, os.path, pathlib, shutil, io, open) with fake implementations
  • Testing Integration: Seamless integration with unittest and pytest frameworks
  • File Objects: FakeFile and FakeDirectory classes represent filesystem entities with full metadata support

The library automatically handles all standard file operations, path manipulations, and filesystem queries through the fake filesystem, providing complete isolation from the real disk.

Capabilities

Core Filesystem Operations

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: ...

Core Filesystem

Testing Framework Integration

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: ...

Testing Integration

Advanced Features

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: ...

Advanced Features

Types

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)