Pytest
Write readable unit and integration tests in Python with assert statements, fixtures, and test parametrization.
pytest is the standard testing framework for Python. It replaces the boilerplate classes of the standard unittest library with standalone functions and plain assert statements. For automated style enforcement alongside tests, see code-quality. When a test fails, pytest uses AST rewriting to report the exact intermediate values of each expression.
Writing and Running Tests
Install pytest using pip:
pip install pytest
By default, pytest discovers files matching test_*.py or *_test.py and executes any function prefixed with test_:
# test_calculator.py
def multiply(a: int, b: int) -> int:
return a * b
def test_positive_multiplication():
assert multiply(3, 4) == 12
def test_zero_multiplication():
assert multiply(5, 0) == 0
Execute tests from your terminal:
pytest
If an assertion fails, pytest prints a diff showing the left-hand and right-hand values rather than just a generic failure message:
def test_failure():
> assert multiply(2, 3) == 7
E assert 6 == 7
E + where 6 = multiply(2, 3)
Testing Exceptions with pytest.raises
Verify that code raises expected errors using the pytest.raises context manager:
import pytest
def parse_port(port_str: str) -> int:
port = int(port_str)
if not (1 <= port <= 65535):
raise ValueError(f"Port out of range: {port}")
return port
def test_invalid_port_range():
with pytest.raises(ValueError) as exc_info:
parse_port("99999")
assert "Port out of range" in str(exc_info.value)
def test_non_numeric_port():
with pytest.raises(ValueError):
parse_port("http")
Fixtures: Setup and Dependency Injection
Fixtures provide a baseline of data or initialized services required by multiple tests. Define a fixture with @pytest.fixture and pass its name as an argument to test functions:
import pytest
@pytest.fixture
def test_db():
# Setup: prepare database connection or test state
db = {"users": ["alex", "sam"], "active": True}
yield db
# Teardown: clean up resources after the test completes
db.clear()
def test_user_count(test_db):
assert len(test_db["users"]) == 2
def test_user_membership(test_db):
assert "alex" in test_db["users"]
The code before the yield statement runs before the test (setup), and any code following yield runs after the test finishes (teardown).
Parametrizing Tests
Test multiple input and output combinations without writing redundant test functions using @pytest.mark.parametrize:
import pytest
def is_palindrome(text: str) -> bool:
clean = text.lower().replace(" ", "")
return clean == clean[::-1]
@pytest.mark.parametrize("word,expected", [
("radar", True),
("Python", False),
("race car", True),
("", True),
])
def test_palindrome(word: str, expected: bool):
assert is_palindrome(word) == expected
pytest executes the test function once for each tuple in the parameter list and reports each run independently.
Command-Line Options
| Flag | Purpose |
|---|---|
pytest -v | Verbose output: prints each test name and outcome |
pytest -k "test_user" | Runs only tests matching the given substring expression |
pytest -x | Stops test execution immediately on the first failure |
pytest --tb=short | Displays shorter tracebacks for faster debugging |
pytest -s | Disables stdout capturing, allowing print statements to show |
Pytest vs Standard Library Unittest
| Feature | pytest | unittest (standard library) |
|---|---|---|
| Structure | Plain functions and modules | Classes inheriting from TestCase |
| Assertions | Standard assert a == b | Methods like self.assertEqual(a, b) |
| Setup/Teardown | Modular dependency-injected fixtures | setUp() and tearDown() methods |
| Parametrization | Built-in via @pytest.mark.parametrize | Requires subTest or third-party packages |
| Output | Detailed expression introspection | Standard tracebacks |