Testing with Pytest
Pytest is Python's most popular testing framework. Write simple, scalable test cases with minimal boilerplate.
๐ป Getting Started
# pip install pytest
# calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
# test_calculator.py
import pytest
from calculator import add, subtract
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
def test_subtract():
assert subtract(5, 3) == 2
assert subtract(0, 5) == -5
# Run: pytest
# Run specific file: pytest test_calculator.py
# Verbose: pytest -v๐ง Fixtures & Parametrize
# Fixtures (setup/teardown)
@pytest.fixture
def sample_data():
return [1, 2, 3, 4, 5]
def test_sum(sample_data):
assert sum(sample_data) == 15
# Parametrized tests
@pytest.mark.parametrize("a, b, expected", [
(2, 3, 5),
(0, 0, 0),
(-1, 1, 0),
(10, 5, 15)
])
def test_add_multiple(a, b, expected):
assert add(a, b) == expected
# Test exceptions
def test_division_by_zero():
with pytest.raises(ZeroDivisionError):
result = 1 / 0๐ฏ Key Takeaways
- assert: Simple assertion syntax
- Fixtures: Reusable test setup
- @pytest.mark.parametrize: Run test with multiple inputs
- pytest.raises(): Test exceptions
- Auto-discovery: Finds test_*.py files
- Detailed output: Clear failure messages