asgi-lifespan is a Python library that enables programmatic control over the startup and shutdown lifecycle events of ASGI applications. It's primarily used for testing or mocking ASGI apps without requiring a full ASGI server, facilitating resource initialization and cleanup during development and CI. The current version is 2.1.0, with releases typically driven by new features, bug fixes, or Python version support.
pip install asgi-lifespanVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `LifespanManager` to programmatically trigger the startup and shutdown events of an ASGI application. It defines a simple Starlette app with a lifespan context manager that prints messages. Running this code will execute the startup logic, proceed through the `async with` block, and then execute the shutdown logic, all without needing to spin up a separate ASGI server. This pattern is particularly useful for testing.
Upgrade your Python environment to 3.7 or newer. If not possible, pin `asgi-lifespan<2.0.0`.
Migrate your code to use `LifespanManager` as an asynchronous context manager, as shown in the quickstart example.
Ensure your ASGI application fully conforms to the ASGI lifespan specification (e.g., sending `lifespan.startup.complete` or `lifespan.shutdown.complete` events). If using an ASGI server like Uvicorn, running with `--lifespan on` might reveal the underlying error during startup/shutdown.
Modify your test client initialization to `httpx.AsyncClient(transport=httpx.ASGITransport(app=manager.app))`.
Ensure all necessary dependencies, specifically `starlette` (or any other module mentioned in a `ModuleNotFoundError`), are installed in the test environment (e.g., `pip install starlette`). Review the script's `import` statements to identify all required packages.
Ensure 'starlette' is installed in your environment by running `pip install starlette`.
Ensure that the ASGI server and application both support the lifespan protocol. If using Uvicorn, you can run it with the `--lifespan on` option to enable lifespan support.
Ensure you have the correct version of 'asgi-lifespan' installed by running 'pip install asgi-lifespan'.
Update 'asgi-lifespan' to the latest version by running 'pip install --upgrade asgi-lifespan'.
Ensure your ASGI application properly defines and handles the lifespan protocol using an `asynccontextmanager` for startup and shutdown events. When testing with `asgi-lifespan`, wrap your application with `LifespanManager` to correctly trigger and manage these events, allowing you to debug any underlying issues in your app's lifespan handlers. You might also run your server with `--lifespan on` to get more detailed error logs if an exception is occurring within your application's lifespan events.