|
| 1 | +import asyncio |
| 2 | +import importlib.util |
| 3 | +import sys |
| 4 | +import types |
| 5 | +import unittest |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +from fastapi import APIRouter |
| 9 | + |
| 10 | + |
| 11 | +class RuntimeTest(unittest.TestCase): |
| 12 | + @classmethod |
| 13 | + def setUpClass(cls): |
| 14 | + config = types.ModuleType("config") |
| 15 | + config.settings = types.SimpleNamespace(DB_URL="mongodb://example/test", DB_NAME="sample", HOST="127.0.0.1", DEBUG_MODE=False, PORT=8000) |
| 16 | + sys.modules["config"] = config |
| 17 | + |
| 18 | + todo_routers = types.ModuleType("apps.todo.routers") |
| 19 | + router = APIRouter() |
| 20 | + @router.get("/hello") |
| 21 | + async def hello(): |
| 22 | + return {"ok": True} |
| 23 | + todo_routers.router = router |
| 24 | + sys.modules["apps.todo.routers"] = todo_routers |
| 25 | + |
| 26 | + target = Path(__file__).resolve().parents[1] / "backend" / "main.py" |
| 27 | + spec = importlib.util.spec_from_file_location("farm_intro_main", target) |
| 28 | + cls.mod = importlib.util.module_from_spec(spec) |
| 29 | + spec.loader.exec_module(cls.mod) |
| 30 | + |
| 31 | + class FakeClient: |
| 32 | + def __init__(self, *args, **kwargs): |
| 33 | + self.closed = False |
| 34 | + def __getitem__(self, name): |
| 35 | + return {"db_name": name} |
| 36 | + def close(self): |
| 37 | + self.closed = True |
| 38 | + |
| 39 | + cls.mod.AsyncMongoClient = FakeClient |
| 40 | + |
| 41 | + def test_startup_and_router_mount(self): |
| 42 | + asyncio.run(self.mod.startup_db_client()) |
| 43 | + self.assertTrue(hasattr(self.mod.app, "mongodb")) |
| 44 | + paths = {route.path for route in self.mod.app.routes} |
| 45 | + self.assertIn("/task/hello", paths) |
| 46 | + asyncio.run(self.mod.shutdown_db_client()) |
| 47 | + self.assertTrue(self.mod.app.mongodb_client.closed) |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + unittest.main() |
0 commit comments