CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyfakefs

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

Pending
Overview
Eval results
Files

advanced-features.mddocs/

Advanced Features

Advanced functionality including real filesystem mapping, pause/resume operations, OS emulation, and filesystem size tracking. These features enable sophisticated testing scenarios and fine-grained control over the fake filesystem behavior.

Capabilities

Real Filesystem Mapping

Map real files and directories into the fake filesystem for hybrid testing scenarios.

def add_real_file(
    self,
    source_path: str,
    target_path: str = None,
    read_only: bool = False,
    encoding: str = None
) -> FakeFile:
    """
    Add a real file from the actual filesystem to the fake filesystem.
    
    Args:
        source_path: Path to the real file to add
        target_path: Path in fake filesystem (defaults to source_path)
        read_only: Whether the file should be read-only in fake filesystem
        encoding: Text encoding for the file
        
    Returns:
        FakeFile object representing the mapped file
        
    Raises:
        FileNotFoundError: If source_path doesn't exist in real filesystem
    """

def add_real_directory(
    self,
    source_path: str,
    target_path: str = None,
    read_only: bool = False,
    lazy_read: bool = True
) -> FakeDirectory:
    """
    Add a real directory tree from actual filesystem to fake filesystem.
    
    Args:
        source_path: Path to the real directory to add
        target_path: Path in fake filesystem (defaults to source_path)
        read_only: Whether files should be read-only in fake filesystem
        lazy_read: Whether to read file contents only when accessed
        
    Returns:
        FakeDirectory object representing the mapped directory
        
    Raises:
        FileNotFoundError: If source_path doesn't exist in real filesystem
    """

def add_real_paths(self, paths: List[str], read_only: bool = False) -> None:
    """
    Add multiple real paths to the fake filesystem.
    
    Args:
        paths: List of real filesystem paths to add
        read_only: Whether added paths should be read-only
    """

Usage example:

# Map a real configuration file into fake filesystem
fs.add_real_file('/etc/hosts', '/etc/hosts', read_only=True)

# Map a real directory tree
fs.add_real_directory('/home/user/config', '/config')

# Map multiple paths
fs.add_real_paths(['/usr/bin/python', '/usr/lib/python3.9'], read_only=True)

# Now test code can access real files through fake filesystem
with open('/etc/hosts', 'r') as f:
    hosts_content = f.read()

Pause and Resume Operations

Temporarily disable filesystem patching to access the real filesystem during tests.

def pause(self) -> None:
    """
    Pause filesystem patching, allowing access to the real filesystem.
    
    All filesystem operations will use the real filesystem until resume() is called.
    Useful for operations that need to access real files during test execution.
    """

def resume(self) -> None:
    """
    Resume filesystem patching after a pause() call.
    
    Restores fake filesystem behavior for all filesystem operations.
    """

def is_paused(self) -> bool:
    """
    Check if filesystem patching is currently paused.
    
    Returns:
        True if patching is paused, False if active
    """

Usage example:

def test_with_pause_resume(fs):
    # Create fake file
    fs.create_file('/fake/test.txt', contents='fake content')
    
    # Pause to access real filesystem
    fs.pause()
    
    # This writes to the real filesystem
    with open('/tmp/real_file.txt', 'w') as f:
        f.write('real content')
    
    # Resume fake filesystem
    fs.resume()
    
    # Back to fake filesystem
    assert os.path.exists('/fake/test.txt')
    assert not os.path.exists('/tmp/real_file.txt')  # Not in fake filesystem

Operating System Emulation

Emulate different operating systems to test cross-platform behavior.

def set_os_type(self, os_type: OSType) -> None:
    """
    Set the operating system type for path and behavior emulation.
    
    Args:
        os_type: Operating system to emulate (OSType.LINUX, OSType.MACOS, OSType.WINDOWS)
    """

def get_os_type(self) -> OSType:
    """
    Get the current operating system type being emulated.
    
    Returns:
        Current OSType being emulated
    """

def is_windows_fs(self) -> bool:
    """Check if emulating Windows filesystem behavior."""

def is_macos(self) -> bool:
    """Check if emulating MacOS filesystem behavior."""

def is_case_sensitive(self) -> bool:
    """Check if filesystem is case-sensitive (depends on OS type)."""

Usage example:

# Test Windows-specific behavior
fs.set_os_type(OSType.WINDOWS)
fs.create_file('C:\\test\\file.txt', contents='Windows path')

# Windows paths are case-insensitive
assert fs.exists('c:\\test\\FILE.TXT')

# Test Linux-specific behavior  
fs.set_os_type(OSType.LINUX)
fs.create_file('/test/file.txt', contents='Linux path')

# Linux paths are case-sensitive
assert not fs.exists('/test/FILE.TXT')

Filesystem Size Tracking

Control and monitor fake filesystem size limits.

def set_total_size(self, total_size: int) -> None:
    """
    Set the total size limit for the fake filesystem.
    
    Args:
        total_size: Maximum filesystem size in bytes (None for unlimited)
        
    Raises:
        OSError: If current filesystem usage exceeds the new limit
    """

def get_total_size(self) -> Optional[int]:
    """
    Get the current total size limit.
    
    Returns:
        Size limit in bytes, or None if unlimited
    """

def get_disk_usage(self, path: str = None) -> tuple:
    """
    Get disk usage statistics.
    
    Args:
        path: Path to check (defaults to filesystem root)
        
    Returns:
        Tuple of (total, used, available) bytes
    """

def get_used_size(self) -> int:
    """
    Get the current used size of the filesystem.
    
    Returns:
        Used size in bytes
    """

Usage example:

# Set filesystem size limit to 1MB
fs.set_total_size(1024 * 1024)

# Create files within limit
fs.create_file('/small.txt', contents='small file')

# Check disk usage
total, used, available = fs.get_disk_usage()
print(f"Used: {used}, Available: {available}")

# This would raise OSError if it exceeds the limit
try:
    large_content = 'x' * (1024 * 1024)  # 1MB of data
    fs.create_file('/large.txt', contents=large_content)
except OSError as e:
    print(f"Filesystem full: {e}")

User and Permission Emulation

Emulate different user contexts and permission scenarios.

def set_uid(self, uid: int) -> None:
    """
    Set the current user ID for filesystem operations.
    
    Args:
        uid: User ID to emulate
    """

def set_gid(self, gid: int) -> None:
    """
    Set the current group ID for filesystem operations.
    
    Args:
        gid: Group ID to emulate
    """

def is_root_user(self) -> bool:
    """Check if currently emulating root user (uid == 0)."""

def change_root_permission(self, permission: bool) -> None:
    """
    Change whether root permissions are emulated.
    
    Args:
        permission: Whether to grant root permissions
    """

Usage example:

# Test as non-root user
fs.set_uid(1000)
fs.set_gid(1000)

# Create file with restricted permissions
fs.create_file('/restricted.txt', contents='secret', st_mode=0o600)

# Test permission checks
fs.set_uid(1001)  # Different user
try:
    with open('/restricted.txt', 'r') as f:
        content = f.read()  # Should raise PermissionError
except PermissionError:
    print("Access denied as expected")

Symbolic Link Support

Create and manage symbolic links in the fake filesystem.

def create_symlink(
    self,
    link_path: str,
    target_path: str,
    create_missing_dirs: bool = True
) -> FakeFile:
    """
    Create a symbolic link in the fake filesystem.
    
    Args:
        link_path: Path where the symbolic link will be created
        target_path: Path that the link points to
        create_missing_dirs: Create parent directories if needed
        
    Returns:
        FakeFile object representing the symbolic link
    """

def readlink(self, link_path: str) -> str:
    """
    Read the target of a symbolic link.
    
    Args:
        link_path: Path to the symbolic link
        
    Returns:
        Target path of the symbolic link
        
    Raises:
        OSError: If path is not a symbolic link
    """

Usage example:

# Create target file and symbolic link
fs.create_file('/target.txt', contents='target content')
fs.create_symlink('/link.txt', '/target.txt')

# Link behaves like the target
with open('/link.txt', 'r') as f:
    content = f.read()
assert content == 'target content'

# Check link properties
assert fs.is_link('/link.txt')
assert fs.readlink('/link.txt') == '/target.txt'

Filesystem State and Debugging

Tools for inspecting and debugging the fake filesystem state.

def reset(self, total_size: int = None) -> None:
    """
    Reset the filesystem to empty state.
    
    Args:
        total_size: Optional size limit for the reset filesystem
    """

def clear_cache(self) -> None:
    """Clear internal filesystem caches and metadata."""

def get_filesystem_size(self) -> int:
    """Get the total size of all files in the filesystem."""

def dump_filesystem(self, path: str = '/') -> str:
    """
    Get a string representation of the filesystem tree.
    
    Args:
        path: Root path for the dump (defaults to filesystem root)
        
    Returns:
        Multi-line string showing filesystem structure
    """

Usage example:

# Create test filesystem structure
fs.create_dir('/app')
fs.create_file('/app/config.ini', contents='[settings]\ndebug=true')
fs.create_file('/app/main.py', contents='print("Hello World")')

# Debug filesystem state
print(fs.dump_filesystem())
# Output:
# /
# ├── app/
# │   ├── config.ini
# │   └── main.py

# Check filesystem size
total_size = fs.get_filesystem_size()
print(f"Total filesystem size: {total_size} bytes")

# Reset when done
fs.reset()

Advanced Types

from typing import List, Optional, Tuple, Union
from enum import Enum

class OSType(Enum):
    """Operating system types for emulation."""
    LINUX = "linux"
    MACOS = "macos"
    WINDOWS = "windows"

# Advanced operation types
RealPath = str
FakePath = str
PathMapping = Tuple[RealPath, FakePath]
DiskUsage = Tuple[int, int, int]  # (total, used, available)
FileMode = int
UserId = int
GroupId = int

Install with Tessl CLI

npx tessl i tessl/pypi-pyfakefs

docs

advanced-features.md

core-filesystem.md

index.md

testing-integration.md

tile.json