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(…
Design Data Helpers with Python TypedDict and Literal
Use TypedDict, Literal, and Union to define typed data shapes and parse values in Python.
from typing import TypedDict, Literal, Optional, Union, List
class User(TypedDict):
name: str
age: int
role: Literal["admin", "user", "guest"]
def describeUser(data: User) -> str:
return f"{data['name']} ({data['age']}) — {data['role']}"
def parse_value(item: Union[int, str, None]) -> str:
if it…
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)
…
Format Data with Type Hints in Python
Build a validated person dict with modern type hints and optional list handling.
from typing import Any, Dict, List, Optional, Union
JsonValue = Union[str, int, float, bool, None, List["JsonValue"], Dict[str, "JsonValue"]]
def format_person(name: str, age: int, hobbies: Optional[List[str]] = None) -> Dict[str, Any]:
"""Build a person dict with validated typing."""
if not name or age < 0:…
Fuzz Test Random Bytes Input Crash in Python
A simple fuzz test generates random byte inputs and runs a parser to find unexpected crashes.
import random
def parse_header(data: bytes) -> dict:
"""Parse a fake binary header format."""
if len(data) < 8:
raise ValueError("header too short")
magic = data[:4]
if magic != b'PARS':
raise ValueError("bad magic")
version = data[4]
if version != 1:
raise ValueErro…
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 Assert Exceptions in Python with pytest.raises
Use pytest.raises as a context manager to assert that a function raises an expected exception and inspect its message in pytest tests.
import pytest
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def test_divide_by_zero():
with pytest.raises(ValueError) as exc_info:
divide(10, 0)
assert str(exc_info.value) == "Cannot divide by zero"
assert "zero" in str(exc_info.value)
def te…
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 Group Data by Key in Python with Type Hints
Group a list of dictionaries by a specified key using a typed helper function and print a summary of each group.
from typing import Any, Dict, List, TypeVar, Union
T = TypeVar("T")
def group_by(data: List[Dict[str, Any]], key: str) -> Dict[Any, List[Dict[str, Any]]]:
"""Group a list of dictionaries by a given key."""
grouped: Dict[Any, List[Dict[str, Any]]] = {}
for item in data:
value = item.get(key)
…
How to Load Test a Local API with Locust in Python
Defines a Locust load test that simulates traffic to local endpoints, enabling manual load testing against a development server.
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 3)
@task
def home_page(self):
self.client.get("/")
@task(3)
def about_page(self):
self.client.get("/about")
if __name__ == "__main__":
print("Run with: locust -f this_file.py --h…
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…
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.