fastapi-testing 0.1.0__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.
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from fastapi_testing.async_fastapi_testing import (
|
|
2
|
+
PortGenerator,
|
|
3
|
+
UvicornTestServer,
|
|
4
|
+
TestServer,
|
|
5
|
+
TestClient,
|
|
6
|
+
TestResponse,
|
|
7
|
+
create_test_server,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"PortGenerator",
|
|
12
|
+
"UvicornTestServer",
|
|
13
|
+
"TestServer",
|
|
14
|
+
"TestClient",
|
|
15
|
+
"TestResponse",
|
|
16
|
+
"create_test_server",
|
|
17
|
+
]
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
import random
|
|
4
|
+
import socket
|
|
5
|
+
from contextlib import closing, asynccontextmanager
|
|
6
|
+
from typing import List, Optional, TypeVar, Any, Set, AsyncGenerator
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import uvicorn
|
|
10
|
+
from fastapi import FastAPI
|
|
11
|
+
from fastapi.applications import AppType
|
|
12
|
+
from starlette.types import Lifespan
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class PortGenerator:
|
|
18
|
+
def __init__(self, start: int = 8001, end: int = 9000):
|
|
19
|
+
self.start = start
|
|
20
|
+
self.end = end
|
|
21
|
+
self.used_ports: Set[int] = set()
|
|
22
|
+
|
|
23
|
+
def is_port_available(self, port: int) -> bool:
|
|
24
|
+
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
|
|
25
|
+
try:
|
|
26
|
+
sock.bind(('localhost', port))
|
|
27
|
+
return True
|
|
28
|
+
except (socket.error, OverflowError):
|
|
29
|
+
return False
|
|
30
|
+
|
|
31
|
+
def get_port(self) -> int:
|
|
32
|
+
available_ports = set(range(self.start, self.end + 1)) - self.used_ports
|
|
33
|
+
if not available_ports:
|
|
34
|
+
raise RuntimeError(f"No available ports in range {self.start}-{self.end}")
|
|
35
|
+
|
|
36
|
+
while available_ports:
|
|
37
|
+
port = random.choice(list(available_ports))
|
|
38
|
+
if self.is_port_available(port):
|
|
39
|
+
self.used_ports.add(port)
|
|
40
|
+
return port
|
|
41
|
+
available_ports.remove(port)
|
|
42
|
+
raise RuntimeError(f"No available ports found in range {self.start}-{self.end}")
|
|
43
|
+
|
|
44
|
+
def release_port(self, port: int) -> None:
|
|
45
|
+
self.used_ports.discard(port)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
_port_generator = PortGenerator()
|
|
49
|
+
|
|
50
|
+
T = TypeVar('T')
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class UvicornTestServer(uvicorn.Server):
|
|
54
|
+
"""Uvicorn test server with startup event support"""
|
|
55
|
+
|
|
56
|
+
def __init__(self, config: uvicorn.Config, startup_handler: asyncio.Event):
|
|
57
|
+
super().__init__(config)
|
|
58
|
+
self.startup_handler = startup_handler
|
|
59
|
+
|
|
60
|
+
async def startup(self, sockets: Optional[List] = None) -> None:
|
|
61
|
+
"""Override startup to signal when ready"""
|
|
62
|
+
await super().startup(sockets=sockets)
|
|
63
|
+
self.startup_handler.set()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class TestServer:
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
lifespan: Optional[Lifespan[AppType]] = None,
|
|
70
|
+
startup_timeout: float = 30.0,
|
|
71
|
+
shutdown_timeout: float = 10.0,
|
|
72
|
+
):
|
|
73
|
+
self.app = FastAPI(lifespan=lifespan)
|
|
74
|
+
self.startup_timeout = startup_timeout
|
|
75
|
+
self.shutdown_timeout = shutdown_timeout
|
|
76
|
+
self._startup_complete = asyncio.Event()
|
|
77
|
+
self._shutdown_complete = asyncio.Event()
|
|
78
|
+
self._server_task: Optional[asyncio.Task] = None
|
|
79
|
+
self._port: Optional[int] = None
|
|
80
|
+
self._host = "127.0.0.1"
|
|
81
|
+
self._client: Optional[TestClient] = None
|
|
82
|
+
self._server: Optional[UvicornTestServer] = None
|
|
83
|
+
|
|
84
|
+
async def start(self) -> None:
|
|
85
|
+
"""Start the server asynchronously with proper lifecycle management"""
|
|
86
|
+
if self._server_task is not None:
|
|
87
|
+
raise RuntimeError("Server is already running")
|
|
88
|
+
|
|
89
|
+
self._port = _port_generator.get_port()
|
|
90
|
+
startup_handler = asyncio.Event()
|
|
91
|
+
|
|
92
|
+
config = uvicorn.Config(
|
|
93
|
+
app=self.app,
|
|
94
|
+
host=self._host,
|
|
95
|
+
port=self._port,
|
|
96
|
+
log_level="error",
|
|
97
|
+
loop="asyncio"
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
self._server = UvicornTestServer(config=config, startup_handler=startup_handler)
|
|
101
|
+
|
|
102
|
+
# Create server task
|
|
103
|
+
self._server_task = asyncio.create_task(self._server.serve())
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
# Wait for startup with timeout
|
|
107
|
+
await asyncio.wait_for(startup_handler.wait(), timeout=self.startup_timeout)
|
|
108
|
+
|
|
109
|
+
# Initialize test client after server is confirmed running
|
|
110
|
+
self._client = TestClient(
|
|
111
|
+
base_url=self.base_url,
|
|
112
|
+
timeout=self.startup_timeout
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
self._startup_complete.set()
|
|
116
|
+
|
|
117
|
+
except (asyncio.TimeoutError, Exception) as e:
|
|
118
|
+
await self.stop()
|
|
119
|
+
if isinstance(e, asyncio.TimeoutError):
|
|
120
|
+
raise RuntimeError("Server startup timed out")
|
|
121
|
+
raise
|
|
122
|
+
|
|
123
|
+
async def stop(self) -> None:
|
|
124
|
+
"""Stop the server and clean up resources"""
|
|
125
|
+
if not self._startup_complete.is_set():
|
|
126
|
+
return
|
|
127
|
+
|
|
128
|
+
# Close the client first to avoid any ongoing requests during shutdown
|
|
129
|
+
if self._client:
|
|
130
|
+
await self._client.close()
|
|
131
|
+
self._client = None
|
|
132
|
+
|
|
133
|
+
if self._server_task:
|
|
134
|
+
try:
|
|
135
|
+
# Signal the server to shutdown gracefully
|
|
136
|
+
if self._server:
|
|
137
|
+
self._server.should_exit = True
|
|
138
|
+
|
|
139
|
+
# Wait for server task to complete
|
|
140
|
+
await asyncio.wait_for(self._server_task, timeout=self.shutdown_timeout)
|
|
141
|
+
|
|
142
|
+
except asyncio.TimeoutError:
|
|
143
|
+
logger.error("Timeout waiting for the server to shut down gracefully. Forcibly canceling the task.")
|
|
144
|
+
# Cancel if it didn't stop gracefully
|
|
145
|
+
if not self._server_task.done():
|
|
146
|
+
self._server_task.cancel()
|
|
147
|
+
await asyncio.gather(self._server_task, return_exceptions=True)
|
|
148
|
+
except asyncio.CancelledError:
|
|
149
|
+
logger.info("Server task was cancelled successfully.")
|
|
150
|
+
finally:
|
|
151
|
+
self._server_task = None
|
|
152
|
+
|
|
153
|
+
# Release the used port
|
|
154
|
+
if self._port:
|
|
155
|
+
_port_generator.release_port(self._port)
|
|
156
|
+
self._port = None
|
|
157
|
+
|
|
158
|
+
# Mark shutdown as complete
|
|
159
|
+
self._shutdown_complete.set()
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def base_url(self) -> str:
|
|
163
|
+
if not self._port:
|
|
164
|
+
raise RuntimeError("Server is not running")
|
|
165
|
+
return f"http://{self._host}:{self._port}"
|
|
166
|
+
|
|
167
|
+
async def __aenter__(self) -> 'TestServer':
|
|
168
|
+
await self.start()
|
|
169
|
+
return self
|
|
170
|
+
|
|
171
|
+
async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
172
|
+
await self.stop()
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def client(self) -> 'TestClient':
|
|
176
|
+
if not self._client:
|
|
177
|
+
raise RuntimeError("Server is not running")
|
|
178
|
+
return self._client
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class TestClient:
|
|
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
|
+
) -> 'TestResponse':
|
|
208
|
+
response = await self._client.request(method, url, **kwargs)
|
|
209
|
+
return TestResponse(response)
|
|
210
|
+
|
|
211
|
+
async def get(self, url: str, **kwargs: Any) -> 'TestResponse':
|
|
212
|
+
return await self.request('GET', url, **kwargs)
|
|
213
|
+
|
|
214
|
+
async def post(self, url: str, **kwargs: Any) -> 'TestResponse':
|
|
215
|
+
return await self.request('POST', url, **kwargs)
|
|
216
|
+
|
|
217
|
+
async def put(self, url: str, **kwargs: Any) -> 'TestResponse':
|
|
218
|
+
return await self.request('PUT', url, **kwargs)
|
|
219
|
+
|
|
220
|
+
async def delete(self, url: str, **kwargs: Any) -> 'TestResponse':
|
|
221
|
+
return await self.request('DELETE', url, **kwargs)
|
|
222
|
+
|
|
223
|
+
async def patch(self, url: str, **kwargs: Any) -> 'TestResponse':
|
|
224
|
+
return await self.request('PATCH', url, **kwargs)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
class TestResponse:
|
|
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) -> 'TestResponse':
|
|
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
|
+
@asynccontextmanager
|
|
247
|
+
async def create_test_server(
|
|
248
|
+
lifespan: Optional[Lifespan[AppType]] = None,
|
|
249
|
+
) -> AsyncGenerator[TestServer, None]:
|
|
250
|
+
"""Create and manage a TestServer instance with proper lifecycle"""
|
|
251
|
+
server = TestServer(lifespan=lifespan)
|
|
252
|
+
try:
|
|
253
|
+
await server.start()
|
|
254
|
+
yield server
|
|
255
|
+
finally:
|
|
256
|
+
await server.stop()
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Descoped
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: fastapi-testing
|
|
3
|
+
Version: 0.1.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.28.1,<0.29.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/main/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.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
fastapi_testing/__init__.py,sha256=y_FNfbR9CTquKShafVCtuK3G98wzURP0_V1XZetg8HU,313
|
|
2
|
+
fastapi_testing/async_fastapi_testing.py,sha256=w34HxkZT-ZSwpfJ7onVCHSqpBRirPYxbtZe-qNDLfYs,8381
|
|
3
|
+
fastapi_testing-0.1.0.dist-info/LICENSE,sha256=FS7LYVt91OiPx9wiH1K3jAWLS90HpvzKnNAvW_XLeqo,1065
|
|
4
|
+
fastapi_testing-0.1.0.dist-info/METADATA,sha256=KsoA2lxTFtxfxb_Ny4_I81ByO09VatwuXoplEMSUZ-E,6306
|
|
5
|
+
fastapi_testing-0.1.0.dist-info/WHEEL,sha256=IYZQI976HJqqOpQU6PHkJ8fb3tMNBFjg-Cn-pwAbaFM,88
|
|
6
|
+
fastapi_testing-0.1.0.dist-info/RECORD,,
|