Python Testing Toolkit
A comprehensive collection of pytest fixtures, helpers, plugins, and configurations for writing robust Python tests. Designed for real-world applications with databases, APIs, external services, and complex data models.
Features
- Database fixtures with automatic setup, teardown, and session management
- HTTP client fixtures for authenticated and anonymous API testing
- Factory functions for generating test data (User, Order, etc.)
- Common mocks for Redis, S3, and SMTP services
- Custom assertions for dictionaries, datetimes, and domain logic
- Snapshot testing for comparing JSON output across test runs
- Coverage reporting with custom HTML and summary output
- pytest plugins for slow test reporting and test ordering
Quick Start
Use Database Fixtures
from fixtures.database import db_session, test_db
def test_create_user(db_session):
"""Test user creation with an auto-rolled-back session."""
user = User(name="Alice", email="alice@example.com")
db_session.add(user)
db_session.flush()
assert user.id is not None
assert db_session.query(User).count() == 1
# Session is rolled back after the test — no cleanup needed
Use API Client Fixtures
from fixtures.api_client import auth_client, anon_client
async def test_protected_endpoint(auth_client):
"""Authenticated client includes a valid Bearer token."""
response = await auth_client.get("/api/v1/profile")
assert response.status_code == 200
assert "email" in response.json()
async def test_unauthorized_access(anon_client):
"""Anonymous client should receive 401."""
response = await anon_client.get("/api/v1/profile")
assert response.status_code == 401
Use Factories
from fixtures.factories import UserFactory, OrderFactory
def test_order_total():
user = UserFactory.create(name="Bob")
order = OrderFactory.create(user=user, items=[
{"product": "Widget", "quantity": 3, "unit_price": 9.99},
])
assert order.total == 29.97
Custom Assertions
from helpers.assertions import assert_dict_subset, assert_datetime_recent
def test_api_response_shape(response_data):
assert_dict_subset(response_data, {"status": "ok", "version": "1.0"})
def test_created_timestamp(user):
assert_datetime_recent(user.created_at, seconds=5)
Snapshot Testing
from helpers.snapshot import snapshot_test
def test_serialization_output(snapshot_test):
result = serialize_user(user)
snapshot_test.assert_match(result, "user_serialized.json")
Project Structure
src/
fixtures/
database.py - Database session and cleanup fixtures
api_client.py - HTTP client fixtures with auth support
factories.py - Factory functions for test data generation
mocks.py - Common service mocks (Redis, S3, SMTP)
helpers/
assertions.py - Custom assertion functions
snapshot.py - Snapshot testing utilities
coverage_reporter.py - Custom coverage report generation
plugins/
slow_test_reporter.py - pytest plugin for slow test detection
test_ordering.py - pytest plugin for test execution order
configs/
pytest.ini - pytest configuration
tox.ini - Multi-Python version testing
.coveragerc - Coverage measurement settings
examples/ - Example test files
guides/ - Testing best practices guide
Running Tests
# Run all tests
pytest
# Run with verbose output and coverage
pytest -v --cov=src --cov-report=html
# Run only fast tests (skip slow ones)
pytest -m "not slow"
# Run tests in a specific order
pytest -p plugins.test_ordering --test-order=alphabetical
Multi-Python Testing with tox
pip install tox
tox
Configuration
All configuration files are in the configs/ directory. Copy them to your project root or reference them directly:
pytest -c configs/pytest.ini
Related Products
- Data Validation Toolkit — Pydantic and data validation patterns
- Python Logging & Config — Production logging configurations
- Python Design Patterns — Gang of Four patterns in Python
This is 1 of 14 resources in the Python Developer Pro toolkit. Get the complete [Python Testing Toolkit] with all files, templates, and documentation for $29.
Or grab the entire Python Developer Pro bundle (14 products) for $159 — save 30%.
Top comments (0)