Files
smeta-web/tests/test_admin_migrate.py

90 lines
3.0 KiB
Python

"""migrate_admin_v2: индексы отдельной командой, init_db их не создаёт."""
import importlib
import os
import sqlite3
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "scripts"))
import migrate_admin_v2 as mig # noqa: E402
def _db(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
monkeypatch.setenv("SESSION_SECRET", "test")
monkeypatch.chdir(ROOT)
import db
importlib.reload(db)
db.init_db()
return tmp_path / "t.db"
def _indexes(db_path):
with sqlite3.connect(db_path) as c:
return {r[0] for r in c.execute(
"SELECT name FROM sqlite_master WHERE type='index'").fetchall()}
def test_init_db_has_no_heavy_indexes_then_migrate_adds(tmp_path, monkeypatch):
db = _db(tmp_path, monkeypatch)
before = _indexes(db)
assert "idx_audit_action_ts" not in before
assert "idx_audit_user_ts" not in before
assert "idx_messages_user_role_ts" not in before
r = mig.run(db)
assert r["ok"] is True and r["integrity"] == "ok", r
after = _indexes(db)
assert {"idx_messages_user_role_ts", "idx_audit_user_ts",
"idx_audit_action_ts"} <= after
r2 = mig.run(db)
assert r2["ok"] is True
assert all(i["status"] == "exists" for i in r2["indexes"]
if i["name"] not in ("idx_topups_status_ts", *mig.LEGACY_DROPS))
def test_dry_run_does_not_create(tmp_path, monkeypatch):
db = _db(tmp_path, monkeypatch)
r = mig.run(db, dry_run=True)
assert r["ok"] is True
assert "idx_audit_action_ts" not in _indexes(db)
def test_topups_index_only_if_table_exists(tmp_path, monkeypatch):
db = _db(tmp_path, monkeypatch)
with sqlite3.connect(db) as c:
c.execute("CREATE TABLE topups (status TEXT, ts REAL)")
r = mig.run(db)
assert r["ok"] is True
assert "idx_topups_status_ts" in _indexes(db)
def test_missing_db_is_code_2(tmp_path):
r = mig.run(tmp_path / "nope.db")
assert r["ok"] is False and r.get("code") == 2
def test_legacy_indexes_are_dropped(tmp_path, monkeypatch):
db = _db(tmp_path, monkeypatch)
with sqlite3.connect(db) as c:
c.execute("CREATE INDEX idx_messages_user_ts ON messages(username, timestamp)")
c.execute("CREATE INDEX idx_audit_user ON audit_log(username)")
r = mig.run(db)
assert r["ok"] is True, r
assert "idx_messages_user_ts" not in _indexes(db)
assert "idx_audit_user" not in _indexes(db)
def test_partial_failure_reports_what_was_created(tmp_path):
db = tmp_path / "partial.db"
with sqlite3.connect(db) as c:
c.executescript("""
CREATE TABLE messages (id INTEGER PRIMARY KEY, username TEXT, role TEXT, timestamp REAL);
CREATE TABLE audit_log (id INTEGER PRIMARY KEY, username TEXT);
""")
r = mig.run(db)
assert r["ok"] is False and r.get("code") == 2
assert any(i.get("status") == "created" for i in r["indexes"])
assert "idx_messages_user_role_ts" in _indexes(db)