or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# pyfakefs

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: pyfakefs

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install pyfakefs`

10

11

## Core Imports

12

13

```python

14

# Core filesystem

15

from pyfakefs.fake_filesystem import FakeFilesystem, OSType, PatchMode

16

17

# unittest integration

18

from pyfakefs.fake_filesystem_unittest import TestCase, TestCaseMixin, patchfs, Patcher, Pause, load_doctests

19

20

# Helper functions

21

from pyfakefs.helpers import set_uid, set_gid, reset_ids, get_uid, get_gid, is_root, reload_cleanup_handler

22

```

23

24

## Basic Usage

25

26

### With pytest (recommended)

27

28

```python

29

def test_file_operations(fs):

30

"""The fs fixture automatically provides a fake filesystem."""

31

# Create a fake file

32

fs.create_file('/fake/file.txt', contents='Hello World')

33

34

# Test file operations

35

with open('/fake/file.txt', 'r') as f:

36

content = f.read()

37

38

assert content == 'Hello World'

39

assert os.path.exists('/fake/file.txt')

40

```

41

42

### With unittest

43

44

```python

45

import unittest

46

from pyfakefs.fake_filesystem_unittest import TestCase

47

48

class MyTest(TestCase):

49

def setUp(self):

50

self.setUpPyfakefs()

51

52

def test_file_operations(self):

53

# Create a fake file

54

self.fs.create_file('/fake/file.txt', contents='Hello World')

55

56

# Test file operations

57

with open('/fake/file.txt', 'r') as f:

58

content = f.read()

59

60

self.assertEqual(content, 'Hello World')

61

self.assertTrue(os.path.exists('/fake/file.txt'))

62

```

63

64

### With context manager

65

66

```python

67

from pyfakefs.fake_filesystem_unittest import Patcher

68

69

def test_with_patcher():

70

with Patcher() as patcher:

71

# Create a fake file

72

patcher.fs.create_file('/fake/file.txt', contents='Hello World')

73

74

# Test file operations

75

with open('/fake/file.txt', 'r') as f:

76

content = f.read()

77

78

assert content == 'Hello World'

79

```

80

81

## Architecture

82

83

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

84

85

- **FakeFilesystem**: Core in-memory filesystem implementation that stores files and directories

86

- **Module Patchers**: Replace real filesystem modules (os, os.path, pathlib, shutil, io, open) with fake implementations

87

- **Testing Integration**: Seamless integration with unittest and pytest frameworks

88

- **File Objects**: FakeFile and FakeDirectory classes represent filesystem entities with full metadata support

89

90

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

91

92

## Capabilities

93

94

### Core Filesystem Operations

95

96

Basic filesystem operations for creating, modifying, and querying files and directories in the fake filesystem.

97

98

```python { .api }

99

class FakeFilesystem:

100

def create_file(self, file_path: str, contents: str = '', **kwargs) -> FakeFile: ...

101

def create_dir(self, directory_path: str, **kwargs) -> FakeDirectory: ...

102

def remove(self, path: str, shutil_rmtree: bool = False) -> None: ...

103

def exists(self, path: str) -> bool: ...

104

def is_file(self, path: str) -> bool: ...

105

def is_dir(self, path: str) -> bool: ...

106

```

107

108

[Core Filesystem](./core-filesystem.md)

109

110

### Testing Framework Integration

111

112

Integration with popular Python testing frameworks including unittest and pytest, with decorators, mixins, and fixtures.

113

114

```python { .api }

115

class TestCase(unittest.TestCase):

116

fs: FakeFilesystem

117

def setUpPyfakefs(self, **kwargs) -> None: ...

118

119

def patchfs(func: Callable) -> Callable: ...

120

121

# pytest fixture

122

def fs() -> FakeFilesystem: ...

123

```

124

125

[Testing Integration](./testing-integration.md)

126

127

### Advanced Features

128

129

Advanced functionality including real filesystem mapping, pause/resume operations, OS emulation, and filesystem size tracking.

130

131

```python { .api }

132

class FakeFilesystem:

133

def add_real_file(self, source_path: str, target_path: str = None, **kwargs) -> FakeFile: ...

134

def add_real_directory(self, source_path: str, target_path: str = None, **kwargs) -> FakeDirectory: ...

135

def pause(self) -> None: ...

136

def resume(self) -> None: ...

137

def set_total_size(self, total_size: int) -> None: ...

138

```

139

140

[Advanced Features](./advanced-features.md)

141

142

## Types

143

144

```python { .api }

145

from typing import Union, Optional, Any, Dict, List, Callable, Tuple

146

from enum import Enum

147

import os

148

149

class OSType(Enum):

150

LINUX = "linux"

151

MACOS = "macos"

152

WINDOWS = "windows"

153

154

class PatchMode(Enum):

155

OFF = "off"

156

ON = "on"

157

158

class FakeFile:

159

name: str

160

contents: bytes

161

size: int

162

st_mode: int

163

st_uid: int

164

st_gid: int

165

st_atime: float

166

st_mtime: float

167

st_ctime: float

168

169

def set_contents(self, contents: Union[str, bytes], encoding: str = None) -> None: ...

170

def copy(self) -> 'FakeFile': ...

171

172

class FakeDirectory:

173

name: str

174

entries: Dict[str, Union[FakeFile, 'FakeDirectory']]

175

size: int

176

st_mode: int

177

st_uid: int

178

st_gid: int

179

st_atime: float

180

st_mtime: float

181

st_ctime: float

182

183

def add_entry(self, entry: Union[FakeFile, 'FakeDirectory']) -> None: ...

184

def get_entry(self, name: str) -> Union[FakeFile, 'FakeDirectory']: ...

185

def remove_entry(self, name: str) -> Union[FakeFile, 'FakeDirectory']: ...

186

def get_entries(self) -> Dict[str, Union[FakeFile, 'FakeDirectory']]: ...

187

188

# Helper types

189

AnyString = Union[str, bytes]

190

AnyPath = Union[str, bytes, os.PathLike]

191

AnyFileWrapper = Union[FakeFile, FakeDirectory]

192

ModulesToPatch = Dict[str, str]

193

ModulesToReload = List[str]

194

SkipNames = List[str]

195

PatchfsDecorator = Callable[[Callable], Callable]

196

DiskUsage = Tuple[int, int, int] # (total, used, available)

197

```