Skip to content

Commit

Permalink
Re-create the temp directory on resetting the filesystem
Browse files Browse the repository at this point in the history
- the temp dir is now created during filesystem
  initialization instead of at patcher setup
- fixes pytest-dev#814
  • Loading branch information
mrbean-bremen committed Apr 22, 2023
1 parent eff3286 commit b6025dc
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 17 deletions.
5 changes: 5 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# pyfakefs Release Notes
The released versions correspond to PyPI releases.

## Unreleased

### Fixes
* Re-create temp directory if resetting file system (see [#814](../../issues/814)).

## [Version 5.2.2](https://pypi.python.org/pypi/pyfakefs/5.2.2) (2023-04-13)
Fixes a regression in 5.2.0

Expand Down
18 changes: 17 additions & 1 deletion pyfakefs/fake_filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
import os
import random
import sys
import tempfile
from collections import namedtuple, OrderedDict
from doctest import TestResults
from enum import Enum
Expand Down Expand Up @@ -247,6 +248,7 @@ def __init__(
self._add_root_mount_point(total_size)
self._add_standard_streams()
self.dev_null: Any = FakeNullFile(self)
self._create_temp_dir()
# set from outside if needed
self.patch_open_code = PatchMode.OFF
self.shuffle_listdir_results = False
Expand Down Expand Up @@ -342,6 +344,7 @@ def reset(self, total_size: Optional[int] = None):
self.mount_points = OrderedDict()
self._add_root_mount_point(total_size)
self._add_standard_streams()
self._create_temp_dir()
from pyfakefs import fake_pathlib

fake_pathlib.init_module(self)
Expand Down Expand Up @@ -1380,7 +1383,7 @@ def exists(self, file_path: AnyPath, check_link: bool = False) -> bool:
"""
if check_link and self.islink(file_path):
return True
path = to_string(make_string_path(file_path))
path = to_string(self.make_string_path(file_path))
if path is None:
raise TypeError
if not path:
Expand Down Expand Up @@ -2915,6 +2918,19 @@ def _add_standard_streams(self) -> None:
self._add_open_file(StandardStreamWrapper(sys.stdout))
self._add_open_file(StandardStreamWrapper(sys.stderr))

def _create_temp_dir(self):
# the temp directory is assumed to exist at least in `tempfile`,
# so we create it here for convenience
temp_dir = tempfile.gettempdir()
if not self.exists(temp_dir):
self.create_dir(temp_dir)
if sys.platform != "win32" and not self.exists("/tmp"):
# under Posix, we also create a link in /tmp if the path does not exist
link = self.create_symlink("/tmp", temp_dir)
# reset the used size to 0 to avoid having the link size counted
# which would make disk size tests more complicated
link.size = 0


def _run_doctest() -> TestResults:
import doctest
Expand Down
14 changes: 1 addition & 13 deletions pyfakefs/fake_filesystem_unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
pyfakefs by simply changing their base class from `:py:class`unittest.TestCase`
to `:py:class`pyfakefs.fake_filesystem_unittest.TestCase`.
"""
import _io # type:ignore [import]
import _io # type:ignore[import]
import doctest
import functools
import genericpath
Expand Down Expand Up @@ -876,7 +876,6 @@ def setUp(self, doctester: Any = None) -> None:
if self.has_fcopy_file:
shutil._HAS_FCOPYFILE = False # type: ignore[attr-defined]

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

# the temp directory is assumed to exist at least in `tempfile`,
# so we create it here for convenience
assert self.fs is not None
self.fs.create_dir(temp_dir)
if sys.platform != "win32" and not self.fs.exists("/tmp"):
# under Posix, we also create a link in /tmp if the path does not exist
self.fs.create_symlink("/tmp", temp_dir)
# reset the used size to 0 to avoid having the link size counted
# which would make disk size tests more complicated
next(iter(self.fs.mount_points.values()))["used_size"] = 0

def start_patching(self) -> None:
if not self._patching:
self._patching = True
Expand Down
16 changes: 16 additions & 0 deletions pyfakefs/pytest_tests/pytest_plugin_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
import tempfile

from pyfakefs.fake_filesystem import OSType
from pyfakefs.fake_filesystem_unittest import Pause
import pyfakefs.pytest_tests.io

Expand Down Expand Up @@ -60,3 +61,18 @@ def test_use_own_io_module(fs):

stream = pyfakefs.pytest_tests.io.InputStream(filepath)
assert stream.read() == "bar"


def test_switch_to_windows(fs):
fs.os = OSType.WINDOWS
assert os.path.exists(tempfile.gettempdir())


def test_switch_to_linux(fs):
fs.os = OSType.LINUX
assert os.path.exists(tempfile.gettempdir())


def test_switch_to_macos(fs):
fs.os = OSType.MACOS
assert os.path.exists(tempfile.gettempdir())
8 changes: 6 additions & 2 deletions pyfakefs/tests/fake_filesystem_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ def test_directory_inode(self):

def test_directory_size(self):
fs = fake_filesystem.FakeFilesystem(path_separator="/")
print("test start", fs.root_dir.size)
foo_dir = fs.create_dir("/foo")
fs.create_file("/foo/bar.txt", st_size=20)
bar_dir = fs.create_dir("/foo/bar/")
Expand Down Expand Up @@ -287,7 +288,6 @@ def setUp(self):
def test_new_filesystem(self):
self.assertEqual("/", self.filesystem.path_separator)
self.assertTrue(stat.S_IFDIR & self.filesystem.root.st_mode)
self.assertEqual({}, self.filesystem.root_dir.entries)

def test_none_raises_type_error(self):
with self.assertRaises(TypeError):
Expand Down Expand Up @@ -316,7 +316,8 @@ def test_get_root_object(self):

def test_add_object_to_root(self):
self.filesystem.add_object(self.root_name, self.fake_file)
self.assertEqual({"foobar": self.fake_file}, self.filesystem.root_dir.entries)
foobar = self.filesystem.root_dir.entries.get("foobar")
self.assertEqual(self.fake_file, foobar)

def test_windows_root_dir_name(self):
self.filesystem.is_windows_fs = True
Expand Down Expand Up @@ -852,6 +853,9 @@ def tearDown(self):

def test_create_top_level_directory(self):
top_level_dir = "/x"
# remove the existing temp dir
for directory in list(self.os.scandir(self.filesystem.root_dir_name)):
self.filesystem.remove_object(directory.path)
self.assertFalse(self.filesystem.exists(top_level_dir))
self.filesystem.create_dir(top_level_dir)
self.assertTrue(self.filesystem.exists("/"))
Expand Down
10 changes: 9 additions & 1 deletion pyfakefs/tests/fake_os_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1467,6 +1467,9 @@ def remove_dirs_check(self, directory):
def test_removedirs(self):
# no exception raised
self.skip_real_fs()
# remove the existing temp dir
for directory in list(self.os.scandir(self.filesystem.root_dir_name)):
self.filesystem.remove_object(directory.path)
data = [
"test1",
("test1", "test2"),
Expand Down Expand Up @@ -1507,7 +1510,9 @@ def test_removedirs(self):
def test_removedirs_raises_if_removing_root(self):
"""Raises exception if asked to remove '/'."""
self.skip_real_fs()
self.os.rmdir(self.base_path)
# remove the existing temp dir and base path
for directory in list(self.os.scandir(self.filesystem.root_dir_name)):
self.filesystem.remove_object(directory.path)
directory = self.os.path.splitdrive(self.base_path)[0] + self.os.path.sep
self.assertTrue(self.os.path.exists(directory))
self.assert_raises_os_error(errno.EBUSY, self.os.removedirs, directory)
Expand All @@ -1519,6 +1524,9 @@ def test_removedirs_raises_if_cascade_removing_root(self):
All of other directories should still be removed, though.
"""
self.skip_real_fs()
# remove the existing temp dir
for directory in list(self.os.scandir(self.filesystem.root_dir_name)):
self.filesystem.remove_object(directory.path)
directory = self.make_path("foo", "bar")
self.create_dir(directory)
self.assertTrue(self.os.path.exists(directory))
Expand Down

0 comments on commit b6025dc

Please sign in to comment.