pyfakefs
sounds very useful: it "was developed initially as a modest fake implementation of core Python modules to support moderately complex file system interactions, and was introduced Google-wide . . . in September 2006. Since then, it has received many (well-tested) contributions to extend its functionality and usefulness, and is used in over 900 Google Python tests."
Documentation appears to currently only be available within docstrings of the source code itself. It explains that the module provides the following elements:
- FakeFile: Provides the appearance of a real file.
- FakeDirectory: Provides the appearance of a real dir.
- FakeFilesystem: Provides the appearance of a real directory hierarchy.
- FakeOsModule: Uses FakeFilesystem to provide a fake os module replacement.
- FakePathModule: Faked os.path module replacement.
- FakeFileOpen: Faked file() and open() function replacements.
Documentation does not, however, explain how to effectively use these elements in testing.
What is the right way to ensure that a module under test accesses a fake filesystem and not the real one?
As the original answer has been deleted, I will add a new one in case someone stumbles over this.
Disclaimer: I'm a maintainer of
pyfakefs
.While at the time of writing the question this has not been the case, the answer is now mostly contained in the documentation. To summarize, there are 4 different possibilities how to emulate all file system functions using
pyfakefs
:pytest
: just use thefs
pluginunittest
: derive your test frompyfakefs.fake_filesystem_unittest.TestCase
and callself.setUpPyfakefs()
insetUp
pyfakefs.fake_filesystem_unittest.Patcher
, either as context manager, or usingsetUp
/tearDown
on the patcher instancepyfakefs.fake_filesystem_unittest.patchfs
and use it as a decorator for your test function (@patchfs
)All these variants allow for some customization, and there are some convenience methods that can be called on the fake filesystem instance (like defining the size in bytes of the file system), but these are optional. Just using one of these methods will replace all Python filesystem calls to calls into a mocked (memory-based) filesystem.
Note also that there are some limitations that restrict the applicability of
pyfakefs
.