Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
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:
…
How to Run Test Coverage with pytest-cov in Python
Run pytest with coverage reporting using pytest-cov on a temporary project and see line-by-line coverage output.
import os
import subprocess
import tempfile
from pathlib import Path
def sample_function(x: int) -> int:
"""A simple function to demonstrate coverage."""
if x > 0:
return x * 2
else:
return -x
def run_pytest_with_coverage() -> str:
"""Run pytest with coverage on a temp project and r…
How to Snapshot Test JSON with Mock in Python
Use pytest-snapshot to capture the exact output of a JSON-loading function, with and without mocking json.loads, so future changes are automatically detected.
import json
from unittest.mock import Mock, patch
import pytest
def load_config(data):
config = json.loads(data)
return {"host": config["host"], "port": config["port"]}
def test_load_config_snapshot(snapshot):
mock_data = json.dumps({"host": "localhost", "port": 8080, "extra": "ignored"})
result = …
How to Test Properties with Random Inputs in Python
Write a simple property-based test in Python using random string generation to verify that string invariants like reverse-twice identity and uppercase idempotence always hold.
import random
import string
def generate_random_string(length: int) -> str:
"""Generate a random alphanumeric string of given length."""
chars = string.ascii_letters + string.digits
return "".join(random.choice(chars) for _ in range(length))
def reverse_twice_is_identity(s: str) -> bool:
"""Propert…
How to Use TypedDict for Data Validation in Python
Define a TypedDict schema and validate raw dictionary input with type hints for safer, more readable data handling.
from typing import Any, Dict, List, Optional, Union, TypedDict, Literal
class Product(TypedDict):
product_id: int
name: str
price: Union[int, float]
in_stock: bool
tags: Optional[List[str]]
def validate_product(data: Dict[str, Any]) -> Product:
product_id: int = int(data["product_id"])
na…
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.