pytest-builder

SKILL.md

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.ini with optimal configuration
  • tests/ directory structure (unit/, integration/, test_data/)
  • tests/conftest.py with 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 fixtures
  • async_database - Async SQLAlchemy database fixtures
  • api_client - FastAPI TestClient fixtures
  • async_client - httpx AsyncClient fixtures
  • mock_external_api - Mock external API calls
  • temp_files - Temporary files and directories
  • sample_user - Sample user model fixtures
  • auth_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

  1. Initialize pytest configuration:
python3 scripts/setup_pytest_config.py . --template fastapi
  1. Generate fixtures:
python3 scripts/generate_fixtures.py --fixtures database api_client sample_user
  1. Generate test files:
python3 scripts/generate_test.py myapp/routers/items.py --type integration
  1. Run tests:
pytest

Adding Tests to Existing Module

  1. Generate test file:
python3 scripts/generate_test.py myapp/services/auth.py --output tests/unit/test_auth.py
  1. Review and customize generated tests

  2. Add specific fixtures if needed:

python3 scripts/generate_fixtures.py --fixtures auth_token --append

Testing Async Database Operations

  1. Generate async fixtures:
python3 scripts/generate_fixtures.py --fixtures async_database async_client
  1. Create async tests following patterns in references/async-testing.md

  2. 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 configuration
  • assets/conftest_basic.py - Basic conftest.py template
  • assets/conftest_fastapi.py - FastAPI-specific conftest.py
  • assets/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
Weekly Installs
2
First Seen
Feb 26, 2026
Installed on
opencode2
gemini-cli2
claude-code2
github-copilot2
codex2
kimi-cli2