fastapi-testing 0.3.3__tar.gz → 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastapi_testing-0.4.0/.python-version +1 -0
- {fastapi_testing-0.3.3 → fastapi_testing-0.4.0}/PKG-INFO +172 -56
- {fastapi_testing-0.3.3 → fastapi_testing-0.4.0}/README.md +162 -49
- {fastapi_testing-0.3.3 → fastapi_testing-0.4.0}/pyproject.toml +60 -15
- fastapi_testing-0.4.0/src/fastapi_testing/__init__.py +48 -0
- fastapi_testing-0.4.0/src/fastapi_testing/async_fastapi_testing.py +1227 -0
- fastapi_testing-0.4.0/src/fastapi_testing/py.typed +0 -0
- fastapi_testing-0.4.0/uv.lock +819 -0
- fastapi_testing-0.3.3/src/fastapi_testing/__init__.py +0 -27
- fastapi_testing-0.3.3/src/fastapi_testing/async_fastapi_testing.py +0 -569
- fastapi_testing-0.3.3/uv.lock +0 -711
- {fastapi_testing-0.3.3 → fastapi_testing-0.4.0}/.coveragerc +0 -0
- {fastapi_testing-0.3.3 → fastapi_testing-0.4.0}/.gitignore +0 -0
- {fastapi_testing-0.3.3 → fastapi_testing-0.4.0}/.vscode/settings.json +0 -0
- {fastapi_testing-0.3.3 → fastapi_testing-0.4.0}/LICENSE +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.13
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: fastapi-testing
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: A lightweight, async-first testing framework for FastAPI applications
|
|
5
5
|
Project-URL: Homepage, https://github.com/descoped/fastapi-testing
|
|
6
6
|
Project-URL: Repository, https://github.com/descoped/fastapi-testing
|
|
@@ -18,15 +18,18 @@ Classifier: Programming Language :: Python :: 3
|
|
|
18
18
|
Classifier: Programming Language :: Python :: 3.11
|
|
19
19
|
Classifier: Programming Language :: Python :: 3.12
|
|
20
20
|
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
21
23
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
24
|
Classifier: Topic :: Software Development :: Testing
|
|
23
25
|
Classifier: Typing :: Typed
|
|
24
26
|
Requires-Python: >=3.11
|
|
25
|
-
Requires-Dist: fastapi>=0.
|
|
26
|
-
Requires-Dist: httpx
|
|
27
|
-
Requires-Dist: starlette>=1.
|
|
28
|
-
Requires-Dist:
|
|
29
|
-
Requires-Dist:
|
|
27
|
+
Requires-Dist: fastapi>=0.165.0
|
|
28
|
+
Requires-Dist: httpx>=0.28.1
|
|
29
|
+
Requires-Dist: starlette>=1.10.0
|
|
30
|
+
Requires-Dist: typing-extensions>=4.4.0; python_full_version < '3.12'
|
|
31
|
+
Requires-Dist: uvicorn>=0.54.0
|
|
32
|
+
Requires-Dist: websockets>=17.4
|
|
30
33
|
Description-Content-Type: text/markdown
|
|
31
34
|
|
|
32
35
|
# FastAPI Testing
|
|
@@ -69,13 +72,15 @@ import pytest
|
|
|
69
72
|
from fastapi import FastAPI
|
|
70
73
|
from fastapi_testing import create_test_server
|
|
71
74
|
|
|
75
|
+
|
|
72
76
|
@pytest.mark.asyncio
|
|
73
77
|
async def test_hello_world():
|
|
74
78
|
async with create_test_server() as server:
|
|
79
|
+
|
|
75
80
|
@server.app.get("/hello")
|
|
76
81
|
async def hello():
|
|
77
82
|
return {"message": "Hello, World!"}
|
|
78
|
-
|
|
83
|
+
|
|
79
84
|
response = await server.client.get("/hello")
|
|
80
85
|
await response.expect_status(200)
|
|
81
86
|
data = await response.json()
|
|
@@ -153,6 +158,34 @@ async with create_test_server() as server:
|
|
|
153
158
|
pass # Server automatically starts and stops
|
|
154
159
|
```
|
|
155
160
|
|
|
161
|
+
### Testing Your Own Application
|
|
162
|
+
|
|
163
|
+
Pass the application your project builds; its own lifespan runs, and its routes are served:
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
from myproject.main import create_app
|
|
167
|
+
|
|
168
|
+
async with create_test_server(app=create_app()) as server:
|
|
169
|
+
response = await server.client.get("/health")
|
|
170
|
+
await response.expect_status(200)
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`app` and `lifespan` are alternatives: `lifespan` is for the empty `FastAPI` app the server creates when no `app` is
|
|
174
|
+
given, so passing both raises `ValueError`.
|
|
175
|
+
|
|
176
|
+
### Timeouts
|
|
177
|
+
|
|
178
|
+
| Parameter | Default | Bounds |
|
|
179
|
+
|---|---|---|
|
|
180
|
+
| `startup_timeout` | 30 s | the application's lifespan startup and the server's own startup, together |
|
|
181
|
+
| `shutdown_timeout` | 10 s | open connections finishing on stop, then the lifespan shutdown |
|
|
182
|
+
| `client_timeout` | 30 s | each request with `server.client`, and opening its WebSocket connections |
|
|
183
|
+
|
|
184
|
+
```python
|
|
185
|
+
async with create_test_server(startup_timeout=60.0, client_timeout=5.0) as server:
|
|
186
|
+
...
|
|
187
|
+
```
|
|
188
|
+
|
|
156
189
|
### AsyncTestClient
|
|
157
190
|
|
|
158
191
|
The `AsyncTestClient` provides methods for making HTTP requests to your test server:
|
|
@@ -172,11 +205,33 @@ The `AsyncTestResponse` class provides convenient methods for assertions:
|
|
|
172
205
|
|
|
173
206
|
```python
|
|
174
207
|
response = await server.client.get("/path")
|
|
175
|
-
await response.expect_status(200) #
|
|
176
|
-
data = await response.json()
|
|
177
|
-
text = await response.text()
|
|
208
|
+
await response.expect_status(200) # Raises AssertionError with the actual status and body, also under python -O
|
|
209
|
+
data = await response.json() # Get JSON response
|
|
210
|
+
text = await response.text() # Get text response
|
|
211
|
+
raw = response.httpx_response # The underlying httpx.Response, for anything else
|
|
178
212
|
```
|
|
179
213
|
|
|
214
|
+
### Streaming Responses and Server-Sent Events
|
|
215
|
+
|
|
216
|
+
`client.stream()` makes a streaming request and yields the `httpx.Response` before its body is read. The response is
|
|
217
|
+
closed when the block exits, so breaking out of an endless stream is safe:
|
|
218
|
+
|
|
219
|
+
```python
|
|
220
|
+
async with server.client.stream("GET", "/events") as response:
|
|
221
|
+
assert response.status_code == 200
|
|
222
|
+
async for line in response.aiter_lines():
|
|
223
|
+
if line.startswith("data:"):
|
|
224
|
+
...
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
### The Server's Client
|
|
228
|
+
|
|
229
|
+
`server.client` is shared for the server's lifetime and closed by `stop()`. `async with server.client as client:`
|
|
230
|
+
does not close it, so it can be used any number of times in a test. A client you create yourself,
|
|
231
|
+
`async with AsyncTestClient(server.base_url) as client:`, is closed when the block exits. WebSocket connections opened
|
|
232
|
+
through `server.client` likewise stay open until you close them or `stop()` runs; close one explicitly with
|
|
233
|
+
`await ws_response.websocket().close()` when a test needs the server to see the disconnect.
|
|
234
|
+
|
|
180
235
|
### WebSocket Testing
|
|
181
236
|
|
|
182
237
|
Test WebSocket endpoints with full protocol support:
|
|
@@ -209,11 +264,7 @@ async def test_mixed_protocols(test_server):
|
|
|
209
264
|
assert http_response.status_code == 200
|
|
210
265
|
|
|
211
266
|
# Configure WebSocket
|
|
212
|
-
config = WebSocketConfig(
|
|
213
|
-
subprotocols=["test-protocol"],
|
|
214
|
-
ping_interval=20.0,
|
|
215
|
-
ping_timeout=20.0
|
|
216
|
-
)
|
|
267
|
+
config = WebSocketConfig(subprotocols=["test-protocol"], ping_interval=20.0, ping_timeout=20.0)
|
|
217
268
|
|
|
218
269
|
# Test WebSocket endpoint
|
|
219
270
|
ws_response = await test_server.client.websocket("/ws/echo", config)
|
|
@@ -249,17 +300,10 @@ json_data = await client.ws.receive_json(ws_response)
|
|
|
249
300
|
binary = await client.ws.receive_binary(ws_response)
|
|
250
301
|
|
|
251
302
|
# Message Expectations
|
|
252
|
-
await client.ws.expect_message(
|
|
253
|
-
ws_response,
|
|
254
|
-
expected="message",
|
|
255
|
-
timeout=1.0
|
|
256
|
-
)
|
|
303
|
+
await client.ws.expect_message(ws_response, expected="message", timeout=1.0)
|
|
257
304
|
|
|
258
|
-
# Collect
|
|
259
|
-
messages = await client.ws.drain_messages(
|
|
260
|
-
ws_response,
|
|
261
|
-
timeout=1.0
|
|
262
|
-
)
|
|
305
|
+
# Collect messages until none arrives within the timeout or the server closes normally (an abnormal close raises)
|
|
306
|
+
messages = await client.ws.drain_messages(ws_response, timeout=1.0)
|
|
263
307
|
```
|
|
264
308
|
|
|
265
309
|
#### WebSocket Configuration
|
|
@@ -269,37 +313,48 @@ Configure connections with various options:
|
|
|
269
313
|
```python
|
|
270
314
|
ws_config = WebSocketConfig(
|
|
271
315
|
subprotocols=["protocol"], # Supported subprotocols
|
|
272
|
-
compression=None,
|
|
273
|
-
extra_headers={},
|
|
274
|
-
ping_interval=20.0,
|
|
275
|
-
ping_timeout=20.0,
|
|
276
|
-
max_size=2
|
|
277
|
-
max_queue=32,
|
|
278
|
-
timeout=30.0
|
|
316
|
+
compression=None, # Compression algorithm
|
|
317
|
+
extra_headers={}, # Additional headers
|
|
318
|
+
ping_interval=20.0, # Keep-alive interval
|
|
319
|
+
ping_timeout=20.0, # Ping timeout
|
|
320
|
+
max_size=2**20, # Max message size (1MB)
|
|
321
|
+
max_queue=32, # Max queued messages
|
|
322
|
+
timeout=30.0, # Connection timeout
|
|
279
323
|
)
|
|
280
324
|
```
|
|
281
325
|
|
|
326
|
+
A field left as `None` uses the default: `max_size` and `max_queue` come from the active `Config`, everything else
|
|
327
|
+
from websockets. To pass `None` itself to websockets, for example to disable keepalive pings, use `options`:
|
|
328
|
+
|
|
329
|
+
```python
|
|
330
|
+
ws_response = await server.client.websocket("/ws", options={"ping_interval": None})
|
|
331
|
+
```
|
|
332
|
+
|
|
282
333
|
## Advanced Usage
|
|
283
334
|
|
|
284
335
|
### Advanced Server Configuration
|
|
285
336
|
|
|
286
|
-
You can customize the server lifecycle using a reusable test fixture
|
|
337
|
+
You can customize the server lifecycle using a reusable test fixture. The lifespan is an
|
|
338
|
+
`@asynccontextmanager` function, the form Starlette's `Lifespan` type describes, so type checkers
|
|
339
|
+
accept it:
|
|
287
340
|
|
|
288
341
|
```python
|
|
289
342
|
@pytest.fixture
|
|
290
343
|
async def test_server(
|
|
291
|
-
test_settings: Settings,
|
|
292
|
-
transaction_manager: TransactionManager
|
|
344
|
+
test_settings: Settings, transaction_manager: TransactionManager
|
|
293
345
|
) -> AsyncGenerator[AsyncTestServer, None]:
|
|
294
346
|
"""Create test server with overridden settings and database connection"""
|
|
295
347
|
|
|
296
|
-
|
|
348
|
+
@asynccontextmanager
|
|
349
|
+
async def custom_lifespan(app: FastAPI) -> AsyncGenerator[None]:
|
|
297
350
|
# Wire up test-specific dependencies
|
|
298
|
-
app.dependency_overrides.update(
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
351
|
+
app.dependency_overrides.update(
|
|
352
|
+
{
|
|
353
|
+
get_settings: lambda: test_settings,
|
|
354
|
+
get_transaction_manager: lambda: transaction_manager,
|
|
355
|
+
get_db_pool: lambda: transaction_manager.pool,
|
|
356
|
+
}
|
|
357
|
+
)
|
|
303
358
|
|
|
304
359
|
yield # Server handles requests during this period
|
|
305
360
|
|
|
@@ -323,13 +378,10 @@ async def test_api(test_server: AsyncTestServer):
|
|
|
323
378
|
# Make requests
|
|
324
379
|
response = await test_server.client.get("/your-endpoint")
|
|
325
380
|
await response.expect_status(200)
|
|
326
|
-
|
|
381
|
+
|
|
327
382
|
# Test concurrent requests
|
|
328
|
-
responses = await asyncio.gather(*[
|
|
329
|
-
|
|
330
|
-
for _ in range(5)
|
|
331
|
-
])
|
|
332
|
-
|
|
383
|
+
responses = await asyncio.gather(*[test_server.client.get("/endpoint") for _ in range(5)])
|
|
384
|
+
|
|
333
385
|
for response in responses:
|
|
334
386
|
await response.expect_status(200)
|
|
335
387
|
```
|
|
@@ -342,6 +394,7 @@ You can define setup and cleanup operations using FastAPI's lifespan:
|
|
|
342
394
|
from contextlib import asynccontextmanager
|
|
343
395
|
from fastapi import FastAPI
|
|
344
396
|
|
|
397
|
+
|
|
345
398
|
@asynccontextmanager
|
|
346
399
|
async def lifespan(app: FastAPI):
|
|
347
400
|
# Setup
|
|
@@ -350,6 +403,7 @@ async def lifespan(app: FastAPI):
|
|
|
350
403
|
# Cleanup
|
|
351
404
|
print("Shutting down server")
|
|
352
405
|
|
|
406
|
+
|
|
353
407
|
async with create_test_server(lifespan=lifespan) as server:
|
|
354
408
|
# Your test code here
|
|
355
409
|
pass
|
|
@@ -363,14 +417,12 @@ The framework supports testing concurrent requests:
|
|
|
363
417
|
import asyncio
|
|
364
418
|
|
|
365
419
|
async with create_test_server() as server:
|
|
420
|
+
|
|
366
421
|
@server.app.get("/ping")
|
|
367
422
|
async def ping():
|
|
368
423
|
return {"status": "ok"}
|
|
369
424
|
|
|
370
|
-
responses = await asyncio.gather(*[
|
|
371
|
-
server.client.get("/ping")
|
|
372
|
-
for _ in range(5)
|
|
373
|
-
])
|
|
425
|
+
responses = await asyncio.gather(*[server.client.get("/ping") for _ in range(5)])
|
|
374
426
|
```
|
|
375
427
|
|
|
376
428
|
## Configuration
|
|
@@ -379,11 +431,72 @@ You can customize the server behavior:
|
|
|
379
431
|
|
|
380
432
|
```python
|
|
381
433
|
server = AsyncTestServer(
|
|
382
|
-
startup_timeout=30.0,
|
|
383
|
-
shutdown_timeout=10.0,
|
|
434
|
+
startup_timeout=30.0, # Seconds for lifespan startup plus the server becoming ready
|
|
435
|
+
shutdown_timeout=10.0, # Seconds open connections get to finish, and again for lifespan shutdown
|
|
384
436
|
)
|
|
385
437
|
```
|
|
386
438
|
|
|
439
|
+
`create_test_server()` accepts the same `startup_timeout` and `shutdown_timeout` arguments.
|
|
440
|
+
|
|
441
|
+
### Lifecycle guarantees
|
|
442
|
+
|
|
443
|
+
`AsyncTestServer` owns the whole lifecycle; uvicorn only serves connections:
|
|
444
|
+
|
|
445
|
+
- **Socket:** the server binds its own listening socket on `127.0.0.1` to a free port in the configured range, so no
|
|
446
|
+
other process can take the port between choosing and binding it. `stop()` always closes it.
|
|
447
|
+
- **Lifespan:** the application's lifespan runs in a task the server owns, through the full ASGI application (so
|
|
448
|
+
middleware sees it). State yielded by the lifespan reaches `request.state` and `websocket.state`. You can assign
|
|
449
|
+
`create_test_server(app=create_app())`, or assign `server.app = create_app()` before `start()`; its lifespan is the
|
|
450
|
+
one that runs.
|
|
451
|
+
- **Startup:** lifespan startup runs first, then the server starts serving. If either fails or takes longer than
|
|
452
|
+
`startup_timeout`, `start()` releases everything acquired so far and raises `ServerStartupError`, chained to the
|
|
453
|
+
application's own exception.
|
|
454
|
+
- **Shutdown:** `stop()` closes the client, stops accepting connections, gives open connections (for example SSE
|
|
455
|
+
streams) `shutdown_timeout` to finish and then closes them, runs the lifespan shutdown, closes the socket and
|
|
456
|
+
releases the port. If the lifespan shutdown fails or times out, `stop()` raises `ServerShutdownError` after all of
|
|
457
|
+
that is done. If `stop()` is cancelled or a step fails, the remaining steps still run, without waiting, before the
|
|
458
|
+
error propagates; on that path the lifespan is cancelled rather than shut down, so the code after its `yield` does
|
|
459
|
+
not run.
|
|
460
|
+
- **Errors from the test come first:** when the body of `async with create_test_server()` (or
|
|
461
|
+
`async with AsyncTestServer()`) raises, that exception is what the test reports. A `ServerShutdownError` from the
|
|
462
|
+
cleanup is attached to it as a note instead of replacing it, and a cancelled test stays cancelled.
|
|
463
|
+
- **Signals:** while serving, SIGINT and SIGTERM stop the server, as in uvicorn. Overlapping servers share the
|
|
464
|
+
process handlers correctly whatever order they stop in, and the original handlers come back when the last
|
|
465
|
+
server stops, so Ctrl-C keeps interrupting the test run.
|
|
466
|
+
|
|
467
|
+
### Global settings
|
|
468
|
+
|
|
469
|
+
Port range, HTTP connection limits, WebSocket limits and connection retries are set with a `Config`. Activate it
|
|
470
|
+
with `set_config()`, for example in `conftest.py`; it applies to every server and connection created afterwards.
|
|
471
|
+
WebSocket connects retry connection errors (refused, closed early, timed out) `ws_retry_attempts` times, `ws_retry_delay` seconds
|
|
472
|
+
apart; a rejected handshake such as a 403 or 404, or a TLS failure, fails at once. Values are checked when the `Config`
|
|
473
|
+
is made: sizes, limits and attempts must be at least 1 (`http_max_keepalive` at least 0), `ws_retry_delay` a finite
|
|
474
|
+
number of at least 0, and the port range from 1 to 65535 with the start not above the end; anything else raises
|
|
475
|
+
`ValueError`:
|
|
476
|
+
|
|
477
|
+
```python
|
|
478
|
+
from fastapi_testing import Config, set_config
|
|
479
|
+
|
|
480
|
+
set_config(Config(port_range_start=9000, port_range_end=9500, ws_retry_attempts=5))
|
|
481
|
+
|
|
482
|
+
# or read FASTAPI_TESTING_* environment variables, e.g. FASTAPI_TESTING_PORT_RANGE_START=9000.
|
|
483
|
+
# Unknown names and invalid values are ignored with a warning; strict=True raises ValueError instead.
|
|
484
|
+
set_config(Config.from_env(strict=True))
|
|
485
|
+
|
|
486
|
+
# or load a JSON or TOML file; pyproject.toml is read from its [tool.fastapi-testing] table
|
|
487
|
+
set_config(Config.from_file("pyproject.toml"))
|
|
488
|
+
```
|
|
489
|
+
|
|
490
|
+
```toml
|
|
491
|
+
[tool.fastapi-testing]
|
|
492
|
+
port_range_start = 9000
|
|
493
|
+
port_range_end = 9500
|
|
494
|
+
ws_max_message_size = 2097152
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
`get_config()` returns the active configuration. Assigning to an imported `global_config` name has no effect on the
|
|
498
|
+
library; use `set_config()` instead.
|
|
499
|
+
|
|
387
500
|
## Best Practices
|
|
388
501
|
|
|
389
502
|
1. Always use the async context manager (`create_test_server`) when possible
|
|
@@ -428,8 +541,11 @@ All tests follow modern async/await patterns and avoid mocks to ensure real-worl
|
|
|
428
541
|
|
|
429
542
|
The framework provides clear error messages for common issues:
|
|
430
543
|
|
|
431
|
-
- Server startup
|
|
432
|
-
|
|
544
|
+
- Server startup failures: if the app's lifespan startup raises, no port is free, or startup times out, `start()`
|
|
545
|
+
raises `ServerStartupError` (a `RuntimeError`), chained to the original exception, and releases everything
|
|
546
|
+
- Server shutdown failures: if the app's lifespan shutdown raises or hangs, `stop()` raises `ServerShutdownError`
|
|
547
|
+
(a `RuntimeError`) after releasing everything, so the test that caused it fails. If the test itself already
|
|
548
|
+
failed, its own exception is raised instead, with the shutdown error as a note
|
|
433
549
|
- Connection errors
|
|
434
550
|
- Invalid request formats
|
|
435
551
|
|
|
@@ -38,13 +38,15 @@ import pytest
|
|
|
38
38
|
from fastapi import FastAPI
|
|
39
39
|
from fastapi_testing import create_test_server
|
|
40
40
|
|
|
41
|
+
|
|
41
42
|
@pytest.mark.asyncio
|
|
42
43
|
async def test_hello_world():
|
|
43
44
|
async with create_test_server() as server:
|
|
45
|
+
|
|
44
46
|
@server.app.get("/hello")
|
|
45
47
|
async def hello():
|
|
46
48
|
return {"message": "Hello, World!"}
|
|
47
|
-
|
|
49
|
+
|
|
48
50
|
response = await server.client.get("/hello")
|
|
49
51
|
await response.expect_status(200)
|
|
50
52
|
data = await response.json()
|
|
@@ -122,6 +124,34 @@ async with create_test_server() as server:
|
|
|
122
124
|
pass # Server automatically starts and stops
|
|
123
125
|
```
|
|
124
126
|
|
|
127
|
+
### Testing Your Own Application
|
|
128
|
+
|
|
129
|
+
Pass the application your project builds; its own lifespan runs, and its routes are served:
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from myproject.main import create_app
|
|
133
|
+
|
|
134
|
+
async with create_test_server(app=create_app()) as server:
|
|
135
|
+
response = await server.client.get("/health")
|
|
136
|
+
await response.expect_status(200)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`app` and `lifespan` are alternatives: `lifespan` is for the empty `FastAPI` app the server creates when no `app` is
|
|
140
|
+
given, so passing both raises `ValueError`.
|
|
141
|
+
|
|
142
|
+
### Timeouts
|
|
143
|
+
|
|
144
|
+
| Parameter | Default | Bounds |
|
|
145
|
+
|---|---|---|
|
|
146
|
+
| `startup_timeout` | 30 s | the application's lifespan startup and the server's own startup, together |
|
|
147
|
+
| `shutdown_timeout` | 10 s | open connections finishing on stop, then the lifespan shutdown |
|
|
148
|
+
| `client_timeout` | 30 s | each request with `server.client`, and opening its WebSocket connections |
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
async with create_test_server(startup_timeout=60.0, client_timeout=5.0) as server:
|
|
152
|
+
...
|
|
153
|
+
```
|
|
154
|
+
|
|
125
155
|
### AsyncTestClient
|
|
126
156
|
|
|
127
157
|
The `AsyncTestClient` provides methods for making HTTP requests to your test server:
|
|
@@ -141,11 +171,33 @@ The `AsyncTestResponse` class provides convenient methods for assertions:
|
|
|
141
171
|
|
|
142
172
|
```python
|
|
143
173
|
response = await server.client.get("/path")
|
|
144
|
-
await response.expect_status(200) #
|
|
145
|
-
data = await response.json()
|
|
146
|
-
text = await response.text()
|
|
174
|
+
await response.expect_status(200) # Raises AssertionError with the actual status and body, also under python -O
|
|
175
|
+
data = await response.json() # Get JSON response
|
|
176
|
+
text = await response.text() # Get text response
|
|
177
|
+
raw = response.httpx_response # The underlying httpx.Response, for anything else
|
|
147
178
|
```
|
|
148
179
|
|
|
180
|
+
### Streaming Responses and Server-Sent Events
|
|
181
|
+
|
|
182
|
+
`client.stream()` makes a streaming request and yields the `httpx.Response` before its body is read. The response is
|
|
183
|
+
closed when the block exits, so breaking out of an endless stream is safe:
|
|
184
|
+
|
|
185
|
+
```python
|
|
186
|
+
async with server.client.stream("GET", "/events") as response:
|
|
187
|
+
assert response.status_code == 200
|
|
188
|
+
async for line in response.aiter_lines():
|
|
189
|
+
if line.startswith("data:"):
|
|
190
|
+
...
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### The Server's Client
|
|
194
|
+
|
|
195
|
+
`server.client` is shared for the server's lifetime and closed by `stop()`. `async with server.client as client:`
|
|
196
|
+
does not close it, so it can be used any number of times in a test. A client you create yourself,
|
|
197
|
+
`async with AsyncTestClient(server.base_url) as client:`, is closed when the block exits. WebSocket connections opened
|
|
198
|
+
through `server.client` likewise stay open until you close them or `stop()` runs; close one explicitly with
|
|
199
|
+
`await ws_response.websocket().close()` when a test needs the server to see the disconnect.
|
|
200
|
+
|
|
149
201
|
### WebSocket Testing
|
|
150
202
|
|
|
151
203
|
Test WebSocket endpoints with full protocol support:
|
|
@@ -178,11 +230,7 @@ async def test_mixed_protocols(test_server):
|
|
|
178
230
|
assert http_response.status_code == 200
|
|
179
231
|
|
|
180
232
|
# Configure WebSocket
|
|
181
|
-
config = WebSocketConfig(
|
|
182
|
-
subprotocols=["test-protocol"],
|
|
183
|
-
ping_interval=20.0,
|
|
184
|
-
ping_timeout=20.0
|
|
185
|
-
)
|
|
233
|
+
config = WebSocketConfig(subprotocols=["test-protocol"], ping_interval=20.0, ping_timeout=20.0)
|
|
186
234
|
|
|
187
235
|
# Test WebSocket endpoint
|
|
188
236
|
ws_response = await test_server.client.websocket("/ws/echo", config)
|
|
@@ -218,17 +266,10 @@ json_data = await client.ws.receive_json(ws_response)
|
|
|
218
266
|
binary = await client.ws.receive_binary(ws_response)
|
|
219
267
|
|
|
220
268
|
# Message Expectations
|
|
221
|
-
await client.ws.expect_message(
|
|
222
|
-
ws_response,
|
|
223
|
-
expected="message",
|
|
224
|
-
timeout=1.0
|
|
225
|
-
)
|
|
269
|
+
await client.ws.expect_message(ws_response, expected="message", timeout=1.0)
|
|
226
270
|
|
|
227
|
-
# Collect
|
|
228
|
-
messages = await client.ws.drain_messages(
|
|
229
|
-
ws_response,
|
|
230
|
-
timeout=1.0
|
|
231
|
-
)
|
|
271
|
+
# Collect messages until none arrives within the timeout or the server closes normally (an abnormal close raises)
|
|
272
|
+
messages = await client.ws.drain_messages(ws_response, timeout=1.0)
|
|
232
273
|
```
|
|
233
274
|
|
|
234
275
|
#### WebSocket Configuration
|
|
@@ -238,37 +279,48 @@ Configure connections with various options:
|
|
|
238
279
|
```python
|
|
239
280
|
ws_config = WebSocketConfig(
|
|
240
281
|
subprotocols=["protocol"], # Supported subprotocols
|
|
241
|
-
compression=None,
|
|
242
|
-
extra_headers={},
|
|
243
|
-
ping_interval=20.0,
|
|
244
|
-
ping_timeout=20.0,
|
|
245
|
-
max_size=2
|
|
246
|
-
max_queue=32,
|
|
247
|
-
timeout=30.0
|
|
282
|
+
compression=None, # Compression algorithm
|
|
283
|
+
extra_headers={}, # Additional headers
|
|
284
|
+
ping_interval=20.0, # Keep-alive interval
|
|
285
|
+
ping_timeout=20.0, # Ping timeout
|
|
286
|
+
max_size=2**20, # Max message size (1MB)
|
|
287
|
+
max_queue=32, # Max queued messages
|
|
288
|
+
timeout=30.0, # Connection timeout
|
|
248
289
|
)
|
|
249
290
|
```
|
|
250
291
|
|
|
292
|
+
A field left as `None` uses the default: `max_size` and `max_queue` come from the active `Config`, everything else
|
|
293
|
+
from websockets. To pass `None` itself to websockets, for example to disable keepalive pings, use `options`:
|
|
294
|
+
|
|
295
|
+
```python
|
|
296
|
+
ws_response = await server.client.websocket("/ws", options={"ping_interval": None})
|
|
297
|
+
```
|
|
298
|
+
|
|
251
299
|
## Advanced Usage
|
|
252
300
|
|
|
253
301
|
### Advanced Server Configuration
|
|
254
302
|
|
|
255
|
-
You can customize the server lifecycle using a reusable test fixture
|
|
303
|
+
You can customize the server lifecycle using a reusable test fixture. The lifespan is an
|
|
304
|
+
`@asynccontextmanager` function, the form Starlette's `Lifespan` type describes, so type checkers
|
|
305
|
+
accept it:
|
|
256
306
|
|
|
257
307
|
```python
|
|
258
308
|
@pytest.fixture
|
|
259
309
|
async def test_server(
|
|
260
|
-
test_settings: Settings,
|
|
261
|
-
transaction_manager: TransactionManager
|
|
310
|
+
test_settings: Settings, transaction_manager: TransactionManager
|
|
262
311
|
) -> AsyncGenerator[AsyncTestServer, None]:
|
|
263
312
|
"""Create test server with overridden settings and database connection"""
|
|
264
313
|
|
|
265
|
-
|
|
314
|
+
@asynccontextmanager
|
|
315
|
+
async def custom_lifespan(app: FastAPI) -> AsyncGenerator[None]:
|
|
266
316
|
# Wire up test-specific dependencies
|
|
267
|
-
app.dependency_overrides.update(
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
317
|
+
app.dependency_overrides.update(
|
|
318
|
+
{
|
|
319
|
+
get_settings: lambda: test_settings,
|
|
320
|
+
get_transaction_manager: lambda: transaction_manager,
|
|
321
|
+
get_db_pool: lambda: transaction_manager.pool,
|
|
322
|
+
}
|
|
323
|
+
)
|
|
272
324
|
|
|
273
325
|
yield # Server handles requests during this period
|
|
274
326
|
|
|
@@ -292,13 +344,10 @@ async def test_api(test_server: AsyncTestServer):
|
|
|
292
344
|
# Make requests
|
|
293
345
|
response = await test_server.client.get("/your-endpoint")
|
|
294
346
|
await response.expect_status(200)
|
|
295
|
-
|
|
347
|
+
|
|
296
348
|
# Test concurrent requests
|
|
297
|
-
responses = await asyncio.gather(*[
|
|
298
|
-
|
|
299
|
-
for _ in range(5)
|
|
300
|
-
])
|
|
301
|
-
|
|
349
|
+
responses = await asyncio.gather(*[test_server.client.get("/endpoint") for _ in range(5)])
|
|
350
|
+
|
|
302
351
|
for response in responses:
|
|
303
352
|
await response.expect_status(200)
|
|
304
353
|
```
|
|
@@ -311,6 +360,7 @@ You can define setup and cleanup operations using FastAPI's lifespan:
|
|
|
311
360
|
from contextlib import asynccontextmanager
|
|
312
361
|
from fastapi import FastAPI
|
|
313
362
|
|
|
363
|
+
|
|
314
364
|
@asynccontextmanager
|
|
315
365
|
async def lifespan(app: FastAPI):
|
|
316
366
|
# Setup
|
|
@@ -319,6 +369,7 @@ async def lifespan(app: FastAPI):
|
|
|
319
369
|
# Cleanup
|
|
320
370
|
print("Shutting down server")
|
|
321
371
|
|
|
372
|
+
|
|
322
373
|
async with create_test_server(lifespan=lifespan) as server:
|
|
323
374
|
# Your test code here
|
|
324
375
|
pass
|
|
@@ -332,14 +383,12 @@ The framework supports testing concurrent requests:
|
|
|
332
383
|
import asyncio
|
|
333
384
|
|
|
334
385
|
async with create_test_server() as server:
|
|
386
|
+
|
|
335
387
|
@server.app.get("/ping")
|
|
336
388
|
async def ping():
|
|
337
389
|
return {"status": "ok"}
|
|
338
390
|
|
|
339
|
-
responses = await asyncio.gather(*[
|
|
340
|
-
server.client.get("/ping")
|
|
341
|
-
for _ in range(5)
|
|
342
|
-
])
|
|
391
|
+
responses = await asyncio.gather(*[server.client.get("/ping") for _ in range(5)])
|
|
343
392
|
```
|
|
344
393
|
|
|
345
394
|
## Configuration
|
|
@@ -348,11 +397,72 @@ You can customize the server behavior:
|
|
|
348
397
|
|
|
349
398
|
```python
|
|
350
399
|
server = AsyncTestServer(
|
|
351
|
-
startup_timeout=30.0,
|
|
352
|
-
shutdown_timeout=10.0,
|
|
400
|
+
startup_timeout=30.0, # Seconds for lifespan startup plus the server becoming ready
|
|
401
|
+
shutdown_timeout=10.0, # Seconds open connections get to finish, and again for lifespan shutdown
|
|
353
402
|
)
|
|
354
403
|
```
|
|
355
404
|
|
|
405
|
+
`create_test_server()` accepts the same `startup_timeout` and `shutdown_timeout` arguments.
|
|
406
|
+
|
|
407
|
+
### Lifecycle guarantees
|
|
408
|
+
|
|
409
|
+
`AsyncTestServer` owns the whole lifecycle; uvicorn only serves connections:
|
|
410
|
+
|
|
411
|
+
- **Socket:** the server binds its own listening socket on `127.0.0.1` to a free port in the configured range, so no
|
|
412
|
+
other process can take the port between choosing and binding it. `stop()` always closes it.
|
|
413
|
+
- **Lifespan:** the application's lifespan runs in a task the server owns, through the full ASGI application (so
|
|
414
|
+
middleware sees it). State yielded by the lifespan reaches `request.state` and `websocket.state`. You can assign
|
|
415
|
+
`create_test_server(app=create_app())`, or assign `server.app = create_app()` before `start()`; its lifespan is the
|
|
416
|
+
one that runs.
|
|
417
|
+
- **Startup:** lifespan startup runs first, then the server starts serving. If either fails or takes longer than
|
|
418
|
+
`startup_timeout`, `start()` releases everything acquired so far and raises `ServerStartupError`, chained to the
|
|
419
|
+
application's own exception.
|
|
420
|
+
- **Shutdown:** `stop()` closes the client, stops accepting connections, gives open connections (for example SSE
|
|
421
|
+
streams) `shutdown_timeout` to finish and then closes them, runs the lifespan shutdown, closes the socket and
|
|
422
|
+
releases the port. If the lifespan shutdown fails or times out, `stop()` raises `ServerShutdownError` after all of
|
|
423
|
+
that is done. If `stop()` is cancelled or a step fails, the remaining steps still run, without waiting, before the
|
|
424
|
+
error propagates; on that path the lifespan is cancelled rather than shut down, so the code after its `yield` does
|
|
425
|
+
not run.
|
|
426
|
+
- **Errors from the test come first:** when the body of `async with create_test_server()` (or
|
|
427
|
+
`async with AsyncTestServer()`) raises, that exception is what the test reports. A `ServerShutdownError` from the
|
|
428
|
+
cleanup is attached to it as a note instead of replacing it, and a cancelled test stays cancelled.
|
|
429
|
+
- **Signals:** while serving, SIGINT and SIGTERM stop the server, as in uvicorn. Overlapping servers share the
|
|
430
|
+
process handlers correctly whatever order they stop in, and the original handlers come back when the last
|
|
431
|
+
server stops, so Ctrl-C keeps interrupting the test run.
|
|
432
|
+
|
|
433
|
+
### Global settings
|
|
434
|
+
|
|
435
|
+
Port range, HTTP connection limits, WebSocket limits and connection retries are set with a `Config`. Activate it
|
|
436
|
+
with `set_config()`, for example in `conftest.py`; it applies to every server and connection created afterwards.
|
|
437
|
+
WebSocket connects retry connection errors (refused, closed early, timed out) `ws_retry_attempts` times, `ws_retry_delay` seconds
|
|
438
|
+
apart; a rejected handshake such as a 403 or 404, or a TLS failure, fails at once. Values are checked when the `Config`
|
|
439
|
+
is made: sizes, limits and attempts must be at least 1 (`http_max_keepalive` at least 0), `ws_retry_delay` a finite
|
|
440
|
+
number of at least 0, and the port range from 1 to 65535 with the start not above the end; anything else raises
|
|
441
|
+
`ValueError`:
|
|
442
|
+
|
|
443
|
+
```python
|
|
444
|
+
from fastapi_testing import Config, set_config
|
|
445
|
+
|
|
446
|
+
set_config(Config(port_range_start=9000, port_range_end=9500, ws_retry_attempts=5))
|
|
447
|
+
|
|
448
|
+
# or read FASTAPI_TESTING_* environment variables, e.g. FASTAPI_TESTING_PORT_RANGE_START=9000.
|
|
449
|
+
# Unknown names and invalid values are ignored with a warning; strict=True raises ValueError instead.
|
|
450
|
+
set_config(Config.from_env(strict=True))
|
|
451
|
+
|
|
452
|
+
# or load a JSON or TOML file; pyproject.toml is read from its [tool.fastapi-testing] table
|
|
453
|
+
set_config(Config.from_file("pyproject.toml"))
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
```toml
|
|
457
|
+
[tool.fastapi-testing]
|
|
458
|
+
port_range_start = 9000
|
|
459
|
+
port_range_end = 9500
|
|
460
|
+
ws_max_message_size = 2097152
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
`get_config()` returns the active configuration. Assigning to an imported `global_config` name has no effect on the
|
|
464
|
+
library; use `set_config()` instead.
|
|
465
|
+
|
|
356
466
|
## Best Practices
|
|
357
467
|
|
|
358
468
|
1. Always use the async context manager (`create_test_server`) when possible
|
|
@@ -397,8 +507,11 @@ All tests follow modern async/await patterns and avoid mocks to ensure real-worl
|
|
|
397
507
|
|
|
398
508
|
The framework provides clear error messages for common issues:
|
|
399
509
|
|
|
400
|
-
- Server startup
|
|
401
|
-
|
|
510
|
+
- Server startup failures: if the app's lifespan startup raises, no port is free, or startup times out, `start()`
|
|
511
|
+
raises `ServerStartupError` (a `RuntimeError`), chained to the original exception, and releases everything
|
|
512
|
+
- Server shutdown failures: if the app's lifespan shutdown raises or hangs, `stop()` raises `ServerShutdownError`
|
|
513
|
+
(a `RuntimeError`) after releasing everything, so the test that caused it fails. If the test itself already
|
|
514
|
+
failed, its own exception is raised instead, with the shutdown error as a note
|
|
402
515
|
- Connection errors
|
|
403
516
|
- Invalid request formats
|
|
404
517
|
|