Skip to content

Commit f8d705e

Browse files
committed
test: 🚨 Ensure FastAPI setup works as expected
1 parent 1825341 commit f8d705e

File tree

4 files changed

+62
-1
lines changed

4 files changed

+62
-1
lines changed

‎README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ from yourapp.loader import loader
5555

5656
@asynccontextmanager
5757
async def lifespan(app: FastAPI):
58-
loader.setup() # Setup everythign on FastAPI startup
58+
loader.setup() # Setup everything on FastAPI startup
5959
yield
6060

6161

‎pyproject.toml

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ flake8-print = "^5.0.0"
2424
flake8-debugger = "^4.1.2"
2525
pytest-cov = ">=3,<5"
2626
tox = ">=3.26,<5.0"
27+
httpx = ">=0.24.1,<1.0.0"
2728

2829
[tool.isort]
2930
multi_line_output = 3

‎tests/test_fastapi_integration.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
from contextlib import asynccontextmanager
2+
3+
from fastapi import FastAPI
4+
from fastapi.testclient import TestClient
5+
6+
from fastapi_module_loader import BaseModule, ModuleLoader
7+
8+
9+
class TrackingModule(BaseModule):
10+
is_load: bool = False
11+
is_pre_setup: bool = False
12+
is_setup: bool = False
13+
is_post_setup: bool = False
14+
15+
def load(self) -> None:
16+
self.is_load = True
17+
18+
def pre_setup(self) -> None:
19+
self.is_pre_setup = True
20+
21+
def setup(self) -> None:
22+
self.is_setup = True
23+
24+
def post_setup(self) -> None:
25+
self.is_post_setup = True
26+
27+
28+
loader = ModuleLoader(
29+
[
30+
"tests.test_fastapi_integration.TrackingModule",
31+
],
32+
)
33+
34+
35+
@asynccontextmanager
36+
async def lifespan(app: FastAPI):
37+
loader.setup() # Setup everything on FastAPI startup
38+
yield
39+
40+
41+
loader.load() # Ensure everything is loaded
42+
app = FastAPI(lifespan=lifespan) # Pass the lifespan context manager to FastAPI
43+
44+
45+
@app.get("/")
46+
async def root():
47+
assert loader.is_loaded is True
48+
assert loader.loaded_modules[0].is_load is True
49+
assert loader.is_setup is True
50+
assert loader.loaded_modules[0].is_pre_setup is True
51+
assert loader.loaded_modules[0].is_setup is True
52+
assert loader.loaded_modules[0].is_post_setup is True
53+
return {"message": "all ok"}
54+
55+
56+
def test_fastapi_integration() -> None:
57+
with TestClient(app) as client:
58+
response = client.get("/")
59+
assert response.status_code == 200

‎tox.ini

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ envlist =
99
[testenv]
1010
deps =
1111
pytest
12+
httpx
1213
setenv =
1314
PYTHONPATH = .
1415
commands = pytest

0 commit comments

Comments
 (0)