docs: migrate testing tutorial from on_event to lifespan by Areeb455 · Pull Request #14960 · fastapi/fastapi
Description
This PR migrates the asynchronous testing documentation and its associated source code from the deprecated @app.on_event("startup") pattern to the modern lifespan async context manager.
FastAPI has deprecated the .on_event() handlers in favor of the lifespan parameter. Current documentation in the "Advanced - Async Tests" section still recommends the legacy pattern to resolve RuntimeError: Task attached to a different loop issues.
By updating this section, we ensure that:
- Users follow the current best practices for resource management.
- The documentation remains consistent with the newer "Lifespan Events" tutorial.
- We reduce the reliance on deprecated features that are slated for removal in future versions.
Changes
- Code: Updated
docs_src/app_testing/tutorial003_py310.pyto implement thelifespancontext manager. - Documentation: Updated
docs/en/docs/advanced/async-tests.mdto update the prose description and provide a link to the main Lifespan documentation.
I have verified the code changes locally using the following:
- Ran
pytest docs_src/app_testing/tutorial003_py310.pyto ensure the test suite still passes with thelifespanimplementation. - Verified that the
TestClientcorrectly triggers the lifespan events during the context manager entry/exit.
Checklist
- The code follows the modern Python 3.10+ style used in the FastAPI docs.
- The documentation text is clear and contains a link to the relevant "Lifespan" reference page.
- All automated tests for the specific source file pass.