fastapi-testing 0.4.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: fastapi-testing
3
- Version: 0.4.0
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
@@ -178,7 +178,7 @@ given, so passing both raises `ValueError`.
178
178
  | Parameter | Default | Bounds |
179
179
  |---|---|---|
180
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 |
181
+ | `shutdown_timeout` | 10 s | the lifespan shutdown; in `"graceful"` mode also open connections finishing on stop |
182
182
  | `client_timeout` | 30 s | each request with `server.client`, and opening its WebSocket connections |
183
183
 
184
184
  ```python
@@ -186,6 +186,30 @@ async with create_test_server(startup_timeout=60.0, client_timeout=5.0) as serve
186
186
  ...
187
187
  ```
188
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
+
189
213
  ### AsyncTestClient
190
214
 
191
215
  The `AsyncTestClient` provides methods for making HTTP requests to your test server:
@@ -451,8 +475,9 @@ server = AsyncTestServer(
451
475
  - **Startup:** lifespan startup runs first, then the server starts serving. If either fails or takes longer than
452
476
  `startup_timeout`, `start()` releases everything acquired so far and raises `ServerStartupError`, chained to the
453
477
  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
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
456
481
  releases the port. If the lifespan shutdown fails or times out, `stop()` raises `ServerShutdownError` after all of
457
482
  that is done. If `stop()` is cancelled or a step fails, the remaining steps still run, without waiting, before the
458
483
  error propagates; on that path the lifespan is cancelled rather than shut down, so the code after its `yield` does
@@ -144,7 +144,7 @@ given, so passing both raises `ValueError`.
144
144
  | Parameter | Default | Bounds |
145
145
  |---|---|---|
146
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 |
147
+ | `shutdown_timeout` | 10 s | the lifespan shutdown; in `"graceful"` mode also open connections finishing on stop |
148
148
  | `client_timeout` | 30 s | each request with `server.client`, and opening its WebSocket connections |
149
149
 
150
150
  ```python
@@ -152,6 +152,30 @@ async with create_test_server(startup_timeout=60.0, client_timeout=5.0) as serve
152
152
  ...
153
153
  ```
154
154
 
155
+ ### Fast and graceful shutdown
156
+
157
+ `stop()` releases every resource in both modes: connections, in-flight requests, the application's lifespan shutdown,
158
+ the socket, the port and the signal handlers. The modes differ only in how long open connections get:
159
+
160
+ | `shutdown` | Open connections and in-flight requests | Cost of `stop()` |
161
+ |---|---|---|
162
+ | `"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 |
163
+ | `"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 |
164
+
165
+ Fast suits test suites that start a server per test. Use graceful for a test that checks what the application does
166
+ while it shuts down, such as an in-flight request still completing:
167
+
168
+ ```python
169
+ async with create_test_server(shutdown="graceful") as server:
170
+ ...
171
+
172
+ set_config(Config(shutdown="graceful")) # or for every server: FASTAPI_TESTING_SHUTDOWN=graceful
173
+ ```
174
+
175
+ A streaming response (for example SSE) still open at stop ends the same way in both modes, and the same way as when
176
+ a browser closes it: Starlette cancels the stream, so cleanup in its generator runs but is cut short at its first
177
+ `await` unless it shields itself (`anyio.CancelScope(shield=True)`).
178
+
155
179
  ### AsyncTestClient
156
180
 
157
181
  The `AsyncTestClient` provides methods for making HTTP requests to your test server:
@@ -417,8 +441,9 @@ server = AsyncTestServer(
417
441
  - **Startup:** lifespan startup runs first, then the server starts serving. If either fails or takes longer than
418
442
  `startup_timeout`, `start()` releases everything acquired so far and raises `ServerStartupError`, chained to the
419
443
  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
444
+ - **Shutdown:** `stop()` closes the client, stops HTTP (in the default `"fast"` mode it closes open connections at
445
+ once; in `"graceful"` mode they get `shutdown_timeout` to finish, see
446
+ [Fast and graceful shutdown](#fast-and-graceful-shutdown)), runs the lifespan shutdown, closes the socket and
422
447
  releases the port. If the lifespan shutdown fails or times out, `stop()` raises `ServerShutdownError` after all of
423
448
  that is done. If `stop()` is cancelled or a step fails, the remaining steps still run, without waiting, before the
424
449
  error propagates; on that path the lifespan is cancelled rather than shut down, so the code after its `yield` does
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "fastapi-testing"
3
- version = "0.4.0"
3
+ version = "0.5.0"
4
4
  description = "A lightweight, async-first testing framework for FastAPI applications"
5
5
  authors = [
6
6
  { name = "Ove Ranheim", email = "oranheim@gmail.com" }
@@ -9,6 +9,7 @@ from fastapi_testing.async_fastapi_testing import (
9
9
  PortGenerator,
10
10
  ServerShutdownError,
11
11
  ServerStartupError,
12
+ ShutdownMode,
12
13
  UvicornTestServer,
13
14
  WebSocketConfig,
14
15
  WebSocketHelper,
@@ -30,6 +31,7 @@ __all__ = [
30
31
  "PortGenerator",
31
32
  "ServerShutdownError",
32
33
  "ServerStartupError",
34
+ "ShutdownMode",
33
35
  "UvicornTestServer",
34
36
  "WebSocketConfig",
35
37
  "WebSocketHelper",
@@ -16,7 +16,7 @@ from contextlib import asynccontextmanager, contextmanager, suppress
16
16
  from dataclasses import dataclass
17
17
  from pathlib import Path
18
18
  from types import FrameType, TracebackType
19
- from typing import Any, Self
19
+ from typing import Any, Literal, Self, get_args
20
20
 
21
21
  import httpx
22
22
  import uvicorn
@@ -41,6 +41,10 @@ DEFAULT_MAX_CONNS = 100
41
41
  DEFAULT_WS_RETRY_ATTEMPTS = 3
42
42
  DEFAULT_WS_RETRY_DELAY = 1.0
43
43
 
44
+ # How a server stops (see AsyncTestServer): "fast" closes open connections at
45
+ # once, "graceful" lets them finish first. Both release every resource.
46
+ ShutdownMode = Literal["fast", "graceful"]
47
+
44
48
 
45
49
  class Config:
46
50
  """Global configuration settings for fastapi-testing.
@@ -62,6 +66,7 @@ class Config:
62
66
  ws_retry_delay: float = DEFAULT_WS_RETRY_DELAY,
63
67
  port_range_start: int = 8001,
64
68
  port_range_end: int = 9000,
69
+ shutdown: ShutdownMode = "fast",
65
70
  ):
66
71
  for name, value in (
67
72
  ("ws_max_message_size", ws_max_message_size),
@@ -72,6 +77,7 @@ class Config:
72
77
  ("ws_retry_delay", ws_retry_delay),
73
78
  ("port_range_start", port_range_start),
74
79
  ("port_range_end", port_range_end),
80
+ ("shutdown", shutdown),
75
81
  ):
76
82
  problem = _out_of_range(name, value)
77
83
  if problem:
@@ -87,6 +93,7 @@ class Config:
87
93
  self.WS_RETRY_DELAY = ws_retry_delay
88
94
  self.PORT_RANGE_START = port_range_start
89
95
  self.PORT_RANGE_END = port_range_end
96
+ self.SHUTDOWN: ShutdownMode = shutdown
90
97
 
91
98
  @classmethod
92
99
  def from_env(cls, prefix: str = "FASTAPI_TESTING_", *, strict: bool = False) -> Self:
@@ -112,7 +119,7 @@ class Config:
112
119
  problems.append(f"{env_key}: unknown setting")
113
120
  continue
114
121
  try:
115
- value = kind(env_value)
122
+ value = env_value if _choices(kind) else kind(env_value)
116
123
  except ValueError:
117
124
  problems.append(f"{env_key}: must be {_describe(kind)}, got {env_value!r}")
118
125
  continue
@@ -173,7 +180,7 @@ class Config:
173
180
  for key, value in data.items():
174
181
  kind = _SETTINGS[key]
175
182
  # An integer is accepted for a float setting; a bool is not a number here.
176
- accepted = (int, float) if kind is float else kind
183
+ accepted = str if _choices(kind) else (int, float) if kind is float else kind
177
184
  if isinstance(value, bool) or not isinstance(value, accepted):
178
185
  raise ValueError(f"{path}: {key!r} must be {_describe(kind)}, got {value!r}")
179
186
  out_of_range = _out_of_range(key, value)
@@ -188,16 +195,25 @@ class Config:
188
195
  return cls(**data)
189
196
 
190
197
 
191
- # Setting name -> type, from the Config constructor (see Config). The annotations are not
192
- # checked statically; tests/test_config.py::TestSettingsSchema checks they are int or float.
193
- _SETTINGS: dict[str, type[int] | type[float]] = {
198
+ # Setting name -> type, from the Config constructor (see Config): int, float, or a Literal
199
+ # of allowed strings. The annotations are not checked statically;
200
+ # tests/test_config.py::TestSettingsSchema checks they are one of those.
201
+ _SETTINGS: dict[str, Any] = {
194
202
  name: parameter.annotation
195
203
  for name, parameter in inspect.signature(Config.__init__, eval_str=True).parameters.items()
196
204
  if name != "self"
197
205
  }
198
206
 
199
207
 
200
- def _describe(kind: type) -> str:
208
+ def _choices(kind: object) -> tuple[str, ...]:
209
+ """The allowed values of a Literal setting, or () for a number setting."""
210
+ return tuple(str(c) for c in get_args(kind)) if getattr(kind, "__origin__", None) is Literal else ()
211
+
212
+
213
+ def _describe(kind: object) -> str:
214
+ choices = _choices(kind)
215
+ if choices:
216
+ return "one of " + ", ".join(map(repr, choices))
201
217
  return "an integer" if kind is int else "a number"
202
218
 
203
219
 
@@ -220,6 +236,9 @@ _MINIMUMS: dict[str, float] = {"http_max_keepalive": 0, "ws_retry_delay": 0}
220
236
 
221
237
  def _out_of_range(name: str, value: object) -> str | None:
222
238
  """Why ``value`` is not acceptable for setting ``name``, or None when it is."""
239
+ choices = _choices(_SETTINGS.get(name))
240
+ if choices:
241
+ return None if value in choices else f"must be {_describe(_SETTINGS[name])}"
223
242
  if isinstance(value, bool) or not isinstance(value, (int, float)):
224
243
  return "must be a number"
225
244
  if name.startswith("port_range_"):
@@ -791,11 +810,13 @@ class UvicornTestServer(uvicorn.Server):
791
810
  yield
792
811
  finally:
793
812
  _signal_handlers.leave(self)
794
- # uvicorn's handle_exit() records the signals in this private attribute.
795
- # test_signal_stops_every_running_server_then_reaches_the_original_handler
796
- # fails if a uvicorn release changes that.
797
- for captured_signal in reversed(self._captured_signals):
798
- signal.raise_signal(captured_signal)
813
+ # Also when serve() is cancelled (a fast stop), so a signal received
814
+ # just before stop() is not lost. uvicorn's handle_exit() records the
815
+ # signals in this private attribute;
816
+ # test_signal_stops_every_running_server_then_reaches_the_original_handler
817
+ # fails if a uvicorn release changes that.
818
+ for captured_signal in reversed(self._captured_signals):
819
+ signal.raise_signal(captured_signal)
799
820
 
800
821
 
801
822
  class _LifespanRunner:
@@ -929,10 +950,10 @@ class AsyncTestServer:
929
950
  failures raise ``ServerStartupError`` chained to the application's own
930
951
  exception, a hung startup fails within ``startup_timeout``, and shutdown
931
952
  failures raise ``ServerShutdownError``.
932
- * ``stop()`` runs in a fixed order: close the client, stop HTTP (open
933
- connections get ``shutdown_timeout`` to finish, then are closed), run the
934
- lifespan shutdown, close the socket, release the port. Every step runs
935
- even when an earlier one fails or ``stop()`` is cancelled.
953
+ * ``stop()`` runs in a fixed order: close the client, stop HTTP (see
954
+ ``shutdown``), run the lifespan shutdown, close the socket, release the
955
+ port. Every step runs even when an earlier one fails or ``stop()`` is
956
+ cancelled.
936
957
 
937
958
  Args:
938
959
  lifespan: lifespan for the empty ``FastAPI`` app the server creates.
@@ -945,6 +966,12 @@ class AsyncTestServer:
945
966
  server creates an empty ``FastAPI`` app to add routes to.
946
967
  client_timeout: timeout in seconds for each request made with
947
968
  ``server.client`` and for opening its WebSocket connections.
969
+ shutdown: how ``stop()`` treats connections still open. ``"fast"``
970
+ closes them at once, as a client disconnect, and cancels requests
971
+ still running after ``request_grace``; ``"graceful"`` gives them
972
+ ``shutdown_timeout`` to finish, as uvicorn does. Both run the
973
+ lifespan shutdown and release every resource. ``None`` (the
974
+ default) uses the active ``Config`` (``"fast"`` unless changed).
948
975
 
949
976
  ``app`` may also be replaced (``server.app = create_app()``) before ``start()``.
950
977
  """
@@ -957,13 +984,19 @@ class AsyncTestServer:
957
984
  *,
958
985
  app: FastAPI | None = None,
959
986
  client_timeout: float = 30.0,
987
+ shutdown: ShutdownMode | None = None,
960
988
  ):
989
+ if shutdown is not None and shutdown not in get_args(ShutdownMode):
990
+ raise ValueError(
991
+ f"shutdown must be one of {', '.join(map(repr, get_args(ShutdownMode)))}, got {shutdown!r}"
992
+ )
961
993
  if app is not None and lifespan is not None:
962
994
  raise ValueError("Pass either app or lifespan: an application brings its own lifespan")
963
995
  self.app = app if app is not None else FastAPI(lifespan=lifespan)
964
996
  self.startup_timeout = startup_timeout
965
997
  self.shutdown_timeout = shutdown_timeout
966
998
  self.client_timeout = client_timeout
999
+ self.shutdown: ShutdownMode | None = shutdown
967
1000
  self._server_task: asyncio.Task[None] | None = None
968
1001
  self._port: int | None = None
969
1002
  self._host = "127.0.0.1"
@@ -971,6 +1004,9 @@ class AsyncTestServer:
971
1004
  self._server: UvicornTestServer | None = None
972
1005
  self._socket: socket.socket | None = None
973
1006
  self._lifespan: _LifespanRunner | None = None
1007
+ # Requests being handled, and whether a fast stop is ending them.
1008
+ self._requests: set[asyncio.Task[Any]] = set()
1009
+ self._aborting = False
974
1010
 
975
1011
  async def _asgi(self, scope: Scope, receive: Receive, send: Send) -> None:
976
1012
  """The ASGI entry point given to uvicorn.
@@ -981,7 +1017,20 @@ class AsyncTestServer:
981
1017
  """
982
1018
  if self._lifespan is not None and scope["type"] in ("http", "websocket"):
983
1019
  scope["state"] = {**self._lifespan.state, **scope.get("state", {})}
984
- await self.app(scope, receive, send)
1020
+ task = asyncio.current_task()
1021
+ if task is not None:
1022
+ self._requests.add(task)
1023
+ try:
1024
+ await self.app(scope, receive, send)
1025
+ except asyncio.CancelledError:
1026
+ if not self._aborting:
1027
+ raise
1028
+ # A fast stop ended this request after its connection was closed.
1029
+ # Returning (instead of raising) keeps uvicorn from logging it as an
1030
+ # application error; the task ends right after.
1031
+ finally:
1032
+ if task is not None:
1033
+ self._requests.discard(task)
985
1034
 
986
1035
  async def _serve(self) -> None:
987
1036
  """Run uvicorn, turning its ``sys.exit()`` on startup failure into an exception.
@@ -1008,6 +1057,7 @@ class AsyncTestServer:
1008
1057
  """
1009
1058
  if self._server_task is not None or self._lifespan is not None:
1010
1059
  raise RuntimeError("Server is already running")
1060
+ self._aborting = False
1011
1061
 
1012
1062
  loop = asyncio.get_running_loop()
1013
1063
  deadline = loop.time() + self.startup_timeout
@@ -1072,12 +1122,65 @@ class AsyncTestServer:
1072
1122
  await self.stop()
1073
1123
  raise
1074
1124
 
1125
+ def _shutdown_mode(self) -> ShutdownMode:
1126
+ return self.shutdown if self.shutdown is not None else global_config.SHUTDOWN
1127
+
1128
+ # How long a fast stop lets requests finish after their connections closed,
1129
+ # before cancelling them. Streaming responses (SSE) end as soon as they see
1130
+ # the disconnect, so this is normally not waited for at all.
1131
+ request_grace: float = 0.5
1132
+
1133
+ async def _stop_http_fast(self, server: "UvicornTestServer | None", task: asyncio.Task[None]) -> None:
1134
+ """Stop serving without uvicorn's graceful drain, releasing everything it would.
1135
+
1136
+ uvicorn's own shutdown spends about 200 ms in fixed polling sleeps even
1137
+ when nothing is open. Here, in order:
1138
+
1139
+ 1. Close the listening servers and stop the server task.
1140
+ 2. Close every open connection, which to the application is the client
1141
+ disconnecting: streaming handlers receive ``http.disconnect`` and end.
1142
+ 3. Wait for requests still running, at most ``request_grace`` seconds,
1143
+ then cancel the rest (quietly, see ``_asgi``) and wait for them.
1144
+ """
1145
+ if server is not None:
1146
+ server.should_exit = True
1147
+ server.force_exit = True
1148
+ # Stop accepting first, so no request starts after the snapshot below.
1149
+ # A server whose startup ended early may not have these yet.
1150
+ for listener in getattr(server, "servers", ()):
1151
+ listener.close()
1152
+ task.cancel()
1153
+ await asyncio.wait({task}, timeout=_LifespanRunner.cancel_timeout)
1154
+ if server is None:
1155
+ return
1156
+ # uvicorn tracks its protocol instances in server_state.connections; its own
1157
+ # shutdown() walks the same set. Closing the transport is a disconnect.
1158
+ for connection in list(getattr(getattr(server, "server_state", None), "connections", ())):
1159
+ transport = getattr(connection, "transport", None)
1160
+ if transport is not None:
1161
+ transport.close()
1162
+ requests = set(self._requests)
1163
+ if requests:
1164
+ _, running = await asyncio.wait(requests, timeout=self.request_grace)
1165
+ if running:
1166
+ self._aborting = True
1167
+ for request in running:
1168
+ request.cancel()
1169
+ _, stuck = await asyncio.wait(running, timeout=_LifespanRunner.cancel_timeout)
1170
+ if stuck:
1171
+ logger.warning("%d request(s) ignored cancellation at stop; leaving them", len(stuck))
1172
+ # Let the closed transports deliver connection_lost before the socket closes.
1173
+ await asyncio.sleep(0)
1174
+
1075
1175
  async def stop(self) -> None:
1076
1176
  """Stop the server and release every resource, in a fixed order.
1077
1177
 
1078
1178
  1. Close the client and its WebSocket connections.
1079
- 2. Stop HTTP: stop accepting, give open connections ``shutdown_timeout``
1080
- to finish, then close them (uvicorn's graceful shutdown).
1179
+ 2. Stop HTTP. ``"fast"`` (the default): close open connections at once,
1180
+ as a client disconnect, and cancel requests still running after
1181
+ ``request_grace``. ``"graceful"``: stop accepting and give open
1182
+ connections ``shutdown_timeout`` to finish (uvicorn's graceful
1183
+ shutdown), then close them.
1081
1184
  3. Run the application's lifespan shutdown, within ``shutdown_timeout``.
1082
1185
  4. Close the socket and release the port.
1083
1186
 
@@ -1101,7 +1204,9 @@ class AsyncTestServer:
1101
1204
  if client is not None:
1102
1205
  await client.close()
1103
1206
 
1104
- if task is not None:
1207
+ if task is not None and self._shutdown_mode() == "fast":
1208
+ await self._stop_http_fast(server, task)
1209
+ elif task is not None:
1105
1210
  if server is not None:
1106
1211
  server.should_exit = True
1107
1212
  # uvicorn bounds the connection wait by timeout_graceful_shutdown;
@@ -1205,6 +1310,7 @@ async def create_test_server(
1205
1310
  *,
1206
1311
  app: FastAPI | None = None,
1207
1312
  client_timeout: float = 30.0,
1313
+ shutdown: ShutdownMode | None = None,
1208
1314
  ) -> AsyncGenerator[AsyncTestServer, None]:
1209
1315
  """Start an ``AsyncTestServer``, yield it, and stop it when the block exits.
1210
1316
 
@@ -1217,6 +1323,7 @@ async def create_test_server(
1217
1323
  shutdown_timeout=shutdown_timeout,
1218
1324
  app=app,
1219
1325
  client_timeout=client_timeout,
1326
+ shutdown=shutdown,
1220
1327
  )
1221
1328
  await server.start() # releases everything itself when it fails
1222
1329
  try:
@@ -215,7 +215,7 @@ wheels = [
215
215
 
216
216
  [[package]]
217
217
  name = "fastapi-testing"
218
- version = "0.4.0"
218
+ version = "0.5.0"
219
219
  source = { editable = "." }
220
220
  dependencies = [
221
221
  { name = "fastapi" },
File without changes