Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
How to Use TypedDict for Structured Dict Typing in Python
Define and use TypedDict to add type hints to dictionaries, improving code clarity and enabling static type checking in your Python projects.
from typing import TypedDict
class User(TypedDict):
name: str
age: int
email: str
def greet(user: User) -> str:
return f"Hello {user['name']}, age {user['age']}, contact {user['email']}"
if __name__ == "__main__":
alice: User = {"name": "Alice", "age": 30, "email": "alice@example.com"}
pr…
How to Use Union Type Hints in Python
This code demonstrates how to use Union type hints to specify that a parameter can accept multiple types (int, float, str) and handle them accordingly.
from typing import Union
def process_value(value: Union[int, float, str]) -> str:
if isinstance(value, (int, float)):
return f"Number: {value * 2}"
return f"String: {value.upper()}"
if __name__ == "__main__":
print(process_value(10))
print(process_value(3.14))
print(process_value("hello"))
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 Use setUp and tearDown in Python unittest TestCase
Demonstrates how to structure unit tests with setUp and tearDown methods in Python's unittest framework for reusable test fixtures.
import unittest
class ExampleTest(unittest.TestCase):
def setUp(self):
self.data = [1, 2, 3]
def tearDown(self):
self.data = None
def test_length(self):
self.assertEqual(len(self.data), 3)
def test_contains(self):
self.assertIn(2, self.data)
if __name__ == "__main…
How to Use the pytest tmp_path Fixture for Temporary Directories
Use pytest's built-in tmp_path fixture to create a unique temporary directory per test for clean file I/O testing.
import pytest
def test_write_and_read_file(tmp_path):
# tmp_path is a pytest fixture that provides a temporary directory
# unique to each test invocation
data_file = tmp_path / "data.txt"
data_file.write_text("hello world")
assert data_file.read_text() == "hello world"
def test_multiple_tmp_pat…
How to Validate Data in Python with Typing Hints
Build a runtime validation helper that checks values against Python type hints like Optional, list, and basic types.
from typing import Any, Optional, Union, TypeVar, get_origin, get_args
T = TypeVar("T")
def validate(value: Any, expected_type: type) -> Optional[str]:
"""Returns an error message if value doesn't match expected_type, else None."""
# Handle Optional[...] types
origin = get_origin(expected_type)
if or…
How to Validate Dataclass Fields with Python Type Hints
A beginner-friendly helper that checks if instance attributes match their declared type hints using dataclasses and get_type_hints.
from typing import Any, TypeVar, get_type_hints
from dataclasses import dataclass
T = TypeVar("T")
@dataclass
class User:
name: str
age: int
email: str
def validate_fields(obj: Any) -> dict[str, bool]:
"""Check if object attributes match declared type hints."""
hints = get_type_hints(obj.__class…
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 Write a Contract Test with Mock in Python
Use unittest.mock to verify a consumer's expectations match the provider's response shape in a Python contract test.
from unittest.mock import Mock
# Contract test: verify consumer expects data shape that provider delivers.
# We mock the provider and assert the consumer's calls match the agreed contract.
def fetch_user(provider_client, user_id):
"""Consumer code: expects provider to return {'id', 'name', 'email'}."""
respo…
How to Write a Fast Smoke Test for a Critical Path in Python
A quick smoke test that validates the /health critical path executes fast enough, raising errors on wrong paths or slow responses.
import time
def smoke_test(path):
if path != "/health":
raise ValueError("Critical path expected /health")
start = time.perf_counter()
# Simulate the critical health check work
time.sleep(0.01)
elapsed = time.perf_counter() - start
if elapsed > 0.05:
raise RuntimeError("Health …
How to Write a pytest Test Function with assert Equal in Python
Define simple pytest test functions that use assert to verify result equality and run them with pytest.main.
import pytest
def add(a, b):
return a + b
def test_add_positive_numbers():
result = add(2, 3)
assert result == 5
def test_add_negative_numbers():
result = add(-2, -3)
assert result == -5
def test_add_mixed_numbers():
result = add(2, -3)
assert result == -1
if __name__ == "__main__":
…
How to Write pytest Test Function Assert Equal in Python
Write three pytest test functions that assert the result of an add() function equals an expected numeric value.
import pytest
def add(a, b):
return a + b
def test_add_positive_numbers():
assert add(2, 3) == 5
def test_add_negative_numbers():
assert add(-1, -2) == -3
def test_add_mixed_numbers():
assert add(5, -3) == 2
if __name__ == "__main__":
pytest.main([__file__, "-v"])
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 mark known bugs with pytest xfail in Python
Use @pytest.mark.xfail to mark tests that are expected to fail due to known bugs, with optional strict mode to control pass/fail behavior.
import pytest
def divide(a: int, b: int) -> float:
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
@pytest.mark.xfail(reason="Known bug: division returns int instead of float", strict=False)
def test_divide_integer_division():
result = divide(10, 4)
assert isinstanc…
How to use Optional type hint in Python
Use the Optional type hint to indicate a parameter can be a string or None, with an example function that handles both cases.
from typing import Optional
def greet(name: Optional[str]) -> str:
if name is None:
return "Hello, anonymous!"
else:
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("Alice"))
print(greet(None))
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) -> …
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())
Mock datetime.now to freeze time in Python
Use unittest.mock.patch to replace datetime.now with a fixed value so your code always sees the same time during tests.
from datetime import datetime
from unittest.mock import patch
def current_message():
now = datetime.now()
return f"Current time: {now:%Y-%m-%d %H:%M:%S}"
if __name__ == "__main__":
with patch("__main__.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2024, 3, 15, 10, 30, 0)
prin…
NamedTuple typed record in Python
Define a lightweight immutable record with type hints using typing.NamedTuple; access fields by name and unpack like a tuple.
from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float
label: str = "origin"
if __name__ == "__main__":
p = Point(3.5, -2.0, "A")
print(p)
print(f"x={p.x}, y={p.y}, label={p.label}")
print("is tuple:", isinstance(p, tuple))
q = Point(1.0, 1.0)
print(q)
# …
Table-Driven Tests in Python (unittest)
Run a single unittest test against many input cases using a list of tuples and subTest.
import unittest
def add(a, b):
return a + b
class TestAddFunction(unittest.TestCase):
def test_add_with_table(self):
cases = [
(1, 2, 3),
(-1, 1, 0),
(0, 0, 0),
(2, -3, -1),
]
for x, y, expected in cases:
with self.subTest(x…
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.