pyfakefs

6.1.6 · active · verified Thu Apr 09

pyfakefs implements a fake file system that mocks the Python file system modules. It allows tests to operate on an in-memory file system without touching the real disk, requiring no modification to the software under test. pyfakefs supports pytest, unittest, and can be used as a context manager. It is actively maintained with frequent releases to support new Python versions and fix bugs.

Warnings

Install

Imports

Quickstart

This example demonstrates basic file operations using the `fs` pytest fixture, which automatically sets up and tears down an in-memory fake filesystem for your test. Simply run `pytest your_test_file.py`.

import os
import pytest

def test_file_operations(fs):
    # The 'fs' fixture provides a fake file system
    # All os.path and file operations will use this fake system
    assert not os.path.exists("/test_dir")
    os.mkdir("/test_dir")
    assert os.path.exists("/test_dir")

    file_path = "/test_dir/my_file.txt"
    with open(file_path, "w") as f:
        f.write("Hello, pyfakefs!")

    assert os.path.exists(file_path)
    with open(file_path, "r") as f:
        content = f.read()
    assert content == "Hello, pyfakefs!"

    os.remove(file_path)
    assert not os.path.exists(file_path)

view raw JSON →