Reference library

Testing & modern typing

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

3 matches
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 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 Use Stubs, Fakes, Spies, and Mocks in Python Testing

Implement four types of test doubles — stubs, fakes, spies, and mocks — as subclasses of a PaymentGateway interface to replace real dependencies during testing.

testing mocks stubs
Python
class PaymentGateway:
    def charge(self, amount):
        raise NotImplementedError


class StubPaymentGateway(PaymentGateway):
    """Returns a fixed response without any logic."""
    def charge(self, amount):
        return {"success": True, "transaction_id": "stub-12345"}


class FakePaymentGateway(PaymentGatewa…
12 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.