fastapi-testing 0.3.0__py3-none-any.whl → 0.3.2__py3-none-any.whl
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/__init__.py +8 -8
- fastapi_testing/async_fastapi_testing.py +92 -117
- {fastapi_testing-0.3.0.dist-info → fastapi_testing-0.3.2.dist-info}/METADATA +39 -1
- fastapi_testing-0.3.2.dist-info/RECORD +6 -0
- fastapi_testing-0.3.0.dist-info/RECORD +0 -6
- {fastapi_testing-0.3.0.dist-info → fastapi_testing-0.3.2.dist-info}/WHEEL +0 -0
- {fastapi_testing-0.3.0.dist-info → fastapi_testing-0.3.2.dist-info}/licenses/LICENSE +0 -0
fastapi_testing/__init__.py
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
from fastapi_testing.async_fastapi_testing import (
|
|
2
|
+
AsyncTestClient,
|
|
3
|
+
AsyncTestResponse,
|
|
4
|
+
AsyncTestServer,
|
|
2
5
|
Config,
|
|
3
|
-
global_config,
|
|
4
6
|
InvalidResponseTypeError,
|
|
5
7
|
PortGenerator,
|
|
6
8
|
UvicornTestServer,
|
|
7
|
-
AsyncTestServer,
|
|
8
|
-
AsyncTestClient,
|
|
9
|
-
AsyncTestResponse,
|
|
10
9
|
WebSocketConfig,
|
|
11
10
|
WebSocketHelper,
|
|
12
11
|
create_test_server,
|
|
12
|
+
global_config,
|
|
13
13
|
)
|
|
14
14
|
|
|
15
15
|
__all__ = [
|
|
16
|
+
"AsyncTestClient",
|
|
17
|
+
"AsyncTestResponse",
|
|
18
|
+
"AsyncTestServer",
|
|
16
19
|
"Config",
|
|
17
|
-
"global_config",
|
|
18
20
|
"InvalidResponseTypeError",
|
|
19
21
|
"PortGenerator",
|
|
20
22
|
"UvicornTestServer",
|
|
21
|
-
"AsyncTestServer",
|
|
22
|
-
"AsyncTestClient",
|
|
23
|
-
"AsyncTestResponse",
|
|
24
23
|
"WebSocketConfig",
|
|
25
24
|
"WebSocketHelper",
|
|
26
25
|
"create_test_server",
|
|
26
|
+
"global_config",
|
|
27
27
|
]
|
|
@@ -2,9 +2,10 @@ import asyncio
|
|
|
2
2
|
import json
|
|
3
3
|
import logging
|
|
4
4
|
import os
|
|
5
|
-
from
|
|
5
|
+
from collections.abc import AsyncGenerator
|
|
6
|
+
from contextlib import asynccontextmanager, suppress
|
|
6
7
|
from dataclasses import dataclass
|
|
7
|
-
from typing import
|
|
8
|
+
from typing import Any
|
|
8
9
|
|
|
9
10
|
import httpx
|
|
10
11
|
import uvicorn
|
|
@@ -17,7 +18,7 @@ from websockets.protocol import State
|
|
|
17
18
|
logger = logging.getLogger(__name__)
|
|
18
19
|
|
|
19
20
|
# Configuration Constants
|
|
20
|
-
DEFAULT_WS_MESSAGE_SIZE = 2
|
|
21
|
+
DEFAULT_WS_MESSAGE_SIZE = 2**20 # 1MB
|
|
21
22
|
DEFAULT_WS_QUEUE_SIZE = 32
|
|
22
23
|
DEFAULT_KEEPALIVE_CONNS = 20
|
|
23
24
|
DEFAULT_MAX_CONNS = 100
|
|
@@ -31,15 +32,15 @@ class Config:
|
|
|
31
32
|
"""
|
|
32
33
|
|
|
33
34
|
def __init__(
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
35
|
+
self,
|
|
36
|
+
ws_max_message_size: int = DEFAULT_WS_MESSAGE_SIZE,
|
|
37
|
+
ws_max_queue_size: int = DEFAULT_WS_QUEUE_SIZE,
|
|
38
|
+
http_max_keepalive: int = DEFAULT_KEEPALIVE_CONNS,
|
|
39
|
+
http_max_connections: int = DEFAULT_MAX_CONNS,
|
|
40
|
+
ws_retry_attempts: int = DEFAULT_WS_RETRY_ATTEMPTS,
|
|
41
|
+
ws_retry_delay: float = DEFAULT_WS_RETRY_DELAY,
|
|
42
|
+
port_range_start: int = 8001,
|
|
43
|
+
port_range_end: int = 9000,
|
|
43
44
|
):
|
|
44
45
|
self.WS_MAX_MESSAGE_SIZE = ws_max_message_size
|
|
45
46
|
self.WS_MAX_QUEUE_SIZE = ws_max_queue_size
|
|
@@ -62,7 +63,7 @@ class Config:
|
|
|
62
63
|
# Convert to expected parameter names
|
|
63
64
|
config_params = {}
|
|
64
65
|
for env_key, env_value in env_vars.items():
|
|
65
|
-
config_key = env_key[len(prefix):].lower()
|
|
66
|
+
config_key = env_key[len(prefix) :].lower()
|
|
66
67
|
# Handle type conversion
|
|
67
68
|
if config_key in [
|
|
68
69
|
"ws_max_message_size",
|
|
@@ -71,17 +72,13 @@ class Config:
|
|
|
71
72
|
"http_max_connections",
|
|
72
73
|
"ws_retry_attempts",
|
|
73
74
|
"port_range_start",
|
|
74
|
-
"port_range_end"
|
|
75
|
+
"port_range_end",
|
|
75
76
|
]:
|
|
76
|
-
|
|
77
|
+
with suppress(ValueError):
|
|
77
78
|
config_params[config_key] = int(env_value)
|
|
78
|
-
except ValueError:
|
|
79
|
-
pass # Silently ignore invalid values
|
|
80
79
|
elif config_key == "ws_retry_delay":
|
|
81
|
-
|
|
80
|
+
with suppress(ValueError):
|
|
82
81
|
config_params[config_key] = float(env_value)
|
|
83
|
-
except ValueError:
|
|
84
|
-
pass
|
|
85
82
|
|
|
86
83
|
return cls(**config_params)
|
|
87
84
|
|
|
@@ -104,6 +101,7 @@ global_config = Config()
|
|
|
104
101
|
|
|
105
102
|
class InvalidResponseTypeError(Exception):
|
|
106
103
|
"""Exception raised when an operation is not supported for the response type."""
|
|
104
|
+
|
|
107
105
|
pass
|
|
108
106
|
|
|
109
107
|
|
|
@@ -121,38 +119,39 @@ class WebSocketConfig:
|
|
|
121
119
|
max_queue: Maximum number of queued messages
|
|
122
120
|
timeout: Connection timeout in seconds
|
|
123
121
|
"""
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
122
|
+
|
|
123
|
+
subprotocols: list[str] | None = None
|
|
124
|
+
compression: str | None = None
|
|
125
|
+
extra_headers: dict[str, str] | None = None
|
|
126
|
+
ping_interval: float | None = None
|
|
127
|
+
ping_timeout: float | None = None
|
|
129
128
|
max_size: int = global_config.WS_MAX_MESSAGE_SIZE
|
|
130
129
|
max_queue: int = global_config.WS_MAX_QUEUE_SIZE
|
|
131
|
-
timeout:
|
|
130
|
+
timeout: float | None = None
|
|
132
131
|
|
|
133
132
|
|
|
134
133
|
class PortGenerator:
|
|
135
|
-
"""Manages port allocation for test servers using configuration from global settings.
|
|
136
|
-
"""
|
|
134
|
+
"""Manages port allocation for test servers using configuration from global settings."""
|
|
137
135
|
|
|
138
|
-
def __init__(self, start:
|
|
136
|
+
def __init__(self, start: int | None = None, end: int | None = None):
|
|
139
137
|
if start is None:
|
|
140
138
|
start = global_config.PORT_RANGE_START
|
|
141
139
|
if end is None:
|
|
142
140
|
end = global_config.PORT_RANGE_END
|
|
143
141
|
self.start = start
|
|
144
142
|
self.end = end
|
|
145
|
-
self.used_ports:
|
|
143
|
+
self.used_ports: set[int] = set()
|
|
146
144
|
|
|
147
145
|
@staticmethod
|
|
148
146
|
def is_port_available(port: int) -> bool:
|
|
149
|
-
from contextlib import closing
|
|
150
147
|
import socket
|
|
148
|
+
from contextlib import closing
|
|
149
|
+
|
|
151
150
|
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
|
|
152
151
|
try:
|
|
153
|
-
sock.bind((
|
|
152
|
+
sock.bind(("localhost", port))
|
|
154
153
|
return True
|
|
155
|
-
except (
|
|
154
|
+
except (OSError, OverflowError):
|
|
156
155
|
return False
|
|
157
156
|
|
|
158
157
|
def get_port(self) -> int:
|
|
@@ -162,6 +161,7 @@ class PortGenerator:
|
|
|
162
161
|
raise RuntimeError(f"No available ports in range {self.start}-{self.end}")
|
|
163
162
|
|
|
164
163
|
import random
|
|
164
|
+
|
|
165
165
|
while available_ports:
|
|
166
166
|
port = random.choice(list(available_ports))
|
|
167
167
|
if self.is_port_available(port):
|
|
@@ -182,7 +182,7 @@ class AsyncTestResponse:
|
|
|
182
182
|
with proper type checking and error handling.
|
|
183
183
|
"""
|
|
184
184
|
|
|
185
|
-
def __init__(self, response:
|
|
185
|
+
def __init__(self, response: httpx.Response | ClientConnection):
|
|
186
186
|
self._response = response
|
|
187
187
|
self._is_websocket = isinstance(response, ClientConnection)
|
|
188
188
|
|
|
@@ -190,14 +190,16 @@ class AsyncTestResponse:
|
|
|
190
190
|
"""Get JSON response (HTTP only)."""
|
|
191
191
|
if self._is_websocket:
|
|
192
192
|
raise InvalidResponseTypeError(
|
|
193
|
-
"Cannot get JSON directly from WebSocket response. Use websocket() methods instead."
|
|
193
|
+
"Cannot get JSON directly from WebSocket response. Use websocket() methods instead."
|
|
194
|
+
)
|
|
194
195
|
return await asyncio.to_thread(self._response.json)
|
|
195
196
|
|
|
196
197
|
async def text(self) -> str:
|
|
197
198
|
"""Get text response (HTTP only)."""
|
|
198
199
|
if self._is_websocket:
|
|
199
200
|
raise InvalidResponseTypeError(
|
|
200
|
-
"Cannot get text directly from WebSocket response. Use websocket() methods instead."
|
|
201
|
+
"Cannot get text directly from WebSocket response. Use websocket() methods instead."
|
|
202
|
+
)
|
|
201
203
|
return await asyncio.to_thread(lambda: self._response.text)
|
|
202
204
|
|
|
203
205
|
@property
|
|
@@ -207,18 +209,26 @@ class AsyncTestResponse:
|
|
|
207
209
|
raise InvalidResponseTypeError("WebSocket connections don't have status codes")
|
|
208
210
|
return self._response.status_code
|
|
209
211
|
|
|
212
|
+
@property
|
|
213
|
+
def headers(self) -> httpx.Headers:
|
|
214
|
+
"""Get response headers (HTTP only)."""
|
|
215
|
+
if self._is_websocket:
|
|
216
|
+
raise InvalidResponseTypeError("WebSocket connections don't have headers")
|
|
217
|
+
return self._response.headers
|
|
218
|
+
|
|
210
219
|
def websocket(self) -> ClientConnection:
|
|
211
220
|
"""Get WebSocket connection (WebSocket only)."""
|
|
212
221
|
if not self._is_websocket:
|
|
213
222
|
raise InvalidResponseTypeError("This response is not a WebSocket connection")
|
|
214
223
|
return self._response
|
|
215
224
|
|
|
216
|
-
async def expect_status(self, status_code: int) ->
|
|
225
|
+
async def expect_status(self, status_code: int) -> "AsyncTestResponse":
|
|
217
226
|
"""Assert expected status code (HTTP only)."""
|
|
218
227
|
if self._is_websocket:
|
|
219
228
|
raise InvalidResponseTypeError("WebSocket connections don't have status codes")
|
|
220
|
-
assert self._response.status_code == status_code,
|
|
229
|
+
assert self._response.status_code == status_code, (
|
|
221
230
|
f"Expected status {status_code}, got {self._response.status_code}"
|
|
231
|
+
)
|
|
222
232
|
return self
|
|
223
233
|
|
|
224
234
|
|
|
@@ -272,15 +282,13 @@ class WebSocketHelper:
|
|
|
272
282
|
|
|
273
283
|
@staticmethod
|
|
274
284
|
async def expect_message(
|
|
275
|
-
|
|
276
|
-
expected: Union[str, dict, bytes],
|
|
277
|
-
timeout: Optional[float] = None
|
|
285
|
+
resp: AsyncTestResponse, expected: str | dict | bytes, timeout: float | None = None
|
|
278
286
|
) -> None:
|
|
279
287
|
"""Assert expected message is received within timeout."""
|
|
280
288
|
ws = resp.websocket()
|
|
281
289
|
try:
|
|
282
290
|
message = await asyncio.wait_for(ws.recv(), timeout)
|
|
283
|
-
except
|
|
291
|
+
except TimeoutError as e:
|
|
284
292
|
logger.error("Timed out waiting for message")
|
|
285
293
|
raise e
|
|
286
294
|
|
|
@@ -294,10 +302,7 @@ class WebSocketHelper:
|
|
|
294
302
|
raise AssertionError(f"Expected message {expected}, got {message}")
|
|
295
303
|
|
|
296
304
|
@staticmethod
|
|
297
|
-
async def drain_messages(
|
|
298
|
-
resp: AsyncTestResponse,
|
|
299
|
-
timeout: Optional[float] = 0.1
|
|
300
|
-
) -> List[Any]:
|
|
305
|
+
async def drain_messages(resp: AsyncTestResponse, timeout: float | None = 0.1) -> list[Any]:
|
|
301
306
|
"""Drain all pending messages from websocket queue."""
|
|
302
307
|
ws = resp.websocket()
|
|
303
308
|
messages = []
|
|
@@ -305,7 +310,7 @@ class WebSocketHelper:
|
|
|
305
310
|
while True:
|
|
306
311
|
message = await asyncio.wait_for(ws.recv(), timeout)
|
|
307
312
|
messages.append(message)
|
|
308
|
-
except
|
|
313
|
+
except TimeoutError:
|
|
309
314
|
pass
|
|
310
315
|
return messages
|
|
311
316
|
|
|
@@ -313,26 +318,17 @@ class WebSocketHelper:
|
|
|
313
318
|
class AsyncTestClient:
|
|
314
319
|
"""Async test client supporting both HTTP and WebSocket connections."""
|
|
315
320
|
|
|
316
|
-
def __init__(
|
|
317
|
-
|
|
318
|
-
base_url: str,
|
|
319
|
-
timeout: float = 30.0,
|
|
320
|
-
follow_redirects: bool = True
|
|
321
|
-
):
|
|
322
|
-
self._base_url = base_url.rstrip('/')
|
|
321
|
+
def __init__(self, base_url: str, timeout: float = 30.0, follow_redirects: bool = True):
|
|
322
|
+
self._base_url = base_url.rstrip("/")
|
|
323
323
|
self._timeout = timeout
|
|
324
|
-
self._websocket_connections:
|
|
324
|
+
self._websocket_connections: set[ClientConnection] = set()
|
|
325
325
|
|
|
326
326
|
limits = httpx.Limits(
|
|
327
327
|
max_keepalive_connections=global_config.HTTP_MAX_KEEPALIVE,
|
|
328
|
-
max_connections=global_config.HTTP_MAX_CONNECTIONS
|
|
328
|
+
max_connections=global_config.HTTP_MAX_CONNECTIONS,
|
|
329
329
|
)
|
|
330
330
|
self._client = httpx.AsyncClient(
|
|
331
|
-
base_url=self._base_url,
|
|
332
|
-
timeout=timeout,
|
|
333
|
-
follow_redirects=follow_redirects,
|
|
334
|
-
limits=limits,
|
|
335
|
-
http2=True
|
|
331
|
+
base_url=self._base_url, timeout=timeout, follow_redirects=follow_redirects, limits=limits, http2=True
|
|
336
332
|
)
|
|
337
333
|
|
|
338
334
|
self.ws = WebSocketHelper()
|
|
@@ -354,21 +350,13 @@ class AsyncTestClient:
|
|
|
354
350
|
if self._client:
|
|
355
351
|
await self._client.aclose()
|
|
356
352
|
|
|
357
|
-
async def request(
|
|
358
|
-
self,
|
|
359
|
-
method: str,
|
|
360
|
-
url: str,
|
|
361
|
-
**kwargs: Any
|
|
362
|
-
) -> AsyncTestResponse:
|
|
353
|
+
async def request(self, method: str, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
363
354
|
"""Make HTTP request."""
|
|
364
355
|
response = await self._client.request(method, url, **kwargs)
|
|
365
356
|
return AsyncTestResponse(response)
|
|
366
357
|
|
|
367
358
|
async def websocket(
|
|
368
|
-
|
|
369
|
-
path: str,
|
|
370
|
-
config: Optional[WebSocketConfig] = None,
|
|
371
|
-
options: Optional[Dict[str, Any]] = None
|
|
359
|
+
self, path: str, config: WebSocketConfig | None = None, options: dict[str, Any] | None = None
|
|
372
360
|
) -> AsyncTestResponse:
|
|
373
361
|
"""Create a websocket connection with configuration."""
|
|
374
362
|
if not (self._base_url.startswith("http://") or self._base_url.startswith("https://")):
|
|
@@ -380,25 +368,25 @@ class AsyncTestClient:
|
|
|
380
368
|
else:
|
|
381
369
|
ws_url = f"ws://{self._base_url}{path}"
|
|
382
370
|
|
|
383
|
-
connect_kwargs:
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
371
|
+
connect_kwargs: dict[str, Any] = {
|
|
372
|
+
"open_timeout": self._timeout,
|
|
373
|
+
"max_size": global_config.WS_MAX_MESSAGE_SIZE,
|
|
374
|
+
"max_queue": global_config.WS_MAX_QUEUE_SIZE,
|
|
387
375
|
}
|
|
388
376
|
|
|
389
377
|
if config:
|
|
390
378
|
if config.subprotocols:
|
|
391
|
-
connect_kwargs[
|
|
379
|
+
connect_kwargs["subprotocols"] = config.subprotocols
|
|
392
380
|
if config.compression:
|
|
393
|
-
connect_kwargs[
|
|
381
|
+
connect_kwargs["compression"] = config.compression
|
|
394
382
|
if config.extra_headers:
|
|
395
|
-
connect_kwargs[
|
|
383
|
+
connect_kwargs["additional_headers"] = config.extra_headers
|
|
396
384
|
if config.ping_interval:
|
|
397
|
-
connect_kwargs[
|
|
385
|
+
connect_kwargs["ping_interval"] = config.ping_interval
|
|
398
386
|
if config.ping_timeout:
|
|
399
|
-
connect_kwargs[
|
|
387
|
+
connect_kwargs["ping_timeout"] = config.ping_timeout
|
|
400
388
|
if config.timeout:
|
|
401
|
-
connect_kwargs[
|
|
389
|
+
connect_kwargs["open_timeout"] = config.timeout
|
|
402
390
|
|
|
403
391
|
if options:
|
|
404
392
|
connect_kwargs.update(options)
|
|
@@ -423,19 +411,19 @@ class AsyncTestClient:
|
|
|
423
411
|
return AsyncTestResponse(ws)
|
|
424
412
|
|
|
425
413
|
async def get(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
426
|
-
return await self.request(
|
|
414
|
+
return await self.request("GET", url, **kwargs)
|
|
427
415
|
|
|
428
416
|
async def post(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
429
|
-
return await self.request(
|
|
417
|
+
return await self.request("POST", url, **kwargs)
|
|
430
418
|
|
|
431
419
|
async def put(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
432
|
-
return await self.request(
|
|
420
|
+
return await self.request("PUT", url, **kwargs)
|
|
433
421
|
|
|
434
422
|
async def delete(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
435
|
-
return await self.request(
|
|
423
|
+
return await self.request("DELETE", url, **kwargs)
|
|
436
424
|
|
|
437
425
|
async def patch(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
438
|
-
return await self.request(
|
|
426
|
+
return await self.request("PATCH", url, **kwargs)
|
|
439
427
|
|
|
440
428
|
async def __aenter__(self) -> "AsyncTestClient":
|
|
441
429
|
return self
|
|
@@ -451,7 +439,7 @@ class UvicornTestServer(uvicorn.Server):
|
|
|
451
439
|
super().__init__(config)
|
|
452
440
|
self.startup_handler = startup_handler
|
|
453
441
|
|
|
454
|
-
async def startup(self, sockets:
|
|
442
|
+
async def startup(self, sockets: list | None = None) -> None:
|
|
455
443
|
"""Override startup to signal when ready."""
|
|
456
444
|
await super().startup(sockets=sockets)
|
|
457
445
|
self.startup_handler.set()
|
|
@@ -465,22 +453,22 @@ class AsyncTestServer:
|
|
|
465
453
|
"""Async test server with proper lifecycle management and WebSocket support."""
|
|
466
454
|
|
|
467
455
|
def __init__(
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
456
|
+
self,
|
|
457
|
+
lifespan: Lifespan[AppType] | None = None,
|
|
458
|
+
startup_timeout: float = 30.0,
|
|
459
|
+
shutdown_timeout: float = 10.0,
|
|
472
460
|
):
|
|
473
461
|
self.app = FastAPI(lifespan=lifespan)
|
|
474
462
|
self.startup_timeout = startup_timeout
|
|
475
463
|
self.shutdown_timeout = shutdown_timeout
|
|
476
464
|
self._startup_complete = asyncio.Event()
|
|
477
465
|
self._shutdown_complete = asyncio.Event()
|
|
478
|
-
self._server_task:
|
|
479
|
-
self._port:
|
|
466
|
+
self._server_task: asyncio.Task | None = None
|
|
467
|
+
self._port: int | None = None
|
|
480
468
|
self._host = "127.0.0.1"
|
|
481
|
-
self._client:
|
|
482
|
-
self._server:
|
|
483
|
-
self._websocket_tasks:
|
|
469
|
+
self._client: AsyncTestClient | None = None
|
|
470
|
+
self._server: UvicornTestServer | None = None
|
|
471
|
+
self._websocket_tasks: set[asyncio.Task] = set()
|
|
484
472
|
|
|
485
473
|
async def start(self) -> None:
|
|
486
474
|
"""Start the server asynchronously with proper lifecycle management."""
|
|
@@ -490,13 +478,7 @@ class AsyncTestServer:
|
|
|
490
478
|
self._port = _port_generator.get_port()
|
|
491
479
|
startup_handler = asyncio.Event()
|
|
492
480
|
|
|
493
|
-
config = uvicorn.Config(
|
|
494
|
-
app=self.app,
|
|
495
|
-
host=self._host,
|
|
496
|
-
port=self._port,
|
|
497
|
-
log_level="error",
|
|
498
|
-
loop="asyncio"
|
|
499
|
-
)
|
|
481
|
+
config = uvicorn.Config(app=self.app, host=self._host, port=self._port, log_level="error", loop="asyncio")
|
|
500
482
|
|
|
501
483
|
self._server = UvicornTestServer(config=config, startup_handler=startup_handler)
|
|
502
484
|
|
|
@@ -505,19 +487,14 @@ class AsyncTestServer:
|
|
|
505
487
|
try:
|
|
506
488
|
await asyncio.wait_for(startup_handler.wait(), timeout=self.startup_timeout)
|
|
507
489
|
|
|
508
|
-
self._client = AsyncTestClient(
|
|
509
|
-
base_url=self.base_url,
|
|
510
|
-
timeout=self.startup_timeout
|
|
511
|
-
)
|
|
490
|
+
self._client = AsyncTestClient(base_url=self.base_url, timeout=self.startup_timeout)
|
|
512
491
|
|
|
513
492
|
self._startup_complete.set()
|
|
514
493
|
|
|
515
|
-
except (
|
|
494
|
+
except (TimeoutError, Exception) as e:
|
|
516
495
|
await self.stop()
|
|
517
496
|
if isinstance(e, asyncio.TimeoutError):
|
|
518
|
-
raise RuntimeError(
|
|
519
|
-
f"Server startup timed out on host {self._host} and port {self._port}"
|
|
520
|
-
) from e
|
|
497
|
+
raise RuntimeError(f"Server startup timed out on host {self._host} and port {self._port}") from e
|
|
521
498
|
raise
|
|
522
499
|
|
|
523
500
|
async def stop(self) -> None:
|
|
@@ -543,10 +520,8 @@ class AsyncTestServer:
|
|
|
543
520
|
|
|
544
521
|
await asyncio.wait_for(self._server_task, timeout=self.shutdown_timeout)
|
|
545
522
|
|
|
546
|
-
except
|
|
547
|
-
logger.error(
|
|
548
|
-
f"Timeout waiting for server shutdown on host {self._host} port {self._port}"
|
|
549
|
-
)
|
|
523
|
+
except TimeoutError:
|
|
524
|
+
logger.error(f"Timeout waiting for server shutdown on host {self._host} port {self._port}")
|
|
550
525
|
if not self._server_task.done():
|
|
551
526
|
self._server_task.cancel()
|
|
552
527
|
await asyncio.gather(self._server_task, return_exceptions=True)
|
|
@@ -567,7 +542,7 @@ class AsyncTestServer:
|
|
|
567
542
|
raise RuntimeError("Server is not running")
|
|
568
543
|
return f"http://{self._host}:{self._port}"
|
|
569
544
|
|
|
570
|
-
async def __aenter__(self) ->
|
|
545
|
+
async def __aenter__(self) -> "AsyncTestServer":
|
|
571
546
|
await self.start()
|
|
572
547
|
return self
|
|
573
548
|
|
|
@@ -583,7 +558,7 @@ class AsyncTestServer:
|
|
|
583
558
|
|
|
584
559
|
@asynccontextmanager
|
|
585
560
|
async def create_test_server(
|
|
586
|
-
|
|
561
|
+
lifespan: Lifespan[AppType] | None = None,
|
|
587
562
|
) -> AsyncGenerator[AsyncTestServer, None]:
|
|
588
563
|
"""Create and manage a TestServer instance with proper lifecycle"""
|
|
589
564
|
server = AsyncTestServer(lifespan=lifespan)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fastapi-testing
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.2
|
|
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
|
|
@@ -31,6 +31,12 @@ Description-Content-Type: text/markdown
|
|
|
31
31
|
|
|
32
32
|
# FastAPI Testing
|
|
33
33
|
|
|
34
|
+
[](https://github.com/descoped/fastapi-testing/actions/workflows/build-test-native.yml)
|
|
35
|
+
[](https://codecov.io/gh/descoped/fastapi-testing)
|
|
36
|
+
[](https://www.python.org/downloads/)
|
|
37
|
+
[](https://opensource.org/licenses/MIT)
|
|
38
|
+
[](https://github.com/descoped/fastapi-testing/releases)
|
|
39
|
+
|
|
34
40
|
A lightweight, async-first testing framework designed specifically for FastAPI applications. This library provides a simple way to write integration tests for FastAPI applications with proper lifecycle management and async support.
|
|
35
41
|
|
|
36
42
|
## Features
|
|
@@ -386,6 +392,38 @@ server = AsyncTestServer(
|
|
|
386
392
|
4. Handle exceptions appropriately in your tests
|
|
387
393
|
5. Use type hints to catch potential issues early
|
|
388
394
|
|
|
395
|
+
## Testing
|
|
396
|
+
|
|
397
|
+
The framework itself is thoroughly tested with >88% code coverage, ensuring reliability for production use.
|
|
398
|
+
|
|
399
|
+
### Running Tests
|
|
400
|
+
|
|
401
|
+
```bash
|
|
402
|
+
# Run all tests
|
|
403
|
+
uv run pytest
|
|
404
|
+
|
|
405
|
+
# Run with coverage report
|
|
406
|
+
uv run pytest --cov=src/fastapi_testing --cov-report=term-missing
|
|
407
|
+
|
|
408
|
+
# Run specific test categories
|
|
409
|
+
uv run pytest tests/test_server.py # Server functionality
|
|
410
|
+
uv run pytest tests/test_websockets.py # WebSocket support
|
|
411
|
+
uv run pytest tests/test_config.py # Configuration tests
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
### Test Structure
|
|
415
|
+
|
|
416
|
+
The test suite includes:
|
|
417
|
+
|
|
418
|
+
- **Integration tests** - Real FastAPI applications with actual network connections
|
|
419
|
+
- **Configuration tests** - Environment variable loading and validation
|
|
420
|
+
- **Error handling tests** - Edge cases and failure scenarios
|
|
421
|
+
- **WebSocket tests** - Real-time bidirectional communication
|
|
422
|
+
- **Lifecycle tests** - Server startup, shutdown, and resource management
|
|
423
|
+
- **Concurrent request tests** - Multiple simultaneous connections
|
|
424
|
+
|
|
425
|
+
All tests follow modern async/await patterns and avoid mocks to ensure real-world reliability.
|
|
426
|
+
|
|
389
427
|
## Error Handling
|
|
390
428
|
|
|
391
429
|
The framework provides clear error messages for common issues:
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
fastapi_testing/__init__.py,sha256=Qgoq80ZJGV1TfLc2nzRuTnLcfbDHRAgOlKrHaY9ROZI,559
|
|
2
|
+
fastapi_testing/async_fastapi_testing.py,sha256=u24Q5svSt1U6i2kdUxDqD2U7ugRpkLQyLeCE_bfwnPo,20648
|
|
3
|
+
fastapi_testing-0.3.2.dist-info/METADATA,sha256=56t73XHdhHCJQigJt6srXtmpz3EsUbgqz5Ud7YVJZR4,13373
|
|
4
|
+
fastapi_testing-0.3.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
5
|
+
fastapi_testing-0.3.2.dist-info/licenses/LICENSE,sha256=FS7LYVt91OiPx9wiH1K3jAWLS90HpvzKnNAvW_XLeqo,1065
|
|
6
|
+
fastapi_testing-0.3.2.dist-info/RECORD,,
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
fastapi_testing/__init__.py,sha256=8mlZPt6aO4FOiULOJjgvlRfPg1UeYvcW_VrahF0cIuw,559
|
|
2
|
-
fastapi_testing/async_fastapi_testing.py,sha256=y5VASmvEXO64Ac5QdYVHczxTQdFBjgO5q3vFARi1dCQ,21066
|
|
3
|
-
fastapi_testing-0.3.0.dist-info/METADATA,sha256=tvJWT0aJZCRefbcWLLHB3XKbOD15LJgO17ZBlI5PPDs,11623
|
|
4
|
-
fastapi_testing-0.3.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
5
|
-
fastapi_testing-0.3.0.dist-info/licenses/LICENSE,sha256=FS7LYVt91OiPx9wiH1K3jAWLS90HpvzKnNAvW_XLeqo,1065
|
|
6
|
-
fastapi_testing-0.3.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|