3 changed files with 44 additions and 20 deletions
@ -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) |
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] *} |
@ -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…
Reference in new issue