pyfakefs fake filesystem: paths, permissions and seeded files: working versions (tested 2026-10-18)
Exercise file-handling code on an in-memory filesystem with the pyfakefs fs fixture: pathlib reads, missing parent dirs, chmod permission errors and pre-populated files.
passed6 passed · 0 failed2026-10-18 03:57 UTC- Status
- passed
- Last passed
- 2026-10-18 03:57 UTC
- Tests
- 6 / 6
- Language
- Python
- Runtime
- Python 3.13.16
uv venv -q .venv && uv pip install -q --python .venv/bin/python -r requirements.txt .venv/bin/python -m pytest -q
Python 3.13.16 linux 6.17.0-1022-azure x64 runner: github-actions 39095370682
The code
Exactly the files that passed. Your agent can pull them with get_recipe("pyfakefs-filesystem-tests") (install), or see them on GitHub.
pyfakefs==6.2.0 pytest==9.1.1
import json
from pathlib import Path
def write_text(path, text):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return path
def read_text(path, default=None):
try:
return Path(path).read_text(encoding="utf-8")
except FileNotFoundError:
return default
def append_line(path, line):
with open(path, "a", encoding="utf-8") as handle:
handle.write(f"{line}\n")
def load_json(path):
return json.loads(read_text(path))
def list_files(directory, pattern="*"):
return sorted(p.name for p in Path(directory).glob(pattern) if p.is_file())
import os
import stat
from pathlib import Path
import pytest
from pyfakefs.helpers import get_uid
from files import append_line, list_files, load_json, read_text, write_text
def test_reads_prepopulated_file(fs):
fs.create_file("/etc/app/config.json", contents='{"retries": 3, "url": "http://x"}')
assert load_json("/etc/app/config.json") == {"retries": 3, "url": "http://x"}
def test_missing_file_returns_default(fs):
assert read_text("/nope/missing.txt", default="fallback") == "fallback"
def test_write_creates_missing_parents(fs):
with pytest.raises(FileNotFoundError):
Path("/deep/a/b/c.txt").write_text("x")
write_text("/deep/a/b/c.txt", "hello")
assert read_text("/deep/a/b/c.txt") == "hello"
def test_lists_only_regular_files(fs):
fs.create_dir("/data/nested")
for name in ("b.txt", "a.txt", "c.txt"):
fs.create_file(f"/data/{name}", contents=name)
assert list_files("/data") == ["a.txt", "b.txt", "c.txt"]
def test_read_only_file_blocks_writes(fs):
from pyfakefs.fake_filesystem import set_uid
previous = get_uid()
set_uid(1000)
try:
fs.create_file(
"/data/ro.txt",
contents="secret\n",
st_mode=stat.S_IFREG | 0o400,
apply_umask=False,
)
assert stat.S_IMODE(os.stat("/data/ro.txt").st_mode) == 0o400
assert read_text("/data/ro.txt") == "secret\n"
with pytest.raises(PermissionError):
append_line("/data/ro.txt", "nope")
os.chmod("/data/ro.txt", 0o600)
append_line("/data/ro.txt", "ok")
assert read_text("/data/ro.txt") == "secret\nok\n"
finally:
set_uid(previous)
def test_simulates_write_error(fs):
def disk_full(_handle):
raise OSError("disk full")
fs.create_file("/var/log/app.log", side_effect=disk_full)
with pytest.raises(OSError, match="disk full"):
append_line("/var/log/app.log", "hello")
[pytest] pythonpath = .
Connect to ProvenPin
Add the free MCP server so your agent can pull this recipe and others like it. Same setup as the docs.
claude mcp add --transport http provenpin https://mcp.provenpin.com/mcp
{ "mcpServers": { "provenpin": { "url": "https://mcp.provenpin.com/mcp" } } }{ "servers": { "provenpin": { "type": "http", "url": "https://mcp.provenpin.com/mcp" } } }{ "mcpServers": { "provenpin": { "serverUrl": "https://mcp.provenpin.com/mcp" } } }{ "mcpServers": { "provenpin": { "type": "streamableHttp", "url": "https://mcp.provenpin.com/mcp" } } }Any other MCP client: Streamable HTTP at https://mcp.provenpin.com/mcp. No API key, no signup.
Related stacks
BeautifulSoup 4 + soupsieve CSS selector scraping
Scrape fixture HTML with BeautifulSoup and soupsieve CSS selectors to pull table cells, links and data attributes, plus the html.parser tbody gotcha.
Capture loguru logs in pytest caplog via a propagate sink and structured extra
Forward loguru records into stdlib logging so pytest caplog sees them, keep bound context as structured extra, and test it offline without a real log backend.
FastAPI dependency_overrides tested offline with httpx ASGITransport
Override FastAPI dependencies (including nested ones) and drive the app in-process with httpx.ASGITransport, no network and no running server.
FastAPI metrics with prometheus_client scraped as text
Instrument FastAPI with prometheus_client using a per-app registry, label by route template to bound cardinality, and scrape the text exposition format offline through httpx.ASGITransport.