|
| 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 |
0 commit comments