Introduction
Pytest is a popular testing framework with powerful features for writing clean, maintainable tests.
Fixtures
import pytest
@pytest.fixture
def sample_data():
return {"name": "test", "values": [1, 2, 3]}
@pytest.fixture
def db_connection():
conn = create_db()
yield conn
conn.close()
def test_with_fixture(sample_data, db_connection):
assert sample_data["name"] == "test"
Parametrized Tests
@pytest.mark.parametrize("input,expected", [
(2, 4),
(3, 9),
(4, 16),
])
def test_square(input, expected):
assert input ** 2 == expected
Markers
@pytest.mark.slow
def test_complex_computation():
pass
@pytest.mark.integration
def test_api_integration():
pass
# Run only marked tests
# pytest -m slow
# pytest -m "not slow"
Practice Problems
- Create fixtures for test data
- Parametrize tests for multiple inputs
- Use markers to categorize tests
- Set up test discovery configuration
- Create conftest.py for shared fixtures