Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
222 lines
7.5 KiB
Python
222 lines
7.5 KiB
Python
import ast
|
||
import html
|
||
import re
|
||
from pathlib import Path
|
||
from types import SimpleNamespace
|
||
|
||
BOT = Path(__file__).resolve().parents[1] / "bot" / "grok_bot.py"
|
||
|
||
|
||
def _tree():
|
||
return ast.parse(BOT.read_text(encoding="utf-8"))
|
||
|
||
|
||
def _find(tree, name):
|
||
for node in tree.body:
|
||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Assign)):
|
||
if isinstance(node, ast.Assign):
|
||
targets = [t.id for t in node.targets if isinstance(t, ast.Name)]
|
||
if name in targets:
|
||
return node
|
||
elif node.name == name:
|
||
return node
|
||
raise AssertionError(f"{name} не найден в bot/grok_bot.py")
|
||
|
||
|
||
def _source(name):
|
||
tree = _tree()
|
||
return ast.get_source_segment(BOT.read_text(encoding="utf-8"), _find(tree, name))
|
||
|
||
|
||
def _exec(name, ns):
|
||
src = _source(name)
|
||
exec(compile(src, str(BOT), "exec"), ns)
|
||
return ns[name]
|
||
|
||
|
||
class _Router:
|
||
def message(self, *a, **k):
|
||
return lambda fn: fn
|
||
|
||
|
||
class _User:
|
||
def __init__(self, uid):
|
||
self.id = uid
|
||
|
||
|
||
class _Message:
|
||
def __init__(self, uid):
|
||
self.from_user = _User(uid)
|
||
self.replies = []
|
||
|
||
async def answer(self, text, **kwargs):
|
||
self.replies.append(text)
|
||
|
||
|
||
def _gate(snapshot):
|
||
return SimpleNamespace(controller=SimpleNamespace(snapshot=snapshot))
|
||
|
||
|
||
def _run_queue(uid, admins, is_admin, gate, sqlite3=None):
|
||
ns = {
|
||
"router": _Router(),
|
||
"Command": lambda *a, **k: object(),
|
||
"Message": _Message,
|
||
"ParseMode": SimpleNamespace(HTML="HTML"),
|
||
"html": html,
|
||
"ADMIN_IDS": set(admins),
|
||
"is_admin": is_admin,
|
||
"_STABILITY_GATE": gate,
|
||
}
|
||
if sqlite3 is not None:
|
||
ns["sqlite3"] = sqlite3
|
||
handler = _exec("cmd_queue", ns)
|
||
msg = _Message(uid)
|
||
|
||
import asyncio
|
||
|
||
asyncio.run(handler(msg))
|
||
return msg.replies
|
||
|
||
|
||
def test_queue_denies_non_admin_without_touching_metrics():
|
||
def boom():
|
||
raise AssertionError("снапшот контроллера не должен читаться для не-админа")
|
||
|
||
replies = _run_queue(42, admins={1}, is_admin=lambda uid: False, gate=_gate(boom))
|
||
assert len(replies) == 1
|
||
assert "⛔" in replies[0]
|
||
assert "в работе" not in replies[0]
|
||
|
||
|
||
def test_queue_admin_gets_controller_metrics_only():
|
||
snap = {
|
||
"active": 2,
|
||
"queued": 7,
|
||
"limits": {"queue": 64, "user_queue": 2, "model": 8, "models": 3},
|
||
"outcomes": {"success": 10, "partial": 1},
|
||
"rejects": {"queue_full": 2},
|
||
"queue_p95_seconds": 4.5,
|
||
"models": {
|
||
"kimi/kimi-k3.1-pro": {"active": 1, "queued": 5, "limit": 8, "circuit": "closed"},
|
||
"claude-opus-5.5": {"active": 1, "queued": 2, "limit": 8, "circuit": "open",
|
||
"retry_after_seconds": 12.0},
|
||
},
|
||
}
|
||
replies = _run_queue(1, admins={1}, is_admin=lambda uid: False, gate=_gate(lambda: snap))
|
||
assert len(replies) == 1
|
||
text = replies[0]
|
||
assert "в работе" in text and "<b>2</b>" in text and "<b>7</b>" in text
|
||
assert "kimi/kimi-k3.1-pro" in text and "claude-opus-5.5" in text
|
||
assert "circuit open" in text and "12с" in text
|
||
assert "queue_full" in text and "p95" in text
|
||
for hostile in ("RAM", "/proc", "one-api", "uptime хоста"):
|
||
assert hostile not in text
|
||
|
||
|
||
def test_queue_never_opens_host_or_upstream_db():
|
||
class _Trap:
|
||
def connect(self, *a, **k):
|
||
raise AssertionError("обработчик /queue не должен открывать БД")
|
||
|
||
snap = {"active": 0, "queued": 0, "limits": {}, "models": {}}
|
||
replies = _run_queue(1, admins={1}, is_admin=lambda uid: False,
|
||
gate=_gate(lambda: snap), sqlite3=_Trap())
|
||
assert len(replies) == 1 and "Очередь пуста" in replies[0]
|
||
src = _source("cmd_queue")
|
||
for forbidden in ("psutil", "/proc/", "one-api", "if True", "sqlite3", "virtual_memory"):
|
||
assert forbidden not in src, forbidden
|
||
|
||
|
||
def test_keys_notice_points_to_miniapp_and_names_subscription_gate():
|
||
ns = {"key_notifications": SimpleNamespace(policy_summary=lambda wait, lang: ""),
|
||
"KEY_WAIT_SEC": 0}
|
||
notice_fn = _exec("keys_mini_notice", ns)
|
||
for lang, marker in (("ru", "подписка на @alstack"), ("en", "subscription to @alstack")):
|
||
text = notice_fn(lang)
|
||
assert "Mini App" in text and marker in text
|
||
assert "Ключи" in text or "Keys" in text
|
||
|
||
|
||
def _lang():
|
||
ns = {}
|
||
exec(compile(_source("LANG"), str(BOT), "exec"), ns)
|
||
return ns["LANG"]
|
||
|
||
|
||
def test_lang_copy_has_no_hardcoded_model_counts():
|
||
lang = _lang()
|
||
for code in ("ru", "en"):
|
||
line = lang[code]["models_line"]
|
||
assert not re.search(r"\b\d{1,2}\b", line), (code, line)
|
||
|
||
|
||
def test_lang_english_copy_has_no_cyrillic():
|
||
lang = _lang()
|
||
for key in ("models_line", "key_line", "gift_line"):
|
||
value = lang["en"][key]
|
||
assert not re.search(r"[\u0400-\u04FF]", value), (key, value)
|
||
|
||
|
||
def test_queue_renders_actual_controller_snapshot_including_zero_wait():
|
||
import asyncio
|
||
from request_stability import StabilityController
|
||
|
||
async def collect():
|
||
controller = StabilityController()
|
||
await controller.run("glm-5.3", lambda: asyncio.sleep(0))
|
||
return controller.snapshot()
|
||
|
||
snapshot = asyncio.run(collect())
|
||
text = _run_queue(1, {1}, lambda uid: False, _gate(lambda: snapshot))[0]
|
||
assert "p95 ожидания: 0.0 с" in text
|
||
assert "success 1" in text
|
||
assert "Очередь пуста" in text
|
||
decorators = _find(_tree(), "cmd_queue").decorator_list
|
||
assert len(decorators) == 1
|
||
|
||
|
||
def test_rank_help_and_rank_stats_describe_cumulative_access_not_availability():
|
||
import asyncio
|
||
|
||
ns = {}
|
||
help_text = _exec("PROJECT_HELP_KB", ns)
|
||
assert "ранг N открывает модели рангов 1…N" in help_text
|
||
assert "не гарантирует работоспособность" in help_text
|
||
assert "а не на каталог" not in help_text
|
||
pages = []
|
||
|
||
async def show_page(*args):
|
||
pages.append(args[2])
|
||
|
||
async def acknowledge():
|
||
pass
|
||
|
||
ns.update({
|
||
"CallbackQuery": SimpleNamespace, "asyncio": asyncio,
|
||
"db_get": lambda uid: {"lang": "ru"},
|
||
"compute_rank_stats": lambda: ({1: 1}, 1),
|
||
"BADGES": _exec("BADGES", {}),
|
||
"rank_rules_line": lambda level: str(level),
|
||
"tge": lambda emoji: emoji, "back_row": lambda lang: "",
|
||
"page_html": lambda lang, body, rows: body, "rich_page_s": show_page,
|
||
})
|
||
callback = SimpleNamespace(answer=acknowledge, from_user=_User(42),
|
||
bot=object(), message=SimpleNamespace(chat=SimpleNamespace(id=42)))
|
||
asyncio.run(_exec("cb_rank_stats", ns)(callback))
|
||
text = "\n".join(pages[0])
|
||
assert "ранг N открывает модели рангов 1…N" in text
|
||
assert "не гарантирует работоспособность" in text
|
||
assert "а не доступ к семействам" not in text
|
||
|
||
|
||
def test_generation_error_text_sanitised():
|
||
ns = {"GenerationError": type("GenerationError", (RuntimeError,), {})}
|
||
fn = _exec("_gen_err_user_text", ns)
|
||
GE = ns["GenerationError"]
|
||
msg = "Выбранная модель сейчас занята. Повтори немного позже."
|
||
assert fn(GE(msg)) == msg
|
||
assert fn(RuntimeError(msg)) == ""
|
||
assert fn(GE("https://gw.local/v1?key=secret")) == ""
|
||
assert fn(GE("<b>boom</b>")) == ""
|
||
assert fn(GE("x" * 500)) == "" |