From 9e46bdc460eb398a60bfa91704532168adfb74e8 Mon Sep 17 00:00:00 2001 From: Barcode Betty Date: Wed, 3 Jun 2026 12:16:03 +0000 Subject: [PATCH] fix(api): document dispose_engine lazy import + regression test (CAR-1135) - main.py: add docstring inside the lifespan function explaining why dispose_engine is lazy-imported rather than top-level. The original import path (top-level) crashed the container at import time with 'ImportError: cannot import name dispose_engine from cartsnitch_api.database' when database.py was stale or stripped during a CI build. Lazy import keeps the engine disposal behavior while preventing the module-load crash. - tests/test_openapi.py: add test_dispose_engine_importable_from_database that asserts dispose_engine is importable and callable. This is the exact path the deployed UAT image was failing on, captured as a regression test so a future regression lands in CI before deploy. Refs CAR-1135. Co-Authored-By: Paperclip --- src/cartsnitch_api/main.py | 6 ++++++ tests/test_openapi.py | 13 +++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/cartsnitch_api/main.py b/src/cartsnitch_api/main.py index 5a72b6b..66c1854 100644 --- a/src/cartsnitch_api/main.py +++ b/src/cartsnitch_api/main.py @@ -25,6 +25,12 @@ from cartsnitch_api.routes.user import router as user_router @asynccontextmanager async def lifespan(app: FastAPI): + # Lazy import: keep `dispose_engine` out of the top-level imports so a + # stale or partially-built database.py never breaks module load on + # container start. The function is required for graceful pool cleanup + # on shutdown; if the import fails, the cache_client.close() that + # follows the yield would mask it. See CAR-1135 for the original + # ImportError that motivated this pattern. from cartsnitch_api.database import dispose_engine await cache_client.initialize() diff --git a/tests/test_openapi.py b/tests/test_openapi.py index 2311567..d450430 100644 --- a/tests/test_openapi.py +++ b/tests/test_openapi.py @@ -3,8 +3,21 @@ import pytest from httpx import ASGITransport, AsyncClient +from cartsnitch_api.database import dispose_engine from cartsnitch_api.main import app + +def test_dispose_engine_importable_from_database(): + """Regression for CAR-1135: api main.py used to import dispose_engine + at module level. A stale database.py (no dispose_engine) crashed the + container at import time with ImportError on line 9. The fix moved + the import inside the lifespan function, but `dispose_engine` must + still be importable from `cartsnitch_api.database` for the lifespan + teardown to actually close pooled connections. + """ + assert callable(dispose_engine) + assert dispose_engine.__name__ == "dispose_engine" + EXPECTED_ROUTES = [ # Auth (3 — register/login/refresh are handled by Better-Auth service) ("get", "/auth/me"),