Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
Capture stdout and stderr with pytest capsys
Use pytest's capsys fixture to capture and assert on standard output and error streams in your tests.
import pytest
# Function under test
def greet(name):
print(f"Hello, {name}!")
print(f"Error: {name} not found", file=sys.stderr)
def test_captures_stdout_and_stderr(capsys):
greet("Alice")
captured = capsys.readouterr()
assert "Hello, Alice!" in captured.out
assert "Error: Alice not foun…
Characterization Test for Legacy Python Code
Capture the exact output of a legacy Python function for known inputs, creating a characterization test that documents current behavior before refactoring.
def legacy_behavior(value):
"""Legacy function that returns a tuple with unconventional types."""
if value == "special":
return None, "legacy-special"
elif value > 100:
return value, "large"
elif value > 0:
return value * 2, "positive-doubled"
elif value == 0:
…
Dataclass with Type Hints Fields in Python
Create a data class with typed fields and default values, then instantiate and inspect it.
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
email: str = "unknown@example.com"
is_active: bool = True
if __name__ == "__main__":
person = Person(name="Alice", age=30)
print(person)
print(f"Name: {person.name}, Age: {person.age}, Email: {person.email}, A…
Dependency Injection in Python for Testability
Inject a config dependency into a service so you can swap a real environment-based config for a fake one in tests.
import os
class Config:
"""Simple config loader that can be easily faked in tests."""
def get(self, key, default=None):
return os.environ.get(key, default)
class UserService:
def __init__(self, config):
self.config = config
def get_timeout(self):
return int(self.config.get(…
Fix and Test a Regression Bug in Python with Unit Tests
This code implements a circle area function that raises ValueError for negative radii, then runs basic tests and a regression check for that edge case.
import math
def calculate_area(radius):
"""Calculate the area of a circle given its radius."""
if radius < 0:
raise ValueError("Radius cannot be negative")
return math.pi * radius ** 2
def main():
test_cases = [0, 1, 2.5, 5, 10]
print("Circle Area Calculator")
print("-" * 30)
…
Generate Fake User Data with Faker in Python
Use the Faker library to generate realistic fake user profiles with names, emails, phone numbers, and addresses for tests or demos.
from faker import Faker
fake = Faker()
def generate_user():
return {
"name": fake.name(),
"email": fake.email(),
"phone": fake.phone_number(),
"address": fake.address().replace("\n", ", "),
}
if __name__ == "__main__":
user = generate_user()
for key, value in user.ite…
How to Benchmark Python Code with pytest-benchmark and mocks
Use pytest-benchmark to measure function performance while combining Mock and patch for controlled test scenarios.
import time
from unittest.mock import Mock, patch
import pytest
from pytest_benchmark.fixture import BenchmarkFixture
def heavy_operation(data: list[int]) -> int:
"""Simulates a CPU-bound operation."""
return sum(x * x for x in data)
def test_heavy_operation_benchmark(benchmark: BenchmarkFixture) -> None:…
How to Capture Logging Records with pytest caplog in Python
Capture and assert on logging records in pytest using the built-in caplog fixture.
import logging
import pytest
def divide(a, b):
"""Divide two numbers and log an error if b is zero."""
if b == 0:
logging.error("Division by zero attempted")
return None
logging.info(f"Dividing {a} by {b}")
return a / b
def test_divide_logs_error(caplog):
with caplog.at_level(logg…
How to Compare Execution Speed Between Python Functions
Measure and compare the average execution time of multiple Python functions using a reusable benchmark helper with time.perf_counter.
import time
import random
def method_a(values):
"""Sort using built-in sorted."""
return sorted(values)
def method_b(values):
"""Sort using list's sort method."""
values_copy = values[:]
values_copy.sort()
return values_copy
def method_c(values):
"""Sort manually using bubble sort (slow,…
How to Compare Files and Show a Diff in Python
Compare two text files and print a unified diff using Python's difflib module to highlight differences.
import difflib
from pathlib import Path
def compare_files(expected_path: str, actual_path: str) -> str:
"""Compare two text files and return a unified diff."""
expected = Path(expected_path).read_text()
actual = Path(actual_path).read_text()
diff = difflib.unified_diff(
expected.splitlines(ke…
How to Compare Floats in pytest with approx
Uses pytest.approx to compare floating-point numbers with tolerance, avoiding precision issues.
import pytest
def test_float_addition():
result = 0.1 + 0.2
expected = 0.3
assert result == pytest.approx(expected)
How to Convert Strings to Types in Python Using TypeVar
A beginner-friendly helper that converts a string to int, float, bool, or str with type hints and graceful failure handling.
from typing import TypeVar, Optional
T = TypeVar("T")
def convert_data(value: str, target_type: type[T]) -> Optional[T]:
"""Convert string value to target type; return None on failure."""
try:
if target_type is int:
return int(value)
elif target_type is float:
return f…
How to Filter Data in Python with Type Hints
A reusable filter_data helper uses optional predicates and numeric bounds with modern Python type hints.
from typing import Iterable, TypeVar, Callable, Any
T = TypeVar("T")
def filter_data(
items: Iterable[T],
predicate: Callable[[T], bool] | None = None,
*,
min_value: float | None = None,
max_value: float | None = None,
) -> list[T]:
"""Filter items by predicate and/or numeric bounds."""
r…
How to Flag Unexpected Diff Changes in Python
Compares two snapshot lists, detects unexpected differences, and returns a flag indicating whether the snapshot should be updated.
import difflib
def snapshot_diff(before, after, intentional_changes=None):
"""Compare snapshots and flag only unexpected differences."""
intentional_changes = intentional_changes or set()
diff = list(difflib.unified_diff(before, after, lineterm=""))
has_unexpected = False
for line in diff:
…
How to Merge TypedDicts in Python
Merge two TypedDict dictionaries with type-aware logic using NotRequired, **kwargs unpacking, and safe key updates.
from typing import TypedDict, NotRequired, merge # hypothetical
class User(TypedDict):
name: str
email: NotRequired[str]
age: NotRequired[int]
def merge_users(base: User, **overrides: User) -> User:
"""Merge two user dicts with typing-aware logic."""
result: User = dict(base)
for key, value …
How to Mock a Factory Boy Model Instance in Python
Create a factory boy factory, then patch its Meta.model with a Mock to control instance behavior in tests.
import factory
from dataclasses import dataclass
from unittest.mock import Mock, patch
import builtins
@dataclass
class User:
name: str
age: int
class UserFactory(factory.Factory):
class Meta:
model = User
name = "Alice"
age = 30
def get_user_name(user):
return user.name
def ma…
How to Mock an Object Method in Python unittest
Mock a method on an instance or class with @patch.object, set its return value, and assert its call arguments in Python unittest.
import unittest
from unittest.mock import patch
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
class TestCalculator(unittest.TestCase):
def test_add_normal(self):
calc = Calculator()
result = calc.add(2, 3)
self.asse…
How to Mock and Stub API Calls in Playwright E2E Tests with Python
This code demonstrates how to mock and stub API responses in Playwright end-to-end tests using Python's unittest.mock patch and Playwright's APIRequestContext.
import re
from unittest.mock import patch
from playwright.sync_api import sync_playwright
def verify_api_mock(page, mock_url, mock_response):
with patch("playwright.sync_api.APIRequestContext.get") as mock_get:
mock_get.return_value.json.return_value = mock_response
mock_get.return_value.status_co…
How to Mock open() in Python for Reading File Data
This example shows how to mock Python's built-in open() function using unittest.mock to simulate file reading without touching the disk.
import builtins
from unittest.mock import patch
def read_file_data(filename):
with open(filename, 'r') as f:
return f.read()
def mock_read_data():
fake_data = "This is mocked file content"
class FakeFile:
def __enter__(self):
return self
def __exit__(self, *args):…
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 Mock requests.get in Python
Mock requests.get with unittest.mock to test code that makes HTTP calls without hitting the network.
import requests
from unittest.mock import Mock, patch
def fetch_user_data(user_id):
response = requests.get(f"https://api.example.com/users/{user_id}")
return response.json()
def process_user(user_id):
mock_response = Mock()
mock_response.json.return_value = {"id": user_id, "name": "Alice", "age": 30…
How to Mock return_value with MagicMock in Python unittest
Use unittest.mock.MagicMock to replace a dependency and set return_value to control what a mocked method returns during unit tests.
import unittest
from unittest.mock import MagicMock
class PaymentGateway:
def charge(self, amount):
raise NotImplementedError
class OrderService:
def __init__(self, gateway):
self.gateway = gateway
def process_order(self, amount):
return self.gateway.charge(amount)
class Test…
How to Mock subprocess.run returncode in Python
Simulate subprocess.run return codes in tests with unittest.mock.patch and CompletedProcess.
import subprocess
from unittest.mock import patch
def run_command(cmd):
result = subprocess.run(cmd, capture_output=True, text=True)
return result.returncode
if __name__ == "__main__":
with patch("subprocess.run") as mock_run:
# Simulate a successful command (returncode 0)
mock_run.retu…
How to Parametrize pytest Tests with Multiple Input Cases in Python
This code shows how to use pytest's @pytest.mark.parametrize decorator to run the same test function across multiple input-output combinations, checking that an add function behaves correctly for each case.
import pytest
def add(a, b):
return a + b
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(5, 5, 10),
(-1, 1, 0),
(0, 0, 0),
(10, -3, 7),
])
def test_add(a, b, expected):
assert add(a, b) == expected
if __name__ == "__main__":
pytest.main([__file__, "-v"])
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.