diff --git a/docs/en/docs/advanced/testing-events.md b/docs/en/docs/advanced/testing-events.md index 0c554c4ec..d67583de8 100644 --- a/docs/en/docs/advanced/testing-events.md +++ b/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] *} diff --git a/docs_src/app_testing/tutorial004.py b/docs_src/app_testing/tutorial004.py new file mode 100644 index 000000000..076c00313 --- /dev/null +++ b/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"} diff --git a/tests/test_tutorial/test_testing/test_tutorial004.py b/tests/test_tutorial/test_testing/test_tutorial004.py new file mode 100644 index 000000000..812ee44c1 --- /dev/null +++ b/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()