Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
How to Mock pathlib Path.read_text with mock_open in Python
Mock pathlib.Path.read_text using patch and mock_open to test file-reading code without touching the filesystem.
import pathlib
from unittest.mock import mock_open, patch
def read_config(filepath: pathlib.Path) -> str:
"""Read file content with pathlib."""
return filepath.read_text()
if __name__ == "__main__":
mock_data = "version: 1.0\nname: demo-app"
with patch("pathlib.Path.open", mock_open(read_data=mo…
How to Use the pytest tmp_path Fixture for Temporary Directories
Use pytest's built-in tmp_path fixture to create a unique temporary directory per test for clean file I/O testing.
import pytest
def test_write_and_read_file(tmp_path):
# tmp_path is a pytest fixture that provides a temporary directory
# unique to each test invocation
data_file = tmp_path / "data.txt"
data_file.write_text("hello world")
assert data_file.read_text() == "hello world"
def test_multiple_tmp_pat…
How to Write a Fast Smoke Test for a Critical Path in Python
A quick smoke test that validates the /health critical path executes fast enough, raising errors on wrong paths or slow responses.
import time
def smoke_test(path):
if path != "/health":
raise ValueError("Critical path expected /health")
start = time.perf_counter()
# Simulate the critical health check work
time.sleep(0.01)
elapsed = time.perf_counter() - start
if elapsed > 0.05:
raise RuntimeError("Health …
Browse by section
Each section groups closely related Python snippets.
Testing & modern typing — Python code examples
What you will find here
This page collects testing & modern typing snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.