fastapi-testing 0.3.3__tar.gz → 0.5.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.
@@ -0,0 +1 @@
1
+ 3.13
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: fastapi-testing
3
- Version: 0.3.3
3
+ Version: 0.5.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.137.2
26
- Requires-Dist: httpx[http2]>=0.28.1
27
- Requires-Dist: starlette>=1.3.1
28
- Requires-Dist: uvicorn>=0.49.0
29
- Requires-Dist: websockets>=16.0
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,58 @@ 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 | the lifespan shutdown; in `"graceful"` mode also open connections finishing on stop |
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
+
189
+ ### Fast and graceful shutdown
190
+
191
+ `stop()` releases every resource in both modes: connections, in-flight requests, the application's lifespan shutdown,
192
+ the socket, the port and the signal handlers. The modes differ only in how long open connections get:
193
+
194
+ | `shutdown` | Open connections and in-flight requests | Cost of `stop()` |
195
+ |---|---|---|
196
+ | `"fast"` (default) | closed at once, which the application sees as its client disconnecting; requests still running after 0.5 s are cancelled | about a millisecond |
197
+ | `"graceful"` | stop accepting and give them `shutdown_timeout` to finish, as uvicorn does in production | about 200 ms (uvicorn's polling), or until they finish |
198
+
199
+ Fast suits test suites that start a server per test. Use graceful for a test that checks what the application does
200
+ while it shuts down, such as an in-flight request still completing:
201
+
202
+ ```python
203
+ async with create_test_server(shutdown="graceful") as server:
204
+ ...
205
+
206
+ set_config(Config(shutdown="graceful")) # or for every server: FASTAPI_TESTING_SHUTDOWN=graceful
207
+ ```
208
+
209
+ A streaming response (for example SSE) still open at stop ends the same way in both modes, and the same way as when
210
+ a browser closes it: Starlette cancels the stream, so cleanup in its generator runs but is cut short at its first
211
+ `await` unless it shields itself (`anyio.CancelScope(shield=True)`).
212
+
156
213
  ### AsyncTestClient
157
214
 
158
215
  The `AsyncTestClient` provides methods for making HTTP requests to your test server:
@@ -172,11 +229,33 @@ The `AsyncTestResponse` class provides convenient methods for assertions:
172
229
 
173
230
  ```python
174
231
  response = await server.client.get("/path")
175
- await response.expect_status(200) # Assert status code
176
- data = await response.json() # Get JSON response
177
- text = await response.text() # Get text response
232
+ await response.expect_status(200) # Raises AssertionError with the actual status and body, also under python -O
233
+ data = await response.json() # Get JSON response
234
+ text = await response.text() # Get text response
235
+ raw = response.httpx_response # The underlying httpx.Response, for anything else
178
236
  ```
179
237
 
238
+ ### Streaming Responses and Server-Sent Events
239
+
240
+ `client.stream()` makes a streaming request and yields the `httpx.Response` before its body is read. The response is
241
+ closed when the block exits, so breaking out of an endless stream is safe:
242
+
243
+ ```python
244
+ async with server.client.stream("GET", "/events") as response:
245
+ assert response.status_code == 200
246
+ async for line in response.aiter_lines():
247
+ if line.startswith("data:"):
248
+ ...
249
+ ```
250
+
251
+ ### The Server's Client
252
+
253
+ `server.client` is shared for the server's lifetime and closed by `stop()`. `async with server.client as client:`
254
+ does not close it, so it can be used any number of times in a test. A client you create yourself,
255
+ `async with AsyncTestClient(server.base_url) as client:`, is closed when the block exits. WebSocket connections opened
256
+ through `server.client` likewise stay open until you close them or `stop()` runs; close one explicitly with
257
+ `await ws_response.websocket().close()` when a test needs the server to see the disconnect.
258
+
180
259
  ### WebSocket Testing
181
260
 
182
261
  Test WebSocket endpoints with full protocol support:
@@ -209,11 +288,7 @@ async def test_mixed_protocols(test_server):
209
288
  assert http_response.status_code == 200
210
289
 
211
290
  # Configure WebSocket
212
- config = WebSocketConfig(
213
- subprotocols=["test-protocol"],
214
- ping_interval=20.0,
215
- ping_timeout=20.0
216
- )
291
+ config = WebSocketConfig(subprotocols=["test-protocol"], ping_interval=20.0, ping_timeout=20.0)
217
292
 
218
293
  # Test WebSocket endpoint
219
294
  ws_response = await test_server.client.websocket("/ws/echo", config)
@@ -249,17 +324,10 @@ json_data = await client.ws.receive_json(ws_response)
249
324
  binary = await client.ws.receive_binary(ws_response)
250
325
 
251
326
  # Message Expectations
252
- await client.ws.expect_message(
253
- ws_response,
254
- expected="message",
255
- timeout=1.0
256
- )
327
+ await client.ws.expect_message(ws_response, expected="message", timeout=1.0)
257
328
 
258
- # Collect Multiple Messages
259
- messages = await client.ws.drain_messages(
260
- ws_response,
261
- timeout=1.0
262
- )
329
+ # Collect messages until none arrives within the timeout or the server closes normally (an abnormal close raises)
330
+ messages = await client.ws.drain_messages(ws_response, timeout=1.0)
263
331
  ```
264
332
 
265
333
  #### WebSocket Configuration
@@ -269,37 +337,48 @@ Configure connections with various options:
269
337
  ```python
270
338
  ws_config = WebSocketConfig(
271
339
  subprotocols=["protocol"], # Supported subprotocols
272
- compression=None, # Compression algorithm
273
- extra_headers={}, # Additional headers
274
- ping_interval=20.0, # Keep-alive interval
275
- ping_timeout=20.0, # Ping timeout
276
- max_size=2 ** 20, # Max message size (1MB)
277
- max_queue=32, # Max queued messages
278
- timeout=30.0 # Connection timeout
340
+ compression=None, # Compression algorithm
341
+ extra_headers={}, # Additional headers
342
+ ping_interval=20.0, # Keep-alive interval
343
+ ping_timeout=20.0, # Ping timeout
344
+ max_size=2**20, # Max message size (1MB)
345
+ max_queue=32, # Max queued messages
346
+ timeout=30.0, # Connection timeout
279
347
  )
280
348
  ```
281
349
 
350
+ A field left as `None` uses the default: `max_size` and `max_queue` come from the active `Config`, everything else
351
+ from websockets. To pass `None` itself to websockets, for example to disable keepalive pings, use `options`:
352
+
353
+ ```python
354
+ ws_response = await server.client.websocket("/ws", options={"ping_interval": None})
355
+ ```
356
+
282
357
  ## Advanced Usage
283
358
 
284
359
  ### Advanced Server Configuration
285
360
 
286
- You can customize the server lifecycle using a reusable test fixture:
361
+ You can customize the server lifecycle using a reusable test fixture. The lifespan is an
362
+ `@asynccontextmanager` function, the form Starlette's `Lifespan` type describes, so type checkers
363
+ accept it:
287
364
 
288
365
  ```python
289
366
  @pytest.fixture
290
367
  async def test_server(
291
- test_settings: Settings,
292
- transaction_manager: TransactionManager
368
+ test_settings: Settings, transaction_manager: TransactionManager
293
369
  ) -> AsyncGenerator[AsyncTestServer, None]:
294
370
  """Create test server with overridden settings and database connection"""
295
371
 
296
- async def custom_lifespan(app: AppType) -> AsyncGenerator[None, Any]:
372
+ @asynccontextmanager
373
+ async def custom_lifespan(app: FastAPI) -> AsyncGenerator[None]:
297
374
  # Wire up test-specific dependencies
298
- app.dependency_overrides.update({
299
- get_settings: lambda: test_settings,
300
- get_transaction_manager: lambda: transaction_manager,
301
- get_db_pool: lambda: transaction_manager.pool
302
- })
375
+ app.dependency_overrides.update(
376
+ {
377
+ get_settings: lambda: test_settings,
378
+ get_transaction_manager: lambda: transaction_manager,
379
+ get_db_pool: lambda: transaction_manager.pool,
380
+ }
381
+ )
303
382
 
304
383
  yield # Server handles requests during this period
305
384
 
@@ -323,13 +402,10 @@ async def test_api(test_server: AsyncTestServer):
323
402
  # Make requests
324
403
  response = await test_server.client.get("/your-endpoint")
325
404
  await response.expect_status(200)
326
-
405
+
327
406
  # Test concurrent requests
328
- responses = await asyncio.gather(*[
329
- test_server.client.get("/endpoint")
330
- for _ in range(5)
331
- ])
332
-
407
+ responses = await asyncio.gather(*[test_server.client.get("/endpoint") for _ in range(5)])
408
+
333
409
  for response in responses:
334
410
  await response.expect_status(200)
335
411
  ```
@@ -342,6 +418,7 @@ You can define setup and cleanup operations using FastAPI's lifespan:
342
418
  from contextlib import asynccontextmanager
343
419
  from fastapi import FastAPI
344
420
 
421
+
345
422
  @asynccontextmanager
346
423
  async def lifespan(app: FastAPI):
347
424
  # Setup
@@ -350,6 +427,7 @@ async def lifespan(app: FastAPI):
350
427
  # Cleanup
351
428
  print("Shutting down server")
352
429
 
430
+
353
431
  async with create_test_server(lifespan=lifespan) as server:
354
432
  # Your test code here
355
433
  pass
@@ -363,14 +441,12 @@ The framework supports testing concurrent requests:
363
441
  import asyncio
364
442
 
365
443
  async with create_test_server() as server:
444
+
366
445
  @server.app.get("/ping")
367
446
  async def ping():
368
447
  return {"status": "ok"}
369
448
 
370
- responses = await asyncio.gather(*[
371
- server.client.get("/ping")
372
- for _ in range(5)
373
- ])
449
+ responses = await asyncio.gather(*[server.client.get("/ping") for _ in range(5)])
374
450
  ```
375
451
 
376
452
  ## Configuration
@@ -379,11 +455,73 @@ You can customize the server behavior:
379
455
 
380
456
  ```python
381
457
  server = AsyncTestServer(
382
- startup_timeout=30.0, # Seconds to wait for server startup
383
- shutdown_timeout=10.0, # Seconds to wait for server shutdown
458
+ startup_timeout=30.0, # Seconds for lifespan startup plus the server becoming ready
459
+ shutdown_timeout=10.0, # Seconds open connections get to finish, and again for lifespan shutdown
384
460
  )
385
461
  ```
386
462
 
463
+ `create_test_server()` accepts the same `startup_timeout` and `shutdown_timeout` arguments.
464
+
465
+ ### Lifecycle guarantees
466
+
467
+ `AsyncTestServer` owns the whole lifecycle; uvicorn only serves connections:
468
+
469
+ - **Socket:** the server binds its own listening socket on `127.0.0.1` to a free port in the configured range, so no
470
+ other process can take the port between choosing and binding it. `stop()` always closes it.
471
+ - **Lifespan:** the application's lifespan runs in a task the server owns, through the full ASGI application (so
472
+ middleware sees it). State yielded by the lifespan reaches `request.state` and `websocket.state`. You can assign
473
+ `create_test_server(app=create_app())`, or assign `server.app = create_app()` before `start()`; its lifespan is the
474
+ one that runs.
475
+ - **Startup:** lifespan startup runs first, then the server starts serving. If either fails or takes longer than
476
+ `startup_timeout`, `start()` releases everything acquired so far and raises `ServerStartupError`, chained to the
477
+ application's own exception.
478
+ - **Shutdown:** `stop()` closes the client, stops HTTP (in the default `"fast"` mode it closes open connections at
479
+ once; in `"graceful"` mode they get `shutdown_timeout` to finish, see
480
+ [Fast and graceful shutdown](#fast-and-graceful-shutdown)), runs the lifespan shutdown, closes the socket and
481
+ releases the port. If the lifespan shutdown fails or times out, `stop()` raises `ServerShutdownError` after all of
482
+ that is done. If `stop()` is cancelled or a step fails, the remaining steps still run, without waiting, before the
483
+ error propagates; on that path the lifespan is cancelled rather than shut down, so the code after its `yield` does
484
+ not run.
485
+ - **Errors from the test come first:** when the body of `async with create_test_server()` (or
486
+ `async with AsyncTestServer()`) raises, that exception is what the test reports. A `ServerShutdownError` from the
487
+ cleanup is attached to it as a note instead of replacing it, and a cancelled test stays cancelled.
488
+ - **Signals:** while serving, SIGINT and SIGTERM stop the server, as in uvicorn. Overlapping servers share the
489
+ process handlers correctly whatever order they stop in, and the original handlers come back when the last
490
+ server stops, so Ctrl-C keeps interrupting the test run.
491
+
492
+ ### Global settings
493
+
494
+ Port range, HTTP connection limits, WebSocket limits and connection retries are set with a `Config`. Activate it
495
+ with `set_config()`, for example in `conftest.py`; it applies to every server and connection created afterwards.
496
+ WebSocket connects retry connection errors (refused, closed early, timed out) `ws_retry_attempts` times, `ws_retry_delay` seconds
497
+ apart; a rejected handshake such as a 403 or 404, or a TLS failure, fails at once. Values are checked when the `Config`
498
+ is made: sizes, limits and attempts must be at least 1 (`http_max_keepalive` at least 0), `ws_retry_delay` a finite
499
+ number of at least 0, and the port range from 1 to 65535 with the start not above the end; anything else raises
500
+ `ValueError`:
501
+
502
+ ```python
503
+ from fastapi_testing import Config, set_config
504
+
505
+ set_config(Config(port_range_start=9000, port_range_end=9500, ws_retry_attempts=5))
506
+
507
+ # or read FASTAPI_TESTING_* environment variables, e.g. FASTAPI_TESTING_PORT_RANGE_START=9000.
508
+ # Unknown names and invalid values are ignored with a warning; strict=True raises ValueError instead.
509
+ set_config(Config.from_env(strict=True))
510
+
511
+ # or load a JSON or TOML file; pyproject.toml is read from its [tool.fastapi-testing] table
512
+ set_config(Config.from_file("pyproject.toml"))
513
+ ```
514
+
515
+ ```toml
516
+ [tool.fastapi-testing]
517
+ port_range_start = 9000
518
+ port_range_end = 9500
519
+ ws_max_message_size = 2097152
520
+ ```
521
+
522
+ `get_config()` returns the active configuration. Assigning to an imported `global_config` name has no effect on the
523
+ library; use `set_config()` instead.
524
+
387
525
  ## Best Practices
388
526
 
389
527
  1. Always use the async context manager (`create_test_server`) when possible
@@ -428,8 +566,11 @@ All tests follow modern async/await patterns and avoid mocks to ensure real-worl
428
566
 
429
567
  The framework provides clear error messages for common issues:
430
568
 
431
- - Server startup timeout
432
- - Port allocation failures
569
+ - Server startup failures: if the app's lifespan startup raises, no port is free, or startup times out, `start()`
570
+ raises `ServerStartupError` (a `RuntimeError`), chained to the original exception, and releases everything
571
+ - Server shutdown failures: if the app's lifespan shutdown raises or hangs, `stop()` raises `ServerShutdownError`
572
+ (a `RuntimeError`) after releasing everything, so the test that caused it fails. If the test itself already
573
+ failed, its own exception is raised instead, with the shutdown error as a note
433
574
  - Connection errors
434
575
  - Invalid request formats
435
576