fastapi-testing 0.2.0__tar.gz → 0.2.1__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.
@@ -0,0 +1,403 @@
1
+ Metadata-Version: 2.3
2
+ Name: fastapi-testing
3
+ Version: 0.2.1
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: pydantic (>=2.10.6,<3.0.0)
25
+ Requires-Dist: pydantic-settings (>=2.7.1,<3.0.0)
26
+ Requires-Dist: starlette (>=0.45.0,<0.46.0)
27
+ Requires-Dist: uvicorn (>=0.34.0,<0.35.0)
28
+ Requires-Dist: websockets (>=15.0,<16.0)
29
+ Project-URL: Homepage, https://github.com/descoped/fastapi-testing
30
+ Project-URL: Repository, https://github.com/descoped/fastapi-testing
31
+ Description-Content-Type: text/markdown
32
+
33
+ # FastAPI Testing
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
+ - Async-first design for modern Python applications
40
+ - Automatic port management for test servers
41
+ - Clean lifecycle management with context managers
42
+ - Built-in HTTP and WebSocket client support
43
+ - Proper cleanup of resources after tests
44
+ - Support for FastAPI's lifespan events
45
+ - Type-safe with full typing support
46
+
47
+ ## Installation
48
+
49
+ ```bash
50
+ pip install fastapi-testing
51
+ ```
52
+
53
+ ## Quick Start
54
+
55
+ Here's a simple example of how to test a FastAPI endpoint:
56
+
57
+ ```python
58
+ import pytest
59
+ from fastapi import FastAPI
60
+ from fastapi_testing import create_test_server
61
+
62
+ @pytest.mark.asyncio
63
+ async def test_hello_world():
64
+ async with create_test_server() as server:
65
+ @server.app.get("/hello")
66
+ async def hello():
67
+ return {"message": "Hello, World!"}
68
+
69
+ response = await server.client.get("/hello")
70
+ await response.expect_status(200)
71
+ data = await response.json()
72
+ assert data["message"] == "Hello, World!"
73
+ ```
74
+
75
+ ## Architecture
76
+
77
+ The following sequence diagram illustrates the lifecycle of a test using this framework:
78
+
79
+ ```mermaid
80
+ sequenceDiagram
81
+ participant Test
82
+ participant AsyncTestServer
83
+ participant PortGenerator
84
+ participant UvicornServer
85
+ participant FastAPI
86
+ participant AsyncTestClient
87
+
88
+ Test->>+AsyncTestServer: create_test_server()
89
+ AsyncTestServer->>+PortGenerator: get_port()
90
+ PortGenerator-->>-AsyncTestServer: available port
91
+
92
+ AsyncTestServer->>+UvicornServer: initialize
93
+ UvicornServer->>FastAPI: configure
94
+
95
+ AsyncTestServer->>+UvicornServer: start()
96
+ UvicornServer->>FastAPI: startup event
97
+ UvicornServer-->>AsyncTestServer: server ready
98
+
99
+ AsyncTestServer->>+AsyncTestClient: initialize
100
+ AsyncTestClient-->>-AsyncTestServer: client ready
101
+ AsyncTestServer-->>-Test: server instance
102
+
103
+ Note over Test,AsyncTestClient: Test execution happens here
104
+
105
+ Test->>+AsyncTestServer: cleanup (context exit)
106
+ AsyncTestServer->>+AsyncTestClient: close()
107
+ AsyncTestClient-->>-AsyncTestServer: closed
108
+
109
+ AsyncTestServer->>+UvicornServer: shutdown
110
+ UvicornServer->>FastAPI: shutdown event
111
+ UvicornServer-->>-AsyncTestServer: shutdown complete
112
+
113
+ AsyncTestServer->>+PortGenerator: release_port()
114
+ PortGenerator-->>-AsyncTestServer: port released
115
+ AsyncTestServer-->>-Test: cleanup complete
116
+ ```
117
+
118
+ ## Key Components
119
+
120
+ ### AsyncTestServer
121
+
122
+ The `AsyncTestServer` class is the core component that manages the lifecycle of your test FastAPI application:
123
+
124
+ ```python
125
+ from fastapi_testing import AsyncTestServer
126
+
127
+ server = AsyncTestServer()
128
+ await server.start()
129
+ # Use server.app to define routes
130
+ # Use server.client to make requests
131
+ await server.stop()
132
+ ```
133
+
134
+ ### Context Manager
135
+
136
+ The recommended way to use the test server is with the async context manager:
137
+
138
+ ```python
139
+ from fastapi_testing import create_test_server
140
+
141
+ async with create_test_server() as server:
142
+ # Your test code here
143
+ pass # Server automatically starts and stops
144
+ ```
145
+
146
+ ### AsyncTestClient
147
+
148
+ The `AsyncTestClient` provides methods for making HTTP requests to your test server:
149
+
150
+ ```python
151
+ # Available HTTP methods
152
+ await server.client.get("/path")
153
+ await server.client.post("/path", json=data)
154
+ await server.client.put("/path", json=data)
155
+ await server.client.delete("/path")
156
+ await server.client.patch("/path", json=data)
157
+ ```
158
+
159
+ ### Response Assertions
160
+
161
+ The `AsyncTestResponse` class provides convenient methods for assertions:
162
+
163
+ ```python
164
+ response = await server.client.get("/path")
165
+ await response.expect_status(200) # Assert status code
166
+ data = await response.json() # Get JSON response
167
+ text = await response.text() # Get text response
168
+ ```
169
+
170
+ ### WebSocket Testing
171
+
172
+ Test WebSocket endpoints with full protocol support:
173
+
174
+ ```python
175
+ @pytest.mark.asyncio
176
+ async def test_mixed_protocols(test_server):
177
+ # Define HTTP endpoint
178
+ @test_server.app.get("/api/data")
179
+ async def get_data():
180
+ return {"status": "ok"}
181
+
182
+ # Define WebSocket endpoint
183
+ @test_server.app.websocket("/ws/echo")
184
+ async def websocket_endpoint(websocket: WebSocket):
185
+ await websocket.accept(subprotocol="test-protocol")
186
+ while True:
187
+ try:
188
+ message = await websocket.receive()
189
+ if "text" in message:
190
+ data = json.loads(message["text"])
191
+ await websocket.send_json(data)
192
+ elif "bytes" in message:
193
+ await websocket.send_bytes(message["bytes"])
194
+ except WebSocketDisconnect:
195
+ return
196
+
197
+ # Test HTTP endpoint
198
+ http_response = await test_server.client.get("/api/data")
199
+ assert http_response.status_code == 200
200
+
201
+ # Configure WebSocket
202
+ config = WebSocketConfig(
203
+ subprotocols=["test-protocol"],
204
+ ping_interval=20.0,
205
+ ping_timeout=20.0
206
+ )
207
+
208
+ # Test WebSocket endpoint
209
+ ws_response = await test_server.client.websocket("/ws/echo", config)
210
+ try:
211
+ # Test JSON messages
212
+ test_json = {"message": "test"}
213
+ await test_server.client.ws.send_json(ws_response, test_json)
214
+ response = await test_server.client.ws.receive_json(ws_response)
215
+ assert response == test_json
216
+
217
+ # Test binary messages
218
+ test_data = b"binary test"
219
+ await test_server.client.ws.send_binary(ws_response, test_data)
220
+ response = await test_server.client.ws.receive_binary(ws_response)
221
+ assert response == test_data
222
+ finally:
223
+ await ws_response.websocket().close()
224
+ ```
225
+
226
+ #### WebSocket Message Operations
227
+
228
+ The WebSocketHelper provides comprehensive message handling:
229
+
230
+ ```python
231
+ # Send Operations
232
+ await client.ws.send_text(ws_response, "message")
233
+ await client.ws.send_json(ws_response, {"key": "value"})
234
+ await client.ws.send_binary(ws_response, b"data")
235
+
236
+ # Receive Operations
237
+ text = await client.ws.receive_text(ws_response)
238
+ json_data = await client.ws.receive_json(ws_response)
239
+ binary = await client.ws.receive_binary(ws_response)
240
+
241
+ # Message Expectations
242
+ await client.ws.expect_message(
243
+ ws_response,
244
+ expected="message",
245
+ timeout=1.0
246
+ )
247
+
248
+ # Collect Multiple Messages
249
+ messages = await client.ws.drain_messages(
250
+ ws_response,
251
+ timeout=1.0
252
+ )
253
+ ```
254
+
255
+ #### WebSocket Configuration
256
+
257
+ Configure connections with various options:
258
+
259
+ ```python
260
+ ws_config = WebSocketConfig(
261
+ subprotocols=["protocol"], # Supported subprotocols
262
+ compression=None, # Compression algorithm
263
+ extra_headers={}, # Additional headers
264
+ ping_interval=20.0, # Keep-alive interval
265
+ ping_timeout=20.0, # Ping timeout
266
+ max_size=2 ** 20, # Max message size (1MB)
267
+ max_queue=32, # Max queued messages
268
+ timeout=30.0 # Connection timeout
269
+ )
270
+ ```
271
+
272
+ ## Advanced Usage
273
+
274
+ ### Advanced Server Configuration
275
+
276
+ You can customize the server lifecycle using a reusable test fixture:
277
+
278
+ ```python
279
+ @pytest.fixture
280
+ async def test_server(
281
+ test_settings: Settings,
282
+ transaction_manager: TransactionManager
283
+ ) -> AsyncGenerator[AsyncTestServer, None]:
284
+ """Create test server with overridden settings and database connection"""
285
+
286
+ async def custom_lifespan(app: AppType) -> AsyncGenerator[None, Any]:
287
+ # Wire up test-specific dependencies
288
+ app.dependency_overrides.update({
289
+ get_settings: lambda: test_settings,
290
+ get_transaction_manager: lambda: transaction_manager,
291
+ get_db_pool: lambda: transaction_manager.pool
292
+ })
293
+
294
+ yield # Server handles requests during this period
295
+
296
+ # Cleanup after tests complete
297
+ await db.cleanup()
298
+
299
+ async with create_test_server(lifespan=custom_lifespan) as server:
300
+ yield server
301
+ ```
302
+
303
+ ### Testing Routes and Routers
304
+
305
+ You can test entire routers and complex route configurations:
306
+
307
+ ```python
308
+ @pytest.mark.asyncio
309
+ async def test_api(test_server: AsyncTestServer):
310
+ # Register routes/routers
311
+ test_server.app.include_router(your_router)
312
+
313
+ # Make requests
314
+ response = await test_server.client.get("/your-endpoint")
315
+ await response.expect_status(200)
316
+
317
+ # Test concurrent requests
318
+ responses = await asyncio.gather(*[
319
+ test_server.client.get("/endpoint")
320
+ for _ in range(5)
321
+ ])
322
+
323
+ for response in responses:
324
+ await response.expect_status(200)
325
+ ```
326
+
327
+ ### Lifecycle Management
328
+
329
+ You can define setup and cleanup operations using FastAPI's lifespan:
330
+
331
+ ```python
332
+ from contextlib import asynccontextmanager
333
+ from fastapi import FastAPI
334
+
335
+ @asynccontextmanager
336
+ async def lifespan(app: FastAPI):
337
+ # Setup
338
+ print("Starting server")
339
+ yield
340
+ # Cleanup
341
+ print("Shutting down server")
342
+
343
+ async with create_test_server(lifespan=lifespan) as server:
344
+ # Your test code here
345
+ pass
346
+ ```
347
+
348
+ ### Concurrent Requests
349
+
350
+ The framework supports testing concurrent requests:
351
+
352
+ ```python
353
+ import asyncio
354
+
355
+ async with create_test_server() as server:
356
+ @server.app.get("/ping")
357
+ async def ping():
358
+ return {"status": "ok"}
359
+
360
+ responses = await asyncio.gather(*[
361
+ server.client.get("/ping")
362
+ for _ in range(5)
363
+ ])
364
+ ```
365
+
366
+ ## Configuration
367
+
368
+ You can customize the server behavior:
369
+
370
+ ```python
371
+ server = AsyncTestServer(
372
+ startup_timeout=30.0, # Seconds to wait for server startup
373
+ shutdown_timeout=10.0, # Seconds to wait for server shutdown
374
+ )
375
+ ```
376
+
377
+ ## Best Practices
378
+
379
+ 1. Always use the async context manager (`create_test_server`) when possible
380
+ 2. Clean up resources in your tests, especially when managing state
381
+ 3. Use pytest.mark.asyncio for your test functions
382
+ 4. Handle exceptions appropriately in your tests
383
+ 5. Use type hints to catch potential issues early
384
+
385
+ ## Error Handling
386
+
387
+ The framework provides clear error messages for common issues:
388
+
389
+ - Server startup timeout
390
+ - Port allocation failures
391
+ - Connection errors
392
+ - Invalid request formats
393
+
394
+ ## Limitations
395
+
396
+ - Only supports async test cases
397
+ - Requires Python 3.11+
398
+ - Designed specifically for FastAPI applications
399
+
400
+ ## Contributing
401
+
402
+ Contributions are welcome! Please feel free to submit a Pull Request.
403
+