From d6218f2e07c31d5be27c976d7d61ff2048f3cde2 Mon Sep 17 00:00:00 2001 From: Michael Chihlas Date: Sat, 25 Apr 2026 02:49:06 -0400 Subject: [PATCH] fix(tests): import all models in conftest so create_all sees the full schema MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The test_db fixture calls Base.metadata.create_all on a fresh test DB. That only creates tables for models that have been imported (and thus registered with Base.metadata) by the time the fixture runs. app.main imports app.core.database (which gives us Base) but does NOT eagerly import the model modules — most are pulled in lazily inside scheduler functions (archive_stale_ai_sessions etc.) and route modules. At fixture-setup time, only the handful of models touched by those eager imports are on the metadata, so any test that exercises PSA, network diagrams, ratings, escalations, etc. fails with \`UndefinedTableError: relation "X" does not exist\` and a cascade of 500s on every endpoint that queries the missing table. Adding \`from app import models as _models\` (rather than the bare \`import app.models\` which would shadow the \`app\` FastAPI instance imported just above) pulls in app/models/__init__.py, which itself imports every model module — registering all ~60 tables with Base.metadata before create_all runs. Verified locally: tests/test_psa_writeback_phase4.py went from 1 failed / 6 errors → 4 failed / 3 passed (the cascading errors were masking the actual passes). Co-Authored-By: Claude Opus 4.7 --- backend/tests/conftest.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 6d6e4358..56f2e94c 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -16,6 +16,14 @@ from app.main import app from app.core.database import Base, get_db from app.core.admin_database import get_admin_db from app.core.config import settings +# Import every model module so all tables are registered with Base.metadata +# before the test_db fixture calls create_all. app.main imports models lazily +# (inside scheduler functions and route modules), which is fine at runtime +# but leaves the metadata incomplete at fixture-setup time — surfacing as +# "relation X does not exist" errors for any model whose route/scheduler +# hasn't been loaded yet. The `from app import models` form avoids +# shadowing the `app` FastAPI instance imported just above. +from app import models as _models # noqa: F401 # Disable invite code requirement for tests settings.REQUIRE_INVITE_CODE = False