Issue Manager / issue-manager (push) Has been cancelled
Build Docs / changes (push) Has been cancelled
Build Docs / langs (push) Has been cancelled
Build Docs / build-docs (push) Has been cancelled
Build Docs / docs-all-green (push) Has been cancelled
Conflict detector / main (push) Has been cancelled
Test Redistribute / test-redistribute (fastapi) (push) Has been cancelled
Test Redistribute / test-redistribute (fastapi-slim) (push) Has been cancelled
Test Redistribute / test-redistribute-alls-green (push) Has been cancelled
Test / lint (push) Has been cancelled
Test / test (pydantic-v1, 3.10) (push) Has been cancelled
Test / test (pydantic-v1, 3.11) (push) Has been cancelled
Test / test (pydantic-v1, 3.13) (push) Has been cancelled
Test / test (pydantic-v1, 3.8) (push) Has been cancelled
Test / test (pydantic-v1, 3.9) (push) Has been cancelled
Test / test (pydantic-v2, 3.10) (push) Has been cancelled
Test / test (pydantic-v2, 3.11) (push) Has been cancelled
Test / test (pydantic-v2, 3.12) (push) Has been cancelled
Test / test (pydantic-v2, 3.13) (push) Has been cancelled
Test / test (pydantic-v2, 3.14) (push) Has been cancelled
Test / test (pydantic-v2, 3.8) (push) Has been cancelled
Test / test (pydantic-v2, 3.9) (push) Has been cancelled
Test / coverage-combine (push) Has been cancelled
Test / check (push) Has been cancelled
Label Approved / label-approved (push) Has been cancelled
FastAPI People Contributors / job (push) Has been cancelled
FastAPI People Sponsors / job (push) Has been cancelled
Update Topic Repos / topic-repos (push) Has been cancelled
FastAPI People / job (push) Has been cancelled
Test / test (pydantic-v1, 3.12) (push) Has been cancelled
44 lines
1.2 KiB
Python
44 lines
1.2 KiB
Python
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
items = {}
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
items["foo"] = {"name": "Fighters"}
|
|
items["bar"] = {"name": "Tenders"}
|
|
yield
|
|
# clean up items
|
|
items.clear()
|
|
|
|
|
|
app = FastAPI(lifespan=lifespan)
|
|
|
|
|
|
@app.get("/items/{item_id}")
|
|
async def read_items(item_id: str):
|
|
return items[item_id]
|
|
|
|
|
|
def test_read_items():
|
|
# Before the lifespan starts, "items" is still empty
|
|
assert items == {}
|
|
|
|
with TestClient(app) as client:
|
|
# Inside the "with TestClient" block, the lifespan starts and items added
|
|
assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}}
|
|
|
|
response = client.get("/items/foo")
|
|
assert response.status_code == 200
|
|
assert response.json() == {"name": "Fighters"}
|
|
|
|
# After the requests is done, the items are still there
|
|
assert items == {"foo": {"name": "Fighters"}, "bar": {"name": "Tenders"}}
|
|
|
|
# The end of the "with TestClient" block simulates terminating the app, so
|
|
# the lifespan ends and items are cleaned up
|
|
assert items == {}
|