Browse Source

Merge 60d25bee54 into 6df50d40fe

pull/13259/merge
z0z0r4 1 day ago
committed by GitHub
parent
commit
4a57339ad2
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 12
      docs/en/docs/advanced/testing-events.md
  2. 30
      docs_src/app_testing/tutorial004.py
  3. 5
      tests/test_tutorial/test_testing/test_tutorial004.py

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

@ -1,5 +1,13 @@
# Testing Events: startup - shutdown
# Testing Events: lifespan and startup - shutdown
When you need your event handlers (`startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement:
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] *}
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)
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] *}

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"}

5
tests/test_tutorial/test_testing/test_tutorial004.py

@ -0,0 +1,5 @@
from docs_src.app_testing.tutorial004 import test_read_items
def test_main():
test_read_items()
Loading…
Cancel
Save