Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
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 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 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.
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"])
How to Run an Integration Test with Docker Compose Mock in Python
Run a Python integration test against a docker-compose environment, using mocks to simulate service health and business logic responses.
import subprocess
import json
from typing import Dict
def run_integration_test() -> Dict[str, str]:
"""
Simulates an integration test against a docker-compose environment
using a mock service that returns canned responses.
"""
# Mock docker-compose environment check
env_ready = subprocess.run(…
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.
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…
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.
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…
How to Use mock.assert_called_with in Python
Verify that a MagicMock received a call with specific positional and keyword arguments using assert_called_with in unittest.
import unittest
from unittest.mock import MagicMock
class TestMockAssertions(unittest.TestCase):
def test_assert_called_with(self):
# Create a mock object
mock = MagicMock()
# Call the mock with specific arguments
mock.send_email("alice@example.com", subject="Greetings", body="Hel…
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.