Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
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 Sort Data in Python
Sort sequences with type-safe helpers that handle mixed data with a string fallback.
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]:
"…
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.
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 "…
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…
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.
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)
…
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.
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)
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.
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…
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) -> …
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.