testing

A testing setup for FastAPI applications, using pytest to run tests and async support for code that performs non-blocking operations.

In plain words
What is it for?
Use it to configure test discovery, reusable fixtures, HTTP testing, mocks, coverage reports, and commands for running selected or complete test suites.
Why use it?
It provides a consistent way to run API tests, measure code coverage, and separate test types such as unit, integration, and end-to-end tests.

Command for Claude Code

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add commands/justdvp/claude-code-templates/testing
Clone the repo
git clone --depth 1 https://github.com/Justdvp/claude-code-templates

Made for: Claude Code.

Per session 0 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 5,706 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.05706
Opus 5 $0.00000 $0.02853
Sonnet 5 $0.00000 $0.01141
Haiku 4.5 $0.00000 $0.00571

Measured yesterday against content hash d5b6335f0a90, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

testing scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

cli-tool/templates/python/examples/fastapi-app/.claude/commands/testing.md · 928 lines

How it starts

The opening of the file, as written. The whole thing — 928 lines — stays where its author put it; the contents beside it link to each section on GitHub.

FastAPI Testing Framework

Comprehensive testing setup for FastAPI applications with pytest and async support.

Usage

# Run all tests
pytest

# Run with coverage
pytest --cov=app --cov-report=html

# Run specific test file
pytest tests/test_api.py

# Run with verbose output
pytest -v -s

Test Configuration

# pytest.ini
[tool:pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts = 
    --cov=app
    --cov-report=term-missing
    --cov-report=html:htmlcov
    --asyncio-mode=auto
    --strict-markers
    --disable-warnings
markers =
    unit: Unit tests
    integration: Integration tests
    e2e: End-to-end tests
    slow: Slow running tests
    auth: Authentication tests
    api: API tests
asyncio_mode = auto

Test Dependencies

# requirements/test.txt
pytest>=7.0.0
pytest-asyncio>=0.21.0
pytest-cov>=4.0.0
httpx>=0.24.0
factory-boy>=3.2.0
faker>=18.0.0
respx>=0.20.0
pytest-mock>=3.10.0

Test Fixtures

# tests/conftest.py
import pytest
import asyncio
from typing import AsyncGenerator, Generator
from fastapi.testclient import TestClient
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from app.main import app
from app.db.database import get_db, Base
from app.models.user import User
from app.core.security import get_password_hash
from tests.factories import UserFactory

# Test database URL
TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"

@pytest.fixture(scope="session")
def event_loop() -> Generator[asyncio.AbstractEventLoop, None, None]:
    """Create event loop for the test session."""
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()

@pytest.fixture(scope="session")
async def test_engine():
    """Create test database engine."""
    engine = create_async_engine(
        TEST_DATABASE_URL,
        echo=False,
        future=True
    )
    
    # Create tables
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    
    yield engine
    
    # Drop tables and dispose engine
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    
    await engine.dispose()

@pytest.fixture
async def db_session(test_engine) -> AsyncGenerator[AsyncSession, None]:
    """Create database session for testing."""
    TestSessionLocal = sessionmaker(
        test_engine, 
        class_=AsyncSession, 
        expire_on_commit=False
    )
    
    async with TestSessionLocal() as session:
        yield session

@pytest.fixture
def override_get_db(db_session: AsyncSession) -> Generator:
    """Override database dependency."""
    async def _override_get_db():
        yield db_session
    
    app.dependency_overrides[get_db] = _override_get_db
    yield
    app.dependency_overrides = {}

@pytest.fixture
def client(override_get_db) -> Generator[TestClient, None, None]:
    """Create test client."""
    with TestClient(app) as test_client:
        yield test_client

@pytest.fixture
async def async_client(override_get_db) -> AsyncGenerator[AsyncClient, None]:
    """Create async test client."""
    async with AsyncClient(app=app, base_url="http://test") as ac:
        yield ac

@pytest.fixture
async def test_user(db_session: AsyncSession) -> User:
    """Create test user."""
    user_data = {
        "username": "testuser",
        "email": "[email protected]",
        "hashed_password": get_password_hash("testpass123"),
        "first_name": "Test",
        "last_name": "User",
        "is_active": True,
        "is_superuser": False
    }
    
    user = User(**user_data)
    db_session.add(user)
    await db_session.commit()
    await db_session.refresh(user)
    return user

@pytest.fixture
async def superuser(db_session: AsyncSession) -> User:
    """Create superuser."""
    user_data = {
        "username": "admin",
        "email": "[email protected]",
        "hashed_password": get_password_hash("adminpass123"),
        "first_name": "Admin",
        "last_name": "User",
        "is_active": True,
        "is_superuser": True
    }
    
    user = User(**user_data)
    db_session.add(user)
    await db_session.commit()
    await db_session.refresh(user)
    return user

@pytest.fixture
def user_token(test_user: User) -> str:
    """Create authentication token for test user."""
    from app.core.security import create_access_token
    return create_access_token(subject=test_user.id)

@pytest.fixture
def superuser_token(superuser: User) -> str:
    """Create authentication token for superuser."""
    from app.core.security import create_access_token
    return create_access_token(subject=superuser.id)

@pytest.fixture
def auth_headers(user_token: str) -> dict[str, str]:
    """Create authorization headers."""
    return {"Authorization": f"Bearer {user_token}"}

@pytest.fixture
def superuser_headers(superuser_token: str) -> dict[str, str]:
    """Create superuser authorization headers."""
    return {"Authorization": f"Bearer {superuser_token}"}

Read the full file on GitHub · 928 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 928 lines · 0 tokens per session scan A d5b6335f0a90

Subscribe to this mod's changes

testing is a command published in the GitHub repository Justdvp/claude-code-templates (7 stars, last pushed yesterday), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 5,706 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.