starlette-testclient is a backport of Starlette's TestClient that utilizes the `requests` library instead of `httpx`. Its primary goal is to offer a familiar synchronous testing interface for ASGI applications, easing the migration for users accustomed to `requests`-based testing. The current version is 0.4.1. Releases are infrequent, with the latest significant update in April 2024, reflecting a maintenance cadence focused on compatibility rather than rapid feature development, as its purpose is to bridge the gap for users transitioning from older Starlette testing practices.
pip install starlette-testclientVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to create a basic Starlette application and then test it using `starlette-testclient`'s synchronous `TestClient`.
Ensure your `anyio` dependency is pinned to `<3` or `>=4`. If using an older `starlette-testclient` version, update to 0.4.0+.
Avoid accessing async resources created within the ASGI app's lifecycle directly from `async def` test functions. If async test logic is necessary, use `httpx.AsyncClient` with `ASGITransport` instead, or ensure resources are managed within the same event loop context.
Ensure cookie `max_age` values are integers. Verify that the `TestClient`'s `base_url` aligns with the domain for which cookies are being set, particularly for explicit domain settings.
As a workaround, you can initialize `TestClient` with `TestClient(app, backend_options={'loop_factory': asyncio.new_event_loop})` or, if using PyCharm, disable `python.debug.asyncio.repl` in `Help | Find Actions | Registry`.Install the package using `pip install starlette-testclient` and ensure the import is `from starlette_testclient import TestClient`.
Ensure you are passing a properly initialized ASGI application instance (e.g., `Starlette()`, `FastAPI()`) to `TestClient`.
`starlette-testclient` is synchronous and does not require `async with` context management or an `aclose()` call; tests are run synchronously.
To use the `requests`-based backport, change the import statement to `from starlette_testclient import TestClient`.