pytest-builder
Pytest Builder
Build comprehensive test suites for Python projects using pytest, with specialized support for FastAPI, async code, and SQLModel/SQLAlchemy.
Quick Start
Generate test file from existing code:
python3 scripts/generate_test.py myapp/users.py --type unit
Setup pytest configuration:
python3 scripts/setup_pytest_config.py . --template fastapi
Generate fixtures:
python3 scripts/generate_fixtures.py --fixtures database api_client --output tests/conftest.py
Core Capabilities
1. Generate Test Files
Create test files from existing Python code with proper structure:
# Basic unit tests
python3 scripts/generate_test.py myapp/module.py
# FastAPI integration tests
python3 scripts/generate_test.py myapp/routers/users.py --type integration
# Async tests
python3 scripts/generate_test.py myapp/async_service.py --async
The script extracts functions and classes from your code and generates test stubs.
2. Setup Pytest Configuration
Initialize pytest with recommended settings:
# Basic Python project
python3 scripts/setup_pytest_config.py . --template basic
# FastAPI project
python3 scripts/setup_pytest_config.py . --template fastapi
# Async project
python3 scripts/setup_pytest_config.py . --template async
This creates:
pytest.iniwith optimal configurationtests/directory structure (unit/, integration/, test_data/)tests/conftest.pywith common fixtures
3. Generate Fixtures
Create reusable fixtures for common testing scenarios:
# List available fixtures
python3 scripts/generate_fixtures.py --list
# Generate specific fixtures
python3 scripts/generate_fixtures.py --fixtures database api_client auth_token
# Generate all fixtures
python3 scripts/generate_fixtures.py --fixtures all
# Append to existing conftest.py
python3 scripts/generate_fixtures.py --fixtures mock_external_api --append
Available fixture types:
database- SQLModel in-memory database fixturesasync_database- Async SQLAlchemy database fixturesapi_client- FastAPI TestClient fixturesasync_client- httpx AsyncClient fixturesmock_external_api- Mock external API callstemp_files- Temporary files and directoriessample_user- Sample user model fixturesauth_token- Authentication token fixtures
Testing Patterns
FastAPI Testing
For detailed FastAPI testing patterns, see references/fastapi-testing.md:
- TestClient usage
- Async endpoint testing with httpx
- Dependency overrides
- Authentication testing
- Response validation
- Error handling
Quick example:
from fastapi.testclient import TestClient
from myapp.main import app
client = TestClient(app)
def test_read_items():
response = client.get("/items/")
assert response.status_code == 200
assert isinstance(response.json(), list)
Async Testing
For async testing patterns, see references/async-testing.md:
- pytest-asyncio setup
- Async fixtures
- Testing async endpoints
- Concurrent operations
- Error handling
Quick example:
import pytest
from httpx import AsyncClient
@pytest.mark.asyncio
async def test_async_endpoint():
async with AsyncClient(app=app, base_url="http://test") as ac:
response = await ac.get("/items/")
assert response.status_code == 200
Database Testing
For database testing patterns, see references/database-testing.md:
- In-memory database setup
- Transaction rollback patterns
- Testing CRUD operations
- Testing relationships
- Query testing
Quick example:
import pytest
from sqlmodel import Session, create_engine, SQLModel
from sqlmodel.pool import StaticPool
@pytest.fixture(name="session")
def session_fixture():
engine = create_engine(
"sqlite:///:memory:",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
yield session
Fixtures Library
For comprehensive fixture patterns, see references/fixtures-library.md:
- Fixture scopes (function, module, session, class)
- Database fixtures
- API client fixtures
- Authentication fixtures
- Mock fixtures
- Parametrized fixtures
- Fixture composition
Common Workflows
Setting Up Tests for a New FastAPI Project
- Initialize pytest configuration:
python3 scripts/setup_pytest_config.py . --template fastapi
- Generate fixtures:
python3 scripts/generate_fixtures.py --fixtures database api_client sample_user
- Generate test files:
python3 scripts/generate_test.py myapp/routers/items.py --type integration
- Run tests:
pytest
Adding Tests to Existing Module
- Generate test file:
python3 scripts/generate_test.py myapp/services/auth.py --output tests/unit/test_auth.py
-
Review and customize generated tests
-
Add specific fixtures if needed:
python3 scripts/generate_fixtures.py --fixtures auth_token --append
Testing Async Database Operations
- Generate async fixtures:
python3 scripts/generate_fixtures.py --fixtures async_database async_client
-
Create async tests following patterns in references/async-testing.md
-
Run with pytest-asyncio:
pytest --asyncio-mode=auto
Best Practices
Test Organization:
- Keep tests isolated and independent
- Use descriptive test names:
test_<feature>_<scenario>_<expected_outcome> - Test both happy paths and edge cases
- Organize tests:
tests/unit/for unit tests,tests/integration/for integration tests
Fixtures:
- Use appropriate scopes (function, module, session)
- Keep fixtures focused and reusable
- Use fixture composition for complex setups
- Clean up resources in fixtures using yield
FastAPI Testing:
- Use dependency overrides for testing
- Test authentication and authorization
- Validate response schemas
- Test error handling
Database Testing:
- Use in-memory databases for speed
- Isolate tests with transactions or fresh databases
- Test relationships and cascades
- Avoid N+1 query problems
Async Testing:
- Use pytest-asyncio for async tests
- Test concurrent operations
- Handle timeouts and cancellations
- Test async context managers
Assets
Template files for quick project setup:
assets/pytest.ini- Recommended pytest configurationassets/conftest_basic.py- Basic conftest.py templateassets/conftest_fastapi.py- FastAPI-specific conftest.pyassets/test_template.py- Example test file with common patterns
Copy these templates to your project as starting points.
Installation Requirements
# Basic pytest
pip install pytest pytest-cov
# Async support
pip install pytest-asyncio
# FastAPI testing
pip install httpx
# Database testing
pip install sqlmodel