fastapi-testing 0.2.2__py3-none-any.whl → 0.3.1__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 +85 -117
- {fastapi_testing-0.2.2.dist-info → fastapi_testing-0.3.1.dist-info}/METADATA +57 -14
- fastapi_testing-0.3.1.dist-info/RECORD +6 -0
- {fastapi_testing-0.2.2.dist-info → fastapi_testing-0.3.1.dist-info}/WHEEL +1 -1
- fastapi_testing-0.2.2.dist-info/RECORD +0 -6
- {fastapi_testing-0.2.2.dist-info → fastapi_testing-0.3.1.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
|
|
@@ -213,12 +215,13 @@ class AsyncTestResponse:
|
|
|
213
215
|
raise InvalidResponseTypeError("This response is not a WebSocket connection")
|
|
214
216
|
return self._response
|
|
215
217
|
|
|
216
|
-
async def expect_status(self, status_code: int) ->
|
|
218
|
+
async def expect_status(self, status_code: int) -> "AsyncTestResponse":
|
|
217
219
|
"""Assert expected status code (HTTP only)."""
|
|
218
220
|
if self._is_websocket:
|
|
219
221
|
raise InvalidResponseTypeError("WebSocket connections don't have status codes")
|
|
220
|
-
assert self._response.status_code == status_code,
|
|
222
|
+
assert self._response.status_code == status_code, (
|
|
221
223
|
f"Expected status {status_code}, got {self._response.status_code}"
|
|
224
|
+
)
|
|
222
225
|
return self
|
|
223
226
|
|
|
224
227
|
|
|
@@ -272,15 +275,13 @@ class WebSocketHelper:
|
|
|
272
275
|
|
|
273
276
|
@staticmethod
|
|
274
277
|
async def expect_message(
|
|
275
|
-
|
|
276
|
-
expected: Union[str, dict, bytes],
|
|
277
|
-
timeout: Optional[float] = None
|
|
278
|
+
resp: AsyncTestResponse, expected: str | dict | bytes, timeout: float | None = None
|
|
278
279
|
) -> None:
|
|
279
280
|
"""Assert expected message is received within timeout."""
|
|
280
281
|
ws = resp.websocket()
|
|
281
282
|
try:
|
|
282
283
|
message = await asyncio.wait_for(ws.recv(), timeout)
|
|
283
|
-
except
|
|
284
|
+
except TimeoutError as e:
|
|
284
285
|
logger.error("Timed out waiting for message")
|
|
285
286
|
raise e
|
|
286
287
|
|
|
@@ -294,10 +295,7 @@ class WebSocketHelper:
|
|
|
294
295
|
raise AssertionError(f"Expected message {expected}, got {message}")
|
|
295
296
|
|
|
296
297
|
@staticmethod
|
|
297
|
-
async def drain_messages(
|
|
298
|
-
resp: AsyncTestResponse,
|
|
299
|
-
timeout: Optional[float] = 0.1
|
|
300
|
-
) -> List[Any]:
|
|
298
|
+
async def drain_messages(resp: AsyncTestResponse, timeout: float | None = 0.1) -> list[Any]:
|
|
301
299
|
"""Drain all pending messages from websocket queue."""
|
|
302
300
|
ws = resp.websocket()
|
|
303
301
|
messages = []
|
|
@@ -305,7 +303,7 @@ class WebSocketHelper:
|
|
|
305
303
|
while True:
|
|
306
304
|
message = await asyncio.wait_for(ws.recv(), timeout)
|
|
307
305
|
messages.append(message)
|
|
308
|
-
except
|
|
306
|
+
except TimeoutError:
|
|
309
307
|
pass
|
|
310
308
|
return messages
|
|
311
309
|
|
|
@@ -313,26 +311,17 @@ class WebSocketHelper:
|
|
|
313
311
|
class AsyncTestClient:
|
|
314
312
|
"""Async test client supporting both HTTP and WebSocket connections."""
|
|
315
313
|
|
|
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('/')
|
|
314
|
+
def __init__(self, base_url: str, timeout: float = 30.0, follow_redirects: bool = True):
|
|
315
|
+
self._base_url = base_url.rstrip("/")
|
|
323
316
|
self._timeout = timeout
|
|
324
|
-
self._websocket_connections:
|
|
317
|
+
self._websocket_connections: set[ClientConnection] = set()
|
|
325
318
|
|
|
326
319
|
limits = httpx.Limits(
|
|
327
320
|
max_keepalive_connections=global_config.HTTP_MAX_KEEPALIVE,
|
|
328
|
-
max_connections=global_config.HTTP_MAX_CONNECTIONS
|
|
321
|
+
max_connections=global_config.HTTP_MAX_CONNECTIONS,
|
|
329
322
|
)
|
|
330
323
|
self._client = httpx.AsyncClient(
|
|
331
|
-
base_url=self._base_url,
|
|
332
|
-
timeout=timeout,
|
|
333
|
-
follow_redirects=follow_redirects,
|
|
334
|
-
limits=limits,
|
|
335
|
-
http2=True
|
|
324
|
+
base_url=self._base_url, timeout=timeout, follow_redirects=follow_redirects, limits=limits, http2=True
|
|
336
325
|
)
|
|
337
326
|
|
|
338
327
|
self.ws = WebSocketHelper()
|
|
@@ -354,21 +343,13 @@ class AsyncTestClient:
|
|
|
354
343
|
if self._client:
|
|
355
344
|
await self._client.aclose()
|
|
356
345
|
|
|
357
|
-
async def request(
|
|
358
|
-
self,
|
|
359
|
-
method: str,
|
|
360
|
-
url: str,
|
|
361
|
-
**kwargs: Any
|
|
362
|
-
) -> AsyncTestResponse:
|
|
346
|
+
async def request(self, method: str, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
363
347
|
"""Make HTTP request."""
|
|
364
348
|
response = await self._client.request(method, url, **kwargs)
|
|
365
349
|
return AsyncTestResponse(response)
|
|
366
350
|
|
|
367
351
|
async def websocket(
|
|
368
|
-
|
|
369
|
-
path: str,
|
|
370
|
-
config: Optional[WebSocketConfig] = None,
|
|
371
|
-
options: Optional[Dict[str, Any]] = None
|
|
352
|
+
self, path: str, config: WebSocketConfig | None = None, options: dict[str, Any] | None = None
|
|
372
353
|
) -> AsyncTestResponse:
|
|
373
354
|
"""Create a websocket connection with configuration."""
|
|
374
355
|
if not (self._base_url.startswith("http://") or self._base_url.startswith("https://")):
|
|
@@ -380,25 +361,25 @@ class AsyncTestClient:
|
|
|
380
361
|
else:
|
|
381
362
|
ws_url = f"ws://{self._base_url}{path}"
|
|
382
363
|
|
|
383
|
-
connect_kwargs:
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
364
|
+
connect_kwargs: dict[str, Any] = {
|
|
365
|
+
"open_timeout": self._timeout,
|
|
366
|
+
"max_size": global_config.WS_MAX_MESSAGE_SIZE,
|
|
367
|
+
"max_queue": global_config.WS_MAX_QUEUE_SIZE,
|
|
387
368
|
}
|
|
388
369
|
|
|
389
370
|
if config:
|
|
390
371
|
if config.subprotocols:
|
|
391
|
-
connect_kwargs[
|
|
372
|
+
connect_kwargs["subprotocols"] = config.subprotocols
|
|
392
373
|
if config.compression:
|
|
393
|
-
connect_kwargs[
|
|
374
|
+
connect_kwargs["compression"] = config.compression
|
|
394
375
|
if config.extra_headers:
|
|
395
|
-
connect_kwargs[
|
|
376
|
+
connect_kwargs["additional_headers"] = config.extra_headers
|
|
396
377
|
if config.ping_interval:
|
|
397
|
-
connect_kwargs[
|
|
378
|
+
connect_kwargs["ping_interval"] = config.ping_interval
|
|
398
379
|
if config.ping_timeout:
|
|
399
|
-
connect_kwargs[
|
|
380
|
+
connect_kwargs["ping_timeout"] = config.ping_timeout
|
|
400
381
|
if config.timeout:
|
|
401
|
-
connect_kwargs[
|
|
382
|
+
connect_kwargs["open_timeout"] = config.timeout
|
|
402
383
|
|
|
403
384
|
if options:
|
|
404
385
|
connect_kwargs.update(options)
|
|
@@ -423,19 +404,19 @@ class AsyncTestClient:
|
|
|
423
404
|
return AsyncTestResponse(ws)
|
|
424
405
|
|
|
425
406
|
async def get(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
426
|
-
return await self.request(
|
|
407
|
+
return await self.request("GET", url, **kwargs)
|
|
427
408
|
|
|
428
409
|
async def post(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
429
|
-
return await self.request(
|
|
410
|
+
return await self.request("POST", url, **kwargs)
|
|
430
411
|
|
|
431
412
|
async def put(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
432
|
-
return await self.request(
|
|
413
|
+
return await self.request("PUT", url, **kwargs)
|
|
433
414
|
|
|
434
415
|
async def delete(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
435
|
-
return await self.request(
|
|
416
|
+
return await self.request("DELETE", url, **kwargs)
|
|
436
417
|
|
|
437
418
|
async def patch(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
438
|
-
return await self.request(
|
|
419
|
+
return await self.request("PATCH", url, **kwargs)
|
|
439
420
|
|
|
440
421
|
async def __aenter__(self) -> "AsyncTestClient":
|
|
441
422
|
return self
|
|
@@ -451,7 +432,7 @@ class UvicornTestServer(uvicorn.Server):
|
|
|
451
432
|
super().__init__(config)
|
|
452
433
|
self.startup_handler = startup_handler
|
|
453
434
|
|
|
454
|
-
async def startup(self, sockets:
|
|
435
|
+
async def startup(self, sockets: list | None = None) -> None:
|
|
455
436
|
"""Override startup to signal when ready."""
|
|
456
437
|
await super().startup(sockets=sockets)
|
|
457
438
|
self.startup_handler.set()
|
|
@@ -465,22 +446,22 @@ class AsyncTestServer:
|
|
|
465
446
|
"""Async test server with proper lifecycle management and WebSocket support."""
|
|
466
447
|
|
|
467
448
|
def __init__(
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
449
|
+
self,
|
|
450
|
+
lifespan: Lifespan[AppType] | None = None,
|
|
451
|
+
startup_timeout: float = 30.0,
|
|
452
|
+
shutdown_timeout: float = 10.0,
|
|
472
453
|
):
|
|
473
454
|
self.app = FastAPI(lifespan=lifespan)
|
|
474
455
|
self.startup_timeout = startup_timeout
|
|
475
456
|
self.shutdown_timeout = shutdown_timeout
|
|
476
457
|
self._startup_complete = asyncio.Event()
|
|
477
458
|
self._shutdown_complete = asyncio.Event()
|
|
478
|
-
self._server_task:
|
|
479
|
-
self._port:
|
|
459
|
+
self._server_task: asyncio.Task | None = None
|
|
460
|
+
self._port: int | None = None
|
|
480
461
|
self._host = "127.0.0.1"
|
|
481
|
-
self._client:
|
|
482
|
-
self._server:
|
|
483
|
-
self._websocket_tasks:
|
|
462
|
+
self._client: AsyncTestClient | None = None
|
|
463
|
+
self._server: UvicornTestServer | None = None
|
|
464
|
+
self._websocket_tasks: set[asyncio.Task] = set()
|
|
484
465
|
|
|
485
466
|
async def start(self) -> None:
|
|
486
467
|
"""Start the server asynchronously with proper lifecycle management."""
|
|
@@ -490,13 +471,7 @@ class AsyncTestServer:
|
|
|
490
471
|
self._port = _port_generator.get_port()
|
|
491
472
|
startup_handler = asyncio.Event()
|
|
492
473
|
|
|
493
|
-
config = uvicorn.Config(
|
|
494
|
-
app=self.app,
|
|
495
|
-
host=self._host,
|
|
496
|
-
port=self._port,
|
|
497
|
-
log_level="error",
|
|
498
|
-
loop="asyncio"
|
|
499
|
-
)
|
|
474
|
+
config = uvicorn.Config(app=self.app, host=self._host, port=self._port, log_level="error", loop="asyncio")
|
|
500
475
|
|
|
501
476
|
self._server = UvicornTestServer(config=config, startup_handler=startup_handler)
|
|
502
477
|
|
|
@@ -505,19 +480,14 @@ class AsyncTestServer:
|
|
|
505
480
|
try:
|
|
506
481
|
await asyncio.wait_for(startup_handler.wait(), timeout=self.startup_timeout)
|
|
507
482
|
|
|
508
|
-
self._client = AsyncTestClient(
|
|
509
|
-
base_url=self.base_url,
|
|
510
|
-
timeout=self.startup_timeout
|
|
511
|
-
)
|
|
483
|
+
self._client = AsyncTestClient(base_url=self.base_url, timeout=self.startup_timeout)
|
|
512
484
|
|
|
513
485
|
self._startup_complete.set()
|
|
514
486
|
|
|
515
|
-
except (
|
|
487
|
+
except (TimeoutError, Exception) as e:
|
|
516
488
|
await self.stop()
|
|
517
489
|
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
|
|
490
|
+
raise RuntimeError(f"Server startup timed out on host {self._host} and port {self._port}") from e
|
|
521
491
|
raise
|
|
522
492
|
|
|
523
493
|
async def stop(self) -> None:
|
|
@@ -543,10 +513,8 @@ class AsyncTestServer:
|
|
|
543
513
|
|
|
544
514
|
await asyncio.wait_for(self._server_task, timeout=self.shutdown_timeout)
|
|
545
515
|
|
|
546
|
-
except
|
|
547
|
-
logger.error(
|
|
548
|
-
f"Timeout waiting for server shutdown on host {self._host} port {self._port}"
|
|
549
|
-
)
|
|
516
|
+
except TimeoutError:
|
|
517
|
+
logger.error(f"Timeout waiting for server shutdown on host {self._host} port {self._port}")
|
|
550
518
|
if not self._server_task.done():
|
|
551
519
|
self._server_task.cancel()
|
|
552
520
|
await asyncio.gather(self._server_task, return_exceptions=True)
|
|
@@ -567,7 +535,7 @@ class AsyncTestServer:
|
|
|
567
535
|
raise RuntimeError("Server is not running")
|
|
568
536
|
return f"http://{self._host}:{self._port}"
|
|
569
537
|
|
|
570
|
-
async def __aenter__(self) ->
|
|
538
|
+
async def __aenter__(self) -> "AsyncTestServer":
|
|
571
539
|
await self.start()
|
|
572
540
|
return self
|
|
573
541
|
|
|
@@ -583,7 +551,7 @@ class AsyncTestServer:
|
|
|
583
551
|
|
|
584
552
|
@asynccontextmanager
|
|
585
553
|
async def create_test_server(
|
|
586
|
-
|
|
554
|
+
lifespan: Lifespan[AppType] | None = None,
|
|
587
555
|
) -> AsyncGenerator[AsyncTestServer, None]:
|
|
588
556
|
"""Create and manage a TestServer instance with proper lifecycle"""
|
|
589
557
|
server = AsyncTestServer(lifespan=lifespan)
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: fastapi-testing
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.1
|
|
4
4
|
Summary: A lightweight, async-first testing framework for FastAPI applications
|
|
5
|
+
Project-URL: Homepage, https://github.com/descoped/fastapi-testing
|
|
6
|
+
Project-URL: Repository, https://github.com/descoped/fastapi-testing
|
|
7
|
+
Project-URL: Issues, https://github.com/descoped/fastapi-testing/issues
|
|
8
|
+
Author-email: Ove Ranheim <oranheim@gmail.com>
|
|
5
9
|
License: MIT
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
Author-email: oranheim@gmail.com
|
|
9
|
-
Requires-Python: >=3.11,<4.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: async,fastapi,integration-testing,pytest,test-framework,testing
|
|
10
12
|
Classifier: Development Status :: 5 - Production/Stable
|
|
11
13
|
Classifier: Framework :: FastAPI
|
|
12
14
|
Classifier: Intended Audience :: Developers
|
|
@@ -19,17 +21,22 @@ Classifier: Programming Language :: Python :: 3.13
|
|
|
19
21
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
22
|
Classifier: Topic :: Software Development :: Testing
|
|
21
23
|
Classifier: Typing :: Typed
|
|
22
|
-
Requires-
|
|
23
|
-
Requires-Dist:
|
|
24
|
-
Requires-Dist:
|
|
25
|
-
Requires-Dist:
|
|
26
|
-
Requires-Dist:
|
|
27
|
-
|
|
28
|
-
Project-URL: Repository, https://github.com/descoped/fastapi-testing
|
|
24
|
+
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
|
|
29
30
|
Description-Content-Type: text/markdown
|
|
30
31
|
|
|
31
32
|
# FastAPI Testing
|
|
32
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
|
+
|
|
33
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.
|
|
34
41
|
|
|
35
42
|
## Features
|
|
@@ -44,6 +51,11 @@ A lightweight, async-first testing framework designed specifically for FastAPI a
|
|
|
44
51
|
|
|
45
52
|
## Installation
|
|
46
53
|
|
|
54
|
+
```bash
|
|
55
|
+
uv add fastapi-testing
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Or with pip:
|
|
47
59
|
```bash
|
|
48
60
|
pip install fastapi-testing
|
|
49
61
|
```
|
|
@@ -380,6 +392,38 @@ server = AsyncTestServer(
|
|
|
380
392
|
4. Handle exceptions appropriately in your tests
|
|
381
393
|
5. Use type hints to catch potential issues early
|
|
382
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
|
+
|
|
383
427
|
## Error Handling
|
|
384
428
|
|
|
385
429
|
The framework provides clear error messages for common issues:
|
|
@@ -398,4 +442,3 @@ The framework provides clear error messages for common issues:
|
|
|
398
442
|
## Contributing
|
|
399
443
|
|
|
400
444
|
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
401
|
-
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
fastapi_testing/__init__.py,sha256=Qgoq80ZJGV1TfLc2nzRuTnLcfbDHRAgOlKrHaY9ROZI,559
|
|
2
|
+
fastapi_testing/async_fastapi_testing.py,sha256=lS7OUJUgfYH3KMfBt9XusBE_ry3UnM2ZtiKdaYV-NG4,20389
|
|
3
|
+
fastapi_testing-0.3.1.dist-info/METADATA,sha256=2_zt4RK0Af0QMMN3yiHIqg6T85JsZF0Ocro6HJSCgDg,13373
|
|
4
|
+
fastapi_testing-0.3.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
5
|
+
fastapi_testing-0.3.1.dist-info/licenses/LICENSE,sha256=FS7LYVt91OiPx9wiH1K3jAWLS90HpvzKnNAvW_XLeqo,1065
|
|
6
|
+
fastapi_testing-0.3.1.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.2.2.dist-info/LICENSE,sha256=FS7LYVt91OiPx9wiH1K3jAWLS90HpvzKnNAvW_XLeqo,1065
|
|
4
|
-
fastapi_testing-0.2.2.dist-info/METADATA,sha256=e6iVWNhZSVzeGGA9JHudBxJFW7M6n3Uoh2O0WFXR1fQ,11544
|
|
5
|
-
fastapi_testing-0.2.2.dist-info/WHEEL,sha256=IYZQI976HJqqOpQU6PHkJ8fb3tMNBFjg-Cn-pwAbaFM,88
|
|
6
|
-
fastapi_testing-0.2.2.dist-info/RECORD,,
|
|
File without changes
|