Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
Fix and Test a Regression Bug in Python with Unit Tests
This code implements a circle area function that raises ValueError for negative radii, then runs basic tests and a regression check for that edge case.
import math
def calculate_area(radius):
"""Calculate the area of a circle given its radius."""
if radius < 0:
raise ValueError("Radius cannot be negative")
return math.pi * radius ** 2
def main():
test_cases = [0, 1, 2.5, 5, 10]
print("Circle Area Calculator")
print("-" * 30)
…
How to Assert Exceptions in Python with pytest.raises
Use pytest.raises as a context manager to assert that a function raises an expected exception and inspect its message in pytest tests.
import pytest
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def test_divide_by_zero():
with pytest.raises(ValueError) as exc_info:
divide(10, 0)
assert str(exc_info.value) == "Cannot divide by zero"
assert "zero" in str(exc_info.value)
def te…
How to Group Data by Key in Python with Type Hints
Group a list of dictionaries by a specified key using a typed helper function and print a summary of each group.
from typing import Any, Dict, List, TypeVar, Union
T = TypeVar("T")
def group_by(data: List[Dict[str, Any]], key: str) -> Dict[Any, List[Dict[str, Any]]]:
"""Group a list of dictionaries by a given key."""
grouped: Dict[Any, List[Dict[str, Any]]] = {}
for item in data:
value = item.get(key)
…
How to Mock open() in Python for Reading File Data
This example shows how to mock Python's built-in open() function using unittest.mock to simulate file reading without touching the disk.
import builtins
from unittest.mock import patch
def read_file_data(filename):
with open(filename, 'r') as f:
return f.read()
def mock_read_data():
fake_data = "This is mocked file content"
class FakeFile:
def __enter__(self):
return self
def __exit__(self, *args):…
How to Parametrize pytest Tests with Multiple Input Cases in Python
This code shows how to use pytest's @pytest.mark.parametrize decorator to run the same test function across multiple input-output combinations, checking that an add function behaves correctly for each case.
import pytest
def add(a, b):
return a + b
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(5, 5, 10),
(-1, 1, 0),
(0, 0, 0),
(10, -3, 7),
])
def test_add(a, b, expected):
assert add(a, b) == expected
if __name__ == "__main__":
pytest.main([__file__, "-v"])
How to Share Fixtures Across Tests with pytest conftest
Learn how to define pytest fixtures in conftest.py and control their scope (function, module, session) so every test in a directory reuses the same setup and teardown.
import pytest
@pytest.fixture
def sample_data():
"""Simple fixture available to all tests in this directory."""
return {"name": "Alice", "age": 30}
@pytest.fixture(scope="session")
def session_data():
"""Fixture created once per test session."""
return {"session_id": 12345}
@pytest.fixture(scope="mo…
How to Use Basic Type Hints (int, str) for Return Values in Python
Declare a simple function with int and str type hints and a typed return value in Python.
def greet(name: str, age: int) -> str:
return f"{name} is {age} years old."
if __name__ == "__main__":
print(greet("Alice", 30))
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 TypedDict and Dataclasses in Python
Create typed data structures with TypedDict and dataclasses, then use them as helper functions for describing objects in a type-safe way.
from typing import TypedDict, NotRequired, Optional
from dataclasses import dataclass
class User(TypedDict):
name: str
age: NotRequired[int]
email: Optional[str]
@dataclass
class Product:
id: int
title: str
price: float = 0.0
def describe_user(user: User) -> str:
age = user.get("age",…
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 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 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))
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.