Fastapi Test Scaffold And Writer
Overview
Generate pytest configuration, fixtures, and example tests for FastAPI apps with unit/integration/e2e layers. Keep tests fast, deterministic, CI-friendly, and offline by default for unit tests.
Inputs
Accept one JSON object with the schema provided by the user prompt. Treat missing optional fields as disabled. If endpoints_spec is empty, still scaffold config + fixtures + placeholder tests.
Workflow
- •Inspect project root
- •Resolve
project_rootto a real path. - •Read existing
pyproject.tomlorpytest.iniand avoid clobbering custom settings. - •Detect existing
tests/structure and merge rather than overwrite.
- •Resolve FastAPI app
- •Import via
app_import_path. - •If import fails, scan common files (
main.py,app.py,src/main.py) for aFastAPI()instance and report the best guess in comments.
- •Create or update pytest config
- •Prefer
pyproject.tomlwhenpreferences.use_pyproject_tomlis true and no config exists. - •Ensure:
testpaths=tests,addopts=-ra -q,strict-markers=true, markers:unit,integration,e2e,slow.
- •Create tests layout
- •
tests/conftest.pywith shared fixtures. - •
tests/unit/,tests/integration/,tests/e2e/with feature-focused files.
- •Build fixtures
- •
appfixture importingapp_import_path. - •
clientfixture usinghttpx.AsyncClient+ASGITransport. - •
auth_headersfixture (stub) for dependency overrides. - •Monkeypatch fixtures for external calls (HTTP/DB/Redis) using
monkeypatchorrespxif installed. - •Optional deterministic fixtures (time/uuid) only if needed by specs.
- •Generate tests per endpoint_spec
- •Unit tests: request validation (422), success (200) with external calls mocked, auth failure tests (401/403) via dependency overrides.
- •Integration tests: DB roundtrip using
TEST_DATABASE_URL; Redis set/get TTL if enabled. - •E2E tests: minimal smoke endpoint call using real dependencies; allow external LLM mock if preferences demand it.
- •CI output
- •If
ci.provider=github_actions, generate.github/workflows/tests.ymlwith unit/integration jobs; include service containers whenintegration_tests_use_dockeris true. - •Otherwise, create
docs/ci_test_commands.mdwith run commands.
Test Conventions
- •Use
pytest-asynciofor async tests. - •Use
httpx.AsyncClientwithASGITransport(never spawn uvicorn). - •Unit tests must be offline and fast; mock outbound HTTP and DB/cache clients.
- •Use
app.dependency_overridesfor auth/rate-limit dependency toggles. - •Keep fixtures small, documented, and deterministic.
Output Format
Return:
- •A short "plan" section.
- •A diff-like file list with full contents for each created/modified file.
- •A final summary listing created/modified files and pytest commands:
- •
pytest -m unit - •
pytest -m integration - •
pytest -m e2e
- •
Do not add extra explanation beyond what is needed to apply changes.