Files
LihonT/tests/test_lihon_ai.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

284 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Unit tests for the Lihon AI web chat (apps/lihon-ai): passwords, codes, sign-up flow."""
from __future__ import annotations
import contextlib
import importlib.util
import io
import re
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location("lihon_ai", ROOT / "apps" / "lihon-ai" / "server.py")
assert SPEC and SPEC.loader
ai = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(ai)
class PasswordTests(unittest.TestCase):
def test_round_trip(self):
stored = ai.hash_password("correct horse battery")
self.assertTrue(ai.check_password(stored, "correct horse battery"))
self.assertFalse(ai.check_password(stored, "correct horse battery!"))
def test_salted(self):
self.assertNotEqual(ai.hash_password("same"), ai.hash_password("same"))
def test_garbage_is_false(self):
self.assertFalse(ai.check_password("", "x"))
self.assertFalse(ai.check_password("md5$a$b$c", "x"))
class EmailTests(unittest.TestCase):
def test_good(self):
for value in ("a@b.co", "bobik@lihon.online", "test+tag@example.com"):
self.assertTrue(ai.valid_email(value), value)
def test_bad(self):
for value in ("", "a@b", "a@@b.co", "a b@c.co", "a@b.c", "@b.co"):
self.assertFalse(ai.valid_email(ai.normalize_email(value)), value)
def test_normalize(self):
self.assertEqual(ai.normalize_email(" Bobik@Lihon.Online "), "bobik@lihon.online")
class CodeTests(unittest.TestCase):
def test_deterministic(self):
self.assertEqual(ai.code_hash("a@b.co", "123456"), ai.code_hash("a@b.co", "123456"))
self.assertNotEqual(ai.code_hash("a@b.co", "123456"), ai.code_hash("a@b.co", "123457"))
self.assertNotEqual(ai.code_hash("a@b.co", "123456"), ai.code_hash("c@d.co", "123456"))
def test_six_digits(self):
for _ in range(20):
self.assertRegex(ai.new_code(), r"^\d{6}$")
class WebSearchTests(unittest.TestCase):
def test_query_uses_last_user_message_and_drops_attachment(self):
messages = [
{"role": "user", "content": "старый вопрос"},
{"role": "assistant", "content": "старый ответ"},
{"role": "user", "content": "курс доллара\n\n[Файл: note.txt]\nсекрет"},
]
self.assertEqual(ai.search_query(messages), "курс доллара")
def test_unwraps_duckduckgo_redirect(self):
self.assertEqual(
ai.unwrap_search_link("//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fa%3Fb%3D1&rut=x"),
"https://example.com/a?b=1",
)
self.assertEqual(ai.unwrap_search_link("javascript:alert(1)"), "")
def test_formats_results_and_empty_search(self):
text = ai.search_results_text("запрос", [{"title": "Заголовок", "url": "https://e.example/a", "snippet": "Описание"}])
self.assertIn("1. Заголовок — https://e.example/a", text)
self.assertIn("Описание", text)
self.assertIn("ничего не нашёл", ai.search_results_text("запрос", []))
def test_page_has_web_toggle(self):
page = (ROOT / "apps" / "lihon-ai" / "static" / "index.html").read_text(encoding="utf-8")
self.assertIn('id="web-toggle"', page)
self.assertIn("web: !!S.web", page)
self.assertIn("DuckDuckGo", page)
def test_page_excerpt_keeps_the_part_with_the_answer(self):
text = ("навигация меню сайта " * 80) + " USD 1 Доллар США 82,2281 " + ("подвал сайта " * 80)
excerpt = ai.page_excerpt(text, "курс доллара к рублю сегодня")
self.assertIn("82,2281", excerpt)
self.assertLessEqual(len(excerpt), 2400)
def test_official_currency_fact_beats_guessing(self):
page = ("с 19.11.2026 840 USD 1 Доллар США 82,2281 978 EUR 1 Евро 90,3605 "
"978 EUR 1 Евро 90,3605")
results = [
{"title": "Банк", "url": "https://bankiros.ru/currency/usd", "snippet": "", "page": "82,4529"},
{"title": "ЦБ РФ", "url": "https://www.cbr.ru/currency_base/daily/", "snippet": "с 19.11.2026", "page": page},
]
text = ai.search_results_text("Курс доллара к рублю сегодня", results)
self.assertIn("1 USD = 82,2281 RUB", text)
self.assertIn("19.11.2026", text)
self.assertLess(text.index("https://www.cbr.ru"), text.index("https://bankiros.ru"))
def test_official_facts_need_the_cbr_page(self):
results = [{"title": "Банк", "url": "https://bankiros.ru/currency/usd", "snippet": "", "page": "82,4529"}]
self.assertEqual(ai.official_currency_facts("курс доллара", results), ([], ""))
self.assertTrue(ai.is_official("https://www.cbr.ru/currency_base/daily/"))
self.assertFalse(ai.is_official("https://cbr.ru.evil.example/"))
def test_cbr_xml_is_parsed_without_the_web(self):
xml = ('<?xml version="1.0" encoding="windows-1251"?><ValCurs Date="19.11.2026">'
'<Valute><CharCode>USD</CharCode><Nominal>1</Nominal><Value>82,2281</Value></Valute>'
'<Valute><CharCode>EUR</CharCode><Nominal>1</Nominal><Value>90,3605</Value></Valute>'
'</ValCurs>').encode("windows-1251")
class Reply:
def __enter__(self):
return self
def __exit__(self, *args):
return False
def read(self, _limit=0):
return xml
from unittest import mock
ai._CBR_CACHE.clear()
with mock.patch.object(ai.urllib.request, "urlopen", return_value=Reply()):
facts = ai.cbr_currency_facts("курс доллара к рублю")
self.assertTrue(any("1 USD = 82,2281 RUB" in fact for fact in facts))
self.assertTrue(any("19.11.2026" in fact for fact in facts))
self.assertEqual(ai.cbr_currency_facts("какая погода"), [])
def test_private_addresses_are_not_fetched(self):
self.assertFalse(ai.safe_public_url("http://127.0.0.1/"))
self.assertFalse(ai.safe_public_url("http://localhost/"))
self.assertFalse(ai.safe_public_url("file:///etc/passwd"))
self.assertFalse(ai.safe_public_url("http://[::1]/"))
class SignUpTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.app = ai.App(
database=str(Path(self.tmp.name) / "ai.sqlite3"),
static=str(ROOT / "apps" / "lihon-ai" / "static"),
code_api="http://127.0.0.1:9/never",
api_key="",
sender="Lihon <noreply@lihon.online>",
dev=True,
secure_cookie=False,
)
def tearDown(self):
self.tmp.cleanup()
def register(self, email="bobik@lihon.online", password="password-123"):
out = io.StringIO()
with contextlib.redirect_stdout(out):
result = self.app.register(email, password)
code = re.search(r": (\d{6})$", out.getvalue().strip(), re.M)
self.assertIsNotNone(code, out.getvalue())
return result, code.group(1)
def test_register_creates_unverified(self):
self.register()
user = self.app.store.user_by_email("bobik@lihon.online")
self.assertEqual(user["verified"], 0)
self.assertNotEqual(user["password"], "password-123")
self.assertTrue(user["password"].startswith("pbkdf2$"))
def test_confirm_and_login(self):
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.app.register("bobik@lihon.online", "password-123")
code = re.search(r": (\d{6})$", out.getvalue().strip(), re.M).group(1)
result = self.app.confirm("bobik@lihon.online", code)
self.assertTrue(result["ok"])
self.assertIsNotNone(self.app.store.user_by_token(result["token"]))
self.assertTrue(self.app.login("bobik@lihon.online", "password-123")["ok"])
def test_wrong_code_and_limit(self):
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.app.register("bobik@lihon.online", "password-123")
code = re.search(r": (\d{6})$", out.getvalue().strip(), re.M).group(1)
wrong = "000000" if code != "000000" else "111111"
for _ in range(5):
with self.assertRaises(ai.ApiError) as caught:
self.app.confirm("bobik@lihon.online", wrong)
self.assertEqual(caught.exception.status, 400)
with self.assertRaises(ai.ApiError) as caught:
self.app.confirm("bobik@lihon.online", code)
self.assertEqual(caught.exception.status, 429)
def test_duplicate_verified(self):
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.app.register("bobik@lihon.online", "password-123")
code = re.search(r": (\d{6})$", out.getvalue().strip(), re.M).group(1)
self.app.confirm("bobik@lihon.online", code)
with self.assertRaises(ai.ApiError) as caught:
self.app.register("bobik@lihon.online", "password-123")
self.assertEqual(caught.exception.status, 409)
def test_weak_password(self):
with self.assertRaises(ai.ApiError) as caught:
self.app.register("bobik@lihon.online", "short")
self.assertEqual(caught.exception.status, 400)
def test_login_before_confirm(self):
self.register()
with self.assertRaises(ai.ApiError) as caught:
self.app.login("bobik@lihon.online", "password-123")
self.assertEqual(caught.exception.status, 403)
self.assertTrue(caught.exception.extra.get("needs_confirm"))
def test_rate_limit(self):
for _ in range(5):
self.assertTrue(self.app.allow("203.0.113.9", "register"))
self.assertFalse(self.app.allow("203.0.113.9", "register"))
class MarkdownTests(unittest.TestCase):
def test_table(self):
page = ai.render_markdown("| Направление | Что добавить |\n|---|---|\n| **Умения** | `код` |")
self.assertIn("<table>", page)
self.assertIn("<th>Направление</th>", page)
self.assertIn("<strong>Умения</strong>", page)
self.assertIn("<code>код</code>", page)
def test_code_and_escaping(self):
page = ai.render_markdown("```python\nprint('<x>')\n```\n<script>alert(1)</script>")
self.assertIn("<pre><code>", page)
self.assertIn("&lt;x&gt;", page)
self.assertNotIn("<script>", page)
self.assertIn("&lt;script&gt;", page)
class ShareTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.app = ai.App(
database=str(Path(self.tmp.name) / "ai.sqlite3"),
static=str(ROOT / "apps" / "lihon-ai" / "static"),
code_api="http://127.0.0.1:9/never",
api_key="",
sender="Lihon <noreply@lihon.online>",
dev=True,
secure_cookie=False,
public="https://example.test/",
)
def tearDown(self):
self.tmp.cleanup()
def test_share_and_page(self):
result = self.app.share([
{"role": "user", "content": "Сделай таблицу"},
{"role": "assistant", "content": "| A | B |\n|---|---|\n| 1 | 2 |"},
])
self.assertRegex(result["id"], r"^[A-Za-z0-9]{7}$")
self.assertEqual(result["url"], "https://example.test/" + result["id"])
record = self.app.store.get_share(result["id"])
self.assertIsNotNone(record)
self.assertIn("Сделай таблицу", ai.share_page(record, self.app.public))
self.assertIn("<table>", ai.share_page(record, self.app.public))
def test_share_needs_answer(self):
with self.assertRaises(ai.ApiError) as caught:
self.app.share([{"role": "user", "content": "Привет"}])
self.assertEqual(caught.exception.status, 400)
def test_share_escapes_html(self):
result = self.app.share([
{"role": "user", "content": "Привет"},
{"role": "assistant", "content": "<script>alert(1)</script>"},
])
page = ai.share_page(self.app.store.get_share(result["id"]), self.app.public)
self.assertNotIn("<script>alert", page)
self.assertIn("&lt;script&gt;", page)
if __name__ == "__main__":
unittest.main()