Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
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.
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(…
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 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.
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…
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.
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…
How to Mock requests.get in Python
Mock requests.get with unittest.mock to test code that makes HTTP calls without hitting the network.
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…
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 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 = …
Interface Segregation with Fake Test Implementations in Python
Defines segregated abstract interfaces (Printer, Scanner) and uses a FakePrinter to record calls for unit testing without real resources.
from abc import ABC, abstractmethod
class Printer(ABC):
@abstractmethod
def print_document(self, doc: str) -> str:
pass
class Scanner(ABC):
@abstractmethod
def scan_document(self) -> str:
pass
class MultiFunctionPrinter(Printer, Scanner):
def print_document(self, doc: str) -> …
Mock datetime with time-machine in Python
Use the time-machine library to travel to a fixed datetime when running tests or scripts, mocking datetime.utcnow().
from time_machine import travel
from datetime import datetime
@travel("2020-01-01 10:30:00")
def check_date():
return datetime.utcnow()
if __name__ == "__main__":
print(check_date())
Use pytest fixture to mock a database connection in Python
This code shows how to use a pytest fixture and unittest.mock to replace a database connection with a Mock, enabling isolated tests without a real database.
import pytest
import sqlite3
from unittest.mock import Mock
class Database:
def __init__(self, connection):
self.connection = connection
def get_user(self, user_id):
cursor = self.connection.cursor()
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
return cursor.…
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.