fastapi-testing 0.3.2__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.
@@ -161,4 +161,8 @@ cython_debug/
161
161
  # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
162
  .idea/
163
163
 
164
+ # macOS
165
+ .DS_Store
166
+ **/.DS_Store
167
+
164
168
 
@@ -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.2
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.116.1
26
- Requires-Dist: httpx[http2]>=0.28.1
27
- Requires-Dist: starlette>=0.47.2
28
- Requires-Dist: uvicorn>=0.35.0
29
- Requires-Dist: websockets>=15.0.1
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) # Assert status code
176
- data = await response.json() # Get JSON response
177
- text = await response.text() # Get text response
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 Multiple Messages
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, # 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
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
- async def custom_lifespan(app: AppType) -> AsyncGenerator[None, Any]:
348
+ @asynccontextmanager
349
+ async def custom_lifespan(app: FastAPI) -> AsyncGenerator[None]:
297
350
  # 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
- })
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
- test_server.client.get("/endpoint")
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, # Seconds to wait for server startup
383
- shutdown_timeout=10.0, # Seconds to wait for server shutdown
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 timeout
432
- - Port allocation failures
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