-->

How to replace file-access references for a module

2020-08-27 05:27发布

问题:

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?

回答1:

See http://github.com/jmcgeheeiv/pyfakefs for code that supports both unittest and doctest, plus a practical example and tutorial.