fastapi-testing 0.2.0__py3-none-any.whl → 0.2.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 +10 -0
- fastapi_testing/async_fastapi_testing.py +432 -94
- fastapi_testing-0.2.2.dist-info/METADATA +401 -0
- fastapi_testing-0.2.2.dist-info/RECORD +6 -0
- fastapi_testing-0.2.0.dist-info/METADATA +0 -231
- fastapi_testing-0.2.0.dist-info/RECORD +0 -6
- {fastapi_testing-0.2.0.dist-info → fastapi_testing-0.2.2.dist-info}/LICENSE +0 -0
- {fastapi_testing-0.2.0.dist-info → fastapi_testing-0.2.2.dist-info}/WHEEL +0 -0
fastapi_testing/__init__.py
CHANGED
|
@@ -1,17 +1,27 @@
|
|
|
1
1
|
from fastapi_testing.async_fastapi_testing import (
|
|
2
|
+
Config,
|
|
3
|
+
global_config,
|
|
4
|
+
InvalidResponseTypeError,
|
|
2
5
|
PortGenerator,
|
|
3
6
|
UvicornTestServer,
|
|
4
7
|
AsyncTestServer,
|
|
5
8
|
AsyncTestClient,
|
|
6
9
|
AsyncTestResponse,
|
|
10
|
+
WebSocketConfig,
|
|
11
|
+
WebSocketHelper,
|
|
7
12
|
create_test_server,
|
|
8
13
|
)
|
|
9
14
|
|
|
10
15
|
__all__ = [
|
|
16
|
+
"Config",
|
|
17
|
+
"global_config",
|
|
18
|
+
"InvalidResponseTypeError",
|
|
11
19
|
"PortGenerator",
|
|
12
20
|
"UvicornTestServer",
|
|
13
21
|
"AsyncTestServer",
|
|
14
22
|
"AsyncTestClient",
|
|
15
23
|
"AsyncTestResponse",
|
|
24
|
+
"WebSocketConfig",
|
|
25
|
+
"WebSocketHelper",
|
|
16
26
|
"create_test_server",
|
|
17
27
|
]
|
|
@@ -1,26 +1,153 @@
|
|
|
1
1
|
import asyncio
|
|
2
|
+
import json
|
|
2
3
|
import logging
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
from
|
|
6
|
-
from typing import List, Optional,
|
|
4
|
+
import os
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import List, Optional, Any, Set, AsyncGenerator, Dict, Union
|
|
7
8
|
|
|
8
9
|
import httpx
|
|
9
10
|
import uvicorn
|
|
10
11
|
from fastapi import FastAPI
|
|
11
12
|
from fastapi.applications import AppType
|
|
12
13
|
from starlette.types import Lifespan
|
|
14
|
+
from websockets.asyncio.client import ClientConnection, connect
|
|
15
|
+
from websockets.protocol import State
|
|
13
16
|
|
|
14
17
|
logger = logging.getLogger(__name__)
|
|
15
18
|
|
|
19
|
+
# Configuration Constants
|
|
20
|
+
DEFAULT_WS_MESSAGE_SIZE = 2 ** 20 # 1MB
|
|
21
|
+
DEFAULT_WS_QUEUE_SIZE = 32
|
|
22
|
+
DEFAULT_KEEPALIVE_CONNS = 20
|
|
23
|
+
DEFAULT_MAX_CONNS = 100
|
|
24
|
+
DEFAULT_WS_RETRY_ATTEMPTS = 3
|
|
25
|
+
DEFAULT_WS_RETRY_DELAY = 1.0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Config:
|
|
29
|
+
"""
|
|
30
|
+
Global configuration settings for fastapi-testing framework.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
ws_max_message_size: int = DEFAULT_WS_MESSAGE_SIZE,
|
|
36
|
+
ws_max_queue_size: int = DEFAULT_WS_QUEUE_SIZE,
|
|
37
|
+
http_max_keepalive: int = DEFAULT_KEEPALIVE_CONNS,
|
|
38
|
+
http_max_connections: int = DEFAULT_MAX_CONNS,
|
|
39
|
+
ws_retry_attempts: int = DEFAULT_WS_RETRY_ATTEMPTS,
|
|
40
|
+
ws_retry_delay: float = DEFAULT_WS_RETRY_DELAY,
|
|
41
|
+
port_range_start: int = 8001,
|
|
42
|
+
port_range_end: int = 9000,
|
|
43
|
+
):
|
|
44
|
+
self.WS_MAX_MESSAGE_SIZE = ws_max_message_size
|
|
45
|
+
self.WS_MAX_QUEUE_SIZE = ws_max_queue_size
|
|
46
|
+
self.HTTP_MAX_KEEPALIVE = http_max_keepalive
|
|
47
|
+
self.HTTP_MAX_CONNECTIONS = http_max_connections
|
|
48
|
+
self.WS_RETRY_ATTEMPTS = ws_retry_attempts
|
|
49
|
+
self.WS_RETRY_DELAY = ws_retry_delay
|
|
50
|
+
self.PORT_RANGE_START = port_range_start
|
|
51
|
+
self.PORT_RANGE_END = port_range_end
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def from_env(cls, prefix: str = "FASTAPI_TESTING_"):
|
|
55
|
+
"""
|
|
56
|
+
Create configuration from environment variables.
|
|
57
|
+
This is an explicit opt-in method.
|
|
58
|
+
"""
|
|
59
|
+
# Only look for variables with the specified prefix
|
|
60
|
+
env_vars = {k: v for k, v in os.environ.items() if k.startswith(prefix)}
|
|
61
|
+
|
|
62
|
+
# Convert to expected parameter names
|
|
63
|
+
config_params = {}
|
|
64
|
+
for env_key, env_value in env_vars.items():
|
|
65
|
+
config_key = env_key[len(prefix):].lower()
|
|
66
|
+
# Handle type conversion
|
|
67
|
+
if config_key in [
|
|
68
|
+
"ws_max_message_size",
|
|
69
|
+
"ws_max_queue_size",
|
|
70
|
+
"http_max_keepalive",
|
|
71
|
+
"http_max_connections",
|
|
72
|
+
"ws_retry_attempts",
|
|
73
|
+
"port_range_start",
|
|
74
|
+
"port_range_end"
|
|
75
|
+
]:
|
|
76
|
+
try:
|
|
77
|
+
config_params[config_key] = int(env_value)
|
|
78
|
+
except ValueError:
|
|
79
|
+
pass # Silently ignore invalid values
|
|
80
|
+
elif config_key == "ws_retry_delay":
|
|
81
|
+
try:
|
|
82
|
+
config_params[config_key] = float(env_value)
|
|
83
|
+
except ValueError:
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
return cls(**config_params)
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def from_file(cls, file_path: str):
|
|
90
|
+
"""Load configuration from a file."""
|
|
91
|
+
# Implementation for loading from a file (JSON, YAML, etc.)
|
|
92
|
+
pass
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# Create the global configuration with defaults
|
|
96
|
+
global_config = Config()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# Users can override it with their own configuration:
|
|
100
|
+
# global_config = Config.from_env()
|
|
101
|
+
# or
|
|
102
|
+
# global_config = Config(ws_max_message_size=2**21, http_max_connections=200)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class InvalidResponseTypeError(Exception):
|
|
106
|
+
"""Exception raised when an operation is not supported for the response type."""
|
|
107
|
+
pass
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class WebSocketConfig:
|
|
112
|
+
"""WebSocket connection configuration.
|
|
113
|
+
|
|
114
|
+
Attributes:
|
|
115
|
+
subprotocols: List of supported subprotocols
|
|
116
|
+
compression: Compression algorithm to use
|
|
117
|
+
extra_headers: Additional headers for the connection
|
|
118
|
+
ping_interval: Interval between ping messages
|
|
119
|
+
ping_timeout: Timeout for ping responses
|
|
120
|
+
max_size: Maximum message size in bytes
|
|
121
|
+
max_queue: Maximum number of queued messages
|
|
122
|
+
timeout: Connection timeout in seconds
|
|
123
|
+
"""
|
|
124
|
+
subprotocols: Optional[List[str]] = None
|
|
125
|
+
compression: Optional[str] = None
|
|
126
|
+
extra_headers: Optional[Dict[str, str]] = None
|
|
127
|
+
ping_interval: Optional[float] = None
|
|
128
|
+
ping_timeout: Optional[float] = None
|
|
129
|
+
max_size: int = global_config.WS_MAX_MESSAGE_SIZE
|
|
130
|
+
max_queue: int = global_config.WS_MAX_QUEUE_SIZE
|
|
131
|
+
timeout: Optional[float] = None
|
|
132
|
+
|
|
16
133
|
|
|
17
134
|
class PortGenerator:
|
|
18
|
-
|
|
135
|
+
"""Manages port allocation for test servers using configuration from global settings.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
def __init__(self, start: Optional[int] = None, end: Optional[int] = None):
|
|
139
|
+
if start is None:
|
|
140
|
+
start = global_config.PORT_RANGE_START
|
|
141
|
+
if end is None:
|
|
142
|
+
end = global_config.PORT_RANGE_END
|
|
19
143
|
self.start = start
|
|
20
144
|
self.end = end
|
|
21
145
|
self.used_ports: Set[int] = set()
|
|
22
146
|
|
|
23
|
-
|
|
147
|
+
@staticmethod
|
|
148
|
+
def is_port_available(port: int) -> bool:
|
|
149
|
+
from contextlib import closing
|
|
150
|
+
import socket
|
|
24
151
|
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
|
|
25
152
|
try:
|
|
26
153
|
sock.bind(('localhost', port))
|
|
@@ -29,10 +156,12 @@ class PortGenerator:
|
|
|
29
156
|
return False
|
|
30
157
|
|
|
31
158
|
def get_port(self) -> int:
|
|
159
|
+
"""Get an available port from the pool."""
|
|
32
160
|
available_ports = set(range(self.start, self.end + 1)) - self.used_ports
|
|
33
161
|
if not available_ports:
|
|
34
162
|
raise RuntimeError(f"No available ports in range {self.start}-{self.end}")
|
|
35
163
|
|
|
164
|
+
import random
|
|
36
165
|
while available_ports:
|
|
37
166
|
port = random.choice(list(available_ports))
|
|
38
167
|
if self.is_port_available(port):
|
|
@@ -42,33 +171,304 @@ class PortGenerator:
|
|
|
42
171
|
raise RuntimeError(f"No available ports found in range {self.start}-{self.end}")
|
|
43
172
|
|
|
44
173
|
def release_port(self, port: int) -> None:
|
|
174
|
+
"""Release a port back to the pool."""
|
|
45
175
|
self.used_ports.discard(port)
|
|
46
176
|
|
|
47
177
|
|
|
48
|
-
|
|
178
|
+
class AsyncTestResponse:
|
|
179
|
+
"""Enhanced response wrapper supporting both HTTP and WebSocket responses.
|
|
180
|
+
|
|
181
|
+
Provides unified interface for handling both HTTP and WebSocket responses
|
|
182
|
+
with proper type checking and error handling.
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
def __init__(self, response: Union[httpx.Response, ClientConnection]):
|
|
186
|
+
self._response = response
|
|
187
|
+
self._is_websocket = isinstance(response, ClientConnection)
|
|
188
|
+
|
|
189
|
+
async def json(self) -> Any:
|
|
190
|
+
"""Get JSON response (HTTP only)."""
|
|
191
|
+
if self._is_websocket:
|
|
192
|
+
raise InvalidResponseTypeError(
|
|
193
|
+
"Cannot get JSON directly from WebSocket response. Use websocket() methods instead.")
|
|
194
|
+
return await asyncio.to_thread(self._response.json)
|
|
195
|
+
|
|
196
|
+
async def text(self) -> str:
|
|
197
|
+
"""Get text response (HTTP only)."""
|
|
198
|
+
if self._is_websocket:
|
|
199
|
+
raise InvalidResponseTypeError(
|
|
200
|
+
"Cannot get text directly from WebSocket response. Use websocket() methods instead.")
|
|
201
|
+
return await asyncio.to_thread(lambda: self._response.text)
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def status_code(self) -> int:
|
|
205
|
+
"""Get status code (HTTP only)."""
|
|
206
|
+
if self._is_websocket:
|
|
207
|
+
raise InvalidResponseTypeError("WebSocket connections don't have status codes")
|
|
208
|
+
return self._response.status_code
|
|
209
|
+
|
|
210
|
+
def websocket(self) -> ClientConnection:
|
|
211
|
+
"""Get WebSocket connection (WebSocket only)."""
|
|
212
|
+
if not self._is_websocket:
|
|
213
|
+
raise InvalidResponseTypeError("This response is not a WebSocket connection")
|
|
214
|
+
return self._response
|
|
215
|
+
|
|
216
|
+
async def expect_status(self, status_code: int) -> 'AsyncTestResponse':
|
|
217
|
+
"""Assert expected status code (HTTP only)."""
|
|
218
|
+
if self._is_websocket:
|
|
219
|
+
raise InvalidResponseTypeError("WebSocket connections don't have status codes")
|
|
220
|
+
assert self._response.status_code == status_code, \
|
|
221
|
+
f"Expected status {status_code}, got {self._response.status_code}"
|
|
222
|
+
return self
|
|
223
|
+
|
|
49
224
|
|
|
50
|
-
|
|
225
|
+
class WebSocketHelper:
|
|
226
|
+
"""Helper methods for WebSocket operations."""
|
|
227
|
+
|
|
228
|
+
@staticmethod
|
|
229
|
+
async def send_json(resp: AsyncTestResponse, data: Any) -> None:
|
|
230
|
+
"""Send JSON data over WebSocket."""
|
|
231
|
+
ws = resp.websocket()
|
|
232
|
+
await ws.send(json.dumps(data))
|
|
233
|
+
|
|
234
|
+
@staticmethod
|
|
235
|
+
async def receive_json(resp: AsyncTestResponse) -> Any:
|
|
236
|
+
"""Receive JSON data from WebSocket."""
|
|
237
|
+
ws = resp.websocket()
|
|
238
|
+
data = await ws.recv()
|
|
239
|
+
if not isinstance(data, str):
|
|
240
|
+
raise TypeError(f"Expected text data to decode JSON, got {type(data)}")
|
|
241
|
+
return json.loads(data)
|
|
242
|
+
|
|
243
|
+
@staticmethod
|
|
244
|
+
async def send_binary(resp: AsyncTestResponse, data: bytes) -> None:
|
|
245
|
+
"""Send binary data over WebSocket."""
|
|
246
|
+
ws = resp.websocket()
|
|
247
|
+
await ws.send(data)
|
|
248
|
+
|
|
249
|
+
@staticmethod
|
|
250
|
+
async def receive_binary(resp: AsyncTestResponse) -> bytes:
|
|
251
|
+
"""Receive binary data from WebSocket."""
|
|
252
|
+
ws = resp.websocket()
|
|
253
|
+
data = await ws.recv()
|
|
254
|
+
if not isinstance(data, bytes):
|
|
255
|
+
raise TypeError(f"Expected bytes, got {type(data)}")
|
|
256
|
+
return data
|
|
257
|
+
|
|
258
|
+
@staticmethod
|
|
259
|
+
async def send_text(resp: AsyncTestResponse, data: str) -> None:
|
|
260
|
+
"""Send text data over WebSocket."""
|
|
261
|
+
ws = resp.websocket()
|
|
262
|
+
await ws.send(data)
|
|
263
|
+
|
|
264
|
+
@staticmethod
|
|
265
|
+
async def receive_text(resp: AsyncTestResponse) -> str:
|
|
266
|
+
"""Receive text data from WebSocket."""
|
|
267
|
+
ws = resp.websocket()
|
|
268
|
+
data = await ws.recv()
|
|
269
|
+
if not isinstance(data, str):
|
|
270
|
+
raise TypeError(f"Expected str, got {type(data)}")
|
|
271
|
+
return data
|
|
272
|
+
|
|
273
|
+
@staticmethod
|
|
274
|
+
async def expect_message(
|
|
275
|
+
resp: AsyncTestResponse,
|
|
276
|
+
expected: Union[str, dict, bytes],
|
|
277
|
+
timeout: Optional[float] = None
|
|
278
|
+
) -> None:
|
|
279
|
+
"""Assert expected message is received within timeout."""
|
|
280
|
+
ws = resp.websocket()
|
|
281
|
+
try:
|
|
282
|
+
message = await asyncio.wait_for(ws.recv(), timeout)
|
|
283
|
+
except asyncio.TimeoutError as e:
|
|
284
|
+
logger.error("Timed out waiting for message")
|
|
285
|
+
raise e
|
|
286
|
+
|
|
287
|
+
if isinstance(expected, dict):
|
|
288
|
+
if not isinstance(message, str):
|
|
289
|
+
raise AssertionError(f"Expected a text message for JSON decoding, got {type(message)}")
|
|
290
|
+
if json.loads(message) != expected:
|
|
291
|
+
raise AssertionError(f"Expected message {expected}, got {message}")
|
|
292
|
+
else:
|
|
293
|
+
if message != expected:
|
|
294
|
+
raise AssertionError(f"Expected message {expected}, got {message}")
|
|
295
|
+
|
|
296
|
+
@staticmethod
|
|
297
|
+
async def drain_messages(
|
|
298
|
+
resp: AsyncTestResponse,
|
|
299
|
+
timeout: Optional[float] = 0.1
|
|
300
|
+
) -> List[Any]:
|
|
301
|
+
"""Drain all pending messages from websocket queue."""
|
|
302
|
+
ws = resp.websocket()
|
|
303
|
+
messages = []
|
|
304
|
+
try:
|
|
305
|
+
while True:
|
|
306
|
+
message = await asyncio.wait_for(ws.recv(), timeout)
|
|
307
|
+
messages.append(message)
|
|
308
|
+
except asyncio.TimeoutError:
|
|
309
|
+
pass
|
|
310
|
+
return messages
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class AsyncTestClient:
|
|
314
|
+
"""Async test client supporting both HTTP and WebSocket connections."""
|
|
315
|
+
|
|
316
|
+
def __init__(
|
|
317
|
+
self,
|
|
318
|
+
base_url: str,
|
|
319
|
+
timeout: float = 30.0,
|
|
320
|
+
follow_redirects: bool = True
|
|
321
|
+
):
|
|
322
|
+
self._base_url = base_url.rstrip('/')
|
|
323
|
+
self._timeout = timeout
|
|
324
|
+
self._websocket_connections: Set[ClientConnection] = set()
|
|
325
|
+
|
|
326
|
+
limits = httpx.Limits(
|
|
327
|
+
max_keepalive_connections=global_config.HTTP_MAX_KEEPALIVE,
|
|
328
|
+
max_connections=global_config.HTTP_MAX_CONNECTIONS
|
|
329
|
+
)
|
|
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
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
self.ws = WebSocketHelper()
|
|
339
|
+
|
|
340
|
+
async def close(self) -> None:
|
|
341
|
+
"""Close all connections and cleanup resources."""
|
|
342
|
+
# Clean up any active websocket connections
|
|
343
|
+
for ws in list(self._websocket_connections):
|
|
344
|
+
try:
|
|
345
|
+
if ws.state == State.CLOSED:
|
|
346
|
+
self._websocket_connections.discard(ws)
|
|
347
|
+
else:
|
|
348
|
+
await ws.close()
|
|
349
|
+
self._websocket_connections.discard(ws)
|
|
350
|
+
except Exception as e:
|
|
351
|
+
logger.warning(f"Error closing websocket connection: {e}")
|
|
352
|
+
self._websocket_connections.clear()
|
|
353
|
+
|
|
354
|
+
if self._client:
|
|
355
|
+
await self._client.aclose()
|
|
356
|
+
|
|
357
|
+
async def request(
|
|
358
|
+
self,
|
|
359
|
+
method: str,
|
|
360
|
+
url: str,
|
|
361
|
+
**kwargs: Any
|
|
362
|
+
) -> AsyncTestResponse:
|
|
363
|
+
"""Make HTTP request."""
|
|
364
|
+
response = await self._client.request(method, url, **kwargs)
|
|
365
|
+
return AsyncTestResponse(response)
|
|
366
|
+
|
|
367
|
+
async def websocket(
|
|
368
|
+
self,
|
|
369
|
+
path: str,
|
|
370
|
+
config: Optional[WebSocketConfig] = None,
|
|
371
|
+
options: Optional[Dict[str, Any]] = None
|
|
372
|
+
) -> AsyncTestResponse:
|
|
373
|
+
"""Create a websocket connection with configuration."""
|
|
374
|
+
if not (self._base_url.startswith("http://") or self._base_url.startswith("https://")):
|
|
375
|
+
raise ValueError("Invalid base URL. Must start with 'http://' or 'https://'")
|
|
376
|
+
if self._base_url.startswith("https://"):
|
|
377
|
+
ws_url = f"wss://{self._base_url.replace('https://', '')}{path}"
|
|
378
|
+
elif self._base_url.startswith("http://"):
|
|
379
|
+
ws_url = f"ws://{self._base_url.replace('http://', '')}{path}"
|
|
380
|
+
else:
|
|
381
|
+
ws_url = f"ws://{self._base_url}{path}"
|
|
382
|
+
|
|
383
|
+
connect_kwargs: Dict[str, Any] = {
|
|
384
|
+
'open_timeout': self._timeout,
|
|
385
|
+
'max_size': global_config.WS_MAX_MESSAGE_SIZE,
|
|
386
|
+
'max_queue': global_config.WS_MAX_QUEUE_SIZE
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
if config:
|
|
390
|
+
if config.subprotocols:
|
|
391
|
+
connect_kwargs['subprotocols'] = config.subprotocols
|
|
392
|
+
if config.compression:
|
|
393
|
+
connect_kwargs['compression'] = config.compression
|
|
394
|
+
if config.extra_headers:
|
|
395
|
+
connect_kwargs['additional_headers'] = config.extra_headers
|
|
396
|
+
if config.ping_interval:
|
|
397
|
+
connect_kwargs['ping_interval'] = config.ping_interval
|
|
398
|
+
if config.ping_timeout:
|
|
399
|
+
connect_kwargs['ping_timeout'] = config.ping_timeout
|
|
400
|
+
if config.timeout:
|
|
401
|
+
connect_kwargs['open_timeout'] = config.timeout
|
|
402
|
+
|
|
403
|
+
if options:
|
|
404
|
+
connect_kwargs.update(options)
|
|
405
|
+
|
|
406
|
+
# Retry logic for establishing a WebSocket connection.
|
|
407
|
+
attempt = 0
|
|
408
|
+
while True:
|
|
409
|
+
try:
|
|
410
|
+
ws = await connect(ws_url, **connect_kwargs)
|
|
411
|
+
break
|
|
412
|
+
except Exception as e:
|
|
413
|
+
attempt += 1
|
|
414
|
+
if attempt >= global_config.WS_RETRY_ATTEMPTS:
|
|
415
|
+
logger.error(
|
|
416
|
+
f"Failed to establish WebSocket connection after "
|
|
417
|
+
f"{global_config.WS_RETRY_ATTEMPTS} attempts: {e}"
|
|
418
|
+
)
|
|
419
|
+
raise
|
|
420
|
+
await asyncio.sleep(global_config.WS_RETRY_DELAY)
|
|
421
|
+
|
|
422
|
+
self._websocket_connections.add(ws)
|
|
423
|
+
return AsyncTestResponse(ws)
|
|
424
|
+
|
|
425
|
+
async def get(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
426
|
+
return await self.request('GET', url, **kwargs)
|
|
427
|
+
|
|
428
|
+
async def post(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
429
|
+
return await self.request('POST', url, **kwargs)
|
|
430
|
+
|
|
431
|
+
async def put(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
432
|
+
return await self.request('PUT', url, **kwargs)
|
|
433
|
+
|
|
434
|
+
async def delete(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
435
|
+
return await self.request('DELETE', url, **kwargs)
|
|
436
|
+
|
|
437
|
+
async def patch(self, url: str, **kwargs: Any) -> AsyncTestResponse:
|
|
438
|
+
return await self.request('PATCH', url, **kwargs)
|
|
439
|
+
|
|
440
|
+
async def __aenter__(self) -> "AsyncTestClient":
|
|
441
|
+
return self
|
|
442
|
+
|
|
443
|
+
async def __aexit__(self, exc_type, exc, tb):
|
|
444
|
+
await self.close()
|
|
51
445
|
|
|
52
446
|
|
|
53
447
|
class UvicornTestServer(uvicorn.Server):
|
|
54
|
-
"""Uvicorn test server with startup event support"""
|
|
448
|
+
"""Uvicorn test server with startup event support."""
|
|
55
449
|
|
|
56
450
|
def __init__(self, config: uvicorn.Config, startup_handler: asyncio.Event):
|
|
57
451
|
super().__init__(config)
|
|
58
452
|
self.startup_handler = startup_handler
|
|
59
453
|
|
|
60
454
|
async def startup(self, sockets: Optional[List] = None) -> None:
|
|
61
|
-
"""Override startup to signal when ready"""
|
|
455
|
+
"""Override startup to signal when ready."""
|
|
62
456
|
await super().startup(sockets=sockets)
|
|
63
457
|
self.startup_handler.set()
|
|
64
458
|
|
|
65
459
|
|
|
460
|
+
# Use the configurable PortGenerator instance
|
|
461
|
+
_port_generator = PortGenerator()
|
|
462
|
+
|
|
463
|
+
|
|
66
464
|
class AsyncTestServer:
|
|
465
|
+
"""Async test server with proper lifecycle management and WebSocket support."""
|
|
466
|
+
|
|
67
467
|
def __init__(
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
468
|
+
self,
|
|
469
|
+
lifespan: Optional[Lifespan[AppType]] = None,
|
|
470
|
+
startup_timeout: float = 30.0,
|
|
471
|
+
shutdown_timeout: float = 10.0,
|
|
72
472
|
):
|
|
73
473
|
self.app = FastAPI(lifespan=lifespan)
|
|
74
474
|
self.startup_timeout = startup_timeout
|
|
@@ -80,9 +480,10 @@ class AsyncTestServer:
|
|
|
80
480
|
self._host = "127.0.0.1"
|
|
81
481
|
self._client: Optional[AsyncTestClient] = None
|
|
82
482
|
self._server: Optional[UvicornTestServer] = None
|
|
483
|
+
self._websocket_tasks: Set[asyncio.Task] = set()
|
|
83
484
|
|
|
84
485
|
async def start(self) -> None:
|
|
85
|
-
"""Start the server asynchronously with proper lifecycle management"""
|
|
486
|
+
"""Start the server asynchronously with proper lifecycle management."""
|
|
86
487
|
if self._server_task is not None:
|
|
87
488
|
raise RuntimeError("Server is already running")
|
|
88
489
|
|
|
@@ -99,14 +500,11 @@ class AsyncTestServer:
|
|
|
99
500
|
|
|
100
501
|
self._server = UvicornTestServer(config=config, startup_handler=startup_handler)
|
|
101
502
|
|
|
102
|
-
# Create server task
|
|
103
503
|
self._server_task = asyncio.create_task(self._server.serve())
|
|
104
504
|
|
|
105
505
|
try:
|
|
106
|
-
# Wait for startup with timeout
|
|
107
506
|
await asyncio.wait_for(startup_handler.wait(), timeout=self.startup_timeout)
|
|
108
507
|
|
|
109
|
-
# Initialize test client after server is confirmed running
|
|
110
508
|
self._client = AsyncTestClient(
|
|
111
509
|
base_url=self.base_url,
|
|
112
510
|
timeout=self.startup_timeout
|
|
@@ -117,45 +515,50 @@ class AsyncTestServer:
|
|
|
117
515
|
except (asyncio.TimeoutError, Exception) as e:
|
|
118
516
|
await self.stop()
|
|
119
517
|
if isinstance(e, asyncio.TimeoutError):
|
|
120
|
-
raise RuntimeError(
|
|
518
|
+
raise RuntimeError(
|
|
519
|
+
f"Server startup timed out on host {self._host} and port {self._port}"
|
|
520
|
+
) from e
|
|
121
521
|
raise
|
|
122
522
|
|
|
123
523
|
async def stop(self) -> None:
|
|
124
|
-
"""Stop the server and clean up resources"""
|
|
524
|
+
"""Stop the server and clean up all resources including WebSocket connections."""
|
|
125
525
|
if not self._startup_complete.is_set():
|
|
126
526
|
return
|
|
127
527
|
|
|
128
|
-
#
|
|
528
|
+
# Cancel all WebSocket tasks
|
|
529
|
+
for task in self._websocket_tasks:
|
|
530
|
+
if not task.done():
|
|
531
|
+
task.cancel()
|
|
532
|
+
await asyncio.gather(*self._websocket_tasks, return_exceptions=True)
|
|
533
|
+
self._websocket_tasks.clear()
|
|
534
|
+
|
|
129
535
|
if self._client:
|
|
130
536
|
await self._client.close()
|
|
131
537
|
self._client = None
|
|
132
538
|
|
|
133
539
|
if self._server_task:
|
|
134
540
|
try:
|
|
135
|
-
# Signal the server to shutdown gracefully
|
|
136
541
|
if self._server:
|
|
137
542
|
self._server.should_exit = True
|
|
138
543
|
|
|
139
|
-
# Wait for server task to complete
|
|
140
544
|
await asyncio.wait_for(self._server_task, timeout=self.shutdown_timeout)
|
|
141
545
|
|
|
142
546
|
except asyncio.TimeoutError:
|
|
143
|
-
logger.error(
|
|
144
|
-
|
|
547
|
+
logger.error(
|
|
548
|
+
f"Timeout waiting for server shutdown on host {self._host} port {self._port}"
|
|
549
|
+
)
|
|
145
550
|
if not self._server_task.done():
|
|
146
551
|
self._server_task.cancel()
|
|
147
552
|
await asyncio.gather(self._server_task, return_exceptions=True)
|
|
148
553
|
except asyncio.CancelledError:
|
|
149
|
-
logger.info("Server task
|
|
554
|
+
logger.info("Server task cancelled successfully")
|
|
150
555
|
finally:
|
|
151
556
|
self._server_task = None
|
|
152
557
|
|
|
153
|
-
# Release the used port
|
|
154
558
|
if self._port:
|
|
155
559
|
_port_generator.release_port(self._port)
|
|
156
560
|
self._port = None
|
|
157
561
|
|
|
158
|
-
# Mark shutdown as complete
|
|
159
562
|
self._shutdown_complete.set()
|
|
160
563
|
|
|
161
564
|
@property
|
|
@@ -172,77 +575,12 @@ class AsyncTestServer:
|
|
|
172
575
|
await self.stop()
|
|
173
576
|
|
|
174
577
|
@property
|
|
175
|
-
def client(self) ->
|
|
578
|
+
def client(self) -> AsyncTestClient:
|
|
176
579
|
if not self._client:
|
|
177
580
|
raise RuntimeError("Server is not running")
|
|
178
581
|
return self._client
|
|
179
582
|
|
|
180
583
|
|
|
181
|
-
class AsyncTestClient:
|
|
182
|
-
def __init__(
|
|
183
|
-
self,
|
|
184
|
-
base_url: str,
|
|
185
|
-
timeout: float = 30.0,
|
|
186
|
-
follow_redirects: bool = True
|
|
187
|
-
):
|
|
188
|
-
self._base_url = base_url.rstrip('/')
|
|
189
|
-
limits = httpx.Limits(max_keepalive_connections=20, max_connections=100)
|
|
190
|
-
self._client = httpx.AsyncClient(
|
|
191
|
-
base_url=self._base_url,
|
|
192
|
-
timeout=timeout,
|
|
193
|
-
follow_redirects=follow_redirects,
|
|
194
|
-
limits=limits,
|
|
195
|
-
http2=True
|
|
196
|
-
)
|
|
197
|
-
|
|
198
|
-
async def close(self) -> None:
|
|
199
|
-
if self._client:
|
|
200
|
-
await self._client.aclose()
|
|
201
|
-
|
|
202
|
-
async def request(
|
|
203
|
-
self,
|
|
204
|
-
method: str,
|
|
205
|
-
url: str,
|
|
206
|
-
**kwargs: Any
|
|
207
|
-
) -> 'AsyncTestResponse':
|
|
208
|
-
response = await self._client.request(method, url, **kwargs)
|
|
209
|
-
return AsyncTestResponse(response)
|
|
210
|
-
|
|
211
|
-
async def get(self, url: str, **kwargs: Any) -> 'AsyncTestResponse':
|
|
212
|
-
return await self.request('GET', url, **kwargs)
|
|
213
|
-
|
|
214
|
-
async def post(self, url: str, **kwargs: Any) -> 'AsyncTestResponse':
|
|
215
|
-
return await self.request('POST', url, **kwargs)
|
|
216
|
-
|
|
217
|
-
async def put(self, url: str, **kwargs: Any) -> 'AsyncTestResponse':
|
|
218
|
-
return await self.request('PUT', url, **kwargs)
|
|
219
|
-
|
|
220
|
-
async def delete(self, url: str, **kwargs: Any) -> 'AsyncTestResponse':
|
|
221
|
-
return await self.request('DELETE', url, **kwargs)
|
|
222
|
-
|
|
223
|
-
async def patch(self, url: str, **kwargs: Any) -> 'AsyncTestResponse':
|
|
224
|
-
return await self.request('PATCH', url, **kwargs)
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
class AsyncTestResponse:
|
|
228
|
-
def __init__(self, response: httpx.Response):
|
|
229
|
-
self._response = response
|
|
230
|
-
|
|
231
|
-
async def json(self) -> Any:
|
|
232
|
-
return self._response.json()
|
|
233
|
-
|
|
234
|
-
async def text(self) -> str:
|
|
235
|
-
return self._response.text
|
|
236
|
-
|
|
237
|
-
def status_code(self) -> int:
|
|
238
|
-
return self._response.status_code
|
|
239
|
-
|
|
240
|
-
async def expect_status(self, status_code: int) -> 'AsyncTestResponse':
|
|
241
|
-
assert self._response.status_code == status_code, \
|
|
242
|
-
f"Expected status {status_code}, got {self._response.status_code}"
|
|
243
|
-
return self
|
|
244
|
-
|
|
245
|
-
|
|
246
584
|
@asynccontextmanager
|
|
247
585
|
async def create_test_server(
|
|
248
586
|
lifespan: Optional[Lifespan[AppType]] = None,
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: fastapi-testing
|
|
3
|
+
Version: 0.2.2
|
|
4
|
+
Summary: A lightweight, async-first testing framework for FastAPI applications
|
|
5
|
+
License: MIT
|
|
6
|
+
Keywords: fastapi,testing,async,pytest,integration-testing,test-framework
|
|
7
|
+
Author: Ove Ranheim
|
|
8
|
+
Author-email: oranheim@gmail.com
|
|
9
|
+
Requires-Python: >=3.11,<4.0
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Framework :: FastAPI
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Topic :: Software Development :: Testing
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Dist: fastapi (>=0.115.0,<0.116.0)
|
|
23
|
+
Requires-Dist: httpx[http2] (>=0.23.0,<0.28.0)
|
|
24
|
+
Requires-Dist: starlette (>=0.45.0,<0.46.0)
|
|
25
|
+
Requires-Dist: uvicorn (>=0.34.0,<0.35.0)
|
|
26
|
+
Requires-Dist: websockets (>=15.0,<16.0)
|
|
27
|
+
Project-URL: Homepage, https://github.com/descoped/fastapi-testing
|
|
28
|
+
Project-URL: Repository, https://github.com/descoped/fastapi-testing
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# FastAPI Testing
|
|
32
|
+
|
|
33
|
+
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
|
+
|
|
35
|
+
## Features
|
|
36
|
+
|
|
37
|
+
- Async-first design for modern Python applications
|
|
38
|
+
- Automatic port management for test servers
|
|
39
|
+
- Clean lifecycle management with context managers
|
|
40
|
+
- Built-in HTTP and WebSocket client support
|
|
41
|
+
- Proper cleanup of resources after tests
|
|
42
|
+
- Support for FastAPI's lifespan events
|
|
43
|
+
- Type-safe with full typing support
|
|
44
|
+
|
|
45
|
+
## Installation
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
pip install fastapi-testing
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Quick Start
|
|
52
|
+
|
|
53
|
+
Here's a simple example of how to test a FastAPI endpoint:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import pytest
|
|
57
|
+
from fastapi import FastAPI
|
|
58
|
+
from fastapi_testing import create_test_server
|
|
59
|
+
|
|
60
|
+
@pytest.mark.asyncio
|
|
61
|
+
async def test_hello_world():
|
|
62
|
+
async with create_test_server() as server:
|
|
63
|
+
@server.app.get("/hello")
|
|
64
|
+
async def hello():
|
|
65
|
+
return {"message": "Hello, World!"}
|
|
66
|
+
|
|
67
|
+
response = await server.client.get("/hello")
|
|
68
|
+
await response.expect_status(200)
|
|
69
|
+
data = await response.json()
|
|
70
|
+
assert data["message"] == "Hello, World!"
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Architecture
|
|
74
|
+
|
|
75
|
+
The following sequence diagram illustrates the lifecycle of a test using this framework:
|
|
76
|
+
|
|
77
|
+
```mermaid
|
|
78
|
+
sequenceDiagram
|
|
79
|
+
participant Test
|
|
80
|
+
participant AsyncTestServer
|
|
81
|
+
participant PortGenerator
|
|
82
|
+
participant UvicornServer
|
|
83
|
+
participant FastAPI
|
|
84
|
+
participant AsyncTestClient
|
|
85
|
+
|
|
86
|
+
Test->>+AsyncTestServer: create_test_server()
|
|
87
|
+
AsyncTestServer->>+PortGenerator: get_port()
|
|
88
|
+
PortGenerator-->>-AsyncTestServer: available port
|
|
89
|
+
|
|
90
|
+
AsyncTestServer->>+UvicornServer: initialize
|
|
91
|
+
UvicornServer->>FastAPI: configure
|
|
92
|
+
|
|
93
|
+
AsyncTestServer->>+UvicornServer: start()
|
|
94
|
+
UvicornServer->>FastAPI: startup event
|
|
95
|
+
UvicornServer-->>AsyncTestServer: server ready
|
|
96
|
+
|
|
97
|
+
AsyncTestServer->>+AsyncTestClient: initialize
|
|
98
|
+
AsyncTestClient-->>-AsyncTestServer: client ready
|
|
99
|
+
AsyncTestServer-->>-Test: server instance
|
|
100
|
+
|
|
101
|
+
Note over Test,AsyncTestClient: Test execution happens here
|
|
102
|
+
|
|
103
|
+
Test->>+AsyncTestServer: cleanup (context exit)
|
|
104
|
+
AsyncTestServer->>+AsyncTestClient: close()
|
|
105
|
+
AsyncTestClient-->>-AsyncTestServer: closed
|
|
106
|
+
|
|
107
|
+
AsyncTestServer->>+UvicornServer: shutdown
|
|
108
|
+
UvicornServer->>FastAPI: shutdown event
|
|
109
|
+
UvicornServer-->>-AsyncTestServer: shutdown complete
|
|
110
|
+
|
|
111
|
+
AsyncTestServer->>+PortGenerator: release_port()
|
|
112
|
+
PortGenerator-->>-AsyncTestServer: port released
|
|
113
|
+
AsyncTestServer-->>-Test: cleanup complete
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Key Components
|
|
117
|
+
|
|
118
|
+
### AsyncTestServer
|
|
119
|
+
|
|
120
|
+
The `AsyncTestServer` class is the core component that manages the lifecycle of your test FastAPI application:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from fastapi_testing import AsyncTestServer
|
|
124
|
+
|
|
125
|
+
server = AsyncTestServer()
|
|
126
|
+
await server.start()
|
|
127
|
+
# Use server.app to define routes
|
|
128
|
+
# Use server.client to make requests
|
|
129
|
+
await server.stop()
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Context Manager
|
|
133
|
+
|
|
134
|
+
The recommended way to use the test server is with the async context manager:
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
from fastapi_testing import create_test_server
|
|
138
|
+
|
|
139
|
+
async with create_test_server() as server:
|
|
140
|
+
# Your test code here
|
|
141
|
+
pass # Server automatically starts and stops
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### AsyncTestClient
|
|
145
|
+
|
|
146
|
+
The `AsyncTestClient` provides methods for making HTTP requests to your test server:
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
# Available HTTP methods
|
|
150
|
+
await server.client.get("/path")
|
|
151
|
+
await server.client.post("/path", json=data)
|
|
152
|
+
await server.client.put("/path", json=data)
|
|
153
|
+
await server.client.delete("/path")
|
|
154
|
+
await server.client.patch("/path", json=data)
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Response Assertions
|
|
158
|
+
|
|
159
|
+
The `AsyncTestResponse` class provides convenient methods for assertions:
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
response = await server.client.get("/path")
|
|
163
|
+
await response.expect_status(200) # Assert status code
|
|
164
|
+
data = await response.json() # Get JSON response
|
|
165
|
+
text = await response.text() # Get text response
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### WebSocket Testing
|
|
169
|
+
|
|
170
|
+
Test WebSocket endpoints with full protocol support:
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
@pytest.mark.asyncio
|
|
174
|
+
async def test_mixed_protocols(test_server):
|
|
175
|
+
# Define HTTP endpoint
|
|
176
|
+
@test_server.app.get("/api/data")
|
|
177
|
+
async def get_data():
|
|
178
|
+
return {"status": "ok"}
|
|
179
|
+
|
|
180
|
+
# Define WebSocket endpoint
|
|
181
|
+
@test_server.app.websocket("/ws/echo")
|
|
182
|
+
async def websocket_endpoint(websocket: WebSocket):
|
|
183
|
+
await websocket.accept(subprotocol="test-protocol")
|
|
184
|
+
while True:
|
|
185
|
+
try:
|
|
186
|
+
message = await websocket.receive()
|
|
187
|
+
if "text" in message:
|
|
188
|
+
data = json.loads(message["text"])
|
|
189
|
+
await websocket.send_json(data)
|
|
190
|
+
elif "bytes" in message:
|
|
191
|
+
await websocket.send_bytes(message["bytes"])
|
|
192
|
+
except WebSocketDisconnect:
|
|
193
|
+
return
|
|
194
|
+
|
|
195
|
+
# Test HTTP endpoint
|
|
196
|
+
http_response = await test_server.client.get("/api/data")
|
|
197
|
+
assert http_response.status_code == 200
|
|
198
|
+
|
|
199
|
+
# Configure WebSocket
|
|
200
|
+
config = WebSocketConfig(
|
|
201
|
+
subprotocols=["test-protocol"],
|
|
202
|
+
ping_interval=20.0,
|
|
203
|
+
ping_timeout=20.0
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
# Test WebSocket endpoint
|
|
207
|
+
ws_response = await test_server.client.websocket("/ws/echo", config)
|
|
208
|
+
try:
|
|
209
|
+
# Test JSON messages
|
|
210
|
+
test_json = {"message": "test"}
|
|
211
|
+
await test_server.client.ws.send_json(ws_response, test_json)
|
|
212
|
+
response = await test_server.client.ws.receive_json(ws_response)
|
|
213
|
+
assert response == test_json
|
|
214
|
+
|
|
215
|
+
# Test binary messages
|
|
216
|
+
test_data = b"binary test"
|
|
217
|
+
await test_server.client.ws.send_binary(ws_response, test_data)
|
|
218
|
+
response = await test_server.client.ws.receive_binary(ws_response)
|
|
219
|
+
assert response == test_data
|
|
220
|
+
finally:
|
|
221
|
+
await ws_response.websocket().close()
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
#### WebSocket Message Operations
|
|
225
|
+
|
|
226
|
+
The WebSocketHelper provides comprehensive message handling:
|
|
227
|
+
|
|
228
|
+
```python
|
|
229
|
+
# Send Operations
|
|
230
|
+
await client.ws.send_text(ws_response, "message")
|
|
231
|
+
await client.ws.send_json(ws_response, {"key": "value"})
|
|
232
|
+
await client.ws.send_binary(ws_response, b"data")
|
|
233
|
+
|
|
234
|
+
# Receive Operations
|
|
235
|
+
text = await client.ws.receive_text(ws_response)
|
|
236
|
+
json_data = await client.ws.receive_json(ws_response)
|
|
237
|
+
binary = await client.ws.receive_binary(ws_response)
|
|
238
|
+
|
|
239
|
+
# Message Expectations
|
|
240
|
+
await client.ws.expect_message(
|
|
241
|
+
ws_response,
|
|
242
|
+
expected="message",
|
|
243
|
+
timeout=1.0
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
# Collect Multiple Messages
|
|
247
|
+
messages = await client.ws.drain_messages(
|
|
248
|
+
ws_response,
|
|
249
|
+
timeout=1.0
|
|
250
|
+
)
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
#### WebSocket Configuration
|
|
254
|
+
|
|
255
|
+
Configure connections with various options:
|
|
256
|
+
|
|
257
|
+
```python
|
|
258
|
+
ws_config = WebSocketConfig(
|
|
259
|
+
subprotocols=["protocol"], # Supported subprotocols
|
|
260
|
+
compression=None, # Compression algorithm
|
|
261
|
+
extra_headers={}, # Additional headers
|
|
262
|
+
ping_interval=20.0, # Keep-alive interval
|
|
263
|
+
ping_timeout=20.0, # Ping timeout
|
|
264
|
+
max_size=2 ** 20, # Max message size (1MB)
|
|
265
|
+
max_queue=32, # Max queued messages
|
|
266
|
+
timeout=30.0 # Connection timeout
|
|
267
|
+
)
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
## Advanced Usage
|
|
271
|
+
|
|
272
|
+
### Advanced Server Configuration
|
|
273
|
+
|
|
274
|
+
You can customize the server lifecycle using a reusable test fixture:
|
|
275
|
+
|
|
276
|
+
```python
|
|
277
|
+
@pytest.fixture
|
|
278
|
+
async def test_server(
|
|
279
|
+
test_settings: Settings,
|
|
280
|
+
transaction_manager: TransactionManager
|
|
281
|
+
) -> AsyncGenerator[AsyncTestServer, None]:
|
|
282
|
+
"""Create test server with overridden settings and database connection"""
|
|
283
|
+
|
|
284
|
+
async def custom_lifespan(app: AppType) -> AsyncGenerator[None, Any]:
|
|
285
|
+
# Wire up test-specific dependencies
|
|
286
|
+
app.dependency_overrides.update({
|
|
287
|
+
get_settings: lambda: test_settings,
|
|
288
|
+
get_transaction_manager: lambda: transaction_manager,
|
|
289
|
+
get_db_pool: lambda: transaction_manager.pool
|
|
290
|
+
})
|
|
291
|
+
|
|
292
|
+
yield # Server handles requests during this period
|
|
293
|
+
|
|
294
|
+
# Cleanup after tests complete
|
|
295
|
+
await db.cleanup()
|
|
296
|
+
|
|
297
|
+
async with create_test_server(lifespan=custom_lifespan) as server:
|
|
298
|
+
yield server
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
### Testing Routes and Routers
|
|
302
|
+
|
|
303
|
+
You can test entire routers and complex route configurations:
|
|
304
|
+
|
|
305
|
+
```python
|
|
306
|
+
@pytest.mark.asyncio
|
|
307
|
+
async def test_api(test_server: AsyncTestServer):
|
|
308
|
+
# Register routes/routers
|
|
309
|
+
test_server.app.include_router(your_router)
|
|
310
|
+
|
|
311
|
+
# Make requests
|
|
312
|
+
response = await test_server.client.get("/your-endpoint")
|
|
313
|
+
await response.expect_status(200)
|
|
314
|
+
|
|
315
|
+
# Test concurrent requests
|
|
316
|
+
responses = await asyncio.gather(*[
|
|
317
|
+
test_server.client.get("/endpoint")
|
|
318
|
+
for _ in range(5)
|
|
319
|
+
])
|
|
320
|
+
|
|
321
|
+
for response in responses:
|
|
322
|
+
await response.expect_status(200)
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
### Lifecycle Management
|
|
326
|
+
|
|
327
|
+
You can define setup and cleanup operations using FastAPI's lifespan:
|
|
328
|
+
|
|
329
|
+
```python
|
|
330
|
+
from contextlib import asynccontextmanager
|
|
331
|
+
from fastapi import FastAPI
|
|
332
|
+
|
|
333
|
+
@asynccontextmanager
|
|
334
|
+
async def lifespan(app: FastAPI):
|
|
335
|
+
# Setup
|
|
336
|
+
print("Starting server")
|
|
337
|
+
yield
|
|
338
|
+
# Cleanup
|
|
339
|
+
print("Shutting down server")
|
|
340
|
+
|
|
341
|
+
async with create_test_server(lifespan=lifespan) as server:
|
|
342
|
+
# Your test code here
|
|
343
|
+
pass
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
### Concurrent Requests
|
|
347
|
+
|
|
348
|
+
The framework supports testing concurrent requests:
|
|
349
|
+
|
|
350
|
+
```python
|
|
351
|
+
import asyncio
|
|
352
|
+
|
|
353
|
+
async with create_test_server() as server:
|
|
354
|
+
@server.app.get("/ping")
|
|
355
|
+
async def ping():
|
|
356
|
+
return {"status": "ok"}
|
|
357
|
+
|
|
358
|
+
responses = await asyncio.gather(*[
|
|
359
|
+
server.client.get("/ping")
|
|
360
|
+
for _ in range(5)
|
|
361
|
+
])
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
## Configuration
|
|
365
|
+
|
|
366
|
+
You can customize the server behavior:
|
|
367
|
+
|
|
368
|
+
```python
|
|
369
|
+
server = AsyncTestServer(
|
|
370
|
+
startup_timeout=30.0, # Seconds to wait for server startup
|
|
371
|
+
shutdown_timeout=10.0, # Seconds to wait for server shutdown
|
|
372
|
+
)
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
## Best Practices
|
|
376
|
+
|
|
377
|
+
1. Always use the async context manager (`create_test_server`) when possible
|
|
378
|
+
2. Clean up resources in your tests, especially when managing state
|
|
379
|
+
3. Use pytest.mark.asyncio for your test functions
|
|
380
|
+
4. Handle exceptions appropriately in your tests
|
|
381
|
+
5. Use type hints to catch potential issues early
|
|
382
|
+
|
|
383
|
+
## Error Handling
|
|
384
|
+
|
|
385
|
+
The framework provides clear error messages for common issues:
|
|
386
|
+
|
|
387
|
+
- Server startup timeout
|
|
388
|
+
- Port allocation failures
|
|
389
|
+
- Connection errors
|
|
390
|
+
- Invalid request formats
|
|
391
|
+
|
|
392
|
+
## Limitations
|
|
393
|
+
|
|
394
|
+
- Only supports async test cases
|
|
395
|
+
- Requires Python 3.11+
|
|
396
|
+
- Designed specifically for FastAPI applications
|
|
397
|
+
|
|
398
|
+
## Contributing
|
|
399
|
+
|
|
400
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
401
|
+
|
|
@@ -0,0 +1,6 @@
|
|
|
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,,
|
|
@@ -1,231 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.3
|
|
2
|
-
Name: fastapi-testing
|
|
3
|
-
Version: 0.2.0
|
|
4
|
-
Summary: A lightweight, async-first testing framework for FastAPI applications
|
|
5
|
-
License: MIT
|
|
6
|
-
Keywords: fastapi,testing,async,pytest,integration-testing,test-framework
|
|
7
|
-
Author: Ove Ranheim
|
|
8
|
-
Author-email: oranheim@gmail.com
|
|
9
|
-
Requires-Python: >=3.11,<4.0
|
|
10
|
-
Classifier: Development Status :: 3 - Alpha
|
|
11
|
-
Classifier: Framework :: FastAPI
|
|
12
|
-
Classifier: Intended Audience :: Developers
|
|
13
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
-
Classifier: Operating System :: OS Independent
|
|
15
|
-
Classifier: Programming Language :: Python :: 3
|
|
16
|
-
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
-
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
-
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
-
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
-
Classifier: Topic :: Software Development :: Testing
|
|
21
|
-
Classifier: Typing :: Typed
|
|
22
|
-
Requires-Dist: fastapi (>=0.115.0,<0.116.0)
|
|
23
|
-
Requires-Dist: httpx[http2] (>=0.23.0,<0.28.0)
|
|
24
|
-
Requires-Dist: pydantic (>=2.10.6,<3.0.0)
|
|
25
|
-
Requires-Dist: starlette (>=0.45.0,<0.46.0)
|
|
26
|
-
Requires-Dist: uvicorn (>=0.34.0,<0.35.0)
|
|
27
|
-
Project-URL: Documentation, https://github.com/descoped/fastapi-testing/tree/master/docs
|
|
28
|
-
Project-URL: Homepage, https://github.com/descoped/fastapi-testing
|
|
29
|
-
Project-URL: Repository, https://github.com/descoped/fastapi-testing
|
|
30
|
-
Description-Content-Type: text/x-rst
|
|
31
|
-
|
|
32
|
-
FastAPI Testing
|
|
33
|
-
===============
|
|
34
|
-
|
|
35
|
-
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.
|
|
36
|
-
|
|
37
|
-
Features
|
|
38
|
-
------------
|
|
39
|
-
|
|
40
|
-
- Async-first design for modern Python applications
|
|
41
|
-
- Automatic port management for test servers
|
|
42
|
-
- Clean lifecycle management with context managers
|
|
43
|
-
- Built-in HTTP client with async support
|
|
44
|
-
- Proper cleanup of resources after tests
|
|
45
|
-
- Support for FastAPI's lifespan events
|
|
46
|
-
- Type-safe with full typing support
|
|
47
|
-
|
|
48
|
-
Installation
|
|
49
|
-
----------------
|
|
50
|
-
|
|
51
|
-
.. code-block:: bash
|
|
52
|
-
|
|
53
|
-
pip install fastapi-testing
|
|
54
|
-
|
|
55
|
-
Quick Start
|
|
56
|
-
--------------
|
|
57
|
-
|
|
58
|
-
Here's a simple example of how to test a FastAPI endpoint:
|
|
59
|
-
|
|
60
|
-
.. code-block:: python
|
|
61
|
-
|
|
62
|
-
import pytest
|
|
63
|
-
from fastapi import FastAPI
|
|
64
|
-
from fastapi_testing import create_test_server
|
|
65
|
-
|
|
66
|
-
@pytest.mark.asyncio
|
|
67
|
-
async def test_hello_world():
|
|
68
|
-
async with create_test_server() as server:
|
|
69
|
-
@server.app.get("/hello")
|
|
70
|
-
async def hello():
|
|
71
|
-
return {"message": "Hello, World!"}
|
|
72
|
-
|
|
73
|
-
response = await server.client.get("/hello")
|
|
74
|
-
await response.expect_status(200)
|
|
75
|
-
data = await response.json()
|
|
76
|
-
assert data["message"] == "Hello, World!"
|
|
77
|
-
|
|
78
|
-
Architecture
|
|
79
|
-
----------------
|
|
80
|
-
|
|
81
|
-
The framework follows a lifecycle-based architecture with proper resource management:
|
|
82
|
-
|
|
83
|
-
1. Test server initialization
|
|
84
|
-
2. Port allocation
|
|
85
|
-
3. Server startup
|
|
86
|
-
4. Test execution
|
|
87
|
-
5. Cleanup and shutdown
|
|
88
|
-
|
|
89
|
-
Key Components
|
|
90
|
-
------------------
|
|
91
|
-
|
|
92
|
-
TestServer
|
|
93
|
-
~~~~~~~~~~~~~~
|
|
94
|
-
|
|
95
|
-
The ``TestServer`` class is the core component that manages the lifecycle of your test FastAPI application:
|
|
96
|
-
|
|
97
|
-
.. code-block:: python
|
|
98
|
-
|
|
99
|
-
from fastapi_testing import TestServer
|
|
100
|
-
|
|
101
|
-
server = TestServer()
|
|
102
|
-
await server.start()
|
|
103
|
-
# Use server.app to define routes
|
|
104
|
-
# Use server.client to make requests
|
|
105
|
-
await server.stop()
|
|
106
|
-
|
|
107
|
-
Context Manager
|
|
108
|
-
~~~~~~~~~~~~~~~~~~
|
|
109
|
-
|
|
110
|
-
The recommended way to use the test server is with the async context manager:
|
|
111
|
-
|
|
112
|
-
.. code-block:: python
|
|
113
|
-
|
|
114
|
-
from fastapi_testing import create_test_server
|
|
115
|
-
|
|
116
|
-
async with create_test_server() as server:
|
|
117
|
-
# Your test code here
|
|
118
|
-
pass # Server automatically starts and stops
|
|
119
|
-
|
|
120
|
-
TestClient
|
|
121
|
-
~~~~~~~~~~~~~
|
|
122
|
-
|
|
123
|
-
The ``TestClient`` provides methods for making HTTP requests to your test server:
|
|
124
|
-
|
|
125
|
-
.. code-block:: python
|
|
126
|
-
|
|
127
|
-
# Available HTTP methods
|
|
128
|
-
await server.client.get("/path")
|
|
129
|
-
await server.client.post("/path", json=data)
|
|
130
|
-
await server.client.put("/path", json=data)
|
|
131
|
-
await server.client.delete("/path")
|
|
132
|
-
await server.client.patch("/path", json=data)
|
|
133
|
-
|
|
134
|
-
Response Assertions
|
|
135
|
-
~~~~~~~~~~~~~~~~~~~~
|
|
136
|
-
|
|
137
|
-
The ``TestResponse`` class provides convenient methods for assertions:
|
|
138
|
-
|
|
139
|
-
.. code-block:: python
|
|
140
|
-
|
|
141
|
-
response = await server.client.get("/path")
|
|
142
|
-
await response.expect_status(200) # Assert status code
|
|
143
|
-
data = await response.json() # Get JSON response
|
|
144
|
-
text = await response.text() # Get text response
|
|
145
|
-
|
|
146
|
-
Advanced Usage
|
|
147
|
-
----------------
|
|
148
|
-
|
|
149
|
-
Lifecycle Management
|
|
150
|
-
~~~~~~~~~~~~~~~~~~~~
|
|
151
|
-
|
|
152
|
-
You can define setup and cleanup operations using FastAPI's lifespan:
|
|
153
|
-
|
|
154
|
-
.. code-block:: python
|
|
155
|
-
|
|
156
|
-
from contextlib import asynccontextmanager
|
|
157
|
-
from fastapi import FastAPI
|
|
158
|
-
|
|
159
|
-
@asynccontextmanager
|
|
160
|
-
async def lifespan(app: FastAPI):
|
|
161
|
-
# Setup
|
|
162
|
-
print("Starting server")
|
|
163
|
-
yield
|
|
164
|
-
# Cleanup
|
|
165
|
-
print("Shutting down server")
|
|
166
|
-
|
|
167
|
-
async with create_test_server(lifespan=lifespan) as server:
|
|
168
|
-
# Your test code here
|
|
169
|
-
pass
|
|
170
|
-
|
|
171
|
-
Concurrent Requests
|
|
172
|
-
~~~~~~~~~~~~~~~~~~~
|
|
173
|
-
|
|
174
|
-
The framework supports testing concurrent requests:
|
|
175
|
-
|
|
176
|
-
.. code-block:: python
|
|
177
|
-
|
|
178
|
-
import asyncio
|
|
179
|
-
|
|
180
|
-
async with create_test_server() as server:
|
|
181
|
-
@server.app.get("/ping")
|
|
182
|
-
async def ping():
|
|
183
|
-
return {"status": "ok"}
|
|
184
|
-
|
|
185
|
-
responses = await asyncio.gather(*[
|
|
186
|
-
server.client.get("/ping")
|
|
187
|
-
for _ in range(5)
|
|
188
|
-
])
|
|
189
|
-
|
|
190
|
-
Configuration
|
|
191
|
-
~~~~~~~~~~~~~~
|
|
192
|
-
|
|
193
|
-
You can customize the server behavior:
|
|
194
|
-
|
|
195
|
-
.. code-block:: python
|
|
196
|
-
|
|
197
|
-
server = TestServer(
|
|
198
|
-
startup_timeout=30.0, # Seconds to wait for server startup
|
|
199
|
-
shutdown_timeout=10.0, # Seconds to wait for server shutdown
|
|
200
|
-
)
|
|
201
|
-
|
|
202
|
-
Best Practices
|
|
203
|
-
----------------
|
|
204
|
-
|
|
205
|
-
1. Always use the async context manager (``create_test_server``) when possible
|
|
206
|
-
2. Clean up resources in your tests, especially when managing state
|
|
207
|
-
3. Use pytest.mark.asyncio for your test functions
|
|
208
|
-
4. Handle exceptions appropriately in your tests
|
|
209
|
-
5. Use type hints to catch potential issues early
|
|
210
|
-
|
|
211
|
-
Error Handling
|
|
212
|
-
----------------
|
|
213
|
-
|
|
214
|
-
The framework provides clear error messages for common issues:
|
|
215
|
-
|
|
216
|
-
- Server startup timeout
|
|
217
|
-
- Port allocation failures
|
|
218
|
-
- Connection errors
|
|
219
|
-
- Invalid request formats
|
|
220
|
-
|
|
221
|
-
Limitations
|
|
222
|
-
--------------
|
|
223
|
-
|
|
224
|
-
- Only supports async test cases
|
|
225
|
-
- Requires Python 3.11+
|
|
226
|
-
- Designed specifically for FastAPI applications
|
|
227
|
-
|
|
228
|
-
Contributing
|
|
229
|
-
---------------
|
|
230
|
-
|
|
231
|
-
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
fastapi_testing/__init__.py,sha256=eLigKm7vW2AtvYSrTPysKdb7AtX8dEuQQOsPMKxRH8A,343
|
|
2
|
-
fastapi_testing/async_fastapi_testing.py,sha256=VSNzXo37dec34MulSY41fHFTZ8LuqVEGltA0hXlz3Ak,8466
|
|
3
|
-
fastapi_testing-0.2.0.dist-info/LICENSE,sha256=FS7LYVt91OiPx9wiH1K3jAWLS90HpvzKnNAvW_XLeqo,1065
|
|
4
|
-
fastapi_testing-0.2.0.dist-info/METADATA,sha256=jTm-INA4mV6q5HqKgoCsZM5KymUz1iAEwZkli4PWvvU,6308
|
|
5
|
-
fastapi_testing-0.2.0.dist-info/WHEEL,sha256=IYZQI976HJqqOpQU6PHkJ8fb3tMNBFjg-Cn-pwAbaFM,88
|
|
6
|
-
fastapi_testing-0.2.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|