Reference library

Testing & modern typing

pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.

55 matches
Testing & modern typing easy

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.

pytest testing capture
Python
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…
12 0 Open
Testing & modern typing medium

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.

characterization-testing legacy-code testing
Python
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:
     …
14 0 Open
Testing & modern typing easy

Dataclass with Type Hints Fields in Python

Create a data class with typed fields and default values, then instantiate and inspect it.

dataclass type hints oop
Python
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…
13 0 Open
Testing & modern typing easy

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.

dependency-injection testing mocking
Python
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(…
17 0 Open
Testing & modern typing easy

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.

regression-testing unit-testing math
Python
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)
   …
16 0 Open
Testing & modern typing easy

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.

faker fake-data testing
Python
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…
9 0 Open
Testing & modern typing medium

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.

pytest benchmark mock
Python
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:…
14 0 Open
Testing & modern typing easy

How to Capture Logging Records with pytest caplog in Python

Capture and assert on logging records in pytest using the built-in caplog fixture.

pytest logging testing
Python
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…
14 0 Open
Testing & modern typing medium

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.

performance benchmarking time
Python
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,…
38 0 Open
Testing & modern typing easy

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.

diff files difflib
Python
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…
10 0 Open
Testing & modern typing easy

How to Compare Floats in pytest with approx

Uses pytest.approx to compare floating-point numbers with tolerance, avoiding precision issues.

pytest floating-point testing
Python
import pytest

def test_float_addition():
    result = 0.1 + 0.2
    expected = 0.3
    assert result == pytest.approx(expected)
13 0 Open
Testing & modern typing easy

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.

typing type-hints conversion
Python
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…
14 0 Open
Testing & modern typing easy

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.

filtering type-hints generics
Python
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…
11 0 Open
Testing & modern typing medium

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.

diffing snapshot-testing difflib
Python
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:
      …
16 0 Open
Testing & modern typing easy

How to Merge TypedDicts in Python

Merge two TypedDict dictionaries with type-aware logic using NotRequired, **kwargs unpacking, and safe key updates.

typing typeddict dict
Python
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 …
13 0 Open
Testing & modern typing medium

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.

factory-boy mocking unit-testing
Python
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…
15 0 Open
Testing & modern typing medium

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.

unittest mock patch
Python
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…
14 0 Open
Testing & modern typing medium

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.

playwright e2e-testing mocking
Python
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…
13 0 Open
Testing & modern typing easy

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.

mock unittest file-io
Python
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):…
14 0 Open
Testing & modern typing easy

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.

testing mock pathlib
Python
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…
14 0 Open
Testing & modern typing easy

How to Mock requests.get in Python

Mock requests.get with unittest.mock to test code that makes HTTP calls without hitting the network.

mocking requests unit-testing
Python
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…
12 0 Open
Testing & modern typing easy

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.

unittest mock magicmock
Python
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…
12 0 Open
Testing & modern typing easy

How to Mock subprocess.run returncode in Python

Simulate subprocess.run return codes in tests with unittest.mock.patch and CompletedProcess.

unittest mock subprocess
Python
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…
14 0 Open
Testing & modern typing easy

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.

pytest parametrize testing
Python
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"])
14 0 Open

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.