### Unittest: Using `setUpPyfakefs()` in `setUp()` method Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Shows how to integrate pyfakefs with Python's `unittest` framework by inheriting from `fake_filesystem_unittest.TestCase`. Calling `self.setUpPyfakefs()` within the `setUp` method automatically patches file system functions for each test, providing a clean fake file system for every test method. ```python import os from pyfakefs.fake_filesystem_unittest import TestCase class ExampleTestCase(TestCase): def setUp(self): self.setUpPyfakefs() def test_create_file(self): file_path = "/test/file.txt" self.assertFalse(os.path.exists(file_path)) self.fs.create_file(file_path) self.assertTrue(os.path.exists(file_path)) ``` -------------------------------- ### Example Function for File Creation with Doctests Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Provides an example Python function `create_file` that manipulates files using `open()`. The snippet includes doctests demonstrating its behavior with a fake filesystem, showing how `os.path` functions interact. ```Python def create_file(path): """Create the specified file and add some content to it. Use the open() built in function. For example, the following file operations occur in the fake file system. In the real file system, we would not even have permission to write /test: >>> os.path.isdir('/test') False >>> os.mkdir('/test') >>> os.path.isdir('/test') True >>> os.path.exists('/test/file.txt') False >>> create_file('/test/file.txt') >>> os.path.exists('/test/file.txt') True >>> with open('/test/file.txt') as f: ... f.readlines() ["This is test file '/test/file.txt'.\n", 'It was created using the open() function.\n'] """ with open(path, "w") as f: f.write("This is test file '{}'.\n".format(path)) f.write("It was created using the open() function.\n") ``` -------------------------------- ### Unittest: Using `setUpClassPyfakefs()` for class-level setup Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Demonstrates how to use `cls.setUpClassPyfakefs()` in the `setUpClass` method of a `unittest.TestCase` subclass. This sets up the fake file system once for all tests within the class, allowing for shared initial file system state and setup using standard file operations or `fake_fs()`. ```python import os import pathlib from pyfakefs.fake_filesystem_unittest import TestCase class ExampleTestCase(TestCase): @classmethod def setUpClass(cls): cls.setUpClassPyfakefs() # setup the fake filesystem using standard functions path = pathlib.Path("/test") path.mkdir() (path / "file1.txt").touch() # you can also access the fake fs via fake_fs() if needed cls.fake_fs().create_file("/test/file2.txt", contents="test") def test1(self): self.assertTrue(os.path.exists("/test/file1.txt")) self.assertTrue(os.path.exists("/test/file2.txt")) def test2(self): self.assertTrue(os.path.exists("/test/file1.txt")) file_path = "/test/file3.txt" # self.fs is the same instance as cls.fake_fs() above self.fs.create_file(file_path) self.assertTrue(os.path.exists(file_path)) ``` -------------------------------- ### Example Pyfakefs Unit Test Class Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst This Python unit test class, `TestExample`, inherits from `fake_filesystem_unittest.TestCase` to demonstrate testing file operations with a fake filesystem. By calling `self.setUpPyfakefs()` in the `setUp` method, all `os` module functions and other file operations are redirected to an in-memory fake filesystem, ensuring isolated and clean tests. The `tearDownPyfakefs()` call is no longer explicitly required. ```python class TestExample(fake_filesystem_unittest.TestCase): def setUp(self): self.setUpPyfakefs() def tearDown(self): # It is no longer necessary to add self.tearDownPyfakefs() pass def test_create_file(self): """Test example.create_file()""" # The os module has been replaced with the fake os module so all of the # following occurs in the fake filesystem. self.assertFalse(os.path.isdir("/test")) os.mkdir("/test") self.assertTrue(os.path.isdir("/test")) self.assertFalse(os.path.exists("/test/file.txt")) example.create_file("/test/file.txt") self.assertTrue(os.path.exists("/test/file.txt")) ``` -------------------------------- ### Install pyfakefs from PyPI Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/intro.rst This command installs the latest stable version of pyfakefs from the Python Package Index (PyPI) using pip. ```bash pip install pyfakefs ``` -------------------------------- ### Manually Initialize and Use pyfakefs Patcher Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Illustrates how to manually initialize and manage the `Patcher` class from `pyfakefs.fake_filesystem_unittest`. This method provides explicit control over the fake filesystem's setup and teardown, suitable for custom test environments. ```Python from pyfakefs.fake_filesystem_unittest import Patcher patcher = Patcher() patcher.setUp() # called in the initialization code ... patcher.tearDown() # somewhere in the cleanup code ``` -------------------------------- ### Install pyfakefs development version from GitHub Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/intro.rst This command installs the latest development version of pyfakefs directly from its GitHub repository's main branch using pip. ```bash pip install git+https://github.com/pytest-dev/pyfakefs ``` -------------------------------- ### Imports for pyfakefs unittest Integration Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Shows the necessary import statements for integrating `pyfakefs` with Python's `unittest` module. It imports `os`, `unittest`, `fake_filesystem_unittest`, and the module under test, `example`. ```Python import os import unittest from pyfakefs import fake_filesystem_unittest # The module under test is example: import example ``` -------------------------------- ### Pytest: Basic `fs` fixture usage Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Demonstrates how to use the `fs` fixture provided by the pyfakefs pytest plugin. This fixture automatically patches file system functions, allowing tests to interact with a fake file system. The example shows creating a fake file and asserting its existence. ```python import os def test_fakefs(fs): # "fs" is the reference to the fake file system fs.create_file("/var/data/xx1.txt") assert os.path.exists("/var/data/xx1.txt") ``` -------------------------------- ### pyfakefs.fake_filesystem.FakeFilesystem Convenience Methods API Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst API documentation for convenience methods available in `pyfakefs.fake_filesystem.FakeFilesystem` for managing fake file systems, including file creation and mapping real file system paths. These methods simplify test setup and interaction with the fake file system. ```APIDOC FakeFilesystem: create_file(path: str, contents: str = None, encoding: str = None, mode: int = None, size: int = None) Purpose: Creates a file and all missing parent directories. Parameters: path: The path of the file to create. contents: The content of the file. encoding: The encoding for the file contents. mode: The file mode. size: The size of the file (if no contents are provided). Notes: If size is used without contents, standard I/O operations may not be possible. create_dir(path: str) Purpose: Creates a directory, behaving like os.makedirs(). Parameters: path: The path of the directory to create. create_symlink(link_path: str, target_path: str) Purpose: Creates a symbolic link, behaving like os.symlink() but with reversed arguments compared to os.symlink(). Missing parent directories are created automatically. Parameters: link_path: The path of the symbolic link. target_path: The target path the symlink points to. create_link(link_path: str, target_path: str) Purpose: Creates a hard link, behaving like os.link(). Missing parent directories are created automatically. Parameters: link_path: The path of the hard link. target_path: The target path the link points to. add_real_file(source_path: str, target_path: str = None, read_only: bool = True) Purpose: Maps a real file into the fake file system. Contents are read on demand. Parameters: source_path: The path of the real file. target_path: The location in the fake filesystem where the file should be mapped (optional). read_only: If the mapped file should be read-only in the fake system (default: True). add_real_directory(source_path: str, target_path: str = None, read_only: bool = True) Purpose: Maps a real directory into the fake file system. Contents are read on demand. Parameters: source_path: The path of the real directory. target_path: The location in the fake filesystem where the directory should be mapped (optional). If target directory exists, contents are merged. read_only: If the mapped directory should be read-only in the fake system (default: True). add_real_symlink(source_path: str, target_path: str = None, read_only: bool = True) Purpose: Maps a real symbolic link into the fake file system. Parameters: source_path: The path of the real symlink. target_path: The location in the fake filesystem where the symlink should be mapped (optional). read_only: If the mapped symlink should be read-only in the fake system (default: True). add_real_paths(paths: list[str], read_only: bool = True) Purpose: Maps a list of real file or directory paths into the fake file system. Parameters: paths: A list of real file or directory paths. read_only: If the mapped paths should be read-only in the fake system (default: True). ``` -------------------------------- ### pyfakefs.fake_filesystem_unittest Module API Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/modules.rst API documentation for the `pyfakefs.fake_filesystem_unittest` module, including the `patchfs` function for test setup. ```APIDOC Module: pyfakefs.fake_filesystem_unittest Members: patchfs() ``` -------------------------------- ### Class-Level Setup for unittest and pytest Source: https://github.com/pytest-dev/pyfakefs/blob/main/CHANGES.md Introduced `setUpClassPyfakefs` for `unittest` and `fs_class` fixture for `pytest` to provide class-scoped fake filesystem setup, improving test efficiency for multiple tests within a class. ```Python unittest: class MyTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.setUpClassPyfakefs() pytest: @pytest.fixture(scope='class') def fs_class(request): # Use fs_class fixture for class-scoped fake filesystem ``` -------------------------------- ### Map Real Directory to Fake Filesystem in unittest Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst Shows how to use `self.fs.add_real_directory()` in a `unittest.TestCase`'s `setUp` method to make a real directory accessible within the fake file system. This illustrates lazy loading of file contents, where contents are copied only upon access. ```Python import os from pyfakefs.fake_filesystem_unittest import TestCase class ExampleTestCase(TestCase): fixture_path = os.path.join(os.path.dirname(__file__), "fixtures") def setUp(self): self.setUpPyfakefs() # make the file accessible in the fake file system self.fs.add_real_directory(self.fixture_path) def test_using_fixture(self): with open(os.path.join(self.fixture_path, "fixture1.txt")) as f: # file contents are copied to the fake file system # only at this point contents = f.read() ``` -------------------------------- ### Load Doctests with unittest in pyfakefs Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Defines the `load_tests` function, commonly used in `unittest` to discover and run doctests. This specific implementation loads doctests from `pyfakefs/example.py` into the `unittest` test suite. ```Python def load_tests(loader, tests, ignore): """Load the pyfakefs/example.py doctest tests into unittest.""" ``` -------------------------------- ### Configure Patcher and TestCase with module patching (Python) Source: https://github.com/pytest-dev/pyfakefs/blob/main/CHANGES.md The `Patcher` class now supports module reloading, and both `Patcher` and `TestCase` allow adding custom fake modules via the `modules_to_patch` argument for flexible testing setups. Dynamic loading of modules after setup is now enabled by default. ```APIDOC Patcher: reload_modules: bool (now available) __init__(..., modules_to_patch: Optional[Iterable[str]] = None, ...) TestCase: __init__(..., modules_to_patch: Optional[Iterable[str]] = None, ...) # Dynamic loading of modules after setup is now on by default. ``` -------------------------------- ### Switch to Main Branch and Pull Latest for pyfakefs Source: https://github.com/pytest-dev/pyfakefs/wiki/Release-procedure These Git commands are executed after a release to return to the `main` branch and synchronize it with the latest changes from the remote repository. This ensures the `main` branch is up-to-date for ongoing development. ```bash git checkout main git pull ``` -------------------------------- ### pyfakefs.fake_filesystem_unittest.Patcher Class API Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/modules.rst API documentation for the `Patcher` class, used to manage the patching of the filesystem for tests, including setup, teardown, and cleanup handlers. ```APIDOC Class: pyfakefs.fake_filesystem_unittest.Patcher Members: setUp() tearDown() pause() resume() register_cleanup_handler() ``` -------------------------------- ### Create Release Branch for pyfakefs Source: https://github.com/pytest-dev/pyfakefs/wiki/Release-procedure This Git command creates a new local branch named `version-M.m.p` from the current branch. This branch is dedicated to the release preparation, ensuring that release-specific changes are isolated from the main development line. ```bash git checkout -b version-M.m.p ``` -------------------------------- ### Push pyfakefs Release Branch to GitHub Source: https://github.com/pytest-dev/pyfakefs/wiki/Release-procedure This Git command pushes the newly created release branch (`version-M.m.p`) to the `origin` remote on GitHub. The `--set-upstream` flag establishes a tracking relationship, making it easier to push and pull changes later. ```bash git push --set-upstream origin version-M.m.p ``` -------------------------------- ### Configure Sphinx Docs Version for pyfakefs Release Source: https://github.com/pytest-dev/pyfakefs/wiki/Release-procedure This Python code snippet demonstrates setting the `version` and `release` attributes in `pyfakefs/docs/conf.py`. These attributes are crucial for Sphinx to generate documentation that correctly corresponds to the `M.m.p` release version. ```python version = 'M.m.p' release = 'M.m.p' ``` -------------------------------- ### Basic File Read Operation Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Demonstrates a simple file read operation using Python's built-in `open()` function. This snippet shows how to open a file, read its contents, and store them in a variable. ```Python with open("/foo/bar") as f: contents = f.read() ``` -------------------------------- ### Pyfakefs: Nested Filesystem Fixtures and Setup Reversion Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/troubleshooting.rst This snippet demonstrates how `pyfakefs` handles nested filesystem fixtures. When a module-scoped `fs_module` fixture is active, using the `fs` fixture in individual tests will reference the existing fake filesystem rather than creating a new one. Consequently, any setup performed within the test using `fs` will not be reverted when that specific test finishes, as only the reference count to the shared fake filesystem decreases. ```python @pytest.fixture(scope="module", autouse=True) def use_fs(fs_module): # do some setup... yield fs_module def test_something(fs): do_more_fs_setup() test_something() # the fs setup done in this test is not reverted! ``` -------------------------------- ### Update CHANGES.md for pyfakefs Release Source: https://github.com/pytest-dev/pyfakefs/wiki/Release-procedure This snippet illustrates the required format for the new version heading in `CHANGES.md`. The 'Unreleased' heading is replaced with the specific version number, a link to the PyPI release, the current date, and a brief description of the release's purpose. ```markdown ## [Version M.mm.pp](https://pypi.python.org/pypi/pyfakefs/M.m.p) (20##-##-##) Short description of the release purpose. ``` -------------------------------- ### Configure Sphinx Docs Version for Next pyfakefs Development Source: https://github.com/pytest-dev/pyfakefs/wiki/Release-procedure This Python code snippet updates the `version` and `release` attributes in `pyfakefs/docs/conf.py` to reflect the next development version (`M.nn.dev`). This ensures that documentation generated from the `main` branch accurately represents the ongoing development state. ```python version = 'M.nn' release = 'M.nn.dev' ``` -------------------------------- ### Reloading Modules with pyfakefs Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/customize.rst Demonstrates how to use `modules_to_reload` to ensure that specific modules are reloaded and patched by `pyfakefs`. Examples are provided for `unittest`, `pytest`, `Patcher` context manager, and the `patchfs` decorator. ```Python import example # example using unittest class ReloadModuleTest(fake_filesystem_unittest.TestCase): def setUp(self): self.setUpPyfakefs(modules_to_reload=[example.sut]) def test_path_exists(self): file_path = "/foo/bar" self.fs.create_dir(file_path) self.assertTrue(example.sut.check_if_exists(file_path)) ``` ```Python import example import pytest # example using pytest @pytest.mark.parametrize("fs", [[None, [example.sut]]], indirect=True) def test_path_exists(fs): file_path = "/foo/bar" fs.create_dir(file_path) assert example.sut.check_if_exists(file_path) ``` ```Python import example from pyfakefs.fake_filesystem_unittest import Patcher # example using Patcher def test_path_exists(): with Patcher(modules_to_reload=[example.sut]) as patcher: file_path = "/foo/bar" patcher.fs.create_dir(file_path) assert example.sut.check_if_exists(file_path) ``` ```Python import example from pyfakefs.fake_filesystem_unittest import patchfs # example using patchfs decorator @patchfs(modules_to_reload=[example.sut]) def test_path_exists(fs): file_path = "/foo/bar" fs.create_dir(file_path) assert example.sut.check_if_exists(file_path) ``` -------------------------------- ### Map `pytz` timezone data directory to `pyfakefs` Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/troubleshooting.rst This example demonstrates how to add the real `zoneinfo` directory of the `pytz` module to the fake filesystem. This is necessary when modules like `pytz` access configuration files directly from the real filesystem, ensuring they function correctly within a `pyfakefs` test environment. ```python from pathlib import Path import pytz from pyfakefs.fake_filesystem_unittest import TestCase class ExampleTestCase(TestCase): def setUp(self): self.setUpPyfakefs() info_dir = Path(pytz.__file__).parent / "zoneinfo" self.fs.add_real_directory(info_dir) ``` -------------------------------- ### Direct Patching: Using `Patcher` as a context manager Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Illustrates how to use `fake_filesystem_unittest.Patcher` as a context manager for direct control over file system patching. This method is suitable for testing frameworks other than pytest or unittest, providing a temporary fake file system accessible via `patcher.fs` within the `with` block. ```python from pyfakefs.fake_filesystem_unittest import Patcher with Patcher() as patcher: # access the fake_filesystem object via patcher.fs patcher.fs.create_file("/foo/bar", contents="test") # the following code works on the fake filesystem ``` -------------------------------- ### Pyfakefs Automatic Patching: Direct Imports Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/customize.rst Shows examples of direct imports of file system modules (`os`, `pathlib.Path`) that `pyfakefs` automatically patches. ```Python import os import pathlib.Path ``` -------------------------------- ### Pyfakefs Automatic Patching: Function Imports Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/customize.rst Shows examples of file system functions imported directly (`from os.path import exists`, `from os import stat`) that are automatically patched. ```Python from os.path import exists from os import stat ``` -------------------------------- ### Use pyfakefs patchfs Decorator in unittest.TestCase Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Illustrates how to apply the `@patchfs` decorator to a test method within a standard `unittest.TestCase` class. This allows individual test methods to utilize the fake filesystem. ```Python class TestSomething(unittest.TestCase): @patchfs def test_something(self, fs): fs.create_file("/foo/bar", contents="test") ``` -------------------------------- ### Standardize IOError/OSError messages (Python) Source: https://github.com/pytest-dev/pyfakefs/blob/main/CHANGES.md Exception messages for `IOError` and `OSError` in the fake file system now consistently start with the message issued by the real file system on Unix, improving debugging and consistency. ```APIDOC try: # File system operation pass except (IOError, OSError) as e: # On Unix, str(e) now starts with the real file system's message. # Example: "[Errno 2] No such file or directory: 'nonexistent_file'" ``` -------------------------------- ### Apply pyfakefs patchfs Decorator to a Test Function Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Shows how to use the `@patchfs` decorator from `pyfakefs.fake_filesystem_unittest` to automatically inject a fake filesystem into a test function. The fake filesystem object is accessible via a positional argument, `fake_fs`. ```Python from pyfakefs.fake_filesystem_unittest import patchfs @patchfs def test_something(fake_fs): # access the fake_filesystem object via fake_fs fake_fs.create_file("/foo/bar", contents="test") ``` -------------------------------- ### Update __version__ for Next pyfakefs Development Cycle Source: https://github.com/pytest-dev/pyfakefs/wiki/Release-procedure This Python code snippet updates the `__version__` attribute in `pyfakefs/fake_filesystem.py` to reflect the next development version (`M.nn.dev0`). This change signifies that the `main` branch is now progressing towards the subsequent release. ```python __version__ = 'M.nn.dev0' ``` -------------------------------- ### Python: Suspending and resuming pyfakefs patching directly Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst This example illustrates how to temporarily pause and resume pyfakefs patching using fs.pause() and fs.resume(). It shows that while paused, real filesystem operations (like os.path.exists on a real temporary file) work, and fake filesystem operations are disabled, and vice-versa when resumed. ```python import os import tempfile from pyfakefs.fake_filesystem_unittest import Pause def test_pause_resume_contextmanager(fs): fake_temp_file = tempfile.NamedTemporaryFile() assert os.path.exists(fake_temp_file.name) fs.pause() assert not os.path.exists(fake_temp_file.name) real_temp_file = tempfile.NamedTemporaryFile() assert os.path.exists(real_temp_file.name) fs.resume() assert not os.path.exists(real_temp_file.name) assert os.path.exists(fake_temp_file.name) ``` -------------------------------- ### Combine pyfakefs patchfs with mock.patch Decorators Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Demonstrates the interaction and argument order when combining the `@patchfs` decorator with `mock.patch` decorators. It highlights that the order of decorators affects the order of positional arguments passed to the test function. ```Python @patchfs @mock.patch("foo.bar") def test_something(fake_fs, mocked_bar): assert foo() @mock.patch("foo.bar") @patchfs def test_something(mocked_bar, fake_fs): assert foo() ``` -------------------------------- ### Python: Adding package metadata to pyfakefs for importlib.metadata Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst This example shows how to use fs.add_package_metadata() within a pytest autouse fixture. This function is crucial for making package metadata files (e.g., for 'Werkzeug') available within the fake filesystem, which is necessary for modules like importlib.metadata or frameworks like flask.testing to function correctly. ```python import pytest @pytest.fixture(autouse=True) def add_werkzeug_metadata(fs): # flask.testing accesses Werkzeug metadata, map it fs.add_package_metadata("Werkzeug") yield ``` -------------------------------- ### Pytest: Renaming `fs` fixture to avoid Pylint warning Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/usage.rst Illustrates how to define a custom pytest fixture in `conftest.py` to provide an alternative name for the `fs` fixture (e.g., `fake_filesystem`). This helps in complying with Pylint's naming conventions while still accessing the fake file system functionality. ```python import pytest @pytest.fixture def fake_filesystem(fs): # pylint:disable=invalid-name """Variable name 'fs' causes a pylint warning. Provide a longer name acceptable to pylint for use in tests. """ yield fs ``` -------------------------------- ### Patching External Modules with pyfakefs (e.g., Django) Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/customize.rst Illustrates how `modules_to_patch` can be used to provide fake implementations for external modules that `pyfakefs` doesn't patch by default, such as `django.core.files.locks`. Includes a custom `FakeLocks` class and usage examples across different testing frameworks. ```Python import django class FakeLocks: """django.core.files.locks uses low level OS functions, fake it.""" _locks_module = django.core.files.locks def __init__(self, fs): """Each fake module expects the fake file system as an __init__ parameter.""" # fs represents the fake filesystem; for a real example, it can be # saved here and used in the implementation pass @staticmethod def lock(f, flags): return True @staticmethod def unlock(f): return True def __getattr__(self, name): return getattr(self._locks_module, name) ``` ```Python from pyfakefs.fake_filesystem_unittest import Patcher # test code using Patcher with Patcher(modules_to_patch={"django.core.files.locks": FakeLocks}): test_django_stuff() ``` ```Python import fake_filesystem_unittest # test code using unittest class TestUsingDjango(fake_filesystem_unittest.TestCase): def setUp(self): self.setUpPyfakefs(modules_to_patch={"django.core.files.locks": FakeLocks}) def test_django_stuff(self): assert foo() ``` ```Python import pytest # test code using pytest @pytest.mark.parametrize( "fs", [[None, None, {"django.core.files.locks": FakeLocks}]], indirect=True ) def test_django_stuff(fs): assert foo() ``` ```Python from pyfakefs.fake_filesystem_unittest import patchfs # test code using patchfs decorator @patchfs(modules_to_patch={"django.core.files.locks": FakeLocks}) def test_django_stuff(fake_fs): assert foo() ``` -------------------------------- ### Use Pyfakefs Reload Cleanup Handler for Modules Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/troubleshooting.rst Demonstrates how to utilize the built-in `reload_cleanup_handler` from `pyfakefs.helpers`. This handler is specifically designed for modules that use filesystem functions and are imported locally, ensuring they are correctly reloaded. The example shows how to assign `reload_cleanup_handler` to `patcher.cleanup_handlers` within a `pytest` fixture for automatic module reloading. ```python from pyfakefs.helpers import reload_cleanup_handler @pytest.fixture def my_fs(): with Patcher() as patcher: patcher.cleanup_handlers["modulename"] = reload_cleanup_handler yield patcher.fs ``` -------------------------------- ### Pyfakefs: Handling Pathlib.Path Object Equality Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/troubleshooting.rst This example illustrates a common pitfall when mixing `pathlib.Path` objects created in the real filesystem with those created within a `pyfakefs` environment. Objects created before `pyfakefs` is active retain references to the real filesystem, causing them to compare as unequal to `FakePath` objects, even if their string representations are identical. It's recommended to compare string paths or create all `pathlib.Path` objects after `pyfakefs` is active. ```python import pathlib # This Path was made in the real filesystem, before the test # stands up the fake filesystem FILE_PATH = pathlib.Path(__file__).parent / "file.csv" def test_path_equality(fs): # This Path was made after the fake filesystem is set up, # and thus patching within pathlib is in effect fake_file_path = pathlib.Path(str(FILE_PATH)) assert FILE_PATH == fake_file_path # fails, compares different objects assert str(FILE_PATH) == str(fake_file_path) # succeeds, compares the actual paths ``` -------------------------------- ### Assert `pyfakefs` temporary directory presence Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/troubleshooting.rst This snippet demonstrates that `pyfakefs` always ensures a temporary directory (e.g., `/tmp` on POSIX systems or `C:\Users\\AppData\Local\Temp` on Windows) is present in the fake filesystem at the start of tests. This is because the `tempfile` module is not faked, and a valid temporary directory is required for its correct operation. ```python import os def test_something(fs): # the temp directory is always present at test start assert len(os.listdir("/")) == 1 ``` -------------------------------- ### Pyfakefs: Ignoring Nested Patcher Invocations Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/troubleshooting.rst This example illustrates that `Patcher` instances created within a test that already has an active `fs` fixture (or `fs_module`/`fs_session`) will be ignored. The arguments passed to the nested `Patcher` (e.g., `allow_root_user=False`) will not take effect, as `pyfakefs` uses reference counting on a single fake filesystem instance and does not support nested fake filesystems. ```python def test_something(fs): with Patcher(allow_root_user=False): # root user is still allowed do_stuff() ``` -------------------------------- ### Create File with pyfakefs in unittest Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst Demonstrates how to use `self.fs.create_file()` within a `unittest.TestCase` to create a file with specified content in the fake file system and then verify its content. This method also handles creation of missing parent directories. ```Python from pyfakefs.fake_filesystem_unittest import TestCase class ExampleTestCase(TestCase): def setUp(self): self.setUpPyfakefs() def test_create_file(self): file_path = "/foo/bar/test.txt" self.fs.create_file(file_path, contents="test") with open(file_path) as f: self.assertEqual("test", f.read()) ``` -------------------------------- ### pyfakefs.fake_filesystem_unittest.TestCaseMixin Class API Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/modules.rst API documentation for the `TestCaseMixin` class, designed to be mixed into `unittest.TestCase` classes to provide `pyfakefs` functionality. It includes methods for setting up and controlling the fake filesystem within tests. ```APIDOC Class: pyfakefs.fake_filesystem_unittest.TestCaseMixin Members: fs setUpPyfakefs() setUpClassPyfakefs() pause() resume() ``` -------------------------------- ### APIDOC: pyfakefs.fake_filesystem_unittest.Pause Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst A context manager class that encapsulates the pause() and resume() calls for a FakeFilesystem instance. It provides a convenient way to temporarily switch to the real filesystem within a with block, ensuring pyfakefs is resumed upon exiting the block. ```APIDOC class pyfakefs.fake_filesystem_unittest.Pause(fs: pyfakefs.fake_filesystem.FakeFilesystem) __enter__() __exit__(exc_type, exc_val, exc_tb) ``` -------------------------------- ### Simulate Windows Path Behavior in Pyfakefs Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst This Python test function demonstrates how to configure pyfakefs to simulate a Windows file system using fs.os = OSType.WINDOWS. It then verifies Windows-specific path behaviors like os.path.join, os.path.splitdrive, and os.path.ismount. ```python import os from pyfakefs.fake_filesystem import OSType def test_windows_paths(fs): fs.os = OSType.WINDOWS assert r"C:\\foo\\bar" == os.path.join("C:\\", "foo", "bar") assert os.path.splitdrive(r"C:\\foo\\bar") == ("C:", r"\\foo\\bar") assert os.path.ismount("C:") ``` -------------------------------- ### Python: Testing disk full scenarios with pyfakefs set_disk_usage Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst This test case demonstrates how to set a specific disk size for the fake filesystem using self.fs.set_disk_usage(). It then attempts to write a file larger than the available space, asserting that an OSError with errno.ENOSPC (No space left on device) is raised, simulating a disk full scenario. ```python import errno import os from pyfakefs.fake_filesystem_unittest import TestCase class ExampleTestCase(TestCase): def setUp(self): self.setUpPyfakefs() self.fs.set_disk_usage(100) def test_disk_full(self): os.mkdir("/foo") with self.assertRaises(OSError) as e: with open("/foo/bar.txt", "w") as f: f.write("a" * 200) self.assertEqual(errno.ENOSPC, e.exception.errno) ``` -------------------------------- ### Pyfakefs Patching Limitation: Decorators Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/customize.rst Shows an example where a file system function used within a decorator is not automatically patched by `pyfakefs`. ```Python import pathlib import click @click.command() @click.argument("foo", type=click.Path(path_type=pathlib.Path)) def hello(foo): pass ``` -------------------------------- ### Pyfakefs.FakeFilesystem OS Simulation Attributes Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst This section details the attributes of pyfakefs.FakeFilesystem that control operating system simulation. These attributes can be set directly or are automatically configured when fs.os is changed, influencing file system behavior like case sensitivity and path separators. ```APIDOC pyfakefs.FakeFilesystem attributes for OS simulation: is_windows_fs: bool If True, a Windows file system (NTFS) is assumed. is_macos: bool If True and is_windows_fs is False, the standard macOS file system (HFS+) is assumed. (default): Linux file system (e.g., ext3) is assumed if both is_windows_fs and is_macos are False. is_case_sensitive: bool Set to True under Linux, False under Windows and macOS by default. Can be changed to alter behavior. path_separator: str Set to '\\' under Windows, '/' under Posix. alternative_path_separator: str Set to '/' under Windows, None under Posix. ``` -------------------------------- ### pyfakefs.fake_filesystem.FakeFilesystem Class API Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/modules.rst API documentation for the central `FakeFilesystem` class, which manages the simulated file system. It includes methods for adding real paths, creating fake directories and files, managing disk usage, and controlling the filesystem's state. ```APIDOC Class: pyfakefs.fake_filesystem.FakeFilesystem Members: add_mount_point() get_disk_usage() set_disk_usage() change_disk_usage() add_real_directory() add_real_file() add_real_symlink() add_real_paths() add_package_metadata() create_dir() create_file() create_symlink() create_link() get_object() pause() resume() ``` -------------------------------- ### pyfakefs.helpers Module API Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/modules.rst API documentation for the `pyfakefs.helpers` module, providing utility functions for managing user and group IDs within the fake filesystem environment. ```APIDOC Module: pyfakefs.helpers Members: get_uid() set_uid() get_gid() set_gid() reset_ids() is_root() ``` -------------------------------- ### pyfakefs: FakeFilesystem.create_link Convenience Method Source: https://github.com/pytest-dev/pyfakefs/blob/main/CHANGES.md Documents the new `FakeFilesystem.create_link` convenience method, which automatically creates intermittent directories for the link target. ```APIDOC FakeFilesystem.create_link(source: str, link_name: str) Description: Creates a hard link from 'source' to 'link_name', automatically creating any missing parent directories for 'link_name'. Supported in pyfakefs: Yes (from v4.4.0) ``` -------------------------------- ### Run pyfakefs unit tests with pytest Source: https://github.com/pytest-dev/pyfakefs/blob/main/README.md Navigate to the pyfakefs directory, set the PYTHONPATH, and execute all pyfakefs unit tests using the pytest framework. This command-line approach allows for direct testing of the library's functionality. ```Bash cd pyfakefs/ export PYTHONPATH=$PWD python -m pytest pyfakefs ``` -------------------------------- ### Set __version__ in pyfakefs/_version.py Source: https://github.com/pytest-dev/pyfakefs/wiki/Release-procedure This Python code snippet shows how to update the `__version__` attribute in `pyfakefs/_version.py`. This attribute defines the package's official version number, which must accurately reflect the new release version `M.mm.p`. ```python __version__ = 'M.mm.p' ``` -------------------------------- ### Add Django project and site-packages to `pyfakefs` using pytest Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/troubleshooting.rst This pytest fixture shows how to map the real project base directory and the Django `site-packages` directory into the fake filesystem. This is crucial for Django applications and their dependencies that expect these directories to exist and be accessible within the test environment when using `pyfakefs`. ```python import os import django import pytest @pytest.fixture def fake_fs(fs): PROJECT_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) fs.add_real_paths( [ PROJECT_BASE_DIR, os.path.dirname(django.__file__), ] ) return fs ``` -------------------------------- ### Skipping Modules from pyfakefs Patching Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/customize.rst Shows how to use `additional_skip_names` to prevent `pyfakefs` from patching specific modules, useful for scenarios where a module needs to access the real file system. Examples include passing module names as strings or module objects. ```Python from pyfakefs.fake_filesystem_unittest import Patcher with Patcher(additional_skip_names=["pydevd"]) as patcher: patcher.fs.create_file("foo") ``` ```Python import pydevd from pyfakefs.fake_filesystem_unittest import Patcher with Patcher(additional_skip_names=[pydevd]) as patcher: patcher.fs.create_file("foo") ``` -------------------------------- ### APIDOC: pyfakefs.fake_filesystem.FakeFilesystem.add_package_metadata Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst Adds metadata distribution files for a given package to the fake filesystem. This is essential for modules like importlib.metadata to find package information within the faked environment. ```APIDOC pyfakefs.fake_filesystem.FakeFilesystem.add_package_metadata(package_name: str) ``` -------------------------------- ### Customize Pyfakefs in Unittest setUpPyfakefs Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/customize.rst Explains how to pass custom `Patcher` arguments to `setUpPyfakefs()` within a `fake_filesystem_unittest.TestCase` subclass for `unittest` based tests. ```Python from pyfakefs.fake_filesystem_unittest import TestCase class SomeTest(TestCase): def setUp(self): self.setUpPyfakefs(allow_root_user=False) def testSomething(self): assert foo() ``` -------------------------------- ### Map Real Directory to Fake Filesystem using pytest fixture Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst Illustrates how to use `fs.add_real_directory()` within a `pytest` fixture to make a real directory available to tests. This approach integrates real file system access seamlessly into pytest's testing framework. ```Python import pytest import os fixture_path = os.path.join(os.path.dirname(__file__), "fixtures") @pytest.fixture def my_fs(fs): fs.add_real_directory(fixture_path) yield fs @pytest.mark.usefixtures("my_fs") def test_using_fixture(): with open(os.path.join(fixture_path, "fixture1.txt")) as f: contents = f.read() ``` -------------------------------- ### APIDOC: pyfakefs.fake_filesystem.FakeFilesystem.get_disk_usage Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst Retrieves the disk usage information for the fake filesystem. This method is modeled after shutil.disk_usage() and provides total, used, and free space for the specified path or the root. ```APIDOC pyfakefs.fake_filesystem.FakeFilesystem.get_disk_usage(path: str = None) -> tuple[int, int, int] ``` -------------------------------- ### APIDOC: pyfakefs.fake_filesystem.FakeFilesystem.pause/resume Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst These methods allow temporary suspension (pause()) and resumption (resume()) of pyfakefs patching. When paused, operations will interact with the real filesystem; when resumed, pyfakefs takes over again. ```APIDOC pyfakefs.fake_filesystem.FakeFilesystem.pause() pyfakefs.fake_filesystem.FakeFilesystem.resume() ``` -------------------------------- ### Correct pyfakefs and mock_open Fixture Order Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/troubleshooting.rst Shows the correct order of pytest fixtures (`fs` before `mocker`) when patching `builtins.open` with `mock_open`. This ensures pyfakefs initializes correctly before `open` is mocked, allowing both to function as expected. ```python def test_mock_open_correct(fs, mocker): # works correctly mocker.patch("builtins.open", mocker.mock_open(read_data="content")) ``` -------------------------------- ### pyfakefs.fake_filesystem_unittest.TestCase Class API Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/modules.rst API documentation for the `TestCase` class, a convenience base class for writing unit tests with `pyfakefs`. ```APIDOC Class: pyfakefs.fake_filesystem_unittest.TestCase ``` -------------------------------- ### Run pyfakefs unit tests with tox Source: https://github.com/pytest-dev/pyfakefs/blob/main/README.md Execute pyfakefs unit tests locally against various supported Python versions using the tox automation tool. This command simplifies testing across different environments and configurations. ```Bash tox ``` -------------------------------- ### Build pyfakefs Docker image for testing Source: https://github.com/pytest-dev/pyfakefs/blob/main/README.md Navigate to the pyfakefs directory and build a Docker image named 'pyfakefs'. This image is configured to run tests on the latest Ubuntu version, providing an isolated testing environment. ```Bash cd pyfakefs/ docker build -t pyfakefs . ``` -------------------------------- ### pyfakefs.fake_os.FakeOsModule Class API Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/modules.rst API documentation for the `FakeOsModule` class, which provides a faked implementation of the standard `os` module. ```APIDOC Class: pyfakefs.fake_os.FakeOsModule ``` -------------------------------- ### Demonstrate Real vs. Fake Temporary File Existence in Pyfakefs Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst This Python snippet illustrates the difference in file existence behavior between a real temporary file created with tempfile.NamedTemporaryFile() and a fake file within pyfakefs. It shows that a real temporary file might be automatically deleted upon closure, while a corresponding fake file persists. ```python real_temp_file = tempfile.NamedTemporaryFile() assert os.path.exists(real_temp_file.name) assert not os.path.exists(real_temp_file.name) assert os.path.exists(fake_temp_file.name) ``` -------------------------------- ### Create Independent Temporary Path Fixture for pyfakefs and Real Filesystem Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/troubleshooting.rst Illustrates how to create a pytest fixture for temporary directories that does not directly depend on the `fs` fixture. This allows the fixture to be used with both the real filesystem and the fake filesystem, providing flexibility for tests. ```python @pytest.fixture def temp_path(): tmp_dir = tempfile.TemporaryDirectory() yield Path(tmp_dir.name) ``` -------------------------------- ### APIDOC: pyfakefs.fake_filesystem.FakeFilesystem.set_disk_usage Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst Sets the total size in bytes of the fake filesystem. By default, this applies to the root partition. If a path parameter is provided, the size is related to the specific mount point. Setting a size enables disk full scenarios where file creation can fail if space is exhausted. ```APIDOC pyfakefs.fake_filesystem.FakeFilesystem.set_disk_usage(size_in_bytes: int, path: str = None) ``` -------------------------------- ### APIDOC: pyfakefs.fake_filesystem.FakeFilesystem.add_mount_point Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/convenience.rst Adds a new mount point to the fake filesystem. Under Linux and macOS, the root path (/) is the default. Each mount point has a separate device ID (st_dev), affecting operations like rename across mount points and per-mount point size limits. ```APIDOC pyfakefs.fake_filesystem.FakeFilesystem.add_mount_point(path: str) ``` -------------------------------- ### pyfakefs.fake_file.FakeDirectory Class API Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/modules.rst API documentation for the `FakeDirectory` class, representing a simulated directory. It includes properties for its contents and size, and methods for managing entries within the directory. ```APIDOC Class: pyfakefs.fake_file.FakeDirectory Members: contents ordered_dirs size get_entry() remove_entry() ``` -------------------------------- ### pyfakefs.fake_filesystem_shutil.FakeShutilModule Class API Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/modules.rst API documentation for the `FakeShutilModule` class, which provides a faked implementation of the standard `shutil` module. ```APIDOC Class: pyfakefs.fake_filesystem_shutil.FakeShutilModule ``` -------------------------------- ### pyfakefs: Correct Handling of UNC Paths in os.path.split Source: https://github.com/pytest-dev/pyfakefs/blob/main/CHANGES.md Documents the fix for correctly handling Universal Naming Convention (UNC) paths in `os.path.split` and directory path evaluation within pyfakefs. ```APIDOC os.path.split(path: PathLike) -> Tuple[str, str] Description: Splits the pathname into a pair (head, tail). Now correctly handles UNC paths. Fixes: Incorrect behavior with UNC paths prior to v4.5.0. ``` -------------------------------- ### Configure pyfakefs User Rights with allow_root_user Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/troubleshooting.rst Demonstrates how to use `allow_root_user=False` in `setUpPyfakefs` to prevent pyfakefs from behaving as a root user, even when the test environment (e.g., Docker) is running as root. This ensures tests respect non-root user permissions. ```python from pyfakefs.fake_filesystem_unittest import TestCase class SomeTest(TestCase): def setUp(self): self.setUpPyfakefs(allow_root_user=False) ``` -------------------------------- ### pyfakefs: Improved str/bytes Path Handling Source: https://github.com/pytest-dev/pyfakefs/blob/main/CHANGES.md Documents the improvements in pyfakefs for consistent and correct handling of both string (`str`) and byte (`bytes`) paths. ```APIDOC str/bytes path handling Description: More robust and consistent handling of string and byte-based paths. Fixes: Inconsistent or incorrect handling of str/bytes paths. ``` -------------------------------- ### Run pyfakefs unit tests with unittest Source: https://github.com/pytest-dev/pyfakefs/blob/main/README.md Navigate to the pyfakefs directory, set the PYTHONPATH, and execute all pyfakefs unit tests using Python's built-in unittest framework. This provides an alternative method for running tests without pytest. ```Bash cd pyfakefs/ export PYTHONPATH=$PWD python -m pyfakefs.tests.all_tests ``` -------------------------------- ### pyfakefs.fake_open.FakeFileOpen Class API Source: https://github.com/pytest-dev/pyfakefs/blob/main/docs/modules.rst API documentation for the `FakeFileOpen` class, which provides a faked implementation of the built-in `open` function. ```APIDOC Class: pyfakefs.fake_open.FakeFileOpen ```