Skip to content
Back to skills

Fastapi Testing Verification

ASecurity

Testing and verification for hexagonal FastAPI backends - in-memory fakes of ports, unit tests per use case, architecture tests (AST + import-linter), policy tests per phase, integration tests on real Mongo/Redis, error-catalog test, labs and benchmarks, load and failure drills, offline evaluation for ranking/ML, make check, and honest verified/not-verified reporting. Use whenever the user asks to test, verify, "make sure it works", prove a phase complete, write pytest tests, load-test, failu...

  • 2 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added November 27, 2026
developmentgoexpressfastapidockertestingapidatabasebackendsecurityperformance

Works with

  • cursor
  • cli
  • api

Security analysis

A100/100

Scanned November 27, 2026

npx -y skills add amralhorimy/fastapi-pro-skills --skill fastapi-testing-verification --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Fastapi Testing Verification?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Fastapi Testing Verification
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/amralhorimy-fastapi-testing-verification/badge)](https://www.skillsdirectory.com/skills/amralhorimy-fastapi-testing-verification)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: fastapi-testing-verification
description: Testing and verification for hexagonal FastAPI backends - in-memory fakes of ports, unit tests per use case, architecture tests (AST + import-linter), policy tests per phase, integration tests on real Mongo/Redis, error-catalog test, labs and benchmarks, load and failure drills, offline evaluation for ranking/ML, make check, and honest verified/not-verified reporting. Use whenever the user asks to test, verify, "make sure it works", prove a phase complete, write pytest tests, load-test, failure-test, benchmark before/after, evaluate a model/ranker, or review whether work is finished.
---

# Testing and Verification

**Nothing is done without evidence**, and the evidence report must say what was **not** verified. A real project report:
"ran and passed: 72 integration tests on real Mongo+Redis, unit + architecture tests, 4 import contracts. Failing, unrelated,
not investigated: 21 tests in ai/chat/comments. Not run: app with Firebase+MinIO, Postman, Docker build, pyright, concurrent load."
That honesty is the standard.

## Layers
| Layer | What | How |
|---|---|---|
| Unit (most) | each use case, entity rule, policy | handlers wired to **in-memory fakes** (`tests/fakes.py`) with `FixedClock` + `SequentialIds` + `InMemoryEventPublisher`; no I/O |
| Architecture | layer rules, independence, absolute imports, module registered in contracts | `tests/architecture/test_layers.py` (AST, stdlib) + `make arch` (import-linter); **a test that the checker detects a planted violation** (no vacuous pass) |
| Policy tests | rules each phase promises (e.g. "feed v2 never reads X", "only audit adapter writes the audit channel", "admin routes all require a permission") | AST/regex over the source, one file per phase |
| Catalog | error codes unique and documented | walk `DomainError` subclasses |
| Integration | adapters, indexes, atomic paths, views/aggregations, streams, the real wiring | `@pytest.mark.integration`, real Mongo + Redis only when these are in the project's stack and an isolated test service is configured (`MONGO_TEST_URL`/`REDIS_TEST_URL` or testcontainers); otherwise mark the integration checks not run, not passed; `make test-integration` |
| Labs | end-to-end scenarios, concurrency, data accumulation, model adapters | `labs/*.py` runnable scripts printing a report; exit non-zero on failure |
| Load / failure | capacity and resilience | k6 scripts (`labs/load_test.js`), benchmarks with **before/after numbers** stored in the module doc; run only against explicitly isolated test targets (see Safety gates) |

`make test` = unit + architecture, no Docker, with `REQUIRE_ALL_IMPORTS=1` (every module must import). `make check` = lint + pyright +
arch + test. Add `make test-integration` before merging adapters when the project's integration stack is configured; do not make absent Mongo/Redis, Docker, or other optional services a prerequisite for unit/AST checks.

## Rules
1. **Fakes implement the ports**, not mock chains - tests assert behaviour (state, emitted events), not call counts.
2. **Fakes may differ from real stores** (atomic updates, unique indexes, `$set` behavior, TTL, aggregation views); cover those exact areas with integration tests when the real store is part of the configured stack. In MongoDB, `$set` to an embedded-document field replaces that field's value rather than recursively merging it. For example, `db.posts.updateOne({_id: postId}, {$set: {public: {name: post.name}}})` replaces the entire `public` value; a dotted update such as `{$set: {"public.name": post.name}}` changes only that subfield. Aggregation `$set` expressions likewise assign the value of the named field; use `$mergeObjects` explicitly when a merge is intended. Do not claim a general data leak from this behavior: identify the exact query/pipeline, document shape and exposure path, and add a reproducible integration test that proves the unauthorized field is returned before describing it as a leak.
3. Test failure paths first: every error code, permission denial, duplicate call, event only after success and **not** on no-op,
   limits (max replies), invalid cursor, infra down (a fake that raises `DependencyUnavailable`).
4. Inject time and ids; never `sleep` to wait - drive the fake clock.
5. Integration tests build the **same wiring helpers** the app uses (`build_feed_wiring`) so wiring bugs are caught.
6. A test file per concern; name tests as sentences; keep `_setup()` helpers returning a dict of handlers and fakes.
7. When a bug is found, add the test that would have caught it before fixing it.
8. **State what each check proves.** AST/regex tests prove only the inspected source has the syntactic/structural pattern encoded by the assertion at the time of inspection. They do not execute the application, prove runtime authorization or isolation, establish database semantics, catch dynamic behavior outside the inspected code, or replace integration/security tests. Import-linter proves configured import contracts, not application correctness.

## Safety gates for failure drills, destructive operations, and load

Treat every chaos, load, worker-kill, database-kill, restore, or destructive drill as potentially production-impacting. Fail closed: if every applicable gate below cannot be positively verified, do not run the drill; report it as not run and give the exact safe setup needed.

1. **Dedicated test target:** require an explicit test-only URI (for example `MONGO_TEST_URL`, never a production/default application URI) and a dedicated test database name with an unmistakable suffix such as `_test` or `_chaos_test`. Reject missing values, production/development fallback configuration, and any URI/database not explicitly designated for the test. Never infer safety from a variable name alone.
2. **Host and database allowlist:** parse the effective connection target before connecting or invoking a destructive action. Match both the normalized host (and port, where relevant) and database name against an explicit allowlist of isolated test services/databases. Reject unknown hosts, cloud production domains, production database names, mismatches, and ambiguous/multi-host targets unless every host is explicitly allowlisted. Apply the same checks to Redis, queues, and other dependencies that a drill can stop or mutate. A test target must not reuse production credentials or a production network.
3. **Synthetic data only:** seed clearly synthetic, disposable fixtures; do not copy production records, personal data, secrets, or production-derived dumps. Use a unique run identifier so the drill can select only its own data.
4. **Bounded impact:** set a hard wall-clock timeout, request/concurrency/rate limits, and a small explicit resource ceiling before start. Document the planned duration, ramp-up, maximum virtual users/workers, request rate, and stop condition. Keep these limits enforced in the test configuration/script, not just in prose; abort on unexpected latency/error rate, target change, or limit breach. Do not load-test a public or shared endpoint without explicit authorization and isolation.
5. **Kill and restore plan:** kill only disposable test workers/dependencies after verifying their instance/container identity. Before any restore, verify the isolated destination again and use a test-only snapshot; never restore into production or overwrite a shared environment. State expected recovery, data-loss boundaries, operator/stop procedure, and how to confirm service health.
6. **Cleanup and evidence:** specify cleanup of run-scoped synthetic data, temporary queues/containers/snapshots and credentials, plus a verification that cleanup affected only the allowlisted test target. Record target identity, limits, timestamps, outcomes, and cleanup result. Leave shared test services in their prior state where feasible; otherwise document how to reset them. No destructive command should have a default target.

## Failure drills (only after all Safety gates pass)
On an isolated disposable test stack, exercise worker termination mid-job; stop the test Redis/Mongo service only if it is dedicated to this run; deliver a job/event twice; fill a bounded test queue (503 + `Retry-After`); disconnect an SSE client (connection gauge falls); slow a test dependency (timeouts fire); restart during shutdown drain (report lists abandoned/cancelled jobs). Set a timeout and an explicit recovery/cleanup plan for every drill. If required stack services or isolation gates are absent, skip the environmental drill; continue unit/fake tests and report the environmental check as not run.

## Benchmarks and load
Measure **before and after** a performance feature on the same synthetic, bounded test dataset (`labs/feed_v2_benchmark.py`): p50/p95/p99, DB round trips,
CPU/RAM; record numbers, target identity, limits and cleanup in the module doc. Find the first bottleneck, fix the cheapest thing, re-run only after all Safety gates pass. Do not run a load benchmark against production, a shared endpoint, or an unverified target.

## Offline evaluation (ranking / ML / grading)
Frozen eval set + baseline (the heuristic) on the same set; report task metrics and cost (latency, memory); thresholds written
**before** rollout; stages: dataset builder -> baseline eval -> train -> **gate** -> shadow -> gated rollout (`RANKER_MODE`). First build
the foundation and let data accumulate (impressions with `snapshot_id`, each action tied to an impression) - a lab
(`ranker_data_lab.py`) generates and checks that data before any training exists.

## Stage report (paste into every phase doc)
```
Ran and passed:   <commands + counts>
Failing (cause?): <list, honest, even if unrelated>
Not run:          <what and why: Docker build, Postman, pyright, load, external services>
Next to run:      <exact commands the user should run, and what output to send back>
```

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.