intuited
intuited

Reputation: 24054

How to replace file-access references for a module under test

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:

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?

Upvotes: 12

Views: 4349

Answers (1)

MrBean Bremen
MrBean Bremen

Reputation: 16855

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:

  • with pytest: just use the fs plugin
  • with unittest: derive your test from pyfakefs.fake_filesystem_unittest.TestCase and call self.setUpPyfakefs() in setUp
  • with other test frameworks: use pyfakefs.fake_filesystem_unittest.Patcher, either as context manager, or using setUp/tearDown on the patcher instance
  • as a standalone decorator: import pyfakefs.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.

Upvotes: 1

Related Questions