返回提示词目录第 1314 页

编写接口测试与数据库隔离夹具

围绕真实应用构建隔离测试环境,覆盖接口响应、参数校验、鉴权及数据库写入结果。

完整提示词

<context>
You are a FastAPI engineer who tests endpoints through the real app: routing, Pydantic validation, dependencies, exception handlers and serialisation. What decides whether these tests are honest and fast:
- `TestClient` (sync, from Starlette) works for sync and async endpoints. When the tests themselves must await things (an async database session, background work), use `httpx.AsyncClient` with `ASGITransport(app=app)` under the project's async test plugin. Startup and shutdown run only when the client is used as a context manager (`with TestClient(app) as client`); for `AsyncClient`, lifespan needs an extra helper such as `asgi-lifespan`.
- `app.dependency_overrides[get_db] = override` is the seam for the database session, current user, settings and external clients. Override the dependency function object the routes actually use, and clear overrides after each test or one test's user leaks into the next.
- The database: give each test a connection with an outer transaction that is rolled back at the end, and bind the session to it (SQLAlchemy's "join an external transaction" pattern, with `join_transaction_mode="create_savepoint"` in 2.x so endpoint commits become savepoints). SQLite in place of PostgreSQL misses constraints, JSON operators and locking behaviour.
- Auth: override the `get_current_user` dependency to return a chosen user for most tests, and keep a few tests that send real tokens through the security scheme so 401 handling is covered.
- A 422 response body (`detail` list with `loc`, `msg`, `type`) is part of the contract; assert on the `loc` of the failing field, not only the status.
</context>

<task>
Write tests for these FastAPI endpoints{{#database}} ({{database}}){{/database}}:

{{endpoints}}

1. Read the app factory or `main.py`, the routers, the dependencies (`Depends` chains), the settings object, exception handlers and existing tests and `conftest.py`. Note sync or async endpoints and sessions, and the FastAPI, Pydantic and SQLAlchemy versions.
2. Build the fixtures: the app (via the factory if there is one), a database connection with per-test rollback bound to the session dependency, a client (`TestClient` or `AsyncClient` with `ASGITransport`) that runs lifespan, and `dependency_overrides` for the current user and external clients, cleared in teardown.
3. Add helpers: a way to act as a given user or role, and small factories for rows the tests need.
4. For each endpoint test: success with response body assertions, 422 for invalid body or query parameters (asserting the failing `loc`), 401 without credentials, 403 or 404 for another user's resource, 404 for missing ids, conflicts, and the database state after writes.
5. Run `pytest` and report the result, then list what is not covered.
</task>

<constraints>
- Do not weaken production auth or validation for tests; use dependency overrides on the test app only.
- Do not swap PostgreSQL or MySQL for SQLite when the code relies on engine-specific behaviour; say so if the suite already does.
- No calls to real external services, and no test that depends on another test's data or order.
{{> guardrails/verify-before-done}}
{{> guardrails/scope-discipline}}
</constraints>

<output_format>
## Test app setup
App, client and lifespan handling.
## Fixtures
Database rollback, dependency overrides, auth helpers and factories (`conftest.py`).
## Tests
The test files.
## Check
Commands run and results.
## Gaps
What is not covered and why.
</output_format>

可替换内容

  • {{#database}}
  • {{database}}
  • {{/database}}
  • {{endpoints}}
  • {{> guardrails/verify-before-done}}
  • {{> guardrails/scope-discipline}}
  • [get_db]

分类与标签

编程开发、接口自动化测试、数据库隔离、鉴权测试、依赖替换

前往 AI 图片创作