"""Casino removal & settlement-only jackpot: behaviour tests over the live bot source. Source-only (AST) tests: no bot DB, no network, no aiogram runtime. """ from __future__ import annotations import ast import asyncio import copy import sqlite3 from pathlib import Path ROOT = Path(__file__).resolve().parents[1] BOT = ROOT / "bot" / "grok_bot.py" PANELS_SRC = (ROOT / "bot" / "forum_panels.py").read_text(encoding="utf-8") SRC = BOT.read_text(encoding="utf-8") TREE = ast.parse(SRC) def _fn(name): for node in TREE.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name: return node raise AssertionError(f"{name} not found in bot/grok_bot.py") def _exec(names, ns): # aiogram-декораторы исполнялись бы против несуществующего `router`: # копируем узлы и снимаем decorator_list (источник не меняем). body = [] for name in names: node = copy.deepcopy(_fn(name)) node.decorator_list = [] body.append(node) mod = ast.Module(body=body, type_ignores=[]) exec(compile(ast.fix_missing_locations(mod), "", "exec"), ns) return ns class FakeMessage: def __init__(self): self.sent = [] self.chat = type("C", (), {"id": 1})() self.from_user = type("U", (), {"id": 1})() async def answer(self, text, **kw): self.sent.append((text, kw)) return self class FakeQuery: def __init__(self): self.answers = [] self.message = FakeMessage() self.from_user = type("U", (), {"id": 1})() async def answer(self, text=None, **kw): self.answers.append((text, kw)) def _trap(*_a, **_k): raise AssertionError("finance/DB helper must not be called by a removed feature") def _ns(): return { "Message": FakeMessage, "CallbackQuery": FakeQuery, "log": type("L", (), {"debug": staticmethod(lambda *a, **k: None), "info": staticmethod(lambda *a, **k: None), "warning": staticmethod(lambda *a, **k: None), "exception": staticmethod(lambda *a, **k: None)})(), "_cas_wallet": _trap, "_cas_sub_cents": _trap, "_cas_add_cents": _trap, "_jpot_db": _trap, "_jpot_start_round": _trap, "_jpot_announce_result": _trap, } def _call_names(node): out = set() for sub in ast.walk(node): if isinstance(sub, ast.Call): f = sub.func if isinstance(f, ast.Name): out.add(f.id) elif isinstance(f, ast.Attribute): out.add(f.attr) return out def test_casino_block_removed(): for name in ("_CAS_BETS", "_CAS_CD", "_cas_get_cents", "_cas_menu_kb", "_cas_bet_kb", "_cb_casino_inner", "_cas_play_slot", "_cas_play_dice", "_cas_play_roul"): assert name not in SRC, name assert "/casino — слоты" not in SRC assert "🎰 /casino" not in SRC def test_casino_stub_answers_without_finance(): ns = _exec(["cmd_casino", "cb_casino"], _ns()) msg = FakeMessage() asyncio.run(ns["cmd_casino"](msg)) assert msg.sent and msg.sent[0][0] q = FakeQuery() asyncio.run(ns["cb_casino"](q)) assert q.answers and q.answers[0][0] def test_jackpot_creates_nothing(): for node in TREE.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in ( "cmd_jpot", "cmd_jpot_now", "_jpot_cb_inner", "cmd_jpot_settle"): calls = _call_names(node) assert "_jpot_start_round" not in calls, node.name assert "_jpot_announce_result" not in calls, node.name def test_cas_fmt_still_shared(): ns = _exec(["_cas_fmt"], _ns()) assert ns["_cas_fmt"](150) == "$1.50" def test_panels_and_topics_in_sync(): econ = None for node in TREE.body: if isinstance(node, ast.Assign) and any( isinstance(t, ast.Name) and t.id == "ECON_PANELS" for t in node.targets): econ = ast.literal_eval(node.value) assert econ is not None, "ECON_PANELS not found" assert "casino" not in econ topics = None for node in ast.parse(PANELS_SRC).body: if isinstance(node, ast.Assign) and any( isinstance(t, ast.Name) and t.id == "TOPICS" for t in node.targets): topics = ast.literal_eval(node.value) assert topics is not None assert "casino" not in {k for k, _ in topics} assert {k for k, _ in topics} == set(econ) class FakeBot: """Записывает вызовы Telegram; падение задаётся через `fail`.""" def __init__(self, fail=None): self.calls = [] self.fail = fail or {} async def edit_message_reply_markup(self, **kw): self.calls.append(("markup", kw)) if "markup" in self.fail: raise self.fail["markup"] async def send_message(self, chat_id, text=None, **kw): self.calls.append(("send", {"chat_id": chat_id, "text": text, **kw})) if "send" in self.fail: raise self.fail["send"] return type("M", (), {"message_id": 99})() async def edit_message_text(self, **kw): self.calls.append(("text", kw)) if "text" in self.fail: raise self.fail["text"] def sent(self): return [c[1]["text"] for c in self.calls if c[0] == "send"] def _closure_env(settle_row=(7,), bot=None): ns = _ns() ns["_cas_fmt"] = _exec(["_cas_fmt"], _ns())["_cas_fmt"] ns["_jpot_db"] = lambda: con return ns def test_jpot_closure_notifier_paid_reports_once(): con = sqlite3.connect(":memory:") con.execute("CREATE TABLE jpot_rounds(id INTEGER PRIMARY KEY, msg_id INTEGER)") con.execute("INSERT INTO jpot_rounds(id, msg_id) VALUES(7, 4242)") ns = {"_cas_fmt": _exec(["_cas_fmt"], _ns())["_cas_fmt"], "_jpot_db": lambda: con, "log": _ns()["log"]} _exec(["_jpot_closure_notify"], ns) fn = ns["_jpot_closure_notify"] bot = FakeBot() asyncio.run(fn(bot, 7, {"chat_id": 10, "pot": 5100, "paid": True, "outcome": "win"})) kinds = [c[0] for c in bot.calls] assert kinds == ["markup", "send"], kinds assert bot.calls[0][1]["message_id"] == 4242 assert bot.calls[0][1]["reply_markup"] is None text = bot.sent()[0] assert "#7" in text and "$51.00" in text assert "_jpot_announce_result" not in text con.close() def test_jpot_closure_notifier_unpaid_only_strips_keyboard(): con = sqlite3.connect(":memory:") con.execute("CREATE TABLE jpot_rounds(id INTEGER PRIMARY KEY, msg_id INTEGER)") con.execute("INSERT INTO jpot_rounds(id, msg_id) VALUES(7, 5)") ns = {"_cas_fmt": _exec(["_cas_fmt"], _ns())["_cas_fmt"], "_jpot_db": lambda: con, "log": _ns()["log"]} _exec(["_jpot_closure_notify"], ns) fn = ns["_jpot_closure_notify"] bot = FakeBot() asyncio.run(fn(bot, 7, {"chat_id": 10, "pot": 0, "outcome": "empty"})) assert [c[0] for c in bot.calls] == ["markup"] asyncio.run(fn(bot, 7, None)) assert [c[0] for c in bot.calls] == ["markup"] con.close() def test_jpot_closure_notifier_survives_telegram_errors(): con = sqlite3.connect(":memory:") con.execute("CREATE TABLE jpot_rounds(id INTEGER PRIMARY KEY, msg_id INTEGER)") con.execute("INSERT INTO jpot_rounds(id, msg_id) VALUES(7, 5)") ns = {"_cas_fmt": _exec(["_cas_fmt"], _ns())["_cas_fmt"], "_jpot_db": lambda: con, "log": _ns()["log"]} _exec(["_jpot_closure_notify"], ns) bot = FakeBot(fail={"markup": RuntimeError("message to edit not found"), "send": RuntimeError("chat not found")}) asyncio.run(ns["_jpot_closure_notify"](bot, 7, {"chat_id": 10, "pot": 100, "paid": True})) assert [c[0] for c in bot.calls] == ["markup", "send"] con.close() def test_worker_and_admin_settle_notify_closure(): worker = _fn("_jpot_worker") calls = _call_names(worker) assert "_jpot_settle" in calls and "_jpot_closure_notify" in calls assert "_jpot_announce_result" not in calls and "_jpot_start_round" not in calls assert "_jpot_closure_notify" in _call_names(_fn("cmd_jpot_settle")) def test_jpot_settle_command_reports_already_closed_without_outcome(): con = sqlite3.connect(":memory:") con.execute("CREATE TABLE jpot_rounds(id INTEGER PRIMARY KEY, status INTEGER, chat_id INTEGER)") con.execute("INSERT INTO jpot_rounds(id, status, chat_id) VALUES(3, 0, 1)") ns = _ns() ns["_jpot_db"] = lambda: con ns["_jpot_is_admin"] = lambda uid: True ns["_jpot_settle"] = lambda rid: None ns["_jpot_closure_notify"] = _trap _exec(["cmd_jpot_settle"], ns) msg = FakeMessage() asyncio.run(ns["cmd_jpot_settle"](msg)) text = msg.sent[-1][0] assert "уже закрыт" in text assert "None" not in text and "outcome" not in text con.close() def test_jpot_stub_strips_stale_keyboard_and_survives_expired_callback(): ns = _ns() _exec(["_jpot_cb_inner"], ns) q = FakeQuery() stripped = [] async def edit_reply_markup(**kw): stripped.append(kw) q.message.edit_reply_markup = edit_reply_markup asyncio.run(ns["_jpot_cb_inner"](q)) assert stripped and stripped[0]["reply_markup"] is None assert q.answers and "отключён" in q.answers[0][0] class Expired(FakeQuery): def __init__(self): super().__init__() self.message = None async def answer(self, text=None, **kw): raise RuntimeError("query is too old and response timeout expired") asyncio.run(ns["_jpot_cb_inner"](Expired())) def _panels_ns(): ns = {"__name__": "forum_panels_under_test"} exec(compile(PANELS_SRC, "forum_panels.py", "exec"), ns) return ns def _forum_db(directory): path = Path(directory) / "bot.db" con = sqlite3.connect(path) con.execute("""CREATE TABLE forum_topics(chat_id INTEGER NOT NULL, kind TEXT NOT NULL, thread_id INTEGER NOT NULL, title TEXT NOT NULL, panel_message_id INTEGER, created INTEGER NOT NULL, PRIMARY KEY(chat_id,kind), UNIQUE(chat_id,thread_id))""") con.commit() con.close() return path def test_retire_casino_panels_idempotent_and_metadata_only(tmp_path): ns = _panels_ns() db = _forum_db(tmp_path) con = sqlite3.connect(db) con.execute("INSERT INTO forum_topics(chat_id,kind,thread_id,title,panel_message_id,created)" " VALUES(10,'casino',77,'🎰 Казино',555,1)") con.execute("INSERT INTO forum_topics(chat_id,kind,thread_id,title,panel_message_id,created)" " VALUES(10,'econ',78,'💰 Экономика',556,1)") con.commit() con.close() bot = FakeBot() res = asyncio.run(ns["retire_casino_panels"](db, bot)) assert res == {"found": 1, "retired": 1, "failed": 0}, res assert [c[0] for c in bot.calls] == ["text"] kw = bot.calls[0][1] assert kw["message_id"] == 555 and kw["reply_markup"] is None and kw["chat_id"] == 10 con = sqlite3.connect(db) kinds = {r[0] for r in con.execute("SELECT kind FROM forum_topics")} con.close() assert kinds == {"econ"} bot2 = FakeBot() assert asyncio.run(ns["retire_casino_panels"](db, bot2)) == {"found": 0, "retired": 0, "failed": 0} assert bot2.calls == [] def test_retire_casino_panels_keeps_row_when_edit_fails_hard(tmp_path): ns = _panels_ns() db = _forum_db(tmp_path) con = sqlite3.connect(db) con.execute("INSERT INTO forum_topics(chat_id,kind,thread_id,title,panel_message_id,created)" " VALUES(10,'casino',77,'🎰 Казино',555,1)") con.commit() con.close() res = asyncio.run(ns["retire_casino_panels"](db, FakeBot(fail={"text": RuntimeError("chat not found")}))) assert res["found"] == 1 and res["retired"] == 0 and res["failed"] == 1, res con = sqlite3.connect(db) assert con.execute("SELECT COUNT(*) FROM forum_topics WHERE kind='casino'").fetchone()[0] == 1 con.close() gone = asyncio.run(ns["retire_casino_panels"]( db, FakeBot(fail={"text": RuntimeError("message to edit not found")}))) assert gone["retired"] == 1 and gone["failed"] == 0, gone def test_setup_retires_stale_casino_rows(): src = ast.parse(PANELS_SRC) setup = next(n for n in src.body if getattr(n, "name", "") == "_setup") assert "retire_casino_panels" in _call_names(setup)