fastapi-testing 0.2.0__tar.gz → 0.2.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastapi_testing-0.2.2/PKG-INFO +401 -0
- fastapi_testing-0.2.2/README.md +370 -0
- {fastapi_testing-0.2.0 → fastapi_testing-0.2.2}/pyproject.toml +7 -6
- {fastapi_testing-0.2.0 → fastapi_testing-0.2.2}/src/fastapi_testing/__init__.py +10 -0
- fastapi_testing-0.2.2/src/fastapi_testing/async_fastapi_testing.py +594 -0
- fastapi_testing-0.2.0/PKG-INFO +0 -231
- fastapi_testing-0.2.0/docs/index.rst +0 -200
- fastapi_testing-0.2.0/src/fastapi_testing/async_fastapi_testing.py +0 -256
- {fastapi_testing-0.2.0 → fastapi_testing-0.2.2}/LICENSE +0 -0
|
@@ -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
|
+
|