Skip to content

12 - pyfakefs

pyfakefs implements a fake filesystem which mocks the Python file system modules. Super handy for mocking file I/O in tests and comes with a built-in pytest plugin.


Read more
The code
import pathlib

from pyfakefs.fake_filesystem import FakeFilesystem

def my_functionality() -> None:
    with open("foo.txt", "w") as f:
        f.write("foo bar baz")

# fs fixture provides a fake filesystem automatically
def test_my_functionality(fs: FakeFilesystem) -> None:
    path = pathlib.Path("foo.txt")
    assert not path.exists()


    assert path.exists()
    with open(path) as f:
        content =
    assert content == "foo bar baz"