719 lines
35 KiB
Python
719 lines
35 KiB
Python
"""Legacy rank/donation fulfillment: paid != delivered, honest API promises, opt-in sales.
|
|
|
|
The helpers live in the ``bot/grok_bot.py`` monolith, so the exact functions and module
|
|
constants are extracted by name and executed against disposable SQLite databases. Every
|
|
assertion below runs the real code: no source-string matching.
|
|
"""
|
|
import ast
|
|
import asyncio
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import unittest
|
|
from contextlib import closing
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
BOT_SRC = ROOT / "bot" / "grok_bot.py"
|
|
# _prem_api_unlim resolves the account's gateway key names through the real helper;
|
|
# a stub would let the tests pass while production mis-resolves token names.
|
|
sys.path.insert(0, str(ROOT / "bot"))
|
|
import account_limits # noqa: E402 (path prepared just above)
|
|
|
|
DONATION_FUNCS = (
|
|
"_prem_api_unlim", "_don_ensure_table", "_don_record_invoice", "_don_claim_paid",
|
|
"_don_fulfill", "_don_pending_api", "_don_reconcile", "_don_answer_text", "_don_confirm_text",
|
|
)
|
|
RANK_FUNCS = (
|
|
"_rb_ensure_table", "_rb_apply", "_rb_settle", "_rb_bonus_settle", "_rb_bonus_grant",
|
|
"_rb_token_bonus", "_rb_token_name", "_rb_reconcile", "_rb_claim_paid", "_rb_bonus_granted",
|
|
"_rb_pending_load", "_rb_pending_save", "_rb_pending_flush",
|
|
"_rb_delivered", "_rb_invoice_delivered",
|
|
"rankbuy_poll_loop",
|
|
)
|
|
GATE_FUNCS = ("_legacy_sales_enabled", "_legacy_gate_text")
|
|
CONSTS = ("_LEGACY_ON", "_LEGACY_GATE_TEXT", "_LEGACY_GATE_LOG")
|
|
|
|
USERS_DDL = ("CREATE TABLE users(tg_id INTEGER PRIMARY KEY, token_name TEXT, banned INTEGER DEFAULT 0,"
|
|
" api_blocked INTEGER DEFAULT 0, unlim_until INTEGER DEFAULT 0,"
|
|
" badge_lock INTEGER DEFAULT 0, badge_until INTEGER DEFAULT 0)")
|
|
TOKENS_DDL = ('CREATE TABLE tokens(id INTEGER PRIMARY KEY, name TEXT, remain_quota INTEGER DEFAULT 0,'
|
|
' unlimited_quota INTEGER DEFAULT 0, status INTEGER DEFAULT 1, deleted_at INTEGER,'
|
|
' "group" TEXT DEFAULT \'t1\')')
|
|
|
|
LOYALTY_BONUS = {2: 500000, 3: 1000000, 4: 2500000}
|
|
|
|
|
|
class _Log:
|
|
def __init__(self):
|
|
self.lines = []
|
|
|
|
def _add(self, level, msg, args):
|
|
self.lines.append((level, (msg % args) if args else str(msg)))
|
|
|
|
def info(self, msg, *a):
|
|
self._add("info", msg, a)
|
|
|
|
def warning(self, msg, *a):
|
|
self._add("warning", msg, a)
|
|
|
|
def error(self, msg, *a):
|
|
self._add("error", msg, a)
|
|
|
|
|
|
def _extract(names, consts):
|
|
tree = ast.parse(BOT_SRC.read_text(encoding="utf-8"))
|
|
wanted, got = [], set()
|
|
for node in tree.body:
|
|
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names:
|
|
wanted.append(node)
|
|
got.add(node.name)
|
|
elif isinstance(node, ast.Assign):
|
|
for target in node.targets:
|
|
if isinstance(target, ast.Name) and target.id in consts:
|
|
wanted.append(node)
|
|
got.add(target.id)
|
|
missing = (set(names) | set(consts)) - got
|
|
if missing:
|
|
raise AssertionError(f"bot/grok_bot.py no longer defines: {sorted(missing)}")
|
|
return wanted
|
|
|
|
|
|
class LegacyFulfillmentCase(unittest.TestCase):
|
|
cryptopay_token = ""
|
|
xrocket_token = ""
|
|
commerce_offers = None
|
|
legacy_products = None
|
|
|
|
def setUp(self):
|
|
temp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(temp.cleanup)
|
|
self.dir = Path(temp.name)
|
|
self.bot_db = str(self.dir / "bot.db")
|
|
self.gw_db = str(self.dir / "api.db")
|
|
self.log = _Log()
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
con.execute(USERS_DDL)
|
|
con.execute("INSERT INTO users(tg_id, token_name) VALUES(123, 'tg123')")
|
|
con.commit()
|
|
with closing(sqlite3.connect(self.gw_db)) as con:
|
|
con.execute(TOKENS_DDL)
|
|
con.commit()
|
|
cfg = {"newapi_db": self.gw_db, "bot_db": self.bot_db}
|
|
if self.commerce_offers is not None:
|
|
cfg["commerce_offers"] = self.commerce_offers
|
|
if self.legacy_products is not None:
|
|
cfg["legacy_products"] = self.legacy_products
|
|
self.ns = {
|
|
"sqlite3": sqlite3, "time": time, "json": json, "os": os, "Path": Path,
|
|
"account_limits": account_limits,
|
|
"log": self.log, "BOT_DB": self.bot_db, "GW_DB": self.gw_db, "CFG": cfg,
|
|
"CRYPTOPAY_TOKEN": self.cryptopay_token, "XROCKET_TOKEN": self.xrocket_token,
|
|
"LOYALTY_BONUS": LOYALTY_BONUS, "RANKBUY_PRICE": 10,
|
|
"RANKBUY_JUMP": {1: 25, 2: 18, 3: 10},
|
|
"capped_bonus": lambda uid, bonus: bonus,
|
|
"_RANK_SYNC": {}, "sync_rank_limits": lambda uid, ttl=0: None,
|
|
"_RB_PENDING_PATH": str(self.dir / "rb_pending_bonus.json"),
|
|
# rankbuy_poll_loop is extracted for the race tests: its `bot: Bot`
|
|
# annotation is evaluated at exec time.
|
|
"Bot": object, "asyncio": asyncio,
|
|
}
|
|
body = _extract(DONATION_FUNCS + RANK_FUNCS + GATE_FUNCS, CONSTS)
|
|
exec(compile(ast.Module(body=body, type_ignores=[]), "legacy-fulfillment", "exec"), self.ns)
|
|
|
|
# ── helpers ────────────────────────────────────────────────────────────
|
|
def call(self, name, *args):
|
|
return self.ns[name](*args)
|
|
|
|
def bot_sql(self, query, params=()):
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
rows = con.execute(query, params).fetchall()
|
|
con.commit()
|
|
return rows
|
|
|
|
def gw_sql(self, query, params=()):
|
|
with closing(sqlite3.connect(self.gw_db)) as con:
|
|
rows = con.execute(query, params).fetchall()
|
|
con.commit()
|
|
return rows
|
|
|
|
def add_token(self, name="tg123", deleted_at=None, remain_quota=0, unlimited=0):
|
|
with closing(sqlite3.connect(self.gw_db)) as con:
|
|
con.execute("INSERT INTO tokens(name, remain_quota, unlimited_quota, deleted_at)"
|
|
" VALUES(?,?,?,?)", (name, remain_quota, unlimited, deleted_at))
|
|
con.commit()
|
|
|
|
def paid_donation(self, inv_id, uid=123, hours=24):
|
|
self.call("_don_record_invoice", inv_id, uid, hours)
|
|
self.assertTrue(self.call("_don_claim_paid", inv_id))
|
|
|
|
def paid_rank(self, inv_id, uid=123, to_lvl=2, amount="10", provider="cp"):
|
|
self.call("_rb_ensure_table")
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
con.execute("INSERT INTO rank_purchases(invoice_id, uid, from_lvl, to_lvl, amount_usd,"
|
|
" status, created, provider) VALUES(?,?,?,?,?, 'paid', ?, ?)",
|
|
(inv_id, uid, to_lvl - 1, to_lvl, amount, int(time.time()) - 60, provider))
|
|
con.commit()
|
|
|
|
|
|
class DonationFulfillmentTests(LegacyFulfillmentCase):
|
|
def test_paid_donation_without_issued_key_keeps_api_obligation_pending(self):
|
|
"""No gateway token yet: premium is issued, the API promise stays pending and honest."""
|
|
self.paid_donation(9001)
|
|
before = int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0])
|
|
self.assertEqual(before, 0)
|
|
started = int(time.time())
|
|
res = self.call("_don_fulfill", 9001)
|
|
|
|
self.assertEqual(res["status"], "pending_api")
|
|
self.assertFalse(res["api"])
|
|
self.assertTrue(res["fresh"])
|
|
# premium starts at payment time, never at the epoch, and is not shortened
|
|
self.assertGreaterEqual(int(res["until"]), started + 24 * 3600)
|
|
self.assertLess(int(res["until"]), started + 24 * 3600 + 120)
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0],
|
|
int(res["until"]))
|
|
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(api_state,'none')"
|
|
" FROM donations WHERE invoice_id=9001")[0],
|
|
("paid", 1, "pending"))
|
|
# the answer must not claim an API key that does not exist
|
|
answer = self.call("_don_answer_text", 24, res)
|
|
self.assertIn("API-безлимит включим автоматически", answer)
|
|
self.assertNotIn("и API-ключ", answer)
|
|
self.assertLessEqual(len(answer), 200)
|
|
self.assertIn("не сгорит", self.call("_don_confirm_text", 24, res))
|
|
|
|
def test_pending_api_entitlement_is_granted_once_the_key_exists(self):
|
|
self.paid_donation(9001)
|
|
first = self.call("_don_fulfill", 9001)
|
|
until_after_first = int(first["until"])
|
|
self.add_token("tg123")
|
|
|
|
granted = self.call("_don_pending_api")
|
|
self.assertEqual(granted, [(123, 9001)])
|
|
self.assertEqual(self.gw_sql("SELECT unlimited_quota, \"group\" FROM tokens WHERE name='tg123'")[0],
|
|
(1, "premium"))
|
|
# a retry neither re-grants nor extends the paid premium a second time
|
|
self.assertEqual(self.call("_don_pending_api"), [])
|
|
again = self.call("_don_fulfill", 9001)
|
|
self.assertEqual(again["status"], "already")
|
|
self.assertTrue(again["api"])
|
|
self.assertFalse(again["fresh"])
|
|
self.assertEqual(int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0]),
|
|
until_after_first)
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(api_state,'none') FROM donations"
|
|
" WHERE invoice_id=9001")[0][0], "granted")
|
|
|
|
def test_premium_hours_are_never_credited_twice(self):
|
|
self.paid_donation(9002, hours=72)
|
|
self.add_token("tg123")
|
|
first = self.call("_don_fulfill", 9002)
|
|
second = self.call("_don_fulfill", 9002)
|
|
self.assertEqual(first["status"], "granted")
|
|
self.assertEqual(second["status"], "already")
|
|
self.assertEqual(int(first["until"]), int(second["until"]))
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(until_ts,0) FROM donations WHERE invoice_id=9002")[0][0],
|
|
int(first["until"]))
|
|
self.assertEqual(self.call("_don_reconcile"), [])
|
|
|
|
def test_blocked_account_keeps_the_payment_without_entitlement(self):
|
|
self.bot_sql("UPDATE users SET banned=1 WHERE tg_id=123")
|
|
self.paid_donation(9003)
|
|
res = self.call("_don_fulfill", 9003)
|
|
|
|
self.assertEqual(res["status"], "blocked")
|
|
self.assertTrue(res["fresh"])
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0], 0)
|
|
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(api_state,'none')"
|
|
" FROM donations WHERE invoice_id=9003")[0], ("paid", 1, "blocked"))
|
|
self.add_token("tg123")
|
|
self.assertEqual(self.call("_don_pending_api"), [])
|
|
self.assertEqual(self.gw_sql("SELECT unlimited_quota FROM tokens WHERE name='tg123'")[0][0], 0)
|
|
# a second pass does not re-notify and does not issue anything
|
|
self.assertEqual(self.call("_don_fulfill", 9003)["status"], "blocked")
|
|
self.assertEqual(self.call("_don_reconcile"), [])
|
|
self.assertIn("ограничен", self.call("_don_answer_text", 24, res))
|
|
|
|
def test_reconcile_delivers_paid_rows_without_any_provider_token(self):
|
|
"""A crash between provider confirmation and delivery is recovered offline."""
|
|
self.call("_don_ensure_table")
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
con.execute("INSERT INTO donations(invoice_id, uid, hours, status, created)"
|
|
" VALUES(9004, 123, 168, 'paid', ?)", (int(time.time()) - 999999,))
|
|
con.commit()
|
|
self.add_token("tg123")
|
|
|
|
rows = self.call("_don_reconcile")
|
|
self.assertEqual([r[:3] for r in rows], [(9004, 123, 168)])
|
|
self.assertEqual(rows[0][3]["status"], "granted")
|
|
self.assertGreater(int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0]),
|
|
int(time.time()))
|
|
self.assertEqual(self.call("_don_reconcile"), [])
|
|
|
|
def test_repeated_invoice_recording_preserves_delivery_state(self):
|
|
self.paid_donation(9005, hours=24)
|
|
self.add_token("tg123")
|
|
res = self.call("_don_fulfill", 9005)
|
|
until = int(res["until"])
|
|
self.call("_don_record_invoice", 9005, 123, 24)
|
|
|
|
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(api_state,'none'),"
|
|
" COALESCE(until_ts,0) FROM donations WHERE invoice_id=9005")[0],
|
|
("paid", 1, "granted", until))
|
|
self.assertEqual(int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0]),
|
|
until)
|
|
self.assertEqual(self.call("_don_fulfill", 9005)["status"], "already")
|
|
|
|
def test_legacy_paid_history_is_not_regranted_by_the_migration(self):
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
con.execute("CREATE TABLE donations(invoice_id INTEGER PRIMARY KEY, uid INTEGER, hours INTEGER,"
|
|
" status TEXT DEFAULT 'pending', created INTEGER)")
|
|
con.execute("INSERT INTO donations VALUES(9006, 123, 24, 'paid', 1700000000)")
|
|
con.execute("INSERT INTO donations VALUES(9007, 123, 24, 'pending', 1700000000)")
|
|
con.commit()
|
|
self.add_token("tg123")
|
|
self.call("_don_ensure_table")
|
|
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(delivered,0), COALESCE(api_state,'none')"
|
|
" FROM donations WHERE invoice_id=9006")[0], (1, "granted"))
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0], 0)
|
|
self.assertEqual(self.gw_sql("SELECT unlimited_quota FROM tokens WHERE name='tg123'")[0][0], 0)
|
|
self.assertEqual(self.call("_don_reconcile"), [])
|
|
# an old pending invoice is still deliverable: the age filter never applied here
|
|
self.call("_don_claim_paid", 9007)
|
|
self.assertEqual(self.call("_don_fulfill", 9007)["status"], "granted")
|
|
|
|
def test_missing_gateway_database_is_reported_not_created(self):
|
|
self.ns["CFG"]["newapi_db"] = str(self.dir / "absent" / "one-api.db")
|
|
self.assertFalse(self.call("_prem_api_unlim", 123))
|
|
self.assertFalse((self.dir / "absent").exists())
|
|
self.assertTrue(any(level == "error" for level, _ in self.log.lines))
|
|
|
|
def test_api_unlim_tells_the_truth_about_deleted_and_live_tokens(self):
|
|
self.assertFalse(self.call("_prem_api_unlim", 123)) # no row at all
|
|
self.add_token("tg123", deleted_at=int(time.time()))
|
|
self.assertFalse(self.call("_prem_api_unlim", 123)) # soft-deleted row is not a grant
|
|
with closing(sqlite3.connect(self.gw_db)) as con:
|
|
con.execute("UPDATE tokens SET deleted_at=NULL WHERE name='tg123'")
|
|
con.commit()
|
|
self.assertTrue(self.call("_prem_api_unlim", 123))
|
|
self.assertEqual(self.gw_sql("SELECT unlimited_quota, \"group\" FROM tokens WHERE name='tg123'")[0],
|
|
(1, "premium"))
|
|
|
|
|
|
class RankFulfillmentTests(LegacyFulfillmentCase):
|
|
def test_failed_grant_is_never_reported_as_activated_and_retry_finishes_it(self):
|
|
self.paid_rank(7001, to_lvl=2)
|
|
self.add_token("tg123")
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
con.execute("CREATE TRIGGER fail_grant BEFORE UPDATE OF badge_lock ON users"
|
|
" BEGIN SELECT RAISE(ABORT, 'injected persistent grant write failure'); END")
|
|
con.commit()
|
|
|
|
self.assertFalse(self.call("_rb_settle", 123, 2, 7001))
|
|
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0) FROM rank_purchases"
|
|
" WHERE invoice_id=7001")[0], ("paid", 0))
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 0)
|
|
# reconcile keeps retrying while the write fails, and reports nothing to the user
|
|
self.assertEqual(self.call("_rb_reconcile"), [])
|
|
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], 0)
|
|
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
con.execute("DROP TRIGGER fail_grant")
|
|
con.commit()
|
|
rows = self.call("_rb_reconcile")
|
|
self.assertEqual([r[:3] for r in rows], [(123, 2, 7001)])
|
|
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(bonus_state,'none')"
|
|
" FROM rank_purchases WHERE invoice_id=7001")[0], ("paid", 1, "granted"))
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 2)
|
|
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
|
|
LOYALTY_BONUS[2])
|
|
# exactly one delivery: no second badge write, no second bonus
|
|
self.assertEqual(self.call("_rb_reconcile"), [])
|
|
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
|
|
LOYALTY_BONUS[2])
|
|
self.assertTrue(self.call("_rb_bonus_granted", 7001))
|
|
|
|
def test_bonus_obligation_survives_a_missing_then_deleted_token_row(self):
|
|
self.call("_rb_pending_save", {"123": LOYALTY_BONUS[3]})
|
|
self.assertEqual(self.call("_rb_pending_flush"), 0)
|
|
self.assertEqual(self.call("_rb_pending_load"), {"123": LOYALTY_BONUS[3]})
|
|
|
|
self.add_token("tg123", deleted_at=int(time.time()))
|
|
self.assertEqual(self.call("_rb_pending_flush"), 0)
|
|
self.assertEqual(self.call("_rb_pending_load"), {"123": LOYALTY_BONUS[3]})
|
|
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], 0)
|
|
|
|
with closing(sqlite3.connect(self.gw_db)) as con:
|
|
con.execute("UPDATE tokens SET deleted_at=NULL, remain_quota=10 WHERE name='tg123'")
|
|
con.commit()
|
|
self.assertEqual(self.call("_rb_pending_flush"), 1)
|
|
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
|
|
LOYALTY_BONUS[3])
|
|
self.assertFalse(os.path.exists(self.ns["_RB_PENDING_PATH"]))
|
|
self.assertEqual(self.call("_rb_pending_flush"), 0)
|
|
|
|
def test_bonus_quota_uses_max_semantics_and_never_accumulates(self):
|
|
"""A retry must not pay the rank bonus twice or shrink an already larger balance."""
|
|
self.add_token("tg123", remain_quota=0)
|
|
self.assertTrue(self.call("_rb_bonus_grant", 123, LOYALTY_BONUS[2]))
|
|
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
|
|
LOYALTY_BONUS[2])
|
|
self.assertTrue(self.call("_rb_bonus_grant", 123, LOYALTY_BONUS[2]))
|
|
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
|
|
LOYALTY_BONUS[2])
|
|
# a user who already has more quota keeps it
|
|
self.assertTrue(self.call("_rb_bonus_grant", 123, 10))
|
|
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
|
|
LOYALTY_BONUS[2])
|
|
# a disabled token is re-enabled, a deleted one is never resurrected
|
|
with closing(sqlite3.connect(self.gw_db)) as con:
|
|
con.execute("UPDATE tokens SET status=4 WHERE name='tg123'")
|
|
con.commit()
|
|
self.assertTrue(self.call("_rb_bonus_grant", 123, LOYALTY_BONUS[2]))
|
|
self.assertEqual(self.gw_sql("SELECT status FROM tokens WHERE name='tg123'")[0][0], 1)
|
|
self.assertFalse(self.call("_rb_bonus_grant", 456, LOYALTY_BONUS[2]))
|
|
|
|
def test_button_delivery_wins_the_race_and_reconcile_stays_silent(self):
|
|
"""One invoice = one delivery and one notification, whoever gets there first."""
|
|
self.paid_rank(7003, to_lvl=2)
|
|
self.add_token("tg123")
|
|
self.assertTrue(self.call("_rb_settle", 123, 2, 7003, True))
|
|
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(bonus_state,'none')"
|
|
" FROM rank_purchases WHERE invoice_id=7003")[0],
|
|
("paid", 1, "granted"))
|
|
# the poller re-reads the same invoice and must neither re-deliver nor announce it
|
|
self.assertEqual(self.call("_rb_reconcile"), [])
|
|
self.assertFalse(self.call("_rb_settle", 123, 2, 7003, True))
|
|
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
|
|
LOYALTY_BONUS[2])
|
|
self.assertTrue(self.call("_rb_invoice_delivered", 7003))
|
|
self.assertIn("rankbuy already delivered", " ".join(line for _, line in self.log.lines))
|
|
|
|
def test_poller_loses_the_button_race_and_does_not_confirm_twice(self):
|
|
"""The paid_list sweep must claim too: the button can deliver mid-sweep."""
|
|
self.call("_rb_ensure_table")
|
|
for inv in (7101, 7102):
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
con.execute("INSERT INTO rank_purchases(invoice_id, uid, from_lvl, to_lvl,"
|
|
" amount_usd, status, created, provider)"
|
|
" VALUES(?, 123, 1, 2, '10', 'pending', ?, 'cp')",
|
|
(inv, int(time.time()) - 60))
|
|
con.commit()
|
|
self.add_token("tg123")
|
|
self.ns["CRYPTOPAY_TOKEN"] = "tok"
|
|
|
|
confirms = []
|
|
|
|
async def _rb_confirm(bot, uid, to_lvl, amount, provider, bonus_ok):
|
|
confirms.append((uid, to_lvl, amount, provider, bonus_ok))
|
|
|
|
async def _rb_inv_paid(provider, inv_id, inv_ext):
|
|
if int(inv_id) == 7102:
|
|
# the sweep is still polling: meanwhile the user pressed «Я оплатил» for 7101
|
|
# (status is already 'paid', delivered=0), which delivers and announces it.
|
|
if self.ns["_rb_settle"](123, 2, 7101, True):
|
|
await _rb_confirm(None, 123, 2, "10", "cp",
|
|
self.ns["_rb_bonus_granted"](7101))
|
|
return False
|
|
return True
|
|
|
|
class _Driver:
|
|
"""One poll pass, then cancellation instead of a real 15s sleep."""
|
|
|
|
CancelledError = asyncio.CancelledError
|
|
to_thread = staticmethod(asyncio.to_thread)
|
|
|
|
def __init__(self):
|
|
self.passes = 0
|
|
|
|
async def sleep(self, *_a):
|
|
self.passes += 1
|
|
if self.passes > 1:
|
|
raise asyncio.CancelledError
|
|
|
|
self.ns["_rb_confirm"] = _rb_confirm
|
|
self.ns["_rb_inv_paid"] = _rb_inv_paid
|
|
self.ns["asyncio"] = _Driver()
|
|
|
|
with self.assertRaises(asyncio.CancelledError):
|
|
asyncio.run(self.ns["rankbuy_poll_loop"](None))
|
|
|
|
# exactly one announcement: the button's. The poller re-settling 7101 must be silent.
|
|
self.assertEqual(confirms, [(123, 2, "10", "cp", True)])
|
|
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(bonus_state,'none')"
|
|
" FROM rank_purchases WHERE invoice_id=7101")[0],
|
|
("paid", 1, "granted"))
|
|
# MAX semantics: the second settle attempt must not double the bonus quota
|
|
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
|
|
LOYALTY_BONUS[2])
|
|
self.assertIn("rankbuy already delivered", " ".join(line for _, line in self.log.lines))
|
|
|
|
def test_claim_rolls_back_when_the_grant_fails_so_retry_can_finish_it(self):
|
|
self.paid_rank(7004, to_lvl=2)
|
|
self.add_token("tg123")
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
con.execute("CREATE TRIGGER fail_grant BEFORE UPDATE OF badge_lock ON users"
|
|
" BEGIN SELECT RAISE(ABORT, 'injected persistent grant write failure'); END")
|
|
con.commit()
|
|
self.assertFalse(self.call("_rb_settle", 123, 2, 7004, True))
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(delivered,0), COALESCE(bonus_state,'none')"
|
|
" FROM rank_purchases WHERE invoice_id=7004")[0][0], 0)
|
|
self.assertFalse(self.call("_rb_invoice_delivered", 7004))
|
|
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
con.execute("DROP TRIGGER fail_grant")
|
|
con.commit()
|
|
self.assertEqual([r[:3] for r in self.call("_rb_reconcile")], [(123, 2, 7004)])
|
|
self.assertTrue(self.call("_rb_invoice_delivered", 7004))
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 2)
|
|
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
|
|
LOYALTY_BONUS[2])
|
|
|
|
def test_delivered_probe_reports_false_on_a_broken_database(self):
|
|
"""A dead DB must not turn into an exception on the callback path."""
|
|
self.call("_rb_ensure_table")
|
|
self.assertFalse(self.call("_rb_invoice_delivered", 9999))
|
|
self.ns["BOT_DB"] = str(self.dir / "no-such-dir" / "bot.db")
|
|
self.assertFalse(self.call("_rb_invoice_delivered", 9999))
|
|
self.assertTrue(any(line.startswith("rb delivered read") for _, line in self.log.lines))
|
|
|
|
def test_claim_paid_is_a_one_shot_transition(self):
|
|
self.call("_rb_ensure_table")
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
con.execute("INSERT INTO rank_purchases(invoice_id, uid, from_lvl, to_lvl, amount_usd,"
|
|
" status, created, provider) VALUES(7002, 123, 1, 2, '10', 'pending', ?, 'cp')",
|
|
(int(time.time()),))
|
|
con.commit()
|
|
self.assertTrue(self.call("_rb_claim_paid", 7002))
|
|
self.assertFalse(self.call("_rb_claim_paid", 7002))
|
|
self.assertEqual(self.bot_sql("SELECT status FROM rank_purchases WHERE invoice_id=7002")[0][0], "paid")
|
|
|
|
|
|
class LegacySalesGateTests(LegacyFulfillmentCase):
|
|
def test_empty_offer_list_is_a_hard_switch_even_with_opt_in(self):
|
|
self.ns["CFG"]["commerce_offers"] = []
|
|
self.ns["CFG"]["legacy_products"] = True
|
|
self.assertFalse(self.call("_legacy_sales_enabled"))
|
|
self.assertTrue(self.call("_legacy_gate_text", "donate"))
|
|
self.assertTrue(self.call("_legacy_gate_text", "rank"))
|
|
self.assertIn("[LEGACY-GATE]", "\n".join(m for _, m in self.log.lines))
|
|
|
|
def test_legacy_products_are_off_by_default(self):
|
|
self.ns["CFG"]["commerce_offers"] = [{"id": "x"}]
|
|
self.assertFalse(self.call("_legacy_sales_enabled"))
|
|
self.assertTrue(self.call("_legacy_gate_text", "donate"))
|
|
self.assertTrue(self.call("_legacy_gate_text", "unknown-kind"))
|
|
|
|
def test_explicit_opt_in_with_offers_reopens_sales(self):
|
|
self.ns["CFG"]["commerce_offers"] = [{"id": "x"}]
|
|
self.ns["CFG"]["legacy_products"] = "yes"
|
|
self.assertTrue(self.call("_legacy_sales_enabled"))
|
|
self.assertIsNone(self.call("_legacy_gate_text", "rank"))
|
|
|
|
def test_gate_blocks_new_invoices_but_never_strands_paid_money(self):
|
|
self.ns["CFG"]["commerce_offers"] = []
|
|
self.assertTrue(self.call("_legacy_gate_text", "donate"))
|
|
self.paid_donation(9100, hours=24)
|
|
res = self.call("_don_fulfill", 9100)
|
|
self.assertEqual(res["status"], "pending_api")
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(delivered,0) FROM donations WHERE invoice_id=9100")[0][0], 1)
|
|
self.paid_rank(7100, to_lvl=2)
|
|
self.assertTrue(self.call("_rb_settle", 123, 2, 7100))
|
|
self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 2)
|
|
|
|
|
|
class DonationCallbackContractTests(LegacyFulfillmentCase):
|
|
"""The button handler must answer honestly for every delivery outcome."""
|
|
|
|
def test_answer_texts_are_short_and_match_their_state(self):
|
|
cases = {
|
|
"granted": "✅ Прем на 24ч! Безлимит: чат, картинки и API-ключ",
|
|
"pending_api": "API-безлимит включим автоматически",
|
|
"blocked": "аккаунт ограничен",
|
|
"already": "Уже активировано",
|
|
"error": "Не удалось подтвердить",
|
|
}
|
|
for status, needle in cases.items():
|
|
text = self.call("_don_answer_text", 24, {"status": status, "until": 0, "api": False})
|
|
self.assertLessEqual(len(text), 200, status)
|
|
self.assertIn(needle, text)
|
|
|
|
def test_confirm_text_reports_the_real_deadline(self):
|
|
until = int(time.time()) + 3600
|
|
text = self.call("_don_confirm_text", 24, {"status": "granted", "until": until, "api": True})
|
|
self.assertIn(time.strftime("%d.%m %H:%M", time.localtime(until)), text)
|
|
self.assertIn("24ч", text)
|
|
self.assertIn("API-безлимит включён", text)
|
|
pending = self.call("_don_confirm_text", 24, {"status": "pending_api", "until": until, "api": False})
|
|
self.assertNotIn("API-безлимит включён", pending)
|
|
self.assertIn("как только выпустится твой ключ", pending)
|
|
|
|
def test_donation_payload_is_json_serialisable_for_the_ui(self):
|
|
self.paid_donation(9200)
|
|
res = self.call("_don_fulfill", 9200)
|
|
self.assertEqual(json.loads(json.dumps(res)), res)
|
|
|
|
|
|
class _PausingConnection:
|
|
"""Real sqlite3 connection whose schema probe can be frozen mid-transaction."""
|
|
|
|
def __init__(self, inner, on_pragma):
|
|
self._inner = inner
|
|
self._on_pragma = on_pragma
|
|
|
|
def __getattr__(self, name):
|
|
return getattr(self._inner, name)
|
|
|
|
@property
|
|
def isolation_level(self):
|
|
return self._inner.isolation_level
|
|
|
|
@isolation_level.setter
|
|
def isolation_level(self, value):
|
|
self._inner.isolation_level = value
|
|
|
|
def execute(self, sql, params=()):
|
|
if str(sql).lstrip().upper().startswith("PRAGMA TABLE_INFO"):
|
|
self._on_pragma()
|
|
return self._inner.execute(sql, params)
|
|
|
|
|
|
class _PausingSqlite3:
|
|
def __init__(self, real, on_pragma):
|
|
self._real = real
|
|
self._on_pragma = on_pragma
|
|
|
|
def __getattr__(self, name):
|
|
return getattr(self._real, name)
|
|
|
|
def connect(self, *args, **kwargs):
|
|
return _PausingConnection(self._real.connect(*args, **kwargs), self._on_pragma)
|
|
|
|
|
|
class MigrationWindowTests(LegacyFulfillmentCase):
|
|
"""The additive migration holds a write lock for its whole read-modify-write span.
|
|
|
|
A stale ``PRAGMA table_info`` snapshot is the classic money bug here: the caller that
|
|
read the old schema still runs the fresh-install backfill seconds later, and every
|
|
``status='paid' AND delivered=0`` row that landed in between is marked delivered
|
|
without ever being granted. Serialising the migration closes that window.
|
|
"""
|
|
|
|
def _assert_migration_blocks_concurrent_writes(self, ensure_fn, table, ddl, invoice):
|
|
paused, release = threading.Event(), threading.Event()
|
|
errors = []
|
|
|
|
with closing(sqlite3.connect(self.bot_db)) as con:
|
|
con.execute(ddl)
|
|
# already-paid history: the backfill must mark it delivered exactly once
|
|
con.execute(f"INSERT INTO {table}(invoice_id, uid, status, created)"
|
|
" VALUES(?, 123, 'paid', 1)", (invoice - 1,))
|
|
con.commit()
|
|
|
|
def migrate():
|
|
try:
|
|
self.call(ensure_fn)
|
|
except BaseException as exc: # reported on the main thread
|
|
errors.append(exc)
|
|
|
|
real_sqlite3 = self.ns["sqlite3"]
|
|
self.ns["sqlite3"] = _PausingSqlite3(
|
|
real_sqlite3, lambda: (paused.set(), release.wait(20)))
|
|
self.addCleanup(self.ns.__setitem__, "sqlite3", real_sqlite3)
|
|
migrator = threading.Thread(target=migrate, daemon=True)
|
|
migrator.start()
|
|
buyers = []
|
|
|
|
def _cleanup():
|
|
# registered before the temp-dir cleanup, so it always runs first: a failing
|
|
# assertion must not leave a thread holding the SQLite file open on Windows
|
|
release.set()
|
|
migrator.join(20)
|
|
for t in buyers:
|
|
t.join(20)
|
|
|
|
self.addCleanup(_cleanup)
|
|
self.assertTrue(paused.wait(20), f"{ensure_fn} never probed the schema")
|
|
|
|
# a brand-new purchase arrives while the migration is between probe and backfill
|
|
landed = threading.Event()
|
|
|
|
def buy():
|
|
try:
|
|
with closing(real_sqlite3.connect(self.bot_db, timeout=20)) as con:
|
|
con.execute(f"INSERT INTO {table}(invoice_id, uid, status, created)"
|
|
" VALUES(?, 123, 'paid', 2)", (invoice,))
|
|
con.commit()
|
|
landed.set()
|
|
except BaseException as exc:
|
|
errors.append(exc)
|
|
|
|
buyer = threading.Thread(target=buy, daemon=True)
|
|
buyers.append(buyer)
|
|
buyer.start()
|
|
buyer.join(4)
|
|
self.assertFalse(landed.is_set(),
|
|
f"{ensure_fn}: a paid invoice landed inside the migration window")
|
|
|
|
release.set()
|
|
migrator.join(20)
|
|
self.assertFalse(migrator.is_alive(), f"{ensure_fn} did not finish")
|
|
self.assertEqual(errors, [])
|
|
buyer.join(20)
|
|
self.assertTrue(landed.is_set(), "the new purchase never landed at all")
|
|
self.assertEqual(errors, [])
|
|
|
|
delivered = dict(self.bot_sql(f"SELECT invoice_id, COALESCE(delivered,0) FROM {table}"))
|
|
self.assertEqual(delivered[invoice - 1], 1,
|
|
"already-paid history must not be re-granted by the poller")
|
|
self.assertEqual(delivered[invoice], 0,
|
|
"the new purchase was marked delivered without being granted")
|
|
|
|
def test_rank_migration_holds_the_write_lock_until_the_backfill_committed(self):
|
|
self._assert_migration_blocks_concurrent_writes(
|
|
"_rb_ensure_table", "rank_purchases",
|
|
"CREATE TABLE rank_purchases(invoice_id INTEGER PRIMARY KEY, uid INTEGER,"
|
|
" from_lvl INTEGER, to_lvl INTEGER, amount_usd TEXT,"
|
|
" status TEXT DEFAULT 'pending', created INTEGER, provider TEXT DEFAULT 'cp')",
|
|
901)
|
|
|
|
def test_donation_migration_holds_the_write_lock_until_the_backfill_committed(self):
|
|
self._assert_migration_blocks_concurrent_writes(
|
|
"_don_ensure_table", "donations",
|
|
"CREATE TABLE donations(invoice_id INTEGER PRIMARY KEY, uid INTEGER,"
|
|
" hours INTEGER, status TEXT DEFAULT 'pending', created INTEGER)",
|
|
902)
|
|
|
|
def test_parallel_migrations_do_not_fail_on_a_duplicate_column(self):
|
|
"""Button and poller migrate at once: exactly one ALTER set wins, nobody raises."""
|
|
failures = []
|
|
start = threading.Barrier(6)
|
|
|
|
def migrate():
|
|
start.wait(10)
|
|
try:
|
|
self.call("_rb_ensure_table")
|
|
except BaseException as exc:
|
|
failures.append(repr(exc))
|
|
|
|
threads = [threading.Thread(target=migrate, daemon=True) for _ in range(6)]
|
|
for t in threads:
|
|
t.start()
|
|
for t in threads:
|
|
t.join(30)
|
|
self.assertFalse(t.is_alive(), "a migration thread hung")
|
|
self.assertEqual(failures, [])
|
|
cols = [r[1] for r in self.bot_sql("PRAGMA table_info(rank_purchases)")]
|
|
for expected in ("provider", "inv_ext", "delivered", "delivered_at",
|
|
"bonus_state", "bonus_due"):
|
|
self.assertEqual(cols.count(expected), 1, f"column {expected} malformed: {cols}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|