Files
iishko-public/tests/test_bot_schema.py
T
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

183 lines
8.9 KiB
Python

"""Bot-owned migrations on real temporary SQLite files, never production DBs."""
import sqlite3
import time
import pytest
import bot_schema
# Literal legacy contract, deliberately independent of the migration's own list.
EXPECTED_USER_COLUMNS = set("""
tg_id username token_name api_key created notified points referred_by ref_time
ref_awarded lang menu_style chat_mode waiting_prompt chat_count img_count quota_date
chat_model img_model vip last_checkin last_loyalty admin captcha_ok banned week_model
week_key last_active warned_at ref_credit key_locked rep quiz_last dice_last
last_bonus_lvl rep_last badge_lock last_bonus_ts rank_cache ref_notify vid_model
mus_model sub_penalized rep_give_day rep_give_n api_blocked api_block_reason
gate_member_ok gate_member_ts gate_warned_at agent_model effort prompt_on badge_until
""".split())
def test_fresh_database_has_complete_versioned_schema_and_indexed_hot_paths(tmp_path):
path = tmp_path / "bot.db"
bot_schema.initialize_bot_db(path)
with sqlite3.connect(path) as con:
assert con.execute("PRAGMA user_version").fetchone()[0] == bot_schema.SCHEMA_VERSION
columns = {row[1] for row in con.execute("PRAGMA table_info(users)")}
assert columns == EXPECTED_USER_COLUMNS
queries = [
("SELECT COUNT(*) FROM group_log WHERE uid=? AND ts>=?", (1, 0)),
("SELECT DISTINCT uid FROM group_log WHERE chat_id=? AND ts>?", (1, 0)),
("DELETE FROM group_log WHERE ts<?", (0,)),
]
for sql, args in queries:
plan = " ".join(row[3] for row in con.execute("EXPLAIN QUERY PLAN " + sql, args))
assert "SEARCH group_log" in plan, plan
assert "SCAN group_log" not in plan, plan
def test_legacy_partial_columns_are_adopted_without_resetting_users_or_money(tmp_path):
path = tmp_path / "legacy.db"
with sqlite3.connect(path) as con:
con.execute("CREATE TABLE users(tg_id INTEGER PRIMARY KEY, username TEXT, token_name TEXT, "
"api_key TEXT, created INTEGER, notified INTEGER DEFAULT 1, points INTEGER DEFAULT 0, "
"banned INTEGER DEFAULT 0)")
con.execute("INSERT INTO users VALUES(7,'fixture','fixture-token','fixture-key',1,1,900,1)")
con.execute("CREATE TABLE fixture_money(uid INTEGER PRIMARY KEY, quota INTEGER)")
con.execute("INSERT INTO fixture_money VALUES(7,123456)")
bot_schema.initialize_bot_db(path)
bot_schema.initialize_bot_db(path)
with sqlite3.connect(path) as con:
assert con.execute("SELECT points,banned,api_key FROM users WHERE tg_id=7").fetchone() == (900, 1, "fixture-key")
assert con.execute("SELECT quota FROM fixture_money WHERE uid=7").fetchone()[0] == 123456
assert con.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
def test_migration_failure_rolls_back_both_ddl_and_version(tmp_path, monkeypatch):
path = tmp_path / "failure.db"
def broken(con):
con.execute("CREATE TABLE should_roll_back(value INTEGER)")
raise sqlite3.OperationalError("fixture failure")
monkeypatch.setattr(bot_schema, "_activity_indexes", broken)
with sqlite3.connect(path) as con:
with pytest.raises(bot_schema.BotSchemaError, match="migration v2 failed"):
bot_schema.migrate_bot_schema(con)
assert not con.in_transaction
assert con.execute("PRAGMA user_version").fetchone()[0] == 0
assert not con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
def test_future_schema_is_refused_without_downgrade_or_data_changes(tmp_path):
path = tmp_path / "future.db"
with sqlite3.connect(path) as con:
con.execute("PRAGMA user_version=999")
con.execute("CREATE TABLE keep_me(value INTEGER)")
con.execute("INSERT INTO keep_me VALUES(12)")
with pytest.raises(bot_schema.BotSchemaError, match="unsupported bot schema version"):
bot_schema.initialize_bot_db(path)
with sqlite3.connect(path) as con:
assert con.execute("PRAGMA user_version").fetchone()[0] == 999
assert con.execute("SELECT value FROM keep_me").fetchall() == [(12,)]
def test_user_version_is_read_after_write_admission(tmp_path):
path = tmp_path / "race.db"
with sqlite3.connect(path) as con:
changed = False
def competing_starter(statement):
nonlocal changed
if statement == "BEGIN IMMEDIATE" and not changed:
changed = True
with sqlite3.connect(path) as other:
other.execute("PRAGMA user_version=999")
con.set_trace_callback(competing_starter)
with pytest.raises(bot_schema.BotSchemaError, match="unsupported bot schema version"):
bot_schema.migrate_bot_schema(con)
assert changed
assert con.execute("PRAGMA user_version").fetchone()[0] == 999
@pytest.mark.parametrize("mode", ["DELETE", "WAL"])
def test_existing_journal_mode_and_foreign_key_policy_are_not_changed(tmp_path, mode):
path = tmp_path / "journal.db"
with sqlite3.connect(path) as con:
con.execute("PRAGMA journal_mode=" + mode)
con.execute("PRAGMA foreign_keys=OFF")
bot_schema.migrate_bot_schema(con)
assert con.execute("PRAGMA journal_mode").fetchone()[0].lower() == mode.lower()
assert con.execute("PRAGMA foreign_keys").fetchone()[0] == 0
def test_active_caller_transaction_is_refused_not_committed(tmp_path):
with sqlite3.connect(tmp_path / "active.db") as con:
con.execute("CREATE TABLE existing(value INTEGER)")
con.execute("INSERT INTO existing VALUES(5)")
with pytest.raises(bot_schema.BotSchemaError, match="outside a transaction"):
bot_schema.migrate_bot_schema(con)
assert con.in_transaction
con.rollback()
assert con.execute("SELECT * FROM existing").fetchall() == []
def test_current_version_with_missing_index_is_not_silently_accepted(tmp_path):
path = tmp_path / "drift.db"
bot_schema.initialize_bot_db(path)
with sqlite3.connect(path) as con:
con.execute("DROP INDEX idx_group_log_ts")
with pytest.raises(bot_schema.BotSchemaError, match="missing bot activity index"):
bot_schema.initialize_bot_db(path)
def test_index_name_collision_does_not_mark_migration_successful(tmp_path):
path = tmp_path / "collision.db"
with sqlite3.connect(path) as con:
bot_schema._initial_schema(con)
con.commit()
con.execute("CREATE INDEX idx_group_log_ts ON group_log(uid)")
with pytest.raises(bot_schema.BotSchemaError, match="incompatible bot activity index"):
bot_schema.migrate_bot_schema(con)
assert con.execute("PRAGMA user_version").fetchone()[0] == 0
def test_initialize_prunes_only_old_group_logs_preserving_recent_records(tmp_path):
path = tmp_path / "retention.db"
bot_schema.initialize_bot_db(path)
now = int(time.time())
with sqlite3.connect(path) as con:
con.executemany("INSERT INTO group_log(chat_id,uid,ts) VALUES(1,2,?)", [(now - 31 * 86400,), (now,)])
bot_schema.initialize_bot_db(path)
with sqlite3.connect(path) as con:
assert con.execute("SELECT ts FROM group_log").fetchall() == [(now,)]
def test_retention_lock_does_not_abort_startup_after_successful_migration(tmp_path, monkeypatch, caplog):
path = tmp_path / "cleanup-lock.db"
real_connect = sqlite3.connect
class RetentionLocked(sqlite3.Connection):
def execute(self, sql, *args, **kwargs):
if sql.startswith("DELETE FROM group_log"):
raise sqlite3.OperationalError("fixture lock")
return super().execute(sql, *args, **kwargs)
monkeypatch.setattr(bot_schema.sqlite3, "connect",
lambda *args, **kwargs: real_connect(*args, factory=RetentionLocked, **kwargs))
bot_schema.initialize_bot_db(path)
assert "bot log retention skipped (OperationalError)" in caplog.text
assert "fixture lock" not in caplog.text
with real_connect(path) as con:
assert con.execute("PRAGMA user_version").fetchone()[0] == bot_schema.SCHEMA_VERSION
def test_migration_leaves_attached_gateway_schema_and_quota_untouched(tmp_path):
gateway = tmp_path / "gateway.db"
with sqlite3.connect(gateway) as con:
con.execute("CREATE TABLE users(id INTEGER PRIMARY KEY, quota INTEGER)")
con.execute("INSERT INTO users VALUES(7,654321)")
with sqlite3.connect(tmp_path / "bot.db") as con:
con.execute("ATTACH DATABASE ? AS gateway", (str(gateway),))
bot_schema.migrate_bot_schema(con)
assert con.execute("SELECT quota FROM gateway.users WHERE id=7").fetchone()[0] == 654321
assert con.execute("PRAGMA gateway.user_version").fetchone()[0] == 0
assert [r[1] for r in con.execute("PRAGMA gateway.table_info(users)")] == ["id", "quota"]