Registry / testing / starlette-testclient

starlette-testclient

JSON →
library0.4.1pypypi✓ verified 28d ago

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-testclient
INSTALL
IMPORT
SIG · STARLETTE-TESTCLIE
S
starlette-testclient
testingpythonv0.4.1
Install
2.5s avg
Import
535ms
Disk
21MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v0.4.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.564s · 23.4MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 2.5s · import 0.506s · 24MB
21MB installed
● package 21MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

TestClient
✓ from starlette_testclient import TestClient
✗ from starlette.testclient import TestClient
While 'starlette.testclient.TestClient' is valid, it uses 'httpx' and has an asynchronous interface. This library specifically provides a 'requests'-based, synchronous client, which users might mistakenly assume is available via the 'starlette' package itself after framework updates.

This example demonstrates how to create a basic Starlette application and then test it using `starlette-testclient`'s synchronous `TestClient`.

from starlette.applications import Starlette from starlette.responses import PlainTextResponse from starlette.routing import Route from starlette_testclient import TestClient async def homepage(request): return PlainTextResponse("Hello, world!") routes = [ Route("/", endpoint=homepage), ] app = Starlette(routes=routes) def test_homepage_sync(): client = TestClient(app) response = client.get("/") assert response.status_code == 200 assert response.text == "Hello, world!" test_homepage_sync() print("Quickstart test passed!")
Debug
Known issues
gotchaVersion 0.4.0 of `starlette-testclient` added explicit support for `anyio<3` and `anyio>=4`. Using `anyio` versions between 3.0 and 3.x (exclusive of <3) may lead to unexpected compatibility issues or errors due to changes in `anyio`'s API, specifically around `start_blocking_portal`.
fix
Ensure your `anyio` dependency is pinned to `<3` or `>=4`. If using an older `starlette-testclient` version, update to 0.4.0+.
affects: <0.4.0 and potentially v0.4.0+ with specific 'anyio' 3.x versions
gotchaStarlette's `TestClient` (and this backport) executes the ASGI application in a separate background thread, providing a synchronous testing interface for an asynchronous application. This can cause problems when attempting to access asynchronous resources (e.g., database connections, `httpx.AsyncClient` instances) that were initialized within the application's startup events from an `async` test function running in the main thread's event loop.
fix
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.
affects: All versions
gotchaWhen using `TestClient`, issues with cookies not being set or retrieved correctly have been reported. This can sometimes be traced to `max_age` cookie parameters being floats instead of integers, or inconsistencies between the `base_url` used in the client and the cookie's domain.
fix
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.
affects: All versions
gotchaDebugging tests with `starlette-testclient` in PyCharm (or other IDEs that patch `asyncio` APIs) can lead to `AttributeError` (e.g., `'_UnixSelectorEventLoop' object has no attribute '_compute_internal_coro'`). This occurs because PyCharm's patched `asyncio.new_event_loop()` clashes with `anyio`'s event loop detection.
fix
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`.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'starlette_testclient'
The `starlette-testclient` package is not installed in the current Python environment or there is a typo in the import statement.
fix
Install the package using `pip install starlette-testclient` and ensure the import is `from starlette_testclient import TestClient`.
TypeError: 'X' object is not callable
The object passed to the `TestClient` constructor is not a valid ASGI application (a callable accepting `scope`, `receive`, `send`).
fix
Ensure you are passing a properly initialized ASGI application instance (e.g., `Starlette()`, `FastAPI()`) to `TestClient`.
AttributeError: 'TestClient' object has no attribute 'aclose'
`starlette-testclient` uses the synchronous `requests` library and does not have an `aclose` method, which is typically found in `httpx`-based clients for asynchronous resource management.
fix
`starlette-testclient` is synchronous and does not require `async with` context management or an `aclose()` call; tests are run synchronously.
from starlette.testclient import TestClient
The user intends to use the `requests`-based `starlette-testclient` but is importing the `TestClient` from the standard `starlette` library, which uses `httpx` and may have different behaviors.
fix
To use the `requests`-based backport, change the import statement to `from starlette_testclient import TestClient`.
Upgrade
Version history
0.4.1latest on PyPI · released Apr 29, 2024
Audit
Dependencies
requestsrequiredThis library explicitly uses 'requests' as its underlying HTTP client for testing, distinguishing it from modern Starlette's 'httpx'-based TestClient.
starletterequiredIt is a backport of Starlette's TestClient and is designed to test Starlette (and FastAPI) applications.
anyiorequiredStarlette itself is built on 'anyio', and starlette-testclient v0.4.0 added explicit compatibility for 'anyio<3' and 'anyio>=4'.
Agent activity
26 hits · last 30 days
node
20
Resources
starlette-testclient — pip install starlette-testclient · libregistry