Reference library

Testing & modern typing

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

7 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

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
Testing & modern typing medium

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.

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

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.

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

How to Test Hypotheses with Property-Based Check in Python

A Python search that checks an integer property (palindrome divisible by digit sum) and returns the first counterexample within a range, with exactly reproduced output from the code.

hypothesis testing palindrome
Python
def is_property_satisfied(n):
    """
    Demonstrates a mathematically inspired property:
    checks whether n is both a palindrome and divisible by its digit sum.
    """
    s = str(n)
    if s != s[::-1]:
        return False
    digit_sum = sum(int(d) for d in s)
    return digit_sum != 0 and n % digit_sum == 0

…
10 0 Open
Testing & modern typing easy

How to Verify Formatted Output with an Approval Test in Python

Write a small Python approval test that verifies a function's exact formatted output using unittest.

approval-testing unittest formatting
Python
import sys
from io import StringIO
import unittest

def generate_output(name, score):
    return f"Player: {name} | Score: {score:03d}"

class TestFormattedOutput(unittest.TestCase):
    def test_output_format(self):
        expected = "Player: Alice | Score: 042"
        result = generate_output("Alice", 42)
        …
13 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.