Reference library

Testing & modern typing

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

11 matches
Testing & modern typing medium

How to Mock an Object Method in Python unittest

Mock a method on an instance or class with @patch.object, set its return value, and assert its call arguments in Python unittest.

unittest mock patch
Python
import unittest
from unittest.mock import patch

class Calculator:
    def add(self, a, b):
        return a + b
    
    def multiply(self, a, b):
        return a * b

class TestCalculator(unittest.TestCase):
    def test_add_normal(self):
        calc = Calculator()
        result = calc.add(2, 3)
        self.asse…
14 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 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

How to Sort Data in Python

Sort sequences with type-safe helpers that handle mixed data with a string fallback.

sorting typing protocol
Python
from typing import Any, TypeVar, Protocol, Sequence, Iterable

T = TypeVar("T")
Comparable = TypeVar("Comparable", bound="Comparable")

class Sortable(Protocol):
    def __lt__(self, other: Any) -> bool: ...

S = TypeVar("S", bound=Sortable)

def sort_data(data: Sequence[S], *, reverse: bool = False) -> list[S]:
    "…
14 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 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.

unittest mock testing
Python
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…
14 0 Open
Testing & modern typing easy

How to Verify Formatted Output with an Approval Test in Python

Write a small Python approval test that verifies a function's exact formatted output using unittest.

approval-testing unittest formatting
Python
import sys
from io import StringIO
import unittest

def generate_output(name, score):
    return f"Player: {name} | Score: {score:03d}"

class TestFormattedOutput(unittest.TestCase):
    def test_output_format(self):
        expected = "Player: Alice | Score: 042"
        result = generate_output("Alice", 42)
        …
13 0 Open
Testing & modern typing easy

How to freeze time in Python tests with freezegun

Use the freezegun decorator to freeze datetime.now() at a fixed timestamp so tests that depend on current time run deterministically.

freezegun datetime testing
Python
from datetime import datetime
from freezegun import freeze_time


@freeze_time("2024-01-15 12:30:00")
def test_frozen_time():
    now = datetime.now()
    return now


if __name__ == "__main__":
    result = test_frozen_time()
    print(result)
15 0 Open
Testing & modern typing easy

How to use unittest mock side_effect with a sequence in Python

Demonstrates using Mock.side_effect with a list to return different values per call and raise an exception at a specific call in unittest.

unittest mock side_effect
Python
import unittest
from unittest.mock import Mock

class TestMockSideEffectSequence(unittest.TestCase):
    def test_side_effect_sequence(self):
        mock = Mock()
        mock.side_effect = [1, 2, 3, Exception("boom")]
        
        self.assertEqual(mock(), 1)
        self.assertEqual(mock(), 2)
        self.asser…
13 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

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.