"""Regression tests for gateway `_tg_store_conn` ALTER seized migration. `gateway/grok-web-skin.py` is an executable aiohttp script with module-level side effects, so the migration function is AST-extracted and executed in an isolated namespace against temp SQLite databases and small fakes. Contract under test: only a real duplicate-column OperationalError is benign; any other OperationalError must be re-raised after the connection is closed, and `_TG_SCHEMA_READY` must stay False. The base schema is pre-seeded in the failure tests so that every statement before the ALTER is a guaranteed no-op and the ALTER is the first write attempt; otherwise the error would surface on `CREATE TABLE IF NOT EXISTS` outside the guarded block and the close-on-failure assertion would be moot. """ from __future__ import annotations import ast import os import sqlite3 from pathlib import Path import pytest ROOT = Path(__file__).resolve().parents[1] GATEWAY = ROOT / "gateway" / "grok-web-skin.py" _BASE_DDL = ( "CREATE TABLE IF NOT EXISTS tg_users(" "tg_id INTEGER PRIMARY KEY, username TEXT, password TEXT, created INTEGER)", "CREATE TABLE IF NOT EXISTS tg_share_events(" "user_id INTEGER, key TEXT, day TEXT, ts INTEGER, " "PRIMARY KEY(user_id, key, day))", "CREATE TABLE IF NOT EXISTS ip_claims(" "ip TEXT NOT NULL, token_name TEXT NOT NULL, " "first_seen INTEGER NOT NULL, last_seen INTEGER NOT NULL, " "PRIMARY KEY(ip, token_name))", "CREATE INDEX IF NOT EXISTS ip_claims_by_ip ON ip_claims(ip)", "CREATE TABLE IF NOT EXISTS ip_lock_events(" "ip TEXT, token_name TEXT, action TEXT, detail TEXT, ts INTEGER)", ) def _extract_source() -> str: text = GATEWAY.read_text(encoding="utf-8") tree = ast.parse(text, filename=str(GATEWAY)) for node in ast.walk(tree): if isinstance(node, ast.FunctionDef) and node.name == "_tg_store_conn": return ast.get_source_segment(text, node) pytest.fail("_tg_store_conn not found in gateway/grok-web-skin.py") class _Cursor: def fetchone(self): return None def fetchall(self): return [] class _TrackedConnection: """Delegates to a real sqlite3 connection and records close().""" def __init__(self, con): self._con = con self.closed = False def execute(self, *args, **kwargs): if self.closed: raise sqlite3.ProgrammingError("Cannot operate on a closed database.") return self._con.execute(*args, **kwargs) def commit(self): return self._con.commit() def close(self): if not self.closed: self.closed = True self._con.close() def __getattr__(self, name): return getattr(self._con, name) class _ScriptedConnection(_TrackedConnection): """Raises a chosen OperationalError on the ALTER statement.""" def __init__(self, error, trigger="ALTER TABLE"): self.error = error self.trigger = trigger self._con = None self.closed = False def execute(self, sql, *args, **kwargs): if self.trigger in sql: raise self.error return _Cursor() def commit(self): return None def close(self): self.closed = True class _SqliteModule: OperationalError = sqlite3.OperationalError ProgrammingError = sqlite3.ProgrammingError def __init__(self, connect): self.connect = connect def _load(connect, db_path, created): def tracking_connect(path, *args, **kwargs): con = connect(path, *args, **kwargs) created.append(con) return con ns = { "__name__": "gateway_tg_store_probe", "sqlite3": _SqliteModule(tracking_connect), "os": os, "TG_PROVISION_DB": str(db_path), "_TG_SCHEMA_READY": False, } exec(compile(_extract_source(), "", "exec"), ns, ns) return ns, ns["_tg_store_conn"] def _seed_base(db: Path) -> None: con = sqlite3.connect(db) for statement in _BASE_DDL: con.execute(statement) con.commit() con.close() def test_duplicate_column_is_ignored(tmp_path): db = tmp_path / "provision.db" _seed_base(db) seed = sqlite3.connect(db) seed.execute("ALTER TABLE tg_share_events ADD COLUMN seized INTEGER DEFAULT 0") seed.commit() seed.close() created = [] def connect_tracked(path, *args, **kwargs): return _TrackedConnection(sqlite3.connect(path, *args, **kwargs)) ns, fn = _load(connect_tracked, db, created) con = fn() try: assert ns["_TG_SCHEMA_READY"] is True assert created[0].closed is False columns = { row[1] for row in con.execute("PRAGMA table_info(tg_share_events)") } assert "seized" in columns assert con.execute("SELECT 1 FROM ip_claims LIMIT 1").fetchone() is None finally: con.close() def test_locked_database_reraises_and_closes(tmp_path): db = tmp_path / "provision.db" _seed_base(db) holder = sqlite3.connect(db, isolation_level=None) holder.execute("BEGIN IMMEDIATE") created = [] def connect_no_wait(path, *args, **kwargs): kwargs.pop("timeout", None) return _TrackedConnection(sqlite3.connect(path, timeout=0, **kwargs)) ns, fn = _load(connect_no_wait, db, created) try: with pytest.raises(sqlite3.OperationalError, match="locked"): fn() finally: holder.execute("ROLLBACK") holder.close() assert ns["_TG_SCHEMA_READY"] is False assert created and created[0].closed is True def test_readonly_database_reraises_and_closes(tmp_path): db = tmp_path / "provision.db" _seed_base(db) created = [] def connect_ro(path, *args, **kwargs): uri = Path(path).resolve().as_uri() + "?mode=ro" return _TrackedConnection(sqlite3.connect(uri, uri=True)) ns, fn = _load(connect_ro, db, created) with pytest.raises(sqlite3.OperationalError): fn() assert ns["_TG_SCHEMA_READY"] is False assert created and created[0].closed is True def test_unrelated_operational_error_is_not_swallowed(tmp_path): db = tmp_path / "provision.db" created = [] def connect_scripted(path, *args, **kwargs): return _ScriptedConnection( sqlite3.OperationalError("database disk image is malformed") ) ns, fn = _load(connect_scripted, db, created) with pytest.raises(sqlite3.OperationalError, match="malformed"): fn() assert ns["_TG_SCHEMA_READY"] is False assert created and created[0].closed is True