Files
homelable/backend/tests/conftest.py
T
Pouzor d52f698de3 fix(docs): bring an existing documents table up to the current shape
Opening the Documentation section against a database that already had a
`documents` table failed with `no such column: documents.edited_at`.

`Base.metadata.create_all` creates a table that is missing; it never adds a
column to one that is already there. `edited_at` landed after the table had
been created on a machine running the branch, so that database kept the older
shape and every query naming the column failed — including the one behind the
section's first request.

The repo convention is that column additions go through `_try_migrate`, and the
documents tables were the one place leaning on `create_all` for more than the
initial CREATE. Every nullable or defaulted column is now restated in
DOCUMENT_DDL as an idempotent ALTER, the way the `device_inventory` migrations
are, so an existing table is brought up to the current shape at boot whatever
shape it starts from.

The test fixture applied the same DDL with a raw `exec_driver_sql`, which was
fine for pure CREATE statements but turns each of those ALTERs into a fatal
"duplicate column" on the fresh database create_all has just built. It goes
through `_try_migrate` too now — which is what its own comment already claimed
it did.

ha-relevant: no
2026-09-07 10:38:24 +02:00

91 lines
3.4 KiB
Python

import importlib
import os
# Must be set before any app import so pydantic-settings can resolve the required field.
os.environ.setdefault("SECRET_KEY", "test-only-secret-key-not-for-production")
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.core.security import hash_password
from app.db.database import DOCUMENT_DDL, Base, _try_migrate, get_db
from app.main import app
TEST_DB_URL = "sqlite+aiosqlite:///:memory:"
@pytest.fixture(autouse=True, scope="session")
def test_credentials():
"""Configure test auth credentials directly on settings."""
from app.core.config import settings
settings.auth_username = "admin"
settings.auth_password_hash = hash_password("admin")
@pytest.fixture
async def db_session():
engine = create_async_engine(TEST_DB_URL)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
# Apply the same documents DDL init_db does, through the same helper, so
# the suite matches boot. `_try_migrate` matters here: on a database
# create_all has just built, every ALTER in that list is a no-op that
# raises "duplicate column" — swallowing it is the point, not a leniency.
for label, sql in DOCUMENT_DDL:
await _try_migrate(conn, sql, label=label)
session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
# Background tasks open their own session through `AsyncSessionLocal` — the
# request-scoped `get_db` override does not reach them. Left alone they would
# run against the *real* configured database, so point the factory at the
# test engine everywhere it was imported by name.
patched = [
importlib.import_module(name)
for name in (
"app.db.database",
"app.api.routes.zigbee",
"app.api.routes.zwave",
"app.api.routes.proxmox",
"app.api.routes.scan",
)
]
originals = [
(module, getattr(module, "AsyncSessionLocal", None)) for module in patched
]
for module, original in originals:
if original is not None:
module.AsyncSessionLocal = session_factory
async with session_factory() as session:
yield session
for module, original in originals:
if original is not None:
module.AsyncSessionLocal = original
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await engine.dispose()
@pytest.fixture
async def client(db_session: AsyncSession):
app.dependency_overrides[get_db] = lambda: db_session
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
yield c
app.dependency_overrides.clear()
@pytest.fixture
async def headers(client: AsyncClient):
"""Authenticated Bearer headers for the default admin test user."""
res = await client.post("/api/v1/auth/login", json={"username": "admin", "password": "admin"})
return {"Authorization": f"Bearer {res.json()['access_token']}"}
@pytest.fixture(autouse=True)
def _reset_doc_search_probe():
"""Forget whether FTS5 was available — each test gets a fresh database."""
from app.services import doc_search
doc_search.reset_availability_cache()
yield
doc_search.reset_availability_cache()