Reference library

Testing & modern typing

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

41 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 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 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…
15 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 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 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
Testing & modern typing easy

How to Parse Data with Type Hints in Python

A beginner-friendly helper that parses simple dictionary- or list-like strings into typed Python structures using modern typing annotations.

type-hints parsing typing
Python
from typing import Any, Dict, List, Union


def parse_data(raw: str) -> Union[Dict[str, Any], List[Any], str]:
    """Parse a simple string into structured data using type hints."""
    cleaned = raw.strip()
    
    if not cleaned:
        return {}
    
    if cleaned.startswith("{") and cleaned.endswith("}"):
     …
11 0 Open
Testing & modern typing easy

How to Share Fixtures Across Tests with pytest conftest

Learn how to define pytest fixtures in conftest.py and control their scope (function, module, session) so every test in a directory reuses the same setup and teardown.

pytest fixtures conftest
Python
import pytest

@pytest.fixture
def sample_data():
    """Simple fixture available to all tests in this directory."""
    return {"name": "Alice", "age": 30}

@pytest.fixture(scope="session")
def session_data():
    """Fixture created once per test session."""
    return {"session_id": 12345}

@pytest.fixture(scope="mo…
13 0 Open
Testing & modern typing easy

How to Test Environment Variables with pytest monkeypatch in Python

Shows how to use pytest's monkeypatch fixture to set and delete environment variables for isolated tests.

pytest monkeypatch environment variables
Python
import os
import pytest

def get_database_url():
    return os.getenv("DATABASE_URL", "postgres://default")

def test_database_url_with_env(monkeypatch):
    monkeypatch.setenv("DATABASE_URL", "postgres://test-db")
    assert get_database_url() == "postgres://test-db"

def test_database_url_default(monkeypatch):
    m…
12 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 Use Basic Type Hints (int, str) for Return Values in Python

Declare a simple function with int and str type hints and a typed return value in Python.

type-hints annotations functions
Python
def greet(name: str, age: int) -> str:
    return f"{name} is {age} years old."


if __name__ == "__main__":
    print(greet("Alice", 30))
12 0 Open
Testing & modern typing easy

How to Use Literal Type Hints in Python

Use typing.Literal to restrict a function parameter to specific allowed string values and get static type checking.

typing type-hints literal
Python
from typing import Literal

def get_status_message(status: Literal["active", "inactive", "pending"]) -> str:
    """Return a message based on the status value."""
    if status == "active":
        return "Account is active"
    elif status == "inactive":
        return "Account is inactive"
    else:
        return "…
15 0 Open
Testing & modern typing easy

How to Use Python Type Hints for Beginners

Build a data helper module with basic type hints — Union, Optional, List, Dict, Any, and TypeVar — to make your code clearer and safer.

type-hints typing annotations
Python
from typing import Any, Union, Optional, List, Dict, Tuple, Callable, TypeVar

T = TypeVar("T")

def describe(value: Any) -> str:
    """Return a human-readable description of the value's type."""
    if isinstance(value, list):
        return f"list of {len(value)} items"
    elif isinstance(value, dict):
        ret…
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.