Skip to content

Commit f702b3a

Browse files
committed
Re-create the temp directory on resetting the filesystem
- the temp dir is now created during filesystem initialization instead of at patcher setup - fixes #814
1 parent eff3286 commit f702b3a

File tree

7 files changed

+57
-20
lines changed

7 files changed

+57
-20
lines changed

CHANGES.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
# pyfakefs Release Notes
22
The released versions correspond to PyPI releases.
33

4+
## Unreleased
5+
6+
### Fixes
7+
* Re-create temp directory if resetting file system (see [#814](../../issues/814)).
8+
49
## [Version 5.2.2](https://pypi.python.org/pypi/pyfakefs/5.2.2) (2023-04-13)
510
Fixes a regression in 5.2.0
611

pyfakefs/fake_filesystem.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@
8585
import os
8686
import random
8787
import sys
88+
import tempfile
8889
from collections import namedtuple, OrderedDict
8990
from doctest import TestResults
9091
from enum import Enum
@@ -247,6 +248,7 @@ def __init__(
247248
self._add_root_mount_point(total_size)
248249
self._add_standard_streams()
249250
self.dev_null: Any = FakeNullFile(self)
251+
self._create_temp_dir()
250252
# set from outside if needed
251253
self.patch_open_code = PatchMode.OFF
252254
self.shuffle_listdir_results = False
@@ -342,6 +344,7 @@ def reset(self, total_size: Optional[int] = None):
342344
self.mount_points = OrderedDict()
343345
self._add_root_mount_point(total_size)
344346
self._add_standard_streams()
347+
self._create_temp_dir()
345348
from pyfakefs import fake_pathlib
346349

347350
fake_pathlib.init_module(self)
@@ -1380,7 +1383,7 @@ def exists(self, file_path: AnyPath, check_link: bool = False) -> bool:
13801383
"""
13811384
if check_link and self.islink(file_path):
13821385
return True
1383-
path = to_string(make_string_path(file_path))
1386+
path = to_string(self.make_string_path(file_path))
13841387
if path is None:
13851388
raise TypeError
13861389
if not path:
@@ -2915,6 +2918,19 @@ def _add_standard_streams(self) -> None:
29152918
self._add_open_file(StandardStreamWrapper(sys.stdout))
29162919
self._add_open_file(StandardStreamWrapper(sys.stderr))
29172920

2921+
def _create_temp_dir(self):
2922+
# the temp directory is assumed to exist at least in `tempfile`,
2923+
# so we create it here for convenience
2924+
temp_dir = tempfile.gettempdir()
2925+
if not self.exists(temp_dir):
2926+
self.create_dir(temp_dir)
2927+
if sys.platform != "win32" and not self.exists("/tmp"):
2928+
# under Posix, we also create a link in /tmp if the path does not exist
2929+
self.create_symlink("/tmp", temp_dir)
2930+
# reset the used size to 0 to avoid having the link size counted
2931+
# which would make disk size tests more complicated
2932+
next(iter(self.mount_points.values()))["used_size"] = 0
2933+
29182934

29192935
def _run_doctest() -> TestResults:
29202936
import doctest

pyfakefs/fake_filesystem_unittest.py

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
pyfakefs by simply changing their base class from `:py:class`unittest.TestCase`
3636
to `:py:class`pyfakefs.fake_filesystem_unittest.TestCase`.
3737
"""
38-
import _io # type:ignore [import]
38+
import _io # type:ignore[import]
3939
import doctest
4040
import functools
4141
import genericpath
@@ -876,7 +876,6 @@ def setUp(self, doctester: Any = None) -> None:
876876
if self.has_fcopy_file:
877877
shutil._HAS_FCOPYFILE = False # type: ignore[attr-defined]
878878

879-
temp_dir = tempfile.gettempdir()
880879
with warnings.catch_warnings():
881880
# ignore warnings, see #542 and #614
882881
warnings.filterwarnings("ignore")
@@ -891,17 +890,6 @@ def setUp(self, doctester: Any = None) -> None:
891890
linecache.open = self.original_open # type: ignore[attr-defined]
892891
tokenize._builtin_open = self.original_open # type: ignore
893892

894-
# the temp directory is assumed to exist at least in `tempfile`,
895-
# so we create it here for convenience
896-
assert self.fs is not None
897-
self.fs.create_dir(temp_dir)
898-
if sys.platform != "win32" and not self.fs.exists("/tmp"):
899-
# under Posix, we also create a link in /tmp if the path does not exist
900-
self.fs.create_symlink("/tmp", temp_dir)
901-
# reset the used size to 0 to avoid having the link size counted
902-
# which would make disk size tests more complicated
903-
next(iter(self.fs.mount_points.values()))["used_size"] = 0
904-
905893
def start_patching(self) -> None:
906894
if not self._patching:
907895
self._patching = True

pyfakefs/pytest_tests/pytest_plugin_test.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import os
33
import tempfile
44

5+
from pyfakefs.fake_filesystem import OSType
56
from pyfakefs.fake_filesystem_unittest import Pause
67
import pyfakefs.pytest_tests.io
78

@@ -60,3 +61,18 @@ def test_use_own_io_module(fs):
6061

6162
stream = pyfakefs.pytest_tests.io.InputStream(filepath)
6263
assert stream.read() == "bar"
64+
65+
66+
def test_switch_to_windows(fs):
67+
fs.os = OSType.WINDOWS
68+
assert os.path.exists(tempfile.gettempdir())
69+
70+
71+
def test_switch_to_linux(fs):
72+
fs.os = OSType.LINUX
73+
assert os.path.exists(tempfile.gettempdir())
74+
75+
76+
def test_switch_to_macos(fs):
77+
fs.os = OSType.MACOS
78+
assert os.path.exists(tempfile.gettempdir())

pyfakefs/tests/fake_filesystem_test.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ def test_directory_inode(self):
167167

168168
def test_directory_size(self):
169169
fs = fake_filesystem.FakeFilesystem(path_separator="/")
170+
root_size = fs.root_dir.size
170171
foo_dir = fs.create_dir("/foo")
171172
fs.create_file("/foo/bar.txt", st_size=20)
172173
bar_dir = fs.create_dir("/foo/bar/")
@@ -178,7 +179,7 @@ def test_directory_size(self):
178179
self.assertEqual(90, foo_dir.size)
179180
self.assertEqual(70, bar_dir.size)
180181
self.assertEqual(110, foo1_dir.size)
181-
self.assertEqual(200, fs.root_dir.size)
182+
self.assertEqual(200 + root_size, fs.root_dir.size)
182183
with self.raises_os_error(errno.EISDIR):
183184
foo1_dir.size = 100
184185

@@ -287,7 +288,6 @@ def setUp(self):
287288
def test_new_filesystem(self):
288289
self.assertEqual("/", self.filesystem.path_separator)
289290
self.assertTrue(stat.S_IFDIR & self.filesystem.root.st_mode)
290-
self.assertEqual({}, self.filesystem.root_dir.entries)
291291

292292
def test_none_raises_type_error(self):
293293
with self.assertRaises(TypeError):
@@ -316,7 +316,8 @@ def test_get_root_object(self):
316316

317317
def test_add_object_to_root(self):
318318
self.filesystem.add_object(self.root_name, self.fake_file)
319-
self.assertEqual({"foobar": self.fake_file}, self.filesystem.root_dir.entries)
319+
foobar = self.filesystem.root_dir.entries.get("foobar")
320+
self.assertEqual(self.fake_file, foobar)
320321

321322
def test_windows_root_dir_name(self):
322323
self.filesystem.is_windows_fs = True
@@ -852,6 +853,9 @@ def tearDown(self):
852853

853854
def test_create_top_level_directory(self):
854855
top_level_dir = "/x"
856+
# remove the existing temp dir
857+
for directory in list(self.os.scandir(self.filesystem.root_dir_name)):
858+
self.filesystem.remove_object(directory.path)
855859
self.assertFalse(self.filesystem.exists(top_level_dir))
856860
self.filesystem.create_dir(top_level_dir)
857861
self.assertTrue(self.filesystem.exists("/"))

pyfakefs/tests/fake_filesystem_unittest_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -657,11 +657,11 @@ class TestTempDirCreation(fake_filesystem_unittest.TestCase):
657657
def setUp(self):
658658
self.setUpPyfakefs()
659659

660-
def testTempDirExists(self):
660+
def test_tempdir_exists(self):
661661
self.assertTrue(os.path.exists(tempfile.gettempdir()))
662662

663663
@unittest.skipIf(sys.platform == "win32", "POSIX only test")
664-
def testTmpExists(self):
664+
def test_tmp_exists(self):
665665
# directory or link under Linux, link under macOS
666666
self.assertTrue(os.path.exists("/tmp"))
667667

pyfakefs/tests/fake_os_test.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1467,6 +1467,9 @@ def remove_dirs_check(self, directory):
14671467
def test_removedirs(self):
14681468
# no exception raised
14691469
self.skip_real_fs()
1470+
# remove the existing temp dir
1471+
for directory in list(self.os.scandir(self.filesystem.root_dir_name)):
1472+
self.filesystem.remove_object(directory.path)
14701473
data = [
14711474
"test1",
14721475
("test1", "test2"),
@@ -1507,7 +1510,9 @@ def test_removedirs(self):
15071510
def test_removedirs_raises_if_removing_root(self):
15081511
"""Raises exception if asked to remove '/'."""
15091512
self.skip_real_fs()
1510-
self.os.rmdir(self.base_path)
1513+
# remove the existing temp dir and base path
1514+
for directory in list(self.os.scandir(self.filesystem.root_dir_name)):
1515+
self.filesystem.remove_object(directory.path)
15111516
directory = self.os.path.splitdrive(self.base_path)[0] + self.os.path.sep
15121517
self.assertTrue(self.os.path.exists(directory))
15131518
self.assert_raises_os_error(errno.EBUSY, self.os.removedirs, directory)
@@ -1519,6 +1524,9 @@ def test_removedirs_raises_if_cascade_removing_root(self):
15191524
All of other directories should still be removed, though.
15201525
"""
15211526
self.skip_real_fs()
1527+
# remove the existing temp dir
1528+
for directory in list(self.os.scandir(self.filesystem.root_dir_name)):
1529+
self.filesystem.remove_object(directory.path)
15221530
directory = self.make_path("foo", "bar")
15231531
self.create_dir(directory)
15241532
self.assertTrue(self.os.path.exists(directory))

0 commit comments

Comments
 (0)