Reference library

Testing & modern typing

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

10 matches
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(…
16 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 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 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 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 medium

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.

docker integration-testing mocking
Python
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(…
15 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

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.

abc interface-segregation testing
Python
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) -> …
13 0 Open
Testing & modern typing easy

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().

testing datetime mock
Python
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())
13 0 Open
Testing & modern typing medium

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.

pytest fixtures unittest.mock
Python
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.…
19 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.