Implements a fake file system that mocks the Python file system modules.
—
Basic filesystem operations for creating, modifying, and querying files and directories in the fake filesystem. These operations form the foundation of pyfakefs functionality and provide the primary interface for setting up test scenarios.
Create files with specific content, permissions, and metadata in the fake filesystem.
def create_file(
self,
file_path: str,
st_mode: int = None,
contents: Union[str, bytes] = "",
st_size: Optional[int] = None,
create_missing_dirs: bool = True,
apply_umask: bool = True,
encoding: Optional[str] = None,
errors: Optional[str] = None,
side_effect: Optional[Callable] = None
) -> FakeFile:
"""
Create a new fake file with the specified content and attributes.
Args:
file_path: Path where the file should be created
st_mode: File permissions (defaults to regular file with standard permissions)
contents: Initial file contents (string or bytes)
st_size: File size for large file mode (if given, contents are ignored)
create_missing_dirs: Create parent directories if they don't exist
apply_umask: Apply system umask to permissions
encoding: Text encoding for string content
errors: Error handling for encoding
side_effect: Optional callable to be executed on file operations
Returns:
FakeFile object representing the created file
"""Usage example:
# Create a simple text file
fs.create_file('/path/to/file.txt', contents='Hello World')
# Create a file with specific permissions
fs.create_file('/path/to/script.sh', contents='#!/bin/bash\necho "Hello"', st_mode=0o755)
# Create a binary file
fs.create_file('/path/to/data.bin', contents=b'\x00\x01\x02\x03')Create directories with specific permissions and metadata in the fake filesystem.
def create_dir(
self,
directory_path: str,
st_mode: int = None,
st_uid: int = None,
st_gid: int = None,
st_atime: float = None,
st_mtime: float = None,
st_ctime: float = None,
create_missing_dirs: bool = True,
apply_umask: bool = False
) -> FakeDirectory:
"""
Create a new fake directory with the specified attributes.
Args:
directory_path: Path where the directory should be created
st_mode: Directory permissions (defaults to 0o777)
st_uid: Directory owner user ID
st_gid: Directory owner group ID
st_atime: Last access time (Unix timestamp)
st_mtime: Last modification time (Unix timestamp)
st_ctime: Creation time (Unix timestamp)
create_missing_dirs: Create parent directories if they don't exist
apply_umask: Apply system umask to permissions
Returns:
FakeDirectory object representing the created directory
"""Usage example:
# Create a simple directory
fs.create_dir('/path/to/directory')
# Create a directory with specific permissions
fs.create_dir('/path/to/secure', st_mode=0o700)
# Create nested directories
fs.create_dir('/deep/nested/path/structure')Query the state and properties of files and directories in the fake filesystem.
def exists(self, path: str) -> bool:
"""Check if a file or directory exists at the given path."""
def is_file(self, path: str) -> bool:
"""Check if the path points to a file."""
def is_dir(self, path: str) -> bool:
"""Check if the path points to a directory."""
def is_link(self, path: str) -> bool:
"""Check if the path points to a symbolic link."""
def get_object(self, path: str) -> Union[FakeFile, FakeDirectory]:
"""
Get the FakeFile or FakeDirectory object at the given path.
Args:
path: Path to the filesystem object
Returns:
FakeFile or FakeDirectory object
Raises:
FileNotFoundError: If the path doesn't exist
"""Usage example:
# Check if files/directories exist
if fs.exists('/path/to/file.txt'):
print("File exists")
if fs.is_file('/path/to/file.txt'):
print("It's a file")
if fs.is_dir('/path/to/directory'):
print("It's a directory")
# Get filesystem object
file_obj = fs.get_object('/path/to/file.txt')
print(f"File size: {file_obj.size}")Remove files and directories from the fake filesystem.
def remove(self, path: str, shutil_rmtree: bool = False) -> None:
"""
Remove a file or directory from the filesystem.
Args:
path: Path to the file or directory to remove
shutil_rmtree: If True, remove directories recursively like shutil.rmtree
Raises:
FileNotFoundError: If the path doesn't exist
OSError: If trying to remove a non-empty directory without shutil_rmtree
"""
def remove_object(self, path: str) -> Union[FakeFile, FakeDirectory]:
"""
Remove and return the filesystem object at the given path.
Args:
path: Path to the filesystem object to remove
Returns:
The removed FakeFile or FakeDirectory object
"""Read and modify file contents in the fake filesystem.
def get_file_contents(self, file_path: str, encoding: str = None) -> Union[str, bytes]:
"""
Get the contents of a file.
Args:
file_path: Path to the file
encoding: Text encoding (if None, returns bytes)
Returns:
File contents as string or bytes
"""
def set_file_contents(
self,
file_path: str,
contents: Union[str, bytes],
encoding: str = None
) -> None:
"""
Set the contents of an existing file.
Args:
file_path: Path to the file
contents: New file contents
encoding: Text encoding for string content
"""Manage the overall state of the fake filesystem.
def reset(self, total_size: int = None) -> None:
"""
Reset the filesystem to an empty state.
Args:
total_size: Optional total filesystem size limit
"""
def clear_cache(self) -> None:
"""Clear internal filesystem caches."""
def get_disk_usage(self, path: str = None) -> tuple:
"""
Get disk usage statistics for the filesystem.
Args:
path: Path to check (defaults to root)
Returns:
Tuple of (total, used, available) bytes
"""class FakeFile:
"""Represents a fake file in the filesystem."""
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:
"""Set the file contents."""
def copy(self) -> 'FakeFile':
"""Create a copy of this file."""
class FakeDirectory:
"""Represents a fake directory in the filesystem."""
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:
"""Add a file or directory entry."""
def get_entry(self, name: str) -> Union[FakeFile, 'FakeDirectory']:
"""Get a specific entry by name."""
def remove_entry(self, name: str) -> Union[FakeFile, 'FakeDirectory']:
"""Remove and return an entry by name."""
def get_entries(self) -> Dict[str, Union[FakeFile, 'FakeDirectory']]:
"""Get all entries in this directory."""Install with Tessl CLI
npx tessl i tessl/pypi-pyfakefs