mirror of https://github.com/tiangolo/fastapi.git
docs: migrate testing tutorial from on_event to lifespan
This commit is contained in:
parent
1e78a36b73
commit
6cb4454b98
|
|
@ -94,6 +94,6 @@ As the testing function is now asynchronous, you can now also call (and `await`)
|
|||
|
||||
/// tip
|
||||
|
||||
If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MongoDB's MotorClient</a>), remember to instantiate objects that need an event loop only within async functions, e.g. an `@app.on_event("startup")` callback.
|
||||
If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using <a href="https://stackoverflow.com/questions/41584243/runtimeerror-task-attached-to-a-different-loop" class="external-link" target="_blank">MongoDB's MotorClient</a>), remember to instantiate objects that need an event loop only within async functions, for example, using a lifespan async context manager.
|
||||
|
||||
///
|
||||
|
|
|
|||
|
|
@ -1,15 +1,19 @@
|
|||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
items = {}
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup_event():
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
items["foo"] = {"name": "Fighters"}
|
||||
items["bar"] = {"name": "Tenders"}
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
|
||||
|
||||
@app.get("/items/{item_id}")
|
||||
|
|
@ -21,4 +25,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"}
|
||||
Loading…
Reference in New Issue