Make legacy payment delivery retryable and keep gateway paths responsive
This commit is contained in:
@@ -2,17 +2,55 @@
|
||||
import ast
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from test_bot_stability import (BOT, Content, Response, Session, actual_gateway,
|
||||
adapter, frame, stability)
|
||||
|
||||
|
||||
class FakeClock:
|
||||
"""Thread-safe monotonic clock that moves only when the test says so.
|
||||
|
||||
Budget accounting can then be asserted exactly instead of hoped for: no real
|
||||
sleep, thread warm-up or scheduling delay can shorten the window.
|
||||
"""
|
||||
|
||||
def __init__(self, start: float = 1000.0) -> None:
|
||||
self.start = start
|
||||
self._value = start
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def monotonic(self) -> float:
|
||||
with self._lock:
|
||||
return self._value
|
||||
|
||||
def advance(self, seconds: float) -> None:
|
||||
with self._lock:
|
||||
self._value += seconds
|
||||
|
||||
|
||||
@contextmanager
|
||||
def fake_timing(clock: FakeClock):
|
||||
"""Drive adapter deadline math *and* event-loop timers from one fake clock.
|
||||
|
||||
The adapter reads ``bot_stability.time.monotonic``; the controller additionally
|
||||
enforces its own deadline with ``loop.time()`` (``asyncio.timeout_at``). Both are
|
||||
replaced, so expiry can only happen through ``clock.advance``.
|
||||
"""
|
||||
loop = asyncio.get_running_loop()
|
||||
with mock.patch.object(adapter, "time", SimpleNamespace(monotonic=clock.monotonic)), \
|
||||
mock.patch.object(loop, "time", clock.monotonic):
|
||||
yield
|
||||
|
||||
|
||||
class StreamEdges(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_default_model_is_admitted_not_bypassed(self):
|
||||
session = Session([Response()])
|
||||
@@ -229,23 +267,44 @@ class AdapterEdges(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertFalse(gate._cap_pending)
|
||||
|
||||
async def test_remaining_budget_recomputed_after_cap_and_success_is_not_refunded(self):
|
||||
calls = []
|
||||
# The cap transaction consumes exactly half of the 125 ms budget, on a clock
|
||||
# the test owns. A dispatch that kept the pre-cap budget (0.125) or that let
|
||||
# real time eat the window cannot produce the asserted numbers.
|
||||
budget, cap_cost = 0.125, 0.0625
|
||||
clock = FakeClock()
|
||||
dispatched, reserved, refunds = [], [], []
|
||||
|
||||
def reserve(uid, model):
|
||||
time.sleep(.02)
|
||||
clock.advance(cap_cost)
|
||||
reserved.append((uid, model))
|
||||
return True, 1, 10, "receipt"
|
||||
|
||||
def release(key):
|
||||
refunds.append(key)
|
||||
return True
|
||||
|
||||
async def stream(messages, model, send, t=360, _deadline=None):
|
||||
calls.append(t)
|
||||
self.assertLess(t, .07)
|
||||
self.assertGreater(t, 0)
|
||||
dispatched.append((model, t, _deadline))
|
||||
return "exact"
|
||||
ns = {"BOT_DB": "unused.db", "gw_chat_stream": stream, "pm_cap_reserve": reserve,
|
||||
"pm_cap_release": lambda key: self.fail("dispatched request must retain its unit")}
|
||||
gate = adapter.BotStability(ns); gate.install_wrappers()
|
||||
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, .08))
|
||||
try: self.assertEqual(await ns["gw_chat_stream"]([], "m", None), "exact")
|
||||
finally: adapter.POLICY.reset(token)
|
||||
self.assertEqual(len(calls), 1)
|
||||
|
||||
ns = {"BOT_DB": "unused.db", "gw_chat_stream": stream,
|
||||
"pm_cap_reserve": reserve, "pm_cap_release": release}
|
||||
gate = adapter.BotStability(
|
||||
ns, controller=stability.StabilityController(clock=clock.monotonic))
|
||||
gate.install_wrappers()
|
||||
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, budget))
|
||||
try:
|
||||
with fake_timing(clock):
|
||||
self.assertEqual(await ns["gw_chat_stream"]([], "m", None), "exact")
|
||||
finally:
|
||||
adapter.POLICY.reset(token)
|
||||
gate._cap_executor.shutdown(wait=False)
|
||||
self.assertEqual(reserved, [(7, "m")])
|
||||
self.assertEqual(dispatched, [("m", budget - cap_cost, clock.start + budget)])
|
||||
self.assertEqual(refunds, [])
|
||||
self.assertFalse(gate._cleanup_tasks)
|
||||
self.assertFalse(gate._cap_pending)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 1)
|
||||
|
||||
async def test_auxiliary_call_keeps_its_shorter_explicit_timeout(self):
|
||||
calls = []
|
||||
|
||||
@@ -2,8 +2,12 @@
|
||||
import ast
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[1] / 'gateway/gateway_errors.py'
|
||||
@@ -294,5 +298,106 @@ class PolicyCodeClassificationTests(unittest.TestCase):
|
||||
self.assertEqual((status, body['error']['code']), (400, 'invalid_request'))
|
||||
|
||||
|
||||
class TokenStateDatabaseTests(unittest.TestCase):
|
||||
"""A 401 diagnostic must read the effective gateway DB, not a legacy literal."""
|
||||
|
||||
ENV = ("GW_NEWAPI_DB", "IISHKO_GW_DB", "GATE_NEWAPI_DB", "GROK_BOT_CFG")
|
||||
|
||||
def setUp(self):
|
||||
self._saved = {name: os.environ.get(name) for name in self.ENV}
|
||||
for name in self.ENV:
|
||||
os.environ.pop(name, None)
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.dir = tmp.name
|
||||
|
||||
def tearDown(self):
|
||||
for name, value in self._saved.items():
|
||||
if value is None:
|
||||
os.environ.pop(name, None)
|
||||
else:
|
||||
os.environ[name] = value
|
||||
|
||||
def db(self, name, rows):
|
||||
path = os.path.join(self.dir, name)
|
||||
with closing(sqlite3.connect(path)) as con:
|
||||
con.execute('CREATE TABLE tokens(id INTEGER PRIMARY KEY, "key" TEXT, status INTEGER,'
|
||||
' remain_quota INTEGER, unlimited_quota INTEGER, deleted_at INTEGER)')
|
||||
con.executemany('INSERT INTO tokens("key", status, remain_quota, unlimited_quota,'
|
||||
' deleted_at) VALUES(?,?,?,?,?)', rows)
|
||||
con.commit()
|
||||
return path
|
||||
|
||||
def auth_error(self, key):
|
||||
return MOD.public_error(401, b'{"error":{"message":"Invalid token"}}',
|
||||
'/v1/chat/completions', api_key=key)
|
||||
|
||||
def write_config(self, newapi_db):
|
||||
path = os.path.join(self.dir, 'config.json')
|
||||
with open(path, 'w', encoding='utf-8-sig') as fh:
|
||||
json.dump({'newapi_db': newapi_db, 'bot_token': 'x'}, fh)
|
||||
os.environ['GROK_BOT_CFG'] = path
|
||||
return path
|
||||
|
||||
def test_shared_resolver_is_wired_and_resolves_late(self):
|
||||
self.assertIsNotNone(MOD._gateway_db_path,
|
||||
'gateway_errors fell back to the hardcoded legacy DB path')
|
||||
# behaviour, not module shape: an alias set after import must be honoured,
|
||||
# which an import-time snapshot could never do
|
||||
late = self.db('late.db', [('k', 1, 42, 0, None)])
|
||||
os.environ['IISHKO_GW_DB'] = late
|
||||
self.assertEqual(MOD.token_state('k'), (1, 42, 0))
|
||||
|
||||
def test_config_json_gateway_db_beats_the_legacy_literal(self):
|
||||
"""A deployment that sets the path only in bot/config.json must not misread 401s."""
|
||||
self.db('legacy.db', [('k', 4, 0, 0, None)])
|
||||
configured = self.db('configured.db', [('k', 1, 7000, 0, None)])
|
||||
self.write_config(configured)
|
||||
self.assertEqual(MOD.token_state('k'), (1, 7000, 0))
|
||||
# an explicit env alias still outvotes the config file
|
||||
os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('k', 2, 900, 0, None)])
|
||||
self.assertEqual(MOD.token_state('k'), (2, 900, 0))
|
||||
|
||||
def test_missing_or_bogus_config_path_falls_back_without_raising(self):
|
||||
os.environ['GROK_BOT_CFG'] = os.path.join(self.dir, 'no-such-dir', 'config.json')
|
||||
self.assertIsNone(MOD.token_state('k'))
|
||||
broken = os.path.join(self.dir, 'broken.json')
|
||||
with open(broken, 'w', encoding='utf-8-sig') as fh:
|
||||
fh.write('{"newapi_db": ')
|
||||
os.environ['GROK_BOT_CFG'] = broken
|
||||
self.assertIsNone(MOD.token_state('k'))
|
||||
# a config that names a nonexistent DB is not an error either: no key state
|
||||
self.write_config(os.path.join(self.dir, 'absent.db'))
|
||||
self.assertIsNone(MOD.token_state('k'))
|
||||
|
||||
def test_env_precedence_decides_which_token_table_is_read(self):
|
||||
stale = self.db('legacy.db', [('k', 4, 0, 0, None)])
|
||||
live = self.db('effective.db', [('k', 1, 5000, 0, None)])
|
||||
os.environ['GW_NEWAPI_DB'] = stale # legacy-only unit keeps working
|
||||
self.assertEqual(MOD.token_state('k'), (4, 0, 0))
|
||||
# a stale legacy alias must not outvote the DB the rest of the stack serves
|
||||
os.environ['GATE_NEWAPI_DB'] = live
|
||||
self.assertEqual(MOD.token_state('k'), (1, 5000, 0))
|
||||
del os.environ['GATE_NEWAPI_DB']
|
||||
self.assertEqual(MOD.token_state('k'), (4, 0, 0))
|
||||
del os.environ['GW_NEWAPI_DB']
|
||||
os.environ['GATE_NEWAPI_DB'] = stale
|
||||
os.environ['IISHKO_GW_DB'] = live # canonical name wins over GATE_NEWAPI_DB
|
||||
self.assertEqual(MOD.token_state('k'), (1, 5000, 0))
|
||||
|
||||
def test_zero_balance_key_is_reported_as_empty_not_invalid(self):
|
||||
os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('deadbeef', 1, 0, 0, None)])
|
||||
status, body = self.auth_error('deadbeef')
|
||||
self.assertEqual((status, body['error']['code']), (402, 'api_key_empty'))
|
||||
|
||||
def test_foreign_database_never_makes_a_healthy_key_look_empty(self):
|
||||
# The old hardcoded path belonged to another deployment: a drained key there
|
||||
# must not change this gateway's verdict about its own healthy key.
|
||||
self.db('legacy.db', [('healthy', 4, 0, 0, None)])
|
||||
os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('healthy', 1, 900000, 0, None)])
|
||||
status, body = self.auth_error('healthy')
|
||||
self.assertEqual((status, body['error']['code']), (401, 'invalid_api_key'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,718 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,197 @@
|
||||
"""A blocked token lookup must not stall unrelated relay work on the event loop."""
|
||||
import ast
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import itertools
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'gateway'))
|
||||
SPEC = importlib.util.spec_from_file_location('responsive_error_relay', ROOT / 'gateway/transparent_api.py')
|
||||
if SPEC is None or SPEC.loader is None:
|
||||
raise RuntimeError('Cannot load the relay under test')
|
||||
RELAY = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(RELAY)
|
||||
|
||||
SKIN = ROOT / 'gateway' / 'grok-web-skin.py'
|
||||
SKIN_ERROR_FUNCS = ('_error_payload', '_finish_error', 'error_response', 'async_error_response')
|
||||
_LOGGERS = itertools.count()
|
||||
|
||||
|
||||
def _skin_error_ns():
|
||||
"""Extract the real skin error-response functions (hyphenated module, import side effects)."""
|
||||
from aiohttp import web
|
||||
from multidict import CIMultiDict
|
||||
import secrets
|
||||
from gateway_errors import public_error, public_json_dumps
|
||||
|
||||
tree = ast.parse(SKIN.read_text(encoding='utf-8'))
|
||||
found = {n.name: n for n in tree.body
|
||||
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name in SKIN_ERROR_FUNCS}
|
||||
missing = [name for name in SKIN_ERROR_FUNCS if name not in found]
|
||||
if missing:
|
||||
raise AssertionError('skin error-response region changed shape; missing %s' % missing)
|
||||
log = logging.getLogger('skin-error-%d' % next(_LOGGERS))
|
||||
log.setLevel(logging.CRITICAL)
|
||||
log.propagate = False
|
||||
ns = {'asyncio': asyncio, 'secrets': secrets, 'web': web, 'CIMultiDict': CIMultiDict,
|
||||
'public_error': public_error, 'public_json_dumps': public_json_dumps, 'LOG': log}
|
||||
for name in SKIN_ERROR_FUNCS:
|
||||
exec(compile(ast.Module(body=[found[name]], type_ignores=[]), str(SKIN), 'exec'), ns)
|
||||
return ns
|
||||
|
||||
|
||||
class ErrorResponsivenessTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def exercise(self, *, embedded=False):
|
||||
loop = asyncio.get_running_loop()
|
||||
started = asyncio.Event()
|
||||
release = threading.Event()
|
||||
owner = threading.get_ident()
|
||||
called = []
|
||||
pending = None
|
||||
|
||||
def mapper(status, raw, path, **context):
|
||||
called.append((status, raw, path, context, threading.get_ident()))
|
||||
loop.call_soon_threadsafe(started.set)
|
||||
if not release.wait(2):
|
||||
raise AssertionError('lookup blocked the relay event loop')
|
||||
return 401, {'error': {'code': 'invalid_api_key', 'retryable': False}}
|
||||
|
||||
class Content:
|
||||
async def iter_chunked(self, size):
|
||||
yield body
|
||||
|
||||
body = json.dumps({'error': {'status': 401, 'message': 'invalid token'}}).encode()
|
||||
upstream = SimpleNamespace(status=200 if embedded else 401,
|
||||
headers={'Content-Type': 'application/json'}, content=Content())
|
||||
request = SimpleNamespace(path='/v1/chat/completions', headers={})
|
||||
try:
|
||||
with patch.object(RELAY, 'public_error', side_effect=mapper):
|
||||
pending = asyncio.create_task(RELAY.relay_api(
|
||||
request, upstream, json_to_sse=embedded, user_balance=7))
|
||||
await asyncio.wait_for(started.wait(), 2)
|
||||
# This coroutine runs while the mapper is still blocked in its worker.
|
||||
self.assertFalse(pending.done())
|
||||
self.assertNotEqual(called[0][-1], owner)
|
||||
release.set()
|
||||
response = await asyncio.wait_for(pending, 2)
|
||||
finally:
|
||||
release.set()
|
||||
if pending is not None and not pending.done():
|
||||
await asyncio.wait_for(asyncio.gather(pending, return_exceptions=True), 2)
|
||||
self.assertEqual(response.status, 401)
|
||||
payload = json.loads(response.body)
|
||||
self.assertEqual(payload['error']['code'], 'invalid_api_key')
|
||||
self.assertFalse(payload['error']['retryable'])
|
||||
self.assertEqual(len(called), 1)
|
||||
self.assertEqual(called[0][0], 401)
|
||||
self.assertEqual(called[0][1], body)
|
||||
self.assertEqual(called[0][2], request.path)
|
||||
self.assertEqual(called[0][3]['user_balance'], 7)
|
||||
self.assertTrue(called[0][3]['from_upstream'])
|
||||
return payload
|
||||
|
||||
async def test_http_401_token_lookup_does_not_stall_other_coroutines(self):
|
||||
payload = await self.exercise()
|
||||
self.assertTrue(payload['error']['gateway_request_id'])
|
||||
|
||||
async def test_embedded_401_uses_the_same_nonblocking_lookup(self):
|
||||
await self.exercise(embedded=True)
|
||||
|
||||
async def test_other_statuses_keep_the_no_worker_fast_path(self):
|
||||
result = (503, {'error': {'code': 'upstream_unavailable'}})
|
||||
with patch.object(RELAY, 'public_error', return_value=result) as mapper:
|
||||
with patch.object(RELAY.asyncio, 'to_thread', side_effect=AssertionError('unexpected worker')):
|
||||
actual = await RELAY._upstream_error(503, b'{}', '/v1/chat/completions', user_balance=5)
|
||||
self.assertIs(actual, result)
|
||||
mapper.assert_called_once_with(503, b'{}', '/v1/chat/completions', user_balance=5)
|
||||
|
||||
|
||||
class SkinErrorResponseTests(unittest.IsolatedAsyncioTestCase):
|
||||
"""The skin shares the relay's rule: only a 401 pays for a worker hop."""
|
||||
|
||||
async def test_non_401_stays_inline_and_matches_the_sync_wire_form(self):
|
||||
ns = _skin_error_ns()
|
||||
owner = threading.get_ident()
|
||||
threads = []
|
||||
real_payload = ns['_error_payload']
|
||||
|
||||
def recording(*args, **kwargs):
|
||||
out = real_payload(*args, **kwargs)
|
||||
threads.append(threading.get_ident())
|
||||
return out
|
||||
|
||||
ns['_error_payload'] = recording
|
||||
with patch.object(asyncio, 'to_thread', side_effect=AssertionError('unexpected worker hop')):
|
||||
response = await ns['async_error_response'](503, b'{}', '/v1/chat/completions')
|
||||
self.assertEqual(threads, [owner])
|
||||
self.assertEqual(response.status, 503)
|
||||
payload = json.loads(response.body)
|
||||
self.assertTrue(payload['error']['gateway_request_id'])
|
||||
self.assertEqual(payload['error']['request_id'], payload['error']['gateway_request_id'])
|
||||
self.assertEqual(response.headers['Cache-Control'], 'no-store')
|
||||
self.assertEqual(response.headers['X-Request-ID'], payload['error']['gateway_request_id'])
|
||||
# identical classification to the synchronous form, with a fresh request id
|
||||
sync = json.loads(ns['error_response'](503, b'{}', '/v1/chat/completions').body)
|
||||
self.assertEqual(payload['error']['code'], sync['error']['code'])
|
||||
self.assertNotEqual(payload['error']['gateway_request_id'], sync['error']['gateway_request_id'])
|
||||
|
||||
async def test_401_token_lookup_leaves_the_skin_event_loop(self):
|
||||
ns = _skin_error_ns()
|
||||
loop = asyncio.get_running_loop()
|
||||
owner = threading.get_ident()
|
||||
started = asyncio.Event()
|
||||
release = threading.Event()
|
||||
threads = []
|
||||
contexts = []
|
||||
|
||||
def mapper(status, raw, path, **context):
|
||||
threads.append(threading.get_ident())
|
||||
contexts.append(context)
|
||||
loop.call_soon_threadsafe(started.set)
|
||||
if not release.wait(2):
|
||||
raise AssertionError('blocked lookup stalled the test')
|
||||
return status, {'error': {'code': 'invalid_api_key', 'retryable': False}}
|
||||
|
||||
ns['public_error'] = mapper
|
||||
ticks = 0
|
||||
|
||||
async def ticker():
|
||||
nonlocal ticks
|
||||
while ticks < 5:
|
||||
ticks += 1
|
||||
await asyncio.sleep(0)
|
||||
|
||||
pending = None
|
||||
try:
|
||||
pending = asyncio.create_task(ns['async_error_response'](
|
||||
401, b'{}', '/v1/chat/completions', api_key='sk-under-test'))
|
||||
await asyncio.wait_for(started.wait(), 2)
|
||||
# unrelated coroutines keep running while the DB lookup is blocked
|
||||
self.assertFalse(pending.done())
|
||||
await asyncio.wait_for(ticker(), 2)
|
||||
release.set()
|
||||
response = await asyncio.wait_for(pending, 2)
|
||||
finally:
|
||||
release.set()
|
||||
if pending is not None and not pending.done():
|
||||
await asyncio.wait_for(asyncio.gather(pending, return_exceptions=True), 2)
|
||||
self.assertNotEqual(threads, [owner])
|
||||
self.assertEqual(ticks, 5)
|
||||
self.assertEqual(contexts[0]['api_key'], 'sk-under-test')
|
||||
self.assertEqual(response.status, 401)
|
||||
payload = json.loads(response.body)
|
||||
self.assertEqual(payload['error']['code'], 'invalid_api_key')
|
||||
self.assertTrue(payload['error']['gateway_request_id'])
|
||||
self.assertEqual(response.headers['Cache-Control'], 'no-store')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,456 @@
|
||||
"""Live-model catalogue of gateway/grok-web-skin.py: effective DB, cache, fail-closed.
|
||||
|
||||
These tests execute the real functions of the skin (top-level `ast` nodes) against a
|
||||
real SQLite file, so DB path resolution, read-only access, caching, retry and alias
|
||||
deduplication are exercised as behaviour rather than asserted against source text.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest import IsolatedAsyncioTestCase
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
SKIN = Path(__file__).resolve().parents[1] / "gateway" / "grok-web-skin.py"
|
||||
|
||||
ASSIGNS = ("_LIVE_DB", "_LIVE_TTL", "_LIVE_RETRY", "_LIVE_MAX_STALE", "_live_lock", "_live_fetch_lock",
|
||||
"_live_cache", "EXTRA_HIDE")
|
||||
FUNCS = ("_live_now", "_live_read", "_live_cached", "_live_note_failure", "_live_snapshot",
|
||||
"live_models_snapshot", "get_live_models", "_hidden", "filter_pricing_body")
|
||||
|
||||
_counter = iter(range(10000))
|
||||
|
||||
|
||||
def _nodes():
|
||||
tree = ast.parse(SKIN.read_text(encoding="utf-8"))
|
||||
assigns, funcs = {}, {}
|
||||
for node in tree.body:
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||
funcs[node.name] = node
|
||||
elif isinstance(node, ast.Assign):
|
||||
for target in node.targets:
|
||||
if isinstance(target, ast.Name) and target.id in ASSIGNS:
|
||||
assigns[target.id] = node
|
||||
return assigns, funcs
|
||||
|
||||
|
||||
def _logger(sink):
|
||||
log = logging.getLogger("skin-catalogue-%d" % next(_counter))
|
||||
log.setLevel(logging.WARNING)
|
||||
log.propagate = False
|
||||
handler = logging.Handler()
|
||||
handler.emit = sink.append
|
||||
log.addHandler(handler)
|
||||
return log
|
||||
|
||||
|
||||
def _ns(db_path, hide=()):
|
||||
"""Namespace with the real catalogue assignments and functions of the skin."""
|
||||
source = SKIN.read_text(encoding="utf-8")
|
||||
assigns, funcs = _nodes()
|
||||
missing = [n for n in ASSIGNS if n not in assigns] + [n for n in FUNCS if n not in funcs]
|
||||
assert not missing, "catalogue region changed shape: missing %s" % missing
|
||||
sink = []
|
||||
ns = {
|
||||
"json": json, "logging": logging, "time": time, "sqlite3": sqlite3,
|
||||
"Path": Path, "_threading": threading,
|
||||
"GATE_NEWAPI_DB": str(db_path),
|
||||
"LOG": _logger(sink),
|
||||
"HIDE_MODEL_NAMES": frozenset(hide),
|
||||
"HIDDEN_GROUP": "vip",
|
||||
"sink": sink,
|
||||
"source": source,
|
||||
}
|
||||
for name in ASSIGNS:
|
||||
exec(compile(ast.Module(body=[assigns[name]], type_ignores=[]), str(SKIN), "exec"), ns)
|
||||
for name in FUNCS:
|
||||
exec(compile(ast.Module(body=[funcs[name]], type_ignores=[]), str(SKIN), "exec"), ns)
|
||||
return ns
|
||||
|
||||
|
||||
def _make_db(path, live=(), disabled=()):
|
||||
con = sqlite3.connect(path)
|
||||
try:
|
||||
con.execute("CREATE TABLE channels (id INTEGER PRIMARY KEY, status INTEGER NOT NULL)")
|
||||
con.execute("CREATE TABLE abilities (id INTEGER PRIMARY KEY, model TEXT, channel_id INTEGER,"
|
||||
" enabled INTEGER NOT NULL)")
|
||||
con.execute("INSERT INTO channels (id, status) VALUES (1, 1), (2, 2)")
|
||||
con.executemany("INSERT INTO abilities (model, channel_id, enabled) VALUES (?, 1, 1)",
|
||||
[(m,) for m in live])
|
||||
con.executemany("INSERT INTO abilities (model, channel_id, enabled) VALUES (?, 2, 1)",
|
||||
[(m,) for m in disabled])
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
return path
|
||||
|
||||
|
||||
def _pricing(*names, **extra):
|
||||
rows = [{"model_name": name} for name in names]
|
||||
body = {"object": "list", "data": rows}
|
||||
body.update(extra)
|
||||
return json.dumps(body).encode("utf-8")
|
||||
|
||||
|
||||
def _kept(raw, ns):
|
||||
filtered = ns["filter_pricing_body"](raw)
|
||||
return [row["model_name"] for row in json.loads(filtered)["data"]]
|
||||
|
||||
|
||||
def _counting_read(ns):
|
||||
"""Replace the DB reader with a wrapper that records every real attempt."""
|
||||
calls = []
|
||||
real = ns["_live_read"]
|
||||
|
||||
def wrapped():
|
||||
calls.append(1)
|
||||
return real()
|
||||
|
||||
ns["_live_read"] = wrapped
|
||||
return calls
|
||||
|
||||
|
||||
# --- database selection ---------------------------------------------------------------
|
||||
|
||||
def test_catalogue_follows_the_supplied_gateway_db(tmp_path):
|
||||
"""A hardcoded legacy path would ignore the effective DB, so both reads must differ."""
|
||||
first = _make_db(tmp_path / "first.db", live=["grok-4.6"])
|
||||
second = _make_db(tmp_path / "second.db", live=["grok-4.7"])
|
||||
|
||||
ns_a, ns_b = _ns(first), _ns(second)
|
||||
|
||||
assert ns_a["_LIVE_DB"] == str(first)
|
||||
assert ns_b["_LIVE_DB"] == str(second)
|
||||
assert ns_a["get_live_models"]() == frozenset({"grok-4.6"})
|
||||
assert ns_b["get_live_models"]() == frozenset({"grok-4.7"})
|
||||
|
||||
|
||||
def test_catalogue_reads_effective_db_not_legacy(tmp_path):
|
||||
effective = _make_db(tmp_path / "effective.db", live=["grok-4.6"])
|
||||
legacy = _make_db(tmp_path / "legacy.db", live=["legacy-only"])
|
||||
ns = _ns(effective)
|
||||
|
||||
models = ns["get_live_models"]()
|
||||
|
||||
assert models == frozenset({"grok-4.6"})
|
||||
assert ns["_LIVE_DB"] == str(effective)
|
||||
assert ns["_LIVE_DB"] != str(legacy)
|
||||
# the legacy file exists and holds other rows; none of them may surface
|
||||
assert legacy.exists()
|
||||
assert "legacy-only" not in models
|
||||
|
||||
|
||||
def test_effective_env_path_overrides_config_file(tmp_path, monkeypatch):
|
||||
"""Regression guard for the mismatch: env path wins over the config-file value."""
|
||||
import runtime_config
|
||||
|
||||
configured = _make_db(tmp_path / "configured.db", live=["legacy-only"])
|
||||
forced = _make_db(tmp_path / "forced.db", live=["grok-4.6"])
|
||||
monkeypatch.setenv("IISHKO_GW_DB", str(forced))
|
||||
monkeypatch.delenv("GATE_NEWAPI_DB", raising=False)
|
||||
|
||||
cfg = runtime_config.effective_bot_config({"newapi_db": str(configured)})
|
||||
assert cfg["newapi_db"] == str(forced)
|
||||
assert _ns(cfg["newapi_db"])["get_live_models"]() == frozenset({"grok-4.6"})
|
||||
|
||||
|
||||
# --- read-only access ----------------------------------------------------------------
|
||||
|
||||
def test_missing_db_is_not_created_and_state_is_unknown(tmp_path):
|
||||
missing = tmp_path / "absent.db"
|
||||
ns = _ns(missing)
|
||||
|
||||
models, known = ns["live_models_snapshot"]()
|
||||
|
||||
assert models == frozenset()
|
||||
assert known is False
|
||||
assert not missing.exists(), "catalogue must never create the gateway database"
|
||||
|
||||
|
||||
def test_broken_db_never_reports_models(tmp_path):
|
||||
broken = tmp_path / "broken.db"
|
||||
broken.write_bytes(b"not a sqlite database")
|
||||
ns = _ns(broken)
|
||||
|
||||
models, known = ns["live_models_snapshot"]()
|
||||
|
||||
assert models == frozenset()
|
||||
assert known is False
|
||||
assert broken.read_bytes() == b"not a sqlite database"
|
||||
|
||||
|
||||
def test_empty_live_set_is_known_and_authoritative(tmp_path):
|
||||
db = _make_db(tmp_path / "empty.db", live=(), disabled=["qwen-max"])
|
||||
ns = _ns(db)
|
||||
|
||||
models, known = ns["live_models_snapshot"]()
|
||||
|
||||
assert models == frozenset(), "disabled channels must not count as live"
|
||||
assert known is True
|
||||
|
||||
|
||||
# --- alias dedup after live/hidden filtering -----------------------------------------
|
||||
|
||||
def test_live_alias_survives_regardless_of_row_order(tmp_path):
|
||||
"""A disabled alias must not win the dedup and drop the live model."""
|
||||
db = _make_db(tmp_path / "live.db", live=["qwen-max"])
|
||||
ns = _ns(db)
|
||||
|
||||
forward = _kept(_pricing("qwen/qwen.max", "qwen-max"), ns)
|
||||
backward = _kept(_pricing("qwen-max", "qwen/qwen.max"), ns)
|
||||
|
||||
assert forward == ["qwen-max"]
|
||||
assert backward == ["qwen-max"]
|
||||
|
||||
|
||||
def test_hidden_row_does_not_shadow_visible_alias(tmp_path):
|
||||
db = _make_db(tmp_path / "live.db", live=["grok-4.6"])
|
||||
ns = _ns(db, hide=("grok-4.6",))
|
||||
|
||||
kept = _kept(_pricing("grok-4.6", "grok-4.6", "x-ai/grok-4.6"), ns)
|
||||
|
||||
assert "grok-4.6" not in kept
|
||||
assert kept == []
|
||||
|
||||
|
||||
def test_known_empty_catalogue_drops_every_row(tmp_path):
|
||||
db = _make_db(tmp_path / "empty.db", live=())
|
||||
ns = _ns(db)
|
||||
|
||||
kept = _kept(_pricing("grok-4.6", "qwen-max"), ns)
|
||||
|
||||
assert kept == [], "a reachable DB with no live models must not advertise anything"
|
||||
|
||||
|
||||
def test_unknown_state_does_not_invent_availability(tmp_path):
|
||||
ns = _ns(tmp_path / "absent.db")
|
||||
|
||||
kept = _kept(_pricing("grok-4.6", "qwen-max"), ns)
|
||||
|
||||
assert kept == [], "unknown live set must fail closed, not pass every row through"
|
||||
|
||||
|
||||
# --- cache, retry and logging --------------------------------------------------------
|
||||
|
||||
def test_repeated_calls_on_empty_db_read_once(tmp_path):
|
||||
db = _make_db(tmp_path / "empty.db", live=())
|
||||
ns = _ns(db)
|
||||
clock = [100.0]
|
||||
ns["_live_now"] = lambda: clock[0]
|
||||
calls = _counting_read(ns)
|
||||
|
||||
for _ in range(25):
|
||||
assert ns["get_live_models"]() == frozenset()
|
||||
|
||||
assert len(calls) == 1
|
||||
assert ns["sink"] == []
|
||||
|
||||
clock[0] += ns["_LIVE_TTL"] + 1
|
||||
ns["get_live_models"]()
|
||||
assert len(calls) == 2, "TTL expiry must refresh exactly once"
|
||||
|
||||
|
||||
def test_failure_is_cached_with_bounded_retry(tmp_path):
|
||||
db = _make_db(tmp_path / "live.db", live=["grok-4.6"])
|
||||
ns = _ns(db)
|
||||
clock = [0.0]
|
||||
ns["_live_now"] = lambda: clock[0]
|
||||
calls = _counting_read(ns)
|
||||
|
||||
assert ns["get_live_models"]() == frozenset({"grok-4.6"})
|
||||
db.unlink()
|
||||
clock[0] += ns["_LIVE_TTL"] + 1
|
||||
|
||||
for _ in range(10):
|
||||
assert ns["get_live_models"]() == frozenset({"grok-4.6"}), "stale set is served on error"
|
||||
|
||||
assert len(calls) == 2, "a failed refresh must not re-hit the DB on every request"
|
||||
assert len(ns["sink"]) == 1, "one warning per retry window, not per request"
|
||||
|
||||
clock[0] = ns["_LIVE_MAX_STALE"]
|
||||
assert ns["live_models_snapshot"]() == (frozenset(), False)
|
||||
assert len(calls) == 2, "expiry must not bypass the failure retry window"
|
||||
|
||||
clock[0] += ns["_LIVE_RETRY"] + 1
|
||||
assert ns["live_models_snapshot"]() == (frozenset(), False)
|
||||
assert len(calls) == 3, "unavailable DB cannot keep advertising the stale set"
|
||||
assert len(ns["sink"]) == 2
|
||||
|
||||
_make_db(db, live=["new-model"])
|
||||
clock[0] += ns["_LIVE_RETRY"] + 1
|
||||
assert ns["get_live_models"]() == frozenset({"new-model"})
|
||||
assert len(calls) == 4, "retry window must allow recovery"
|
||||
|
||||
|
||||
def test_broken_db_stays_cached_between_requests(tmp_path):
|
||||
broken = tmp_path / "broken.db"
|
||||
broken.write_bytes(b"garbage")
|
||||
ns = _ns(broken)
|
||||
clock = [0.0]
|
||||
ns["_live_now"] = lambda: clock[0]
|
||||
calls = _counting_read(ns)
|
||||
|
||||
for _ in range(30):
|
||||
models, known = ns["live_models_snapshot"]()
|
||||
assert models == frozenset() and known is False
|
||||
|
||||
assert len(calls) == 1
|
||||
assert len(ns["sink"]) == 1
|
||||
|
||||
|
||||
def test_concurrent_refresh_runs_once(tmp_path):
|
||||
db = _make_db(tmp_path / "live.db", live=["grok-4.6"])
|
||||
ns = _ns(db)
|
||||
clock = [0.0]
|
||||
ns["_live_now"] = lambda: clock[0]
|
||||
calls = _counting_read(ns)
|
||||
real = ns["_live_read"]
|
||||
|
||||
def slow_read():
|
||||
time.sleep(0.15)
|
||||
return real()
|
||||
|
||||
ns["_live_read"] = slow_read
|
||||
results = []
|
||||
barrier = threading.Barrier(8)
|
||||
|
||||
def worker():
|
||||
barrier.wait()
|
||||
results.append(ns["get_live_models"]())
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(8)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join(10)
|
||||
|
||||
assert not any(thread.is_alive() for thread in threads)
|
||||
assert len(results) == 8
|
||||
assert set(results) == {frozenset({"grok-4.6"})}
|
||||
assert len(calls) == 1, "single-flight: one DB read for the whole burst"
|
||||
|
||||
|
||||
def test_snapshot_is_immutable(tmp_path):
|
||||
db = _make_db(tmp_path / "live.db", live=["grok-4.6"])
|
||||
ns = _ns(db)
|
||||
|
||||
models = ns["get_live_models"]()
|
||||
|
||||
assert isinstance(models, frozenset)
|
||||
assert not hasattr(models, "add")
|
||||
assert models is ns["live_models_snapshot"]()[0], "no per-request copy churn"
|
||||
|
||||
|
||||
# --- pricing semantics unchanged -----------------------------------------------------
|
||||
|
||||
def test_pricing_body_preserves_billing_rules(tmp_path):
|
||||
db = _make_db(tmp_path / "live.db", live=["grok-4.6", "kimi/kimi-k3.1-pro"])
|
||||
ns = _ns(db)
|
||||
raw = json.dumps({"data": [
|
||||
{"model_name": "grok-4.6", "model_ratio": 4, "model_price": 0.5,
|
||||
"enable_groups": ["default", "vip"]},
|
||||
{"model_name": "kimi/kimi-k3.1-pro", "model_ratio": 3},
|
||||
], "group_ratio": {"default": 1, "vip": 2}, "usable_group": {"default": "x", "vip": "y"}}
|
||||
).encode("utf-8")
|
||||
|
||||
body = json.loads(ns["filter_pricing_body"](raw))
|
||||
|
||||
grok, kimi = body["data"]
|
||||
assert grok["model_ratio"] == 2 and grok["model_price"] == 0.25
|
||||
assert grok["enable_groups"] == ["default"]
|
||||
assert kimi["model_ratio"] == 3, "explicit kimi tariffs must not be halved"
|
||||
assert body["group_ratio"] == {"default": 1}
|
||||
assert body["usable_group"] == {"default": "x"}
|
||||
|
||||
|
||||
def test_unfiltered_body_returns_original_bytes(tmp_path):
|
||||
ns = _ns(_make_db(tmp_path / "live.db", live=["grok-4.6"]))
|
||||
raw = json.dumps({"data": ["not-a-model-row"]}).encode("utf-8")
|
||||
|
||||
assert ns["filter_pricing_body"](raw) is raw
|
||||
|
||||
|
||||
def test_real_rows_without_tariff_changes_return_original_bytes(tmp_path):
|
||||
"""Byte identity must hold for a genuine dict payload, not only a non-dict row.
|
||||
|
||||
The billing pass used to flag every dict row as modified, so each pricing body
|
||||
was re-serialized even when no tariff or group actually changed.
|
||||
"""
|
||||
ns = _ns(_make_db(tmp_path / "live.db", live=["grok-4.6", "kimi/kimi-k3.1-pro"]))
|
||||
raw = json.dumps({"data": [
|
||||
{"model_name": "grok-4.6", "enable_groups": ["default"]},
|
||||
{"model_name": "kimi/kimi-k3.1-pro", "model_ratio": 3},
|
||||
]}).encode("utf-8")
|
||||
|
||||
assert ns["filter_pricing_body"](raw) is raw
|
||||
|
||||
|
||||
def test_halved_tariff_still_marks_the_body_changed(tmp_path):
|
||||
ns = _ns(_make_db(tmp_path / "live.db", live=["grok-4.6"]))
|
||||
raw = json.dumps({"data": [{"model_name": "grok-4.6", "model_ratio": 4}]}).encode("utf-8")
|
||||
|
||||
body = ns["filter_pricing_body"](raw)
|
||||
|
||||
assert body is not raw
|
||||
assert json.loads(body)["data"][0]["model_ratio"] == 2
|
||||
|
||||
|
||||
def test_empty_pricing_rows_skip_the_database_entirely(tmp_path):
|
||||
db = _make_db(tmp_path / "live.db", live=["grok-4.6"])
|
||||
ns = _ns(db)
|
||||
calls = _counting_read(ns)
|
||||
raw = json.dumps({"data": []}).encode("utf-8")
|
||||
|
||||
assert ns["filter_pricing_body"](raw) is raw
|
||||
assert calls == []
|
||||
|
||||
|
||||
class PricingResponsivenessTests(IsolatedAsyncioTestCase):
|
||||
async def test_cold_catalogue_lookup_keeps_the_relay_event_loop_responsive(self):
|
||||
loop = asyncio.get_running_loop()
|
||||
entered = asyncio.Event()
|
||||
release = threading.Event()
|
||||
owner = threading.get_ident()
|
||||
callers = []
|
||||
raw = b'{"data":[{"model_name":"demo"}]}'
|
||||
filtered = b'{"data":[]}'
|
||||
|
||||
def filter_body(body):
|
||||
callers.append((body, threading.get_ident()))
|
||||
loop.call_soon_threadsafe(entered.set)
|
||||
if not release.wait(3):
|
||||
raise AssertionError("catalogue lookup blocked the event loop")
|
||||
return filtered
|
||||
|
||||
_, funcs = _nodes()
|
||||
ns = {"asyncio": asyncio, "web": web, "SKIP": (), "LOG": logging.getLogger(__name__),
|
||||
"response_headers": dict, "filter_pricing_body": filter_body}
|
||||
exec(compile(ast.Module(body=[funcs["relay"]], type_ignores=[]), str(SKIN), "exec"), ns)
|
||||
|
||||
async def read():
|
||||
return raw
|
||||
|
||||
request = SimpleNamespace(path="/api/pricing", method="GET")
|
||||
upstream = SimpleNamespace(status=200, headers={"Content-Type": "application/json"}, read=read)
|
||||
pending = asyncio.create_task(ns["relay"](request, upstream))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 3)
|
||||
self.assertFalse(pending.done())
|
||||
self.assertEqual(callers[0][0], raw)
|
||||
self.assertNotEqual(callers[0][1], owner)
|
||||
release.set()
|
||||
response = await asyncio.wait_for(pending, 3)
|
||||
finally:
|
||||
release.set()
|
||||
if not pending.done():
|
||||
await asyncio.wait_for(asyncio.gather(pending, return_exceptions=True), 3)
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(response.body, filtered)
|
||||
self.assertEqual(response.headers["Content-Type"], "application/json")
|
||||
@@ -37,3 +37,171 @@ def test_tg_login_refuses_cross_site_origin():
|
||||
resp = asyncio.run(ns["tg_login"](req))
|
||||
assert resp.status == 403
|
||||
assert json.loads(resp.body)["error"] == "bad_origin"
|
||||
|
||||
|
||||
def test_tg_login_never_holds_the_store_open_across_provisioning():
|
||||
"""connect+DDL must not run on the loop, and no connection may span a network await."""
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import tempfile
|
||||
from contextlib import closing
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = os.path.join(tmp, "tg-provision.db")
|
||||
token_file = os.path.join(tmp, "admin.token")
|
||||
with open(token_file, "w", encoding="utf-8") as fh:
|
||||
fh.write("bearer-token\n")
|
||||
|
||||
state = {"opened": 0, "closed": 0, "held": [], "links": []}
|
||||
|
||||
class _Conn:
|
||||
def __init__(self, con):
|
||||
self._con = con
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._con, name)
|
||||
|
||||
def close(self):
|
||||
state["closed"] += 1
|
||||
self._con.close()
|
||||
|
||||
class _Req:
|
||||
headers = {"Origin": "https://example.com"}
|
||||
host = "example.com"
|
||||
app = {"sess": object()}
|
||||
|
||||
async def text(self):
|
||||
return json.dumps({"id": 123, "auth_date": str(int(time.time())), "hash": "0" * 64})
|
||||
|
||||
async def _newapi_call(session, method, path, bearer, body=None):
|
||||
# the store must already be closed when the request goes out
|
||||
state["held"].append(state["opened"] - state["closed"])
|
||||
if path == "/api/user/login":
|
||||
return 200, b'{"success": false}', None
|
||||
return 200, b'{"success": true, "data": {"id": 7}}', None
|
||||
|
||||
ns = _load("tg_login", "_tg_store_conn", "_tg_store_password", "_tg_store_password_put",
|
||||
sqlite3=sqlite3, os=os, secrets=secrets, asyncio=asyncio,
|
||||
logging=logging, LOG=logging.getLogger("tg_login_store"),
|
||||
TG_PROVISION_DB=db, _TG_SCHEMA_READY=False, TG_ADMIN_TOKEN_FILE=token_file,
|
||||
CONTROL_SESSION_KEY="sess", _tg_normalize=lambda data: data,
|
||||
_tg_check_hash=lambda data: True, _newapi_call=_newapi_call,
|
||||
_json_ok=lambda status, body: status == 200 and json.loads(body).get("success") is True,
|
||||
_tg_link_upsert=lambda *args: state["links"].append(args))
|
||||
real_conn = ns["_tg_store_conn"]
|
||||
|
||||
def tracked_conn():
|
||||
state["opened"] += 1
|
||||
return _Conn(real_conn())
|
||||
|
||||
ns["_tg_store_conn"] = tracked_conn
|
||||
|
||||
resp = asyncio.run(ns["tg_login"](_Req()))
|
||||
|
||||
assert resp.status == 502
|
||||
assert json.loads(resp.body)["error"] == "login_failed"
|
||||
# a read for the missing password plus a write once provisioning succeeded
|
||||
assert state["opened"] >= 2
|
||||
assert state["held"] and set(state["held"]) == {0}, state["held"]
|
||||
assert state["opened"] == state["closed"]
|
||||
assert state["links"] == [(123, "tg123")]
|
||||
# `with sqlite3.connect(...)` commits but does not close: on Windows the open
|
||||
# handle would break TemporaryDirectory cleanup.
|
||||
with closing(sqlite3.connect(db)) as con:
|
||||
row = con.execute("SELECT username, length(password) FROM tg_users"
|
||||
" WHERE tg_id=123").fetchone()
|
||||
assert row[0] == "tg123" and row[1] >= 24
|
||||
|
||||
|
||||
def test_tg_login_provision_recovery_keeps_the_store_closed_across_awaits():
|
||||
"""create->search->get->put recovery runs four round trips; no connection may span one."""
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import tempfile
|
||||
from contextlib import closing
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = os.path.join(tmp, "tg-provision.db")
|
||||
token_file = os.path.join(tmp, "admin.token")
|
||||
with open(token_file, "w", encoding="utf-8") as fh:
|
||||
fh.write("bearer-token\n")
|
||||
|
||||
state = {"opened": 0, "closed": 0, "held": [], "links": [], "calls": [], "put_body": None}
|
||||
|
||||
class _Conn:
|
||||
def __init__(self, con):
|
||||
self._con = con
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._con, name)
|
||||
|
||||
def close(self):
|
||||
state["closed"] += 1
|
||||
self._con.close()
|
||||
|
||||
class _Req:
|
||||
headers = {"Origin": "https://example.com"}
|
||||
host = "example.com"
|
||||
app = {"sess": object()}
|
||||
|
||||
async def text(self):
|
||||
return json.dumps({"id": 123, "auth_date": str(int(time.time())), "hash": "0" * 64})
|
||||
|
||||
async def _newapi_call(session, method, path, bearer, body=None):
|
||||
# the store must already be closed when each of the four requests goes out
|
||||
state["held"].append(state["opened"] - state["closed"])
|
||||
state["calls"].append((method, path))
|
||||
if method == "POST" and path == "/api/user/":
|
||||
return 200, b'{"success": false, "message": "username already exists"}', None
|
||||
if method == "GET" and path.startswith("/api/user/search"):
|
||||
return 200, b'{"success": true, "data": {"items": [{"id": 7, "username": "tg123"}]}}', None
|
||||
if method == "GET" and path == "/api/user/7":
|
||||
return 200, b'{"success": true, "data": {"id": 7, "username": "tg123", "display_name": "tg"}}', None
|
||||
if method == "PUT" and path == "/api/user/":
|
||||
state["put_body"] = body
|
||||
return 200, b'{"success": true}', None
|
||||
if path == "/api/user/login":
|
||||
return 200, b'{"success": false}', None
|
||||
return 404, b'{"success": false}', None
|
||||
|
||||
ns = _load("tg_login", "_tg_store_conn", "_tg_store_password", "_tg_store_password_put",
|
||||
"_find_user_id", "_json_ok",
|
||||
sqlite3=sqlite3, os=os, secrets=secrets, asyncio=asyncio,
|
||||
logging=logging, LOG=logging.getLogger("tg_login_recovery"),
|
||||
TG_PROVISION_DB=db, _TG_SCHEMA_READY=False, TG_ADMIN_TOKEN_FILE=token_file,
|
||||
CONTROL_SESSION_KEY="sess", _tg_normalize=lambda data: data,
|
||||
_tg_check_hash=lambda data: True, _newapi_call=_newapi_call,
|
||||
_tg_link_upsert=lambda *args: state["links"].append(args))
|
||||
real_conn = ns["_tg_store_conn"]
|
||||
|
||||
def tracked_conn():
|
||||
state["opened"] += 1
|
||||
return _Conn(real_conn())
|
||||
|
||||
ns["_tg_store_conn"] = tracked_conn
|
||||
|
||||
resp = asyncio.run(ns["tg_login"](_Req()))
|
||||
|
||||
assert resp.status == 502
|
||||
assert json.loads(resp.body)["error"] == "login_failed"
|
||||
# the whole recovery chain ran, in order, and the full user object was resent
|
||||
assert state["calls"] == [("POST", "/api/user/"),
|
||||
("GET", "/api/user/search?keyword=tg123"),
|
||||
("GET", "/api/user/7"),
|
||||
("PUT", "/api/user/"),
|
||||
("POST", "/api/user/login")]
|
||||
assert state["put_body"]["id"] == 7 and state["put_body"]["username"] == "tg123"
|
||||
assert len(state["put_body"]["password"]) >= 24
|
||||
# no connection was open while a request was in flight, and none leaked
|
||||
assert state["held"] and set(state["held"]) == {0}, state["held"]
|
||||
assert state["opened"] == state["closed"]
|
||||
assert state["links"] == [(123, "tg123")]
|
||||
# the recovered password is what the store will serve on the next login
|
||||
with closing(sqlite3.connect(db)) as con:
|
||||
stored = con.execute("SELECT password FROM tg_users WHERE tg_id=123").fetchone()[0]
|
||||
assert stored == state["put_body"]["password"]
|
||||
|
||||
@@ -78,6 +78,8 @@ class PublicTransparentTests(unittest.IsolatedAsyncioTestCase):
|
||||
'TIMEOUT': aiohttp.ClientTimeout(total=5), 'SKIP': ('/v1/',),
|
||||
'_GEN_PATHS': {'/v1/chat/completions', '/v1/messages', '/v1/responses'},
|
||||
'LOG': logging.getLogger('transparent_test'),
|
||||
'public_error': public_error, 'public_json_dumps': public_json_dumps,
|
||||
'secrets': secrets,
|
||||
'gate_check': AsyncMock(return_value=(False, '')), '_rl_check_sync': Mock(return_value=None),
|
||||
'_DEV_ROLE_INCOMPAT_PREFIXES': ("qwen", "glm", "deepseek", "kimi"),
|
||||
'_key_balance_usd': Mock(return_value=None),
|
||||
@@ -93,8 +95,11 @@ class PublicTransparentTests(unittest.IsolatedAsyncioTestCase):
|
||||
names = {'CONTROL_SESSION_KEY', 'GENERATION_CONNECTIONS', 'CONTROL_CONNECTIONS'}
|
||||
constants = [node for node in tree.body if isinstance(node, ast.Assign) and any(isinstance(target, ast.Name) and target.id in names for target in node.targets)]
|
||||
exec(compile(ast.Module(body=constants, type_ignores=[]), str(SKIN), 'exec'), self.ns)
|
||||
# real error wire form: proxy's failure paths must exercise the offloaded
|
||||
# mapping, not a stub, otherwise a reverted sync call would still pass.
|
||||
extract(SKIN, {'proxy', 'response_headers', '_dev_role_incompat_model',
|
||||
'_normalize_developer_roles', '_open_upstream_sessions', '_close_upstream_sessions'}, self.ns)
|
||||
'_normalize_developer_roles', '_open_upstream_sessions', '_close_upstream_sessions',
|
||||
'async_error_response', '_error_payload', '_finish_error'}, self.ns)
|
||||
self.app.router.add_route('*', '/{path:.*}', self.ns['proxy'])
|
||||
self.client = TestClient(TestServer(self.app))
|
||||
await self.client.start_server()
|
||||
@@ -246,7 +251,7 @@ class PublicErrorWireTests(unittest.IsolatedAsyncioTestCase):
|
||||
'public_error': public_error, 'public_json_dumps': public_json_dumps,
|
||||
'LOG': logging.getLogger('error_wire_test'),
|
||||
}
|
||||
extract(SKIN, {'error_response'}, namespace)
|
||||
extract(SKIN, {'error_response', '_error_payload', '_finish_error'}, namespace)
|
||||
|
||||
async def handler(request):
|
||||
return namespace['error_response'](
|
||||
|
||||
Reference in New Issue
Block a user