"""Schema guard (D-13, D-17): Alembic is the only source of the schema, and it matches the models. If test_no_drift fails, you changed a model without a revision (or the reverse): cd local_backend alembic revision --autogenerate --rev-id NNNN_short_name -m "what changed" then REVIEW the generated file (SQLite batch ops, data moves) and run the tests again. """ import re from pathlib import Path import pytest from alembic.autogenerate import compare_metadata from alembic.migration import MigrationContext from sqlalchemy import create_engine, inspect, text from core.schema import V1DatabaseError, current_head, upgrade_to_head BACKEND = Path(__file__).resolve().parents[2] def _fresh_engine(tmp_path): return create_engine(f"sqlite:///{(tmp_path / 'g.db').as_posix()}") def test_upgrade_empty_db_then_no_drift(tmp_path): from database import Base import models.all # noqa: F401 eng = _fresh_engine(tmp_path) upgrade_to_head(eng) with eng.connect() as conn: ctx = MigrationContext.configure(conn, opts={"compare_type": True, "render_as_batch": True}) diff = compare_metadata(ctx, Base.metadata) version = conn.execute(text("select version_num from alembic_version")).scalar() eng.dispose() assert diff == [], "models and migrations drifted:\n" + "\n".join(map(str, diff)) assert version == current_head() def test_upgrade_is_idempotent(tmp_path): eng = _fresh_engine(tmp_path) upgrade_to_head(eng) upgrade_to_head(eng) # second start of the app: nothing to do, no error eng.dispose() def test_install_defaults_seeded(tmp_path): eng = _fresh_engine(tmp_path) upgrade_to_head(eng) with eng.connect() as conn: method = conn.execute(text("select value from pos_settings where key='security.login_method'")).scalar() eng.dispose() assert method == "password" def test_v1_database_is_refused(tmp_path): eng = _fresh_engine(tmp_path) with eng.begin() as conn: conn.execute(text("create table orders (id integer primary key)")) with pytest.raises(V1DatabaseError): upgrade_to_head(eng) assert "alembic_version" not in inspect(eng).get_table_names() eng.dispose() def test_nothing_calls_create_all(): offenders = [] for f in BACKEND.rglob("*.py"): rel = f.relative_to(BACKEND).as_posix() if rel.startswith(("tests/", "migrations/")) or "/__pycache__/" in rel: continue if re.search(r"\.create_all\(", f.read_text(encoding="utf-8", errors="ignore")): offenders.append(rel) assert offenders == [], f"use core.schema.upgrade_to_head() instead of create_all: {offenders}"