Files
iishko-public/tests/test_daily_wallet_gate.py
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

180 lines
7.0 KiB
Python

"""Focused regression tests for the daily cube wallet gate.
Synthetic temp SQLite only. The only source-level assertion is that
``_daily_flow`` no longer accepts a caller-supplied token flag.
"""
import ast
import sqlite3
import sys
import time
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent))
import daily_checkin
import quest_economy
UID = 1001
HERE = Path(__file__).resolve().parent
BOT = HERE.parent / "bot" / "grok_bot.py"
def _bot_db(path, token_name=None):
if path.exists():
path.unlink()
con = sqlite3.connect(str(path))
con.executescript("""
CREATE TABLE users(
tg_id INTEGER PRIMARY KEY, token_name TEXT, banned INTEGER DEFAULT 0,
api_blocked INTEGER DEFAULT 0, quiz_last TEXT, last_checkin TEXT,
gate_member_ok INTEGER, gate_member_ts INTEGER DEFAULT 0,
created INTEGER DEFAULT 0, lang TEXT, badge_lock INTEGER DEFAULT 0,
badge_until INTEGER DEFAULT 0, points INTEGER DEFAULT 0, rep INTEGER DEFAULT 0);
CREATE TABLE econ_tx(
id INTEGER PRIMARY KEY AUTOINCREMENT, src INTEGER NOT NULL, dst INTEGER NOT NULL,
units INTEGER NOT NULL, type TEXT NOT NULL, ts INTEGER NOT NULL, ref TEXT,
wallet_id INTEGER);
CREATE TABLE kv(k TEXT PRIMARY KEY, v TEXT);
CREATE TABLE group_log(uid INTEGER, ts INTEGER);
""")
con.execute("INSERT INTO users(tg_id,token_name,lang) VALUES(?,?,'ru')", (UID, token_name))
con.commit()
con.close()
def _gw_db(path, token_name, token_id=7, remain=0, status=1, deleted_at=None):
if path.exists():
path.unlink()
con = sqlite3.connect(str(path))
con.executescript("""
CREATE TABLE users(tg_id INTEGER PRIMARY KEY, token_name TEXT,
banned INTEGER DEFAULT 0, api_blocked INTEGER DEFAULT 0);
CREATE TABLE tokens(id INTEGER PRIMARY KEY, name TEXT, remain_quota INTEGER,
status INTEGER DEFAULT 1, deleted_at INTEGER);
""")
con.execute("INSERT INTO users(tg_id,token_name) VALUES(?,?)", (UID, token_name))
con.execute("INSERT INTO tokens(id,name,remain_quota,status,deleted_at) VALUES(?,?,?,?,?)",
(token_id, token_name, remain, status, deleted_at))
con.commit()
con.close()
def _env(tmp_path, token_name, bot_token_name=None):
bot = tmp_path / "bot.db"
gw = tmp_path / "gw.db"
_bot_db(bot, bot_token_name)
_gw_db(gw, token_name)
quest_economy.prepare(str(bot), str(gw))
return str(bot), str(gw)
def _count(path, sql, args=()):
con = sqlite3.connect(path)
try:
return con.execute(sql, args).fetchone()[0]
finally:
con.close()
def test_canonical_live_key_rolls_even_when_binding_is_empty(tmp_path):
bot, gw = _env(tmp_path, "tg1001", bot_token_name=None)
st = daily_checkin.claim(bot, gw, UID, 1, now=int(time.time()), value=3, source="bot")
assert st.get("ok") is True, st
assert st.get("error") is None
assert _count(bot, "SELECT COUNT(*) FROM econ_tx WHERE ref=?", ("daily:%d:%s" % (UID, daily_checkin._day()),)) == 1
def test_only_unbound_secondary_key_is_refused_without_consuming_day(tmp_path):
bot, gw = _env(tmp_path, "tg1001-k2", bot_token_name=None)
now = int(time.time())
st = daily_checkin.claim(bot, gw, UID, 1, now=now, value=3, source="bot")
assert st.get("ok") is False
assert st.get("error") == "wallet"
assert st.get("paid") is not True
day = daily_checkin._day(now)
assert _count(bot, "SELECT COUNT(*) FROM econ_tx WHERE ref=?", ("daily:%d:%s" % (UID, day),)) == 0
assert _count(bot, "SELECT COUNT(*) FROM kv WHERE k LIKE 'ec_ddice:%' OR k LIKE 'ec_dice:%' "
"OR k LIKE 'ec_q:%'") == 0
assert _count(bot, "SELECT COUNT(*) FROM users WHERE tg_id=? AND last_checkin IS NULL", (UID,)) == 1
def test_bound_secondary_has_a_wallet(tmp_path):
# Existing explicit binding is wallet authority even for a secondary name.
bot, gw = _env(tmp_path, "tg1001-k2", bot_token_name="tg1001-k2")
st = daily_checkin.status(bot, gw, UID, rank=1, now=int(time.time()))
assert st.get("ok") is True, st
assert st.get("wallet") is True
assert st.get("claimed") is False
def test_pm_binding_has_a_wallet(tmp_path):
bot, gw = _env(tmp_path, "pm1001", bot_token_name="pm1001")
st = daily_checkin.status(bot, gw, UID, rank=1, now=int(time.time()))
assert st.get("ok") is True, st
assert st.get("wallet") is True
@pytest.mark.skipif(not BOT.exists(), reason="run beside the patched iishko_bot.py")
def test_daily_flow_has_no_caller_token_flag():
tree = ast.parse(BOT.read_text(encoding="utf-8"))
flow = None
for node in ast.walk(tree):
if isinstance(node, ast.AsyncFunctionDef) and node.name == "_daily_flow":
flow = node
break
assert flow is not None
assert [a.arg for a in flow.args.args] == ["bot", "chat_id", "uid"]
assert "token_ok" not in {n.id for n in ast.walk(flow) if isinstance(n, ast.Name)}
calls = [n for n in ast.walk(tree)
if isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
and n.func.id == "_daily_flow"]
assert len(calls) == 2
assert all(len(call.args) == 3 for call in calls)
src = BOT.read_text(encoding="utf-8")
assert 'if not st.get("wallet")' in src
assert '{**st, "ok": False, "error": "wallet"}' in src
@pytest.mark.parametrize(
"state,expected_calls,error",
[
({"ok": True, "claimed": False, "wallet": True}, ["roll"], None),
({"ok": True, "claimed": False, "wallet": False}, [], "wallet"),
({"ok": True, "claimed": True, "pending": True, "wallet": True}, ["claim"], None),
({"ok": True, "claimed": True, "paid": True, "wallet": True}, [], None),
({"ok": False, "error": "blocked"}, [], "blocked"),
],
)
def test_daily_flow_uses_authoritative_wallet_and_never_rerolls_paid(state, expected_calls, error):
import asyncio
import logging
tree = ast.parse(BOT.read_text(encoding="utf-8"))
flow = next(n for n in tree.body if isinstance(n, ast.AsyncFunctionDef)
and n.name == "_daily_flow")
calls = []
async def status(uid, rank):
return dict(state)
async def roll(*args):
calls.append("roll")
return {"ok": True, "paid": True}
async def claim(*args):
calls.append("claim")
return {"ok": True, "paid": True}
namespace = {
"asyncio": asyncio, "log": logging.getLogger(__name__),
"_daily_rank": lambda uid: 1, "_daily_status": status,
"_daily_roll": roll, "_daily_claim": claim, "_daily_body": lambda st, uid: st,
}
exec(compile(ast.Module(body=[flow], type_ignores=[]), str(BOT), "exec"), namespace)
_, result = asyncio.run(namespace["_daily_flow"](object(), 1, UID))
assert calls == expected_calls
assert result.get("error") == error