From 5a6f4cd44c0df57f2e6241e2ff7cf2720861df69 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 | 7 +++++++ tests/test_openapi.py | 13 +++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/cartsnitch_api/main.py b/src/cartsnitch_api/main.py index bd5a569..265ba54 100644 --- a/src/cartsnitch_api/main.py +++ b/src/cartsnitch_api/main.py @@ -25,7 +25,14 @@ 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() yield await cache_client.close() diff --git a/tests/test_openapi.py b/tests/test_openapi.py index 7379f84..5cb5f77 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 (7) ("post", "/auth/register"),