Testing (TestClient)
Relevant source files
The following files were used as context for generating this wiki page:
The TestClient is a specialized HTTP client built on top of httpx that allows for in-process testing of Starlette applications. It provides a synchronous interface to trigger the ASGI application's request/response cycle without requiring an external web server process.
It supports both HTTP and WebSocket protocols, handles lifespan events (startup and shutdown), and allows for complex testing scenarios including cookie persistence, redirect following, and custom header configurations. Sources: README.md:21-31, starlette/testclient.py
Architecture and Core Mechanics
The TestClient functions by wrapping an ASGI application and using httpx.Client to dispatch requests to it via a specialized transport. Instead of communicating over a network socket, it invokes the application directly in a separate thread or event loop, ensuring that anyio backends (like asyncio or trio) are correctly handled. Sources: starlette/testclient.py, tests/test_testclient.py:91-118
Lifecycle Management
The TestClient can be used as a context manager to manage the application's lifespan. When entering the context, it triggers the lifespan.startup event; when exiting, it triggers lifespan.shutdown. Sources: tests/test_testclient.py:91-118, tests/test_applications.py:279-291
The diagram shows how the TestClient orchestrates the application's lifecycle and internal request handling. Sources: tests/test_testclient.py:91-118
Request Flow
When a request is made (e.g., client.get("/")), the client converts the request into an ASGI scope. It then executes the application's __call__ method. For standard HTTP requests, it utilizes the httpx interface. Sources: starlette/testclient.py, tests/test_testclient.py:176-184
| Component | Description |
|---|---|
ASGIApp | The Starlette/ASGI application being tested. |
httpx.Client | The underlying client providing the user-facing API (get, post, etc.). |
BaseURL | Default is http://testserver. |
Lifespan | Manages startup/shutdown state during the client's lifecycle. |
HTTP Testing
The TestClient supports the full range of HTTP methods and handles responses similarly to a standard browser or HTTP library.
Key Features
- Automatic Redirects: Can follow redirects if
follow_redirects=Trueis set. Sources: tests/test_responses.py:72-84, tests/test_testclient.py:245-256 - Cookie Persistence: Maintains a cookie jar across multiple requests to simulate session behavior. Sources: tests/test_responses.py:269-278, tests/test_testclient.py:216-243
- Exception Handling: By default, server-side exceptions are raised in the test. This can be disabled using
raise_server_exceptions=Falseto test custom error pages. Sources: tests/test_applications.py:165-168 - Header Manipulation: Supports custom headers and duplicate headers (using lists of tuples). Sources: tests/test_testclient.py:76-85, tests/test_testclient.py:259-264
Request Configuration
The TestClient constructor accepts several parameters to define the testing environment:
| Parameter | Type | Default | Description |
|---|---|---|---|
app | ASGIApp | Required | The application instance to test. |
base_url | str | http://testserver | The base URL for all requests. |
raise_server_exceptions | bool | True | Whether to re-raise exceptions from the app. |
root_path | str | "" | The ASGI root_path (useful for mounted apps). |
follow_redirects | bool | True | Whether the client should follow 3xx responses. |
Sources: starlette/testclient.py, tests/test_testclient.py:199-204
WebSocket Testing
WebSocket testing is performed using the websocket_connect context manager, which returns a session object for interacting with the socket.
The sequence diagram illustrates the bidirectional communication between the test script and the ASGI application through the TestClient. Sources: tests/test_websockets.py:11-18, tests/test_testclient.py:145-166
WebSocket Session Methods
The session object provided by websocket_connect supports the following:
send_text(data)/receive_text()send_bytes(data)/receive_bytes()send_json(data)/receive_json()close(code, reason)
Sources: tests/test_websockets.py:72-110
Denial Responses
The TestClient specifically handles "Denial Responses" where an application rejects a WebSocket upgrade with a standard HTTP response (e.g., 401 Unauthorized). This raises a WebSocketDenialResponse exception in the test. Sources: tests/test_websockets.py:175-184, tests/test_applications.py:126-130
Advanced Usage
Path Parameters and Routing
The TestClient respects Starlette's routing logic, including path converters (int, float, uuid, path) and subdomains. Sources: tests/test_routing.py:151-177, tests/test_applications.py:144-148
# Testing integer converters
def test_int_converter(test_client_factory):
app = Router([Route("/int/{param:int}", endpoint=int_convertor)])
client = test_client_factory(app)
response = client.get("/int/5")
assert response.json() == {"int": 5}
Sources: tests/test_routing.py:152-156
Mocking Services
TestClient can be used inside an application to mock external services. This allows an application to "call" another Starlette app in-process during integration tests. Sources: tests/test_testclient.py:59-73
def test_use_testclient_in_endpoint(test_client_factory):
def homepage(request: Request):
client = test_client_factory(mock_service)
response = client.get("/")
return JSONResponse(response.json())
app = Starlette(routes=[Route("/", endpoint=homepage)])
client = test_client_factory(app)
response = client.get("/")
assert response.json() == {"mock": "example"}
Sources: tests/test_testclient.py:65-73
Threading and Event Loops
The client ensures that the application's event loop runs in a background thread if necessary, allowing the test to remain synchronous while the application executes asynchronously. This is critical for Lifespan management where task groups must be entered and exited in the same task. Sources: tests/test_testclient.py:91-118, tests/test_formparsers.py:270-285
Summary
The TestClient is the primary tool for validating Starlette applications. By simulating the ASGI environment and providing an easy-to-use synchronous wrapper around httpx, it enables comprehensive testing of HTTP endpoints, WebSockets, and application lifecycles. Its ability to run in-process without network overhead makes it ideal for unit and integration testing suites. Sources: README.md:21-31, starlette/testclient.py