332 lines
12 KiB
Python
332 lines
12 KiB
Python
import re
|
|
|
|
import pytest
|
|
from alembic.config import Config
|
|
from alembic.script import ScriptDirectory
|
|
from sqlalchemy import Table, inspect, text
|
|
from sqlalchemy.exc import OperationalError
|
|
from sqlmodel import Session, SQLModel, create_engine, select
|
|
|
|
from alembic import command
|
|
from app.model.models import Card, UserDB
|
|
from app.services.database import (
|
|
add_and_refresh,
|
|
configure_engine,
|
|
create_db_and_tables,
|
|
get_engine,
|
|
reset_engine,
|
|
)
|
|
from app.services.settings import settings
|
|
|
|
|
|
def test_configure_engine_and_reset(tmp_path, db_session):
|
|
"""configure_engine() is the single injection point for the whole app.
|
|
reset_engine() drops the engine again and rebuilds from settings
|
|
conftest's autouse _installed_engine fixture puts the shared test engine back.
|
|
"""
|
|
from app.services import database as database_service
|
|
|
|
url = f"sqlite:///{tmp_path / 'injected.db'}"
|
|
injected = create_engine(url, connect_args={"check_same_thread": False})
|
|
configure_engine(injected)
|
|
assert get_engine() is injected
|
|
|
|
# Clean database: create_db_and_tables() must create the file and stamp
|
|
# *the configured engine*, not the URL from alembic.ini/settings.
|
|
create_db_and_tables()
|
|
assert tmp_path.joinpath("injected.db").exists()
|
|
with Session(injected) as session:
|
|
stamped = session.exec(text("SELECT version_num FROM alembic_version")).all()
|
|
head = ScriptDirectory.from_config(
|
|
Config(settings.alembic_config)
|
|
).get_current_head()
|
|
assert [row[0] for row in stamped] == [head]
|
|
|
|
reset_engine()
|
|
rebuilt = get_engine()
|
|
assert rebuilt is not injected
|
|
assert str(rebuilt.url) == str(database_service.settings.sqlalchemy_database_url)
|
|
|
|
|
|
def test_add_and_refresh(db_session):
|
|
"""Test add_and_refresh helper function."""
|
|
user = UserDB(name="Test User", passwordhash="hashed")
|
|
|
|
# Add user
|
|
result = add_and_refresh(db_session, user)
|
|
|
|
# Assert that user is now in database with ID
|
|
assert result.id is not None
|
|
assert result.name == "Test User"
|
|
|
|
# Verify in database
|
|
db_user = db_session.get(UserDB, result.id)
|
|
assert db_user is not None
|
|
assert db_user.name == "Test User"
|
|
|
|
|
|
CARD_MIGRATION_REVISION = "b7c1d2e3f4a5"
|
|
CARD_COLUMNS = ["id", "key", "card_serial", "enabled", "name", "group_id", "last_used"]
|
|
PREVIOUS_REVISION = "93e8dda267e5"
|
|
|
|
|
|
def _upgrade_head(db_url: str) -> None:
|
|
alembic_cfg = Config(settings.alembic_config)
|
|
alembic_cfg.set_main_option("sqlalchemy.url", db_url)
|
|
command.upgrade(alembic_cfg, "head")
|
|
|
|
|
|
def _downgrade(db_url: str, to: str) -> None:
|
|
alembic_cfg = Config(settings.alembic_config)
|
|
alembic_cfg.set_main_option("sqlalchemy.url", db_url)
|
|
command.downgrade(alembic_cfg, to)
|
|
|
|
|
|
def _stamp(db_url: str, revision: str) -> None:
|
|
"""Mark a database as being exactly at *revision*.
|
|
|
|
command.stamp() walks the whole chain and would run the intermediate
|
|
revisions' upgrade(), which fails on a database that never had the timetable
|
|
table. The version row is all alembic needs to know where to continue.
|
|
"""
|
|
engine = create_engine(db_url)
|
|
with engine.connect() as connection:
|
|
connection.exec_driver_sql(
|
|
"CREATE TABLE IF NOT EXISTS alembic_version "
|
|
"(version_num VARCHAR(32) NOT NULL)"
|
|
)
|
|
connection.exec_driver_sql("DELETE FROM alembic_version")
|
|
connection.exec_driver_sql(
|
|
"INSERT INTO alembic_version (version_num) VALUES (?)", (revision,)
|
|
)
|
|
connection.commit()
|
|
engine.dispose()
|
|
|
|
|
|
LEGACY_CARD_DDL = """CREATE TABLE card (
|
|
\tid INTEGER NOT NULL,
|
|
\t"key" VARCHAR NOT NULL,
|
|
\tcard_serial VARCHAR NOT NULL,
|
|
\tenabled BOOLEAN NOT NULL,
|
|
\tname VARCHAR(32) NOT NULL,
|
|
\tgroup_id INTEGER,
|
|
\tPRIMARY KEY (id),
|
|
\tUNIQUE (name),
|
|
\tFOREIGN KEY(group_id) REFERENCES groupdb (id)
|
|
)"""
|
|
|
|
|
|
def _legacy_card_db(tmp_path):
|
|
"""A database as it looked before the last_used / non-nullable group_id change.
|
|
|
|
The card table is written with the DDL SQLite produced from the old model
|
|
(nullable group_id, unnamed FK, no last_used) and the database is stamped at
|
|
the previous revision, so `alembic upgrade head` has to repair it.
|
|
"""
|
|
db_file = tmp_path / "legacy.db"
|
|
engine = create_engine(f"sqlite:///{db_file}")
|
|
|
|
# Base tables from the current model, minus the card table built afterwards.
|
|
metadata = SQLModel.metadata
|
|
with engine.begin() as connection:
|
|
for table in metadata.sorted_tables:
|
|
if table.name != "card":
|
|
table.create(connection)
|
|
connection.execute(text(LEGACY_CARD_DDL))
|
|
connection.execute(text("INSERT INTO groupdb (name) VALUES ('legacy group')"))
|
|
connection.execute(
|
|
text(
|
|
"INSERT INTO card (key, card_serial, enabled, name, group_id)"
|
|
" VALUES ('legacy-key', '00:00:00:00:00:00:00', 1,"
|
|
" 'legacy_attached_card', 1)"
|
|
)
|
|
)
|
|
# Allowed only because the old column was nullable.
|
|
connection.execute(
|
|
text(
|
|
"INSERT INTO card (key, card_serial, enabled, name, group_id)"
|
|
" VALUES ('orphan-key', '00:00:00:00:00:00:00', 1,"
|
|
" 'legacy_orphan_card', NULL)"
|
|
)
|
|
)
|
|
|
|
_stamp(f"sqlite:///{db_file}", PREVIOUS_REVISION)
|
|
return db_file, engine
|
|
|
|
|
|
def _dispose(*engines) -> None:
|
|
"""sqlite engines keep their connection open, which pytest reports as
|
|
ResourceWarning: unclosed database."""
|
|
for engine in engines:
|
|
engine.dispose()
|
|
|
|
|
|
def _card_columns(engine):
|
|
return [
|
|
(column["name"], str(column["type"]), column["nullable"])
|
|
for column in inspect(engine).get_columns("card")
|
|
]
|
|
|
|
|
|
def _split_clauses(ddl: str) -> list[str]:
|
|
"""Split a CREATE TABLE body on top level commas (VARCHAR(32) keeps its own)."""
|
|
body = ddl[ddl.index("(") + 1 : ddl.rindex(")")]
|
|
clauses, depth, current = [], 0, ""
|
|
for char in body:
|
|
if char == "(":
|
|
depth += 1
|
|
elif char == ")":
|
|
depth -= 1
|
|
if char == "," and depth == 0:
|
|
clauses.append(current.strip())
|
|
current = ""
|
|
else:
|
|
current += char
|
|
clauses.append(current.strip())
|
|
return [clause for clause in clauses if clause]
|
|
|
|
|
|
def _card_ddl(engine) -> str:
|
|
"""The card CREATE TABLE as stored in sqlite_master, normalized so it can be
|
|
compared across databases.
|
|
|
|
op.batch_alter_table quotes the table name and reorders the table level
|
|
constraints, which is cosmetic; the columns and their nullability are what
|
|
the comparison is about.
|
|
"""
|
|
with engine.connect() as connection:
|
|
row = connection.execute(
|
|
text("SELECT sql FROM sqlite_master WHERE name = 'card'")
|
|
).one()
|
|
clauses = _split_clauses(row[0].replace('"', ""))
|
|
columns = [clause for clause in clauses if clause.split(" ")[0] in CARD_COLUMNS]
|
|
constraints = sorted(clause for clause in clauses if clause not in columns)
|
|
return re.sub(
|
|
r"\s+", " ", "CREATE TABLE card ( " + ", ".join(columns + constraints) + " )"
|
|
).strip()
|
|
|
|
|
|
def test_card_not_null_migration_matches_the_model_schema(tmp_path):
|
|
"""alembic upgrade head on a pre-change database ends up with exactly the
|
|
schema SQLModel.metadata.create_all() builds from the current model.
|
|
|
|
create_db_and_tables() only bootstraps an *empty* database, so without this
|
|
migration every existing deployment keeps a nullable group_id and no
|
|
last_used column, and reading a Card fails with
|
|
'no such column: card.last_used'.
|
|
"""
|
|
db_file, legacy_engine = _legacy_card_db(tmp_path)
|
|
assert "last_used" not in [name for name, _, _ in _card_columns(legacy_engine)]
|
|
assert [c for c in _card_columns(legacy_engine) if c[0] == "group_id"][0][2] is True
|
|
|
|
_upgrade_head(f"sqlite:///{db_file}")
|
|
|
|
fresh_engine = create_engine(f"sqlite:///{tmp_path / 'fresh.db'}")
|
|
SQLModel.metadata.create_all(fresh_engine)
|
|
assert _card_columns(legacy_engine) == _card_columns(fresh_engine)
|
|
assert _card_ddl(legacy_engine) == _card_ddl(fresh_engine)
|
|
_dispose(legacy_engine, fresh_engine)
|
|
assert _card_columns(legacy_engine) == [
|
|
("id", "INTEGER", False),
|
|
("key", "VARCHAR", False),
|
|
("card_serial", "VARCHAR", False),
|
|
("enabled", "BOOLEAN", False),
|
|
("name", "VARCHAR(32)", False),
|
|
("group_id", "INTEGER", False),
|
|
("last_used", "DATETIME", False),
|
|
]
|
|
|
|
|
|
def test_card_not_null_migration_backfills_and_keeps_assigned_cards(tmp_path):
|
|
"""Existing rows get a last_used value and the attached card keeps its group;
|
|
only the orphaned row the nullable FK allowed is removed."""
|
|
db_file, engine = _legacy_card_db(tmp_path)
|
|
_upgrade_head(f"sqlite:///{db_file}")
|
|
|
|
with Session(engine) as session:
|
|
attached = session.exec(
|
|
select(Card).where(Card.name == "legacy_attached_card")
|
|
).one()
|
|
assert attached.group_id is not None
|
|
assert attached.last_used is not None
|
|
assert attached.last_used.tzinfo is not None
|
|
assert (
|
|
session.exec(
|
|
select(Card).where(Card.name == "legacy_orphan_card")
|
|
).one_or_none()
|
|
is None
|
|
)
|
|
|
|
|
|
def test_card_not_null_migration_round_trip(tmp_path):
|
|
"""The downgrade restores the old nullable schema and the upgrade reapplies
|
|
the change without a batch reflection error."""
|
|
db_file, engine = _legacy_card_db(tmp_path)
|
|
_upgrade_head(f"sqlite:///{db_file}")
|
|
migrated_ddl = _card_ddl(engine)
|
|
|
|
_downgrade(f"sqlite:///{db_file}", PREVIOUS_REVISION)
|
|
assert [c for c in _card_columns(engine) if c[0] == "group_id"][0][2] is True
|
|
assert "last_used" not in [name for name, _, _ in _card_columns(engine)]
|
|
|
|
_upgrade_head(f"sqlite:///{db_file}")
|
|
assert _card_ddl(engine) == migrated_ddl
|
|
_dispose(engine)
|
|
|
|
|
|
def test_card_not_null_migration_leaves_a_bootstrapped_database_alone(tmp_path):
|
|
"""A database create_db_and_tables() bootstrapped from the current model is
|
|
stamped at head, so `alembic upgrade head` is a no-op on it."""
|
|
db_file = tmp_path / "current.db"
|
|
url = f"sqlite:///{db_file}"
|
|
engine = create_engine(url)
|
|
with engine.begin() as connection:
|
|
for table in SQLModel.metadata.sorted_tables:
|
|
Table(table.name, SQLModel.metadata).create(connection)
|
|
_stamp(url, CARD_MIGRATION_REVISION)
|
|
before = _card_ddl(engine)
|
|
|
|
_upgrade_head(url)
|
|
|
|
assert _card_ddl(engine) == before
|
|
_dispose(engine)
|
|
|
|
|
|
def test_card_not_null_migration_is_not_repeatable_on_an_already_tightened_table(
|
|
tmp_path,
|
|
):
|
|
"""The revision is not idempotent SQL: it assumes a pre-change card table.
|
|
|
|
A deployment that already has the column (manually patched, or rebuilt from
|
|
the model) but is still stamped at the previous revision fails here. That is
|
|
why create_db_and_tables() stamps a freshly created database at head instead
|
|
of running the scripts.
|
|
"""
|
|
db_file = tmp_path / "already_tightened.db"
|
|
url = f"sqlite:///{db_file}"
|
|
engine = create_engine(url)
|
|
with engine.begin() as connection:
|
|
for table in SQLModel.metadata.sorted_tables:
|
|
Table(table.name, SQLModel.metadata).create(connection)
|
|
_stamp(url, PREVIOUS_REVISION)
|
|
|
|
with pytest.raises(OperationalError) as excinfo:
|
|
_upgrade_head(url)
|
|
assert "duplicate column name: last_used" in str(excinfo.value)
|
|
_dispose(engine)
|
|
|
|
|
|
def test_card_not_null_migration_head_is_the_scripts_head(tmp_path):
|
|
"""The new revision is the head the rest of the suite stamps databases with."""
|
|
db_file, engine = _legacy_card_db(tmp_path)
|
|
_upgrade_head(f"sqlite:///{db_file}")
|
|
with engine.connect() as connection:
|
|
stamped = connection.execute(
|
|
text("SELECT version_num FROM alembic_version")
|
|
).all()
|
|
head = ScriptDirectory.from_config(
|
|
Config(settings.alembic_config)
|
|
).get_current_head()
|
|
assert [row[0] for row in stamped] == [head] == [CARD_MIGRATION_REVISION]
|
|
_dispose(engine)
|