/py-pit:pytest-servicefrom py-pit
Writes disciplined backend tests for FastAPI services with pytest. Covers async SQLAlchemy fixtures, AsyncClient with DI overrides, mocking external clients, and test maintainability.
Ships in py-pit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
This skill establishes clean, reliable backend testing using pytest.
The goal is to produce tests that are:
Tests should optimize for scanability and maintainability, not clever abstractions.
Prefer simple local tests with minimal infrastructure.
Rules:
httpx.AsyncClient with ASGITransport for FastAPI endpoint testsasync def; asyncio_mode = "auto" eliminates per-test markerspytest_asyncio fixtures for async setup/teardowntest_* functions only; fixtures handle all setuppytest, pytest-asyncio, httpxTests must run reliably with a simple pytest. No external services required.
Tests should live in a tests/ directory.
tests/
conftest.py
test_health.py
test_users.py
factories/
user_factory.py
conftest.py holds shared fixturestests/factories/ or conftest.pyShared setup belongs in pytest fixtures, not duplicated code.
@pytest.fixture for reusable setupAvoid inline setup repeated across tests.
Choose fixture scope based on what the fixture creates and how expensive it is.
scope="session" — for things that are expensive to create and safe to share (e.g., the SQLAlchemy engine, schema creation)scope="function" (default) — for anything that holds mutable state or must be isolated per test (e.g., sessions, clients, mocks)A common pattern: session-scoped async engine, function-scoped async session with rollback.
@pytest_asyncio.fixture(scope="session")
async def engine():
eng = create_async_engine("sqlite+aiosqlite:///:memory:")
async with eng.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield eng
async with eng.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await eng.dispose()
@pytest_asyncio.fixture
async def db_session(engine) -> AsyncSession:
async with engine.connect() as conn:
async with conn.begin() as trans:
session = async_sessionmaker(bind=conn, expire_on_commit=False)()
yield session
await session.close()
await trans.rollback()
The rollback in teardown means tests never bleed into each other even when they write data. expire_on_commit=False prevents lazy-load errors after commit in async sessions.
Use factory fixtures when tests require variations of objects. Factories are appropriate for sample data, request payloads, ORM objects, mocked clients, and service configurations — not just data.
@pytest.fixture
def user_payload_factory():
def _factory(**overrides):
payload = {
"email": "[email protected]",
"name": "Test User",
}
payload.update(overrides)
return payload
return _factory
Fixtures should configure objects, not contain decision trees.
Bad:
if status == "ok":
client.charge.return_value = ...
elif status == "declined":
...
Good:
@pytest.fixture
def payment_client_factory():
def _factory(charge_response=None):
charge_response = charge_response or {"status": "ok"}
client = MagicMock(spec=PaymentClient)
client.charge.return_value = charge_response
return client
return _factory
Tests should control behavior explicitly rather than relying on fixture branching.
Use app.dependency_overrides to swap FastAPI dependencies in tests. Do not patch internals directly.
@pytest_asyncio.fixture
async def client(db_session: AsyncSession) -> AsyncClient:
async def override_get_db():
yield db_session
app.dependency_overrides[get_db] = override_get_db
async with AsyncClient(
transport=ASGITransport(app=app), base_url="http://test"
) as c:
yield c
app.dependency_overrides.clear()
Always clear dependency_overrides in teardown so overrides don't leak between tests.
Use httpx.AsyncClient with ASGITransport for endpoint tests.
async def test_health_endpoint(client: AsyncClient):
response = await client.get("/health")
assert response.status_code == 200
assert response.json()["status"] == "ok"
External services must be mocked.
MagicMock(spec=ClientType) or create_autospecShared mock setups should be implemented as fixtures or factory fixtures.
Use pytest parametrization when only inputs vary.
@pytest.mark.parametrize(
"email",
[
"[email protected]",
"[email protected]",
],
)
def test_email_validation(email):
...
Tests should not depend on the system clock or random values. Freeze time with freezegun; use explicit, stable inputs rather than uuid4() or random.
@freeze_time("2025-01-01")
def test_token_expiry():
...
What SKILL.md sets; muted values are Claude Code's defaults
Generated from the plugin's indexed repository (robhowley/py-pit-skills) — no native marketplace selected
npx claudepluginhub p/robhowley-py-pit16 skills in this plugin
/alembic-migrationsProduction-safe Alembic migration workflows for SQLAlchemy 2.x projects. Use this skill when adding Alembic, generating migrations, reviewing autogenerate diffs, fixing broken migrations, or establishing a safe schema evolution workflow in a Python backend./background-jobs-boundariesGuardrails for background work in FastAPI and Python services. Prevent misuse of in-process background execution (e.g. FastAPI BackgroundTasks)./click-cliDesign, generate, and improve Python CLIs using the Click library. Focus on idiomatic architecture, command groups, modular layouts, CLI UX conventions, and avoiding common Click anti-patterns.Other plugins' skills for the same job