Files
LihonT/tests/test_members_codegate.py
cheb0chik 3540ac84ea LihonT 2.3.0 (Serena): profile music, AI video dubbing, PiP & bg play, fonts, cleaner
- Shared moderated MP3 profile music (with floating mini-player and MediaSession controls, zero bubble when absent)
- AI video dubbing into Russian with burned-in ASS subtitles inside AgentChat (`services/members/dub.py`)
- Picture-in-Picture 9:16 and background audio playback (`PlayControl` + `play_patch.py`)
- System/custom .ttf fonts & emoji packs (`FontsAndEmoji`), account cleaner (`AccountCleaner`)
- Feed blacklist, muted sound restoration, OLED burn-in shift, A/B flag editor, presets, long comments
- Updated site homepage (`src/web/index.html`) for LihonT 2.3.0 Serena
2026-11-26 15:40:32 +03:00

252 lines
13 KiB
Python

import importlib.util
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
MEMBERS = Path(__file__).resolve().parents[1] / "services" / "members"
sys.path.insert(0, str(MEMBERS))
SPEC = importlib.util.spec_from_file_location("members_server_code", MEMBERS / "server.py")
server = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(server)
import lihonc # noqa: E402 (the copy next to server.py, as on the server)
INSTALL, INSTALL2, INSTALL3 = "a" * 64, "b" * 64, "c" * 64
DEVICE, DEVICE2 = "d" * 64, "e" * 64
class FakeResponse:
def __init__(self, payload, lines=None):
self.data = json.dumps(payload).encode()
self.lines = iter(lines or [])
def read(self):
return self.data
def __iter__(self):
return self.lines
def close(self):
pass
class FakeRouter(lihonc.Router):
"""Answers without a network: `script` maps a provider to an HTTP status (200 by default)."""
def __init__(self):
super().__init__({spec["key"]: "k" for spec in lihonc.PROVIDERS.values()})
self.script = {}
self.seen = []
def open(self, provider, model, body):
self.seen.append((provider, model, body))
status = self.script.get(provider, 200)
if status != 200:
if status in (402, 429):
self.cool(provider)
raise lihonc.UpstreamError(provider, status, "nope")
if body.get("stream"):
pieces = [{"model": model, "choices": [{"index": 0, "delta": {"content": part}}]} for part in ("при", "вет")]
pieces.append({"model": model, "choices": [], "usage": {"total_tokens": 800}})
return FakeResponse({}, [b"data: " + json.dumps(c).encode() + b"\n" for c in pieces] + [b"data: [DONE]\n"])
return FakeResponse({"model": model, "usage": {"total_tokens": 1000},
"choices": [{"message": {"role": "assistant", "content": provider}}]})
class CodeGateTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.now = 1_790_000_000
self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now)
self.gate = self.registry.codegate
self.router = FakeRouter()
self.gate.router = self.router
def chat(self, model="LihonC-1-auto", installation=INSTALL, device=DEVICE, ip="1.1.1.1", **extra):
return self.gate.call("code_chat", {"installation": installation, "device": device, "_ip": ip, "model": model,
"messages": [{"role": "user", "content": "hi"}], **extra})
def status(self, installation=INSTALL, device=DEVICE, ip="1.1.1.1"):
return self.gate.call("code_status", {"installation": installation, "device": device, "_ip": ip})
def exhaust(self, installation=INSTALL, device=DEVICE, ip="1.1.1.1"):
who = self.gate._who({"installation": installation, "device": device, "_ip": ip})
self.gate._spend(who, server.codegate.DEVICE_TOKENS)
def test_needs_installation_and_device(self):
for bad in ({"installation": "x"}, {"device": "short"}, {"device": None}):
payload = {"installation": INSTALL, "device": DEVICE, "model": "LihonC-1-auto", "messages": [{"role": "user", "content": "x"}], **bad}
with self.assertRaises(ValueError):
self.gate.call("code_chat", payload)
def test_auto_answers_with_our_name_and_falls_through(self):
self.router.script = {"groq": 429}
reply = self.chat()
self.assertEqual(reply["completion"]["model"], "LihonC-1-auto")
self.assertEqual(reply["completion"]["choices"][0]["message"]["content"], "gemini")
def test_tools_and_fields_pass_but_nothing_else(self):
tools = [{"type": "function", "function": {"name": "f", "parameters": {"type": "object"}}}]
self.chat(tools=tools, max_tokens=50, evil="x", stream="yes")
body = self.router.seen[-1][2]
self.assertEqual(body["tools"], tools)
self.assertFalse(body["stream"])
self.assertNotIn("evil", body)
def test_bad_input(self):
for bad in ({"model": "gpt-9"}, {"messages": []}, {"messages": [{"role": "hacker"}]}, {"messages": "x"}):
payload = {"installation": INSTALL, "device": DEVICE, "model": "LihonC-1-auto", "messages": [{"role": "user", "content": "x"}], **bad}
with self.assertRaises(ValueError):
self.gate.call("code_chat", payload)
def test_arena_consent_then_answer(self):
self.assertEqual(self.chat("LihonC-1-deepseek:arena")["error"]["type"], "arena_consent_required")
self.gate.call("code_consent", {"installation": INSTALL, "device": DEVICE, "accept": True})
reply = self.chat("LihonC-1-deepseek:arena")
self.assertEqual(reply["completion"]["model"], "LihonC-1-deepseek:arena")
self.assertEqual(self.router.seen[-1][1], "deepseek-v4-1-flash-1017")
self.assertTrue(self.status()["arena_consent"])
def test_arena_down_offers_auto_or_falls_back(self):
self.gate.call("code_consent", {"installation": INSTALL, "device": DEVICE, "accept": True})
self.router.script = {"coarena": 402}
reply = self.chat("LihonC-1-deepseek:arena")
self.assertEqual(reply["error"]["type"], "arena_unavailable")
self.assertEqual(reply["error"]["switch_to"], "LihonC-1-auto")
reply = self.chat("LihonC-1-deepseek:arena", fallback="auto")
self.assertTrue(reply["switched"])
self.assertEqual(self.status()["today"]["calls"], 1) # only the answered call is counted
def test_all_busy_is_not_counted(self):
self.router.script = {name: 503 for name in lihonc.PROVIDERS}
self.assertEqual(self.chat()["error"]["type"], "all_providers_busy")
self.assertEqual(self.status()["today"]["tokens"], 0)
def test_effort_is_passed_and_weighs_more(self):
self.chat(effort="high")
self.assertEqual(self.router.seen[-1][2]["reasoning_effort"], "high")
self.assertEqual(self.status()["today"]["tokens"], 3000)
self.chat(effort="low")
self.assertEqual(self.status()["today"]["tokens"], 4000)
self.chat(effort="extreme")
self.assertEqual(self.router.seen[-1][2]["reasoning_effort"], "medium")
def test_effort_words_per_provider(self):
body = {"messages": [], "reasoning_effort": "low"}
self.assertEqual(lihonc.clean_body(body, "groq", "m")["reasoning_effort"], "low")
self.assertEqual(lihonc.clean_body(body, "coarena", "m")["reasoning_effort"], "none")
self.assertEqual(lihonc.clean_body(body, "openrouter", "m")["reasoning"], {"effort": "low"})
self.assertNotIn("reasoning_effort", lihonc.clean_body(body, "cohere", "m"))
self.assertEqual(lihonc.clean_body(body, "zhipu", "m")["thinking"], {"type": "disabled"})
self.assertNotIn("reasoning_effort", lihonc.clean_body(body, "zhipu", "m"))
def test_daily_limit_on_the_same_network_is_only_a_limit(self):
self.exhaust()
for _ in range(5):
self.assertEqual(self.chat()["error"]["type"], "daily_limit")
self.assertIsNone(self.status()["banned_until"])
def test_going_around_warns_once_then_bans_everything(self):
self.exhaust()
self.assertEqual(self.chat()["error"]["type"], "daily_limit")
self.assertEqual(self.chat(ip="2.2.2.2")["error"]["type"], "device_limit") # another network: a warning
self.assertEqual(self.chat(ip="2.2.2.2")["error"]["type"], "daily_limit") # the same one again: no new strike
self.assertEqual(self.chat(installation=INSTALL2, ip="2.2.2.2")["error"]["type"], "banned") # a new installation: shut out
# the device, its installations and its addresses are out; another computer behind one of those addresses too, for a day
self.assertEqual(self.chat(installation=INSTALL3, device=DEVICE2, ip="1.1.1.1")["error"]["type"], "banned")
self.now += 86400 + 60 # the next day: the addresses are free again, the device is not
self.assertIn("completion", self.chat(installation=INSTALL3, device=DEVICE2, ip="1.1.1.1"))
self.assertEqual(self.chat(ip="3.3.3.3")["error"]["type"], "banned")
self.assertEqual(self.gate.unban(self.gate._hash("d", DEVICE)[2:10]), 1)
self.assertIn("completion", self.chat(ip="3.3.3.3"))
def test_a_shared_address_has_its_own_bigger_budget(self):
who = self.gate._who({"installation": INSTALL2, "device": DEVICE2, "_ip": "5.5.5.5"})
self.gate._spend(who, server.codegate.ADDRESS_TOKENS)
self.assertEqual(self.chat(ip="5.5.5.5")["error"]["type"], "address_limit")
self.assertIn("completion", self.chat(ip="6.6.6.6"))
def test_server_ceiling(self):
who = self.gate._who({"installation": INSTALL2, "device": DEVICE2, "_ip": "9.9.9.9"})
self.gate._spend(who, server.codegate.SERVER_TOKENS)
self.assertEqual(self.chat()["error"]["type"], "server_limit")
def test_owner_device_is_not_limited(self):
os.environ["CODE_OWNER_DEVICES"] = DEVICE
self.addCleanup(os.environ.pop, "CODE_OWNER_DEVICES", None)
self.exhaust()
self.assertIn("completion", self.chat(ip="7.7.7.7"))
def test_nothing_raw_is_stored(self):
self.chat(ip="8.8.4.4")
with self.registry.connect() as db:
dump = "\n".join(str(row) for table in ("code_use", "code_seen") for row in db.execute("SELECT * FROM %s" % table))
for raw in ("8.8.4.4", INSTALL, DEVICE):
self.assertNotIn(raw, dump)
def test_stream_sends_pieces_with_our_name_and_charges_at_the_end(self):
stream = self.chat(stream=True, effort="low")
self.assertIsInstance(stream, server.codegate.Stream)
events = list(stream)
text = "".join(c["choices"][0]["delta"]["content"] for c in events if c.get("choices"))
self.assertEqual(text, "привет")
self.assertTrue(all(c["model"] == "LihonC-1-auto" for c in events if "choices" in c))
self.assertTrue(events[-1]["lihonc_done"])
self.assertEqual(self.status()["today"]["tokens"], 800)
self.assertTrue(self.router.seen[-1][2]["stream"])
def test_stream_that_never_starts_falls_through(self):
self.router.script = {"groq": 429}
events = list(self.chat(stream=True))
self.assertEqual(self.router.seen[-1][0], "gemini")
self.assertTrue(events[-1]["lihonc_done"])
def test_pictures_go_to_a_provider_that_sees_them(self):
picture = {"role": "user", "content": [{"type": "text", "text": "что тут?"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}]}
self.gate.call("code_chat", {"installation": INSTALL, "device": DEVICE, "_ip": "1.1.1.1", "model": "LihonC-1-auto", "messages": [picture]})
self.assertEqual(self.router.seen[-1][0], "gemini")
def test_paid_reserve_stops_at_its_daily_ceiling(self):
os.environ["LIHONC_ALLOW_PAID"] = "1"
self.addCleanup(os.environ.pop, "LIHONC_ALLOW_PAID", None)
free = [name for name, spec in lihonc.PROVIDERS.items() if not spec.get("paid") and name != "coarena"]
self.router.script = {name: 503 for name in free}
reply = self.chat()
self.assertEqual(self.router.seen[-1][0], "apinet")
self.router.cooling.clear()
self.router.charge("apinet", lihonc.PROVIDERS["apinet"]["daily_tokens"])
self.chat()
self.assertEqual(self.router.seen[-1][0], "nordrouter")
self.router.cooling.clear()
self.router.charge("nordrouter", lihonc.PROVIDERS["nordrouter"]["daily_tokens"])
self.assertEqual(self.chat()["error"]["type"], "all_providers_busy")
self.router.charge("groq", 10**9) # free ones are never capped here
self.assertTrue(self.router.available("groq") or "groq" in self.router.cooling)
def test_paid_reserves_are_off_by_default(self):
os.environ.pop("LIHONC_ALLOW_PAID", None)
names = [provider for provider, _ in self.router.chain("LihonC-1-auto", {"messages": []})]
self.assertNotIn("apinet", names)
self.assertNotIn("nordrouter", names)
self.assertEqual(names[:3], ["groq", "gemini", "cohere"])
def test_a_hidden_address_is_neither_counted_nor_banned(self):
self.exhaust(ip="127.0.0.1")
self.assertEqual(self.chat(ip="127.0.0.1")["error"]["type"], "daily_limit")
self.chat(installation=INSTALL2, ip="127.0.0.1")
self.chat(installation=INSTALL3, ip="127.0.0.1") # going around: the device is banned...
self.assertEqual(self.chat(ip="127.0.0.1")["error"]["type"], "banned")
# ...but another person behind the same hidden address is not
self.assertIn("completion", self.chat(installation="f" * 64, device=DEVICE2, ip="127.0.0.1"))
def test_routes_exist_in_the_server(self):
for operation in ("code_status", "code_chat", "code_consent"):
self.assertIn(operation, server.OPERATIONS)
if __name__ == "__main__":
unittest.main()