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:

  1. Users follow the current best practices for resource management.
  2. The documentation remains consistent with the newer "Lifespan Events" tutorial.
  3. We reduce the reliance on deprecated features that are slated for removal in future versions.

Changes

  • Code: Updated docs_src/app_testing/tutorial003_py310.py to implement the lifespan context manager.
  • Documentation: Updated docs/en/docs/advanced/async-tests.md to 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.py to ensure the test suite still passes with the lifespan implementation.
  • Verified that the TestClient correctly 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.