From 6cb4454b98aa194d41bee65f8626a0347551084d Mon Sep 17 00:00:00 2001
From: Areeb455 <141515705+Areeb455@users.noreply.github.com>
Date: Sat, 21 Feb 2026 22:13:15 +0000
Subject: [PATCH] docs: migrate testing tutorial from on_event to lifespan
---
docs/en/docs/advanced/async-tests.md | 2 +-
docs_src/app_testing/tutorial003_py310.py | 14 +++++++++-----
2 files changed, 10 insertions(+), 6 deletions(-)
diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md
index cefb1d1841..23745b5ce3 100644
--- a/docs/en/docs/advanced/async-tests.md
+++ b/docs/en/docs/advanced/async-tests.md
@@ -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 MongoDB's MotorClient), 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 MongoDB's MotorClient), remember to instantiate objects that need an event loop only within async functions, for example, using a lifespan async context manager.
///
diff --git a/docs_src/app_testing/tutorial003_py310.py b/docs_src/app_testing/tutorial003_py310.py
index ca6b45ce03..45f6f678c6 100644
--- a/docs_src/app_testing/tutorial003_py310.py
+++ b/docs_src/app_testing/tutorial003_py310.py
@@ -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"}
\ No newline at end of file