Browse Source

fox: Add single testing docs for lifespan

pull/13259/head
z0z0r4 3 weeks ago
parent
commit
e4e7c3ea8e
No known key found for this signature in database GPG Key ID: 448EF3037425FD6A
  1. 12
      docs/en/docs/advanced/testing-events.md
  2. 22
      docs_src/app_testing/tutorial003.py
  3. 30
      docs_src/app_testing/tutorial004.py

12
docs/en/docs/advanced/testing-events.md

@ -1,7 +1,13 @@
# Testing Events: startup - shutdown
# Testing Events: lifespan and startup - shutdown
When you need `lifespan` to run in your tests, you can use the `TestClient` with a `with` statement:
{* ../../docs_src/app_testing/tutorial004.py hl[9:15,26:30] *}
When you need your event handlers (`lifespan`, `startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement:
You can read more details about the ["Running lifespan in tests in the official Starlette documentation site."](https://www.starlette.io/lifespan/#running-lifespan-in-tests)
{* ../../docs_src/app_testing/tutorial003.py hl[9:15,32:37] *}
For the deprecated `startup` and `shutdown` events, you can use the `TestClient` as follows:
{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *}

22
docs_src/app_testing/tutorial003.py

@ -1,27 +1,15 @@
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
items = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
@app.on_event("startup")
async def startup_event():
items["foo"] = {"name": "Fighters"}
items["bar"] = {"name": "Tenders"}
yield
# clean up items or other work
...
app = FastAPI(lifespan=lifespan)
# startup event and shutdown event are deprecated, you should use lifespan instead
# @app.on_event("startup")
# async def startup_event():
# items["foo"] = {"name": "Fighters"}
# items["bar"] = {"name": "Tenders"}
@app.get("/items/{item_id}")
@ -33,4 +21,4 @@ def test_read_items():
with TestClient(app) as client:
response = client.get("/items/foo")
assert response.status_code == 200
assert response.json() == {"name": "Fighters"}
assert response.json() == {"name": "Fighters"}

30
docs_src/app_testing/tutorial004.py

@ -0,0 +1,30 @@
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 or other work
...
app = FastAPI(lifespan=lifespan)
@app.get("/items/{item_id}")
async def read_items(item_id: str):
return items[item_id]
def test_read_items():
with TestClient(app) as client:
response = client.get("/items/foo")
assert response.status_code == 200
assert response.json() == {"name": "Fighters"}
Loading…
Cancel
Save