- 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
621 lines
36 KiB
Python
621 lines
36 KiB
Python
"""lihont-ltp: the Python library for plugin authors. Its checks and its defender must agree with the app's own."""
|
||
|
||
import json
|
||
import os
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import unittest
|
||
import zipfile
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
SDK = ROOT / "sdk" / "lihont-ltp"
|
||
sys.path.insert(0, str(SDK))
|
||
|
||
from lihont_ltp import * # noqa: E402,F401,F403
|
||
from lihont_ltp import guard as guard_module # noqa: E402
|
||
from lihont_ltp import validate # noqa: E402
|
||
from lihont_ltp.cli import main as cli_main # noqa: E402
|
||
from lihont_ltp.errors import LtpError # noqa: E402
|
||
from lihont_ltp.pack import read_ltp # noqa: E402
|
||
|
||
CORE = ["Act", "Cond", "Ctx", "Defender", "DownloadSpec", "Evaluator", "Fields", "GuardDump", "Journal", "Json",
|
||
"LtpException", "OverlaySpec", "Permission", "Plugin", "PluginPackage", "Rule", "ThemeData"]
|
||
|
||
|
||
def build(plugin):
|
||
return plugin.build(SDK / "examples")
|
||
|
||
|
||
class Language(unittest.TestCase):
|
||
def test_a_rule_reads_like_a_sentence_and_rights_are_worked_out(self):
|
||
plugin = Plugin("Тихая ночь", author="Вася")
|
||
plugin.video(hashtag("fyp", "#ForYou"), hide, say("скрыто"))
|
||
manifest = build(plugin)[0]
|
||
self.assertEqual(manifest["id"], "vasya.tihaya-noch")
|
||
self.assertEqual(manifest["permissions"], ["feed.hide", "ui.notice"])
|
||
self.assertEqual(manifest["rules"][0]["if"], {"hashtag": ["fyp", "#ForYou"]})
|
||
self.assertEqual(manifest["rules"][0]["do"], [{"feed.hide": True}, {"notice": "скрыто"}])
|
||
|
||
def test_and_or_not_make_groups_and_flatten_chains(self):
|
||
plugin = Plugin("X", author="Вася")
|
||
plugin.video(word("a") & word("b") & ~hashtag("c"), hide)
|
||
condition = build(plugin)[0]["rules"][0]["if"]
|
||
self.assertEqual(condition, {"all": [{"text": ["a"]}, {"text": ["b"]}, {"not": {"hashtag": ["c"]}}]})
|
||
plugin = Plugin("X", author="Вася")
|
||
plugin.video(word("a") | word("b") | word("c"), hide)
|
||
self.assertEqual(build(plugin)[0]["rules"][0]["if"], {"any": [{"text": ["a"]}, {"text": ["b"]}, {"text": ["c"]}]})
|
||
|
||
def test_me_means_the_author_in_videos_and_the_name_in_names(self):
|
||
plugin = Plugin("X", author="Вася")
|
||
plugin.video(me, say("моё"))
|
||
plugin.name(me & morning, after("!"))
|
||
rules = build(plugin)[0]["rules"]
|
||
self.assertEqual(rules[0]["if"], {"author": ["self"]})
|
||
self.assertEqual(rules[1]["if"], {"all": [{"uid": ["self"]}, {"time": "06:00-12:00"}]})
|
||
|
||
def test_weekdays_accept_english_and_russian_names(self):
|
||
self.assertEqual(weekday("fri", "сб").to_json("video"), {"weekday": [5, 6]})
|
||
with self.assertRaises(LtpError):
|
||
weekday("funday")
|
||
|
||
def test_the_picture_collects_its_taps_and_rights(self):
|
||
plugin = Plugin("Кот", author="Вася")
|
||
plugin.screen(picture("star.png", on_tap=[wiggle, like]))
|
||
manifest = build(plugin)[0]
|
||
self.assertEqual(manifest["permissions"], ["ui.overlay", "feed.like"])
|
||
self.assertEqual(manifest["rules"][0]["do"][0]["overlay"]["tap"], ["animate", "like"])
|
||
|
||
def test_a_download_lists_its_sites_by_itself_and_comes_with_the_right(self):
|
||
plugin = Plugin("Кот из сети", author="Вася")
|
||
plugin.screen(download("https://cdn.example.com/a/cat.png", "cat.png"),
|
||
download("https://img.example.org/dog.gif", "dog.gif", sha256="ab" * 32),
|
||
picture("cat.png"))
|
||
manifest, assets, report = build(plugin)
|
||
self.assertEqual(manifest["permissions"], ["net.download", "ui.overlay"])
|
||
self.assertEqual(manifest["net"], {"hosts": ["cdn.example.com", "img.example.org"]})
|
||
self.assertEqual(assets, {}) # fetched files are not packed
|
||
self.assertTrue(report.net and report.level == guard_module.WATCH)
|
||
self.assertIn("ходить куда-либо, кроме названных сайтов", report.text())
|
||
self.assertEqual(list(manifest)[-2:], ["net", "rules"])
|
||
|
||
def test_the_licence_and_the_ai_go_into_the_manifest_and_the_review_checks_them(self):
|
||
from lihont_ltp import review
|
||
plugin = Plugin("Своё", author="Вася", description="Скрывает fyp", license="MIT", ai="Claude Sonnet 5.5")
|
||
plugin.video(hashtag("fyp"), hide)
|
||
manifest, assets, report = build(plugin)
|
||
self.assertEqual(manifest["license"], "MIT")
|
||
self.assertEqual(manifest["ai"], ["Claude Sonnet 5.5"])
|
||
self.assertNotIn("не указал лицензию", report.text())
|
||
self.assertEqual(review.problems(manifest, assets), [])
|
||
# a plugin that says nothing, hides everything and fetches without a pin has things to fix
|
||
bad = Plugin("Плохое", author="Вася")
|
||
bad.video(hide)
|
||
bad.screen(download("https://cdn.example.com/c.png", "c.png"), picture("c.png"))
|
||
manifest, assets, report = build(bad)
|
||
self.assertIn("Автор не указал лицензию плагина.", report.text())
|
||
found = " ".join(review.problems(manifest, assets))
|
||
for needle in ("MIT или VCBFU-2", "Нет описания", "Осторожно", "без sha256"):
|
||
self.assertIn(needle, found)
|
||
other = Plugin("Другое", author="В", description="x", license="GPL-3.0")
|
||
other.video(hashtag("a"), hide)
|
||
self.assertIn("указано «GPL-3.0»", " ".join(review.problems(*build(other)[:2])))
|
||
for name in ("VCBFU-2", "vcbfu", "mit"):
|
||
fine = Plugin("Ок", author="В", description="x", license=name)
|
||
fine.video(hashtag("a"), hide)
|
||
self.assertEqual(review.problems(*build(fine)[:2]), [], name)
|
||
|
||
def test_the_fields_are_checked_like_in_the_app(self):
|
||
def make(**kw):
|
||
plugin = Plugin("X", author="В", **kw)
|
||
plugin.video(hashtag("a"), hide)
|
||
return lambda: build(plugin)
|
||
for kwargs, needle in (({"license": "x" * 41}, "не больше 40"), ({"ai": ["a"] * 5}, "не больше 4"),
|
||
({"ai": [" "]}, "пустая запись"), ({"ai": [7]}, "нужен текст")):
|
||
with self.assertRaises(LtpError, msg=str(kwargs)) as raised:
|
||
make(**kwargs)()
|
||
self.assertIn(needle, str(raised.exception))
|
||
|
||
def test_a_plugin_without_downloads_has_no_net_part(self):
|
||
plugin = Plugin("X", author="Вася")
|
||
plugin.video(hashtag("a"), hide)
|
||
manifest, _assets, report = build(plugin)
|
||
self.assertNotIn("net", manifest)
|
||
self.assertFalse(report.net)
|
||
self.assertIn("выходить в интернет", report.text())
|
||
|
||
def test_a_forgotten_condition_means_always(self):
|
||
plugin = Plugin("X", author="Вася")
|
||
plugin.video(hide)
|
||
manifest = build(plugin)[0]
|
||
self.assertNotIn("if", manifest["rules"][0])
|
||
self.assertEqual(build(plugin)[2].level, guard_module.CAREFUL)
|
||
|
||
def test_the_russian_names_work(self):
|
||
from lihont_ltp.ru import Плагин, скрыть, хэштег
|
||
plugin = Плагин("Тест", автор="Вася")
|
||
plugin.видео(хэштег("fyp"), скрыть)
|
||
self.assertEqual(build(plugin)[0]["rules"][0]["do"], [{"feed.hide": True}])
|
||
|
||
|
||
class FriendlyErrors(unittest.TestCase):
|
||
def fails(self, make, needle):
|
||
with self.assertRaises(LtpError) as raised:
|
||
make()
|
||
self.assertIn(needle, str(raised.exception))
|
||
|
||
def test_mistakes_are_explained_in_russian(self):
|
||
self.fails(lambda: Plugin("X"), "Укажи автора")
|
||
self.fails(lambda: Plugin("X", author="В").video("fyp", hide), "условие")
|
||
self.fails(lambda: Plugin("X", author="В").video(hashtag("a")), "нет действий")
|
||
self.fails(lambda: Plugin("X", author="В").video(hashtag("a"), "hide"), "действия")
|
||
self.fails(lambda: hashtag(), "напиши хотя бы одно")
|
||
self.fails(lambda: hashtag(5), "в кавычках")
|
||
self.fails(lambda: Plugin("X", author="В").screen(say("x"), when=me), "me")
|
||
|
||
def test_rules_of_the_app_are_checked_before_the_phone_sees_the_file(self):
|
||
def bad(setup):
|
||
plugin = Plugin("X", author="Вася")
|
||
setup(plugin)
|
||
return lambda: build(plugin)
|
||
self.fails(bad(lambda p: p.name(me, hide)), "только в правилах про видео")
|
||
self.fails(bad(lambda p: p.video(always, after("x"))), "только в правилах про имена")
|
||
self.fails(bad(lambda p: p.video(hashtag("a"), say("x" * 81))), "не больше 80")
|
||
self.fails(bad(lambda p: p.video(between("10:00", "10:00"), hide)), "начало не равно концу")
|
||
self.fails(bad(lambda p: p.screen(picture("Cat.GIF"))), "нельзя")
|
||
self.fails(bad(lambda p: p.screen(picture("nope.png"))), "нет рядом со скриптом")
|
||
self.fails(bad(lambda p: p.video(hashtag("a"), say("x"), limit=99)), "от 1 до 20")
|
||
self.fails(bad(lambda p: p.screen(picture("star.png", on_tap=[sound("star.png")]))), "Звук")
|
||
self.fails(lambda: build(Plugin("X", author="Вася", id="Ab").video(hide)), "id")
|
||
|
||
def test_mistakes_in_downloads_are_explained(self):
|
||
def screen(*actions):
|
||
plugin = Plugin("X", author="Вася")
|
||
plugin.screen(*actions)
|
||
return lambda: build(plugin)
|
||
pic = picture("cat.png")
|
||
self.fails(screen(download("http://cdn.example.com/cat.png", "cat.png"), pic), "https://")
|
||
self.fails(screen(download("https://cdn.example.com:8443/cat.png", "cat.png"), pic), "порта")
|
||
self.fails(screen(download("https://me@cdn.example.com/cat.png", "cat.png"), pic), "логина")
|
||
self.fails(screen(download("https://10.0.0.1/cat.png", "cat.png"), pic), "имя сайта")
|
||
self.fails(screen(download("https://localhost/cat.png", "cat.png"), pic), "имя сайта")
|
||
self.fails(screen(download("https://cdn.example.com", "cat.png"), pic), "нужен путь")
|
||
self.fails(screen(download("https://cdn.example.com/../cat.png", "cat.png"), pic), "лишние знаки")
|
||
self.fails(screen(download("https://cdn.example.com/cat.png", "cat.txt"), pic), "png, gif, webp")
|
||
self.fails(screen(download("https://cdn.example.com/cat.png", "Cat.PNG"), pic), "нельзя")
|
||
self.fails(screen(download("https://cdn.example.com/cat.png", "cat.png", sha256="abc"), pic), "64 цифры")
|
||
self.fails(screen(download("https://cdn.example.com/a.png", "cat.png"),
|
||
download("https://cdn.example.com/b.png", "cat.png"), pic), "дважды")
|
||
self.fails(lambda: download("https://cdn.example.com/cat.png", 5), "в кавычках")
|
||
many = [download("https://cdn.example.com/c%d.png" % n, "c%d.png" % n) for n in range(5)]
|
||
self.fails(screen(*many, pic), "больше 4")
|
||
plugin = Plugin("X", author="Вася")
|
||
plugin.video(always, download("https://cdn.example.com/cat.png", "cat.png"))
|
||
self.fails(lambda: build(plugin), "только в правилах про экран")
|
||
# a picture that points at its own file and the same name downloaded: the plugin already holds it
|
||
plugin = Plugin("X", author="Вася")
|
||
plugin.screen(download("https://cdn.example.com/star.png", "star.png"), picture("star.png"))
|
||
manifest, assets, _report = build(plugin)
|
||
self.assertEqual(assets, {}) # star.png lies next to the examples, but a fetched name is never packed
|
||
|
||
def test_too_many_conditions_and_rules_are_refused(self):
|
||
plugin = Plugin("X", author="Вася")
|
||
for number in range(33):
|
||
plugin.video(word("w%d" % number), hide)
|
||
self.fails(lambda: build(plugin), "больше 32")
|
||
deep = word("a")
|
||
for _ in range(5):
|
||
deep = ~deep
|
||
plugin = Plugin("X", author="Вася")
|
||
plugin.video(deep, hide)
|
||
self.fails(lambda: build(plugin), "глубоко")
|
||
|
||
|
||
class Files(unittest.TestCase):
|
||
def setUp(self):
|
||
self.temporary = tempfile.TemporaryDirectory(prefix="ltp-sdk-")
|
||
self.addCleanup(self.temporary.cleanup)
|
||
self.out = Path(self.temporary.name)
|
||
|
||
def test_the_examples_build_and_read_back(self):
|
||
env = dict(os.environ, LTP_OUT_DIR=str(self.out), PYTHONPATH=str(SDK), PYTHONIOENCODING="utf-8")
|
||
examples = sorted((SDK / "examples").glob("*.py"))
|
||
self.assertGreaterEqual(len(examples), 5)
|
||
for example in examples:
|
||
done = subprocess.run([sys.executable, "-X", "utf8", str(example)], env=env, capture_output=True, text=True,
|
||
encoding="utf-8")
|
||
self.assertEqual(done.returncode, 0, "%s\n%s" % (example.name, done.stderr))
|
||
self.assertIn("Защитник:", done.stdout)
|
||
files = sorted(self.out.glob("*.ltp"))
|
||
self.assertEqual(len(files), len(examples))
|
||
for file in files:
|
||
manifest, assets, _icon = read_ltp(file)
|
||
self.assertTrue(manifest["id"])
|
||
with zipfile.ZipFile(file) as archive:
|
||
for name in archive.namelist():
|
||
self.assertTrue(name in ("plugin.json", "icon.png") or name.startswith("assets/"))
|
||
|
||
def test_the_cli_makes_a_template_that_runs_and_checks_a_file(self):
|
||
cwd = os.getcwd()
|
||
os.chdir(self.out)
|
||
try:
|
||
self.assertEqual(cli_main(["new", "Мой плагин", "--author", "Вася"]), 0)
|
||
self.assertEqual(cli_main(["new", "Мой плагин"]), 1) # does not overwrite
|
||
env = dict(os.environ, PYTHONPATH=str(SDK), PYTHONIOENCODING="utf-8")
|
||
done = subprocess.run([sys.executable, "-X", "utf8", "moy-plagin.py"], env=env, capture_output=True,
|
||
text=True, encoding="utf-8")
|
||
self.assertEqual(done.returncode, 0, done.stderr)
|
||
self.assertTrue((self.out / "vasya.moy-plagin.ltp").is_file())
|
||
self.assertEqual(cli_main(["guard", "vasya.moy-plagin.ltp"]), 0)
|
||
(self.out / "broken.ltp").write_bytes(b"not a zip")
|
||
self.assertEqual(cli_main(["guard", "broken.ltp"]), 1)
|
||
# the template has no licence yet: the review says so; with one it passes
|
||
self.assertEqual(cli_main(["review", "vasya.moy-plagin.ltp"]), 1)
|
||
good = Plugin("Готовый", author="Вася", description="Скрывает fyp", license="MIT")
|
||
good.video(hashtag("fyp"), hide)
|
||
path = good.save(self.out, show=False)
|
||
self.assertEqual(cli_main(["review", str(path)]), 0)
|
||
finally:
|
||
os.chdir(cwd)
|
||
|
||
def test_a_file_with_extra_things_inside_is_refused(self):
|
||
path = self.out / "evil.ltp"
|
||
with zipfile.ZipFile(path, "w") as archive:
|
||
archive.writestr("plugin.json", "{}")
|
||
archive.writestr("classes.dex", b"dex")
|
||
with self.assertRaises(LtpError):
|
||
read_ltp(path)
|
||
|
||
|
||
class AgreesWithTheApp(unittest.TestCase):
|
||
"""The same plugin must get the same words from the Java defender and from this library's."""
|
||
|
||
@classmethod
|
||
def setUpClass(cls):
|
||
cls.javac = shutil.which("javac")
|
||
cls.java = shutil.which("java")
|
||
if not cls.javac or not cls.java:
|
||
raise RuntimeError("these tests need a JDK")
|
||
cls.temporary = tempfile.TemporaryDirectory(prefix="ltp-sdk-java-")
|
||
cls.addClassCleanup(cls.temporary.cleanup)
|
||
cls.work = Path(cls.temporary.name)
|
||
cls.classes = cls.work / "classes"
|
||
cls.classes.mkdir()
|
||
sources = []
|
||
for name in CORE:
|
||
folder = ROOT / "tests" / "java" if name == "GuardDump" else ROOT / "src"
|
||
sources.append(str(folder / "lihont" / "two" / "plugin" / (name + ".java")))
|
||
done = subprocess.run([cls.javac, "-encoding", "UTF-8", "-d", str(cls.classes)] + sources,
|
||
capture_output=True, text=True)
|
||
if done.returncode != 0:
|
||
raise RuntimeError(done.stdout + done.stderr)
|
||
|
||
def java_says(self, folders):
|
||
done = subprocess.run([self.java, "-Dfile.encoding=UTF-8", "-Dstdout.encoding=UTF-8", "-cp", str(self.classes),
|
||
"lihont.two.plugin.GuardDump"] + [str(f) for f in folders],
|
||
capture_output=True, encoding="utf-8", cwd=str(ROOT))
|
||
self.assertEqual(done.returncode, 0, done.stderr)
|
||
result = {}
|
||
for block in done.stdout.split("=====")[1:]:
|
||
name, _, text = block.partition("\n")
|
||
result[name.strip()] = text.rstrip("\n")
|
||
return result
|
||
|
||
def folder_of(self, name, manifest, assets):
|
||
folder = self.work / name
|
||
(folder / "assets").mkdir(parents=True)
|
||
(folder / "plugin.json").write_text(json.dumps(manifest, ensure_ascii=False), encoding="utf-8")
|
||
for asset, body in assets.items():
|
||
(folder / "assets" / asset).write_bytes(body)
|
||
return folder
|
||
|
||
def test_the_shipped_plugins_get_identical_words(self):
|
||
folders, python = [], {}
|
||
for folder in sorted(p for p in (ROOT / "plugins").iterdir() if p.is_dir() and (p / "plugin.json").is_file()):
|
||
manifest = json.loads((folder / "plugin.json").read_text(encoding="utf-8"))
|
||
assets = {a.name: a.read_bytes() for a in (folder / "assets").glob("*")} if (folder / "assets").is_dir() else {}
|
||
validate.check_manifest(manifest, assets)
|
||
python[folder.name] = guard_module.check(manifest, assets.keys()).text()
|
||
folders.append(folder)
|
||
self.assertGreaterEqual(len(folders), 6)
|
||
java = self.java_says(folders)
|
||
for name, text in python.items():
|
||
self.assertEqual(java[name], text, name)
|
||
|
||
def theme_manifest(self, **theme):
|
||
base = {"name": "Тест", "page": "#2b1d3a", "card": "#3d2b52", "text": "#fbe9ff", "accent": "#ff8a5b", "on_accent": "#2b1d3a"}
|
||
base.update(theme)
|
||
return {"ltp": 1, "id": "lihont.theme-test", "name": "Тема", "version": "1.0", "author": "тест",
|
||
"license": "MIT", "permissions": ["ui.theme"], "theme": base}
|
||
|
||
def test_a_theme_gets_identical_words_in_both_defenders_and_a_low_contrast_is_flagged_in_both(self):
|
||
good = self.theme_manifest()
|
||
murky = self.theme_manifest(text="#777777", card="#808080", on_accent="#ffffff", accent="#eeeeee")
|
||
folders, python = [], {}
|
||
for name, manifest in (("good", good), ("murky", murky)):
|
||
validate.check_manifest(manifest, {})
|
||
python[name] = guard_module.check(manifest, []).text()
|
||
folders.append(self.folder_of(name, manifest, {}))
|
||
self.assertNotIn("плохо читается", python["good"])
|
||
self.assertIn("Текст на карточках темы плохо читается", python["murky"])
|
||
self.assertIn("Текст на кнопках и заголовках темы плохо читается", python["murky"])
|
||
java = self.java_says(folders)
|
||
for name, text in python.items():
|
||
self.assertEqual(java[name], text, name)
|
||
|
||
def test_a_theme_that_is_not_in_order_is_refused_the_same_way_by_the_library(self):
|
||
def refused(manifest, word):
|
||
with self.assertRaises(LtpError) as caught:
|
||
validate.check_manifest(manifest, {})
|
||
self.assertIn(word, str(caught.exception))
|
||
|
||
no_right = self.theme_manifest()
|
||
no_right["permissions"] = []
|
||
refused(no_right, "ui.theme")
|
||
refused(self.theme_manifest(page="#2B1D3A"), "#rrggbb")
|
||
refused(self.theme_manifest(page="red"), "#rrggbb")
|
||
refused(self.theme_manifest(radius=99), "от 0 до 40")
|
||
refused(self.theme_manifest(bevel="yes"), "true или false")
|
||
refused(self.theme_manifest(layout="grid"), "нет поля")
|
||
no_theme = self.theme_manifest()
|
||
del no_theme["theme"]
|
||
refused(no_theme, "ui.theme")
|
||
|
||
def test_the_preview_cards_of_a_theme_are_checked(self):
|
||
png = bytes([0x89]) + b"PNG" + bytes([0x0D, 0x0A, 0x1A, 0x0A]) + bytes(32)
|
||
good = self.theme_manifest(preview=["a.png", "b.png"])
|
||
validate.check_manifest(good, {"a.png": png, "b.png": png})
|
||
text = guard_module.check(good, ["a.png", "b.png"]).text()
|
||
self.assertIn("К теме приложены картинки-превью", text)
|
||
|
||
def refused(manifest, word, assets):
|
||
with self.assertRaises(LtpError) as caught:
|
||
validate.check_manifest(manifest, assets)
|
||
self.assertIn(word, str(caught.exception))
|
||
|
||
refused(self.theme_manifest(preview=["a.png"]), "a.png", {})
|
||
refused(self.theme_manifest(preview=["a.ogg"]), "png, gif или webp", {})
|
||
refused(self.theme_manifest(preview=[]), "от 1 до 4", {})
|
||
refused(self.theme_manifest(preview=["a.png"] * 2), "дважды", {"a.png": png})
|
||
refused(self.theme_manifest(preview=["%d.png" % n for n in range(5)]), "от 1 до 4", {})
|
||
java = self.java_says([self.folder_of("previewed", good, {"a.png": png, "b.png": png})])
|
||
self.assertEqual(java["previewed"], text)
|
||
|
||
def test_a_theme_can_come_with_rules_and_the_right_is_not_asked_to_be_used_by_a_rule(self):
|
||
both = self.theme_manifest()
|
||
both["permissions"] = ["feed.hide", "ui.theme"]
|
||
both["rules"] = [{"title": "Без fyp", "when": "feed.item", "if": {"hashtag": ["fyp"]}, "do": [{"feed.hide": True}]}]
|
||
validate.check_manifest(both, {})
|
||
text = guard_module.check(both, []).text()
|
||
self.assertIn("Без fyp:", text)
|
||
self.assertIn("Тема «Тест»", text)
|
||
|
||
def test_the_fun_functions_get_identical_words_in_both_defenders(self):
|
||
png = bytes([0x89]) + b"PNG" + bytes([0x0D, 0x0A, 0x1A, 0x0A]) + bytes(32)
|
||
manifest = {"ltp": 1, "id": "lihont.fun-test", "name": "Приколы", "version": "1.0", "author": "тест",
|
||
"license": "MIT", "permissions": ["names", "ui.overlay"],
|
||
"rules": [
|
||
{"title": "Все имена волной", "when": "name.show", "do": [{"name.style": "wave"}]},
|
||
{"title": "Моё имя наоборот", "when": "name.show", "if": {"uid": ["self"]},
|
||
"do": [{"name.style": "reverse"}]},
|
||
{"title": "Звезда", "when": "screen.show",
|
||
"do": [{"overlay": {"image": "star.png", "tap": ["animate", "confetti", "buzz"]}}]}]}
|
||
validate.check_manifest(manifest, {"star.png": png})
|
||
python = guard_module.check(manifest, ["star.png"]).text()
|
||
self.assertIn("меняет вид всех имён на экране (волной (пРиВеТ))", python)
|
||
self.assertIn("Меняет вид имён у выбранных аккаунтов", python)
|
||
self.assertIn("Конфетти или лёгкая вибрация по нажатию на картинку.", python)
|
||
self.assertIn("по нажатию: играет анимация, конфетти, вибрация", python)
|
||
java = self.java_says([self.folder_of("fun", manifest, {"star.png": png})])
|
||
self.assertEqual(java["fun"], python)
|
||
|
||
def test_the_number_conditions_get_identical_words_in_both_defenders(self):
|
||
p = Plugin("Умная", author="тест", id="lihont.smart-test", license="MIT")
|
||
p.video(shorter(15), hide, title="короткие")
|
||
p.video(longer(600) & likes(min=1000), hide, title="длинные")
|
||
p.video(comments(min=10) & shares(max=5) & plays(min=100), hide, title="числа")
|
||
p.video(fresh(7) & followers(min=100000) & verified & photo & liked, hide, title="флаги")
|
||
p.video(music("phonk", "jazz") & chance(10), hide, title="музыка")
|
||
p.video(always, hide, title="всё")
|
||
p.video(hashtag("cats"), keep, title="коты")
|
||
manifest, assets, report = build(p)
|
||
self.assertIn("видео длительностью не больше 15 секунд", report.text())
|
||
self.assertIn("лайков не меньше 1000", report.text())
|
||
self.assertIn("видео не старше 7 дней", report.text())
|
||
self.assertIn("подписчиков у автора не меньше 100000", report.text())
|
||
self.assertIn("автор с галочкой", report.text())
|
||
self.assertIn("это фото, а не видео", report.text())
|
||
self.assertIn("вы уже лайкнули это видео", report.text())
|
||
self.assertIn("в музыке есть «phonk», «jazz»", report.text())
|
||
self.assertIn("с вероятностью 10%", report.text())
|
||
self.assertIn("оставить видео, даже если другие правила его скрывают", report.text())
|
||
java = self.java_says([self.folder_of("smart", manifest, assets)])
|
||
self.assertEqual(java["smart"], report.text())
|
||
|
||
def icons_manifest(self, **icons):
|
||
return {"ltp": 1, "id": "lihont.icons-test", "name": "Значки", "version": "1.0", "author": "тест",
|
||
"license": "MIT", "permissions": ["ui.icons"], "icons": icons or {"like": "heart.png"}}
|
||
|
||
def test_icons_are_checked_like_the_app_checks_them(self):
|
||
png = bytes([0x89]) + b"PNG" + bytes([0x0D, 0x0A, 0x1A, 0x0A]) + bytes(32)
|
||
validate.check_manifest(self.icons_manifest(like="heart.png", share="plane.png"), {"heart.png": png, "plane.png": png})
|
||
|
||
def refused(manifest, word, assets=None):
|
||
with self.assertRaises(LtpError) as caught:
|
||
validate.check_manifest(manifest, {"heart.png": png} if assets is None else assets)
|
||
self.assertIn(word, str(caught.exception))
|
||
|
||
no_right = self.icons_manifest()
|
||
no_right["permissions"] = []
|
||
refused(no_right, "ui.icons")
|
||
no_field = self.icons_manifest()
|
||
del no_field["icons"]
|
||
refused(no_field, "ui.icons")
|
||
refused(self.icons_manifest(follow="x.png"), "нет кнопки")
|
||
refused(self.icons_manifest(like="heart.ogg"), "png, gif или webp")
|
||
refused(self.icons_manifest(like="heart.png"), "heart.png", assets={})
|
||
empty = self.icons_manifest()
|
||
empty["icons"] = {}
|
||
refused(empty, "хотя бы одну")
|
||
|
||
def test_icons_get_identical_words_in_both_defenders(self):
|
||
png = bytes([0x89]) + b"PNG" + bytes([0x0D, 0x0A, 0x1A, 0x0A]) + bytes(32)
|
||
manifest = self.icons_manifest(share="plane.png", like="heart.png")
|
||
python = guard_module.check(manifest, ["heart.png", "plane.png"]).text()
|
||
self.assertIn("Значки кнопок в ленте (лайк, поделиться)", python)
|
||
self.assertIn("Меняет картинки кнопок справа в ленте", python)
|
||
java = self.java_says([self.folder_of("icons", manifest, {"heart.png": png, "plane.png": png})])
|
||
self.assertEqual(java["icons"], python)
|
||
|
||
def test_the_feed_buttons_are_found_by_the_sentences_they_say(self):
|
||
source = (ROOT / "src" / "lihont" / "two" / "plugin" / "IconSkin.java").read_text(encoding="utf-8")
|
||
for sentence in ("поставить лайк", "прочитать или оставить комментар", "добавьте это видео в избранное", "поделиться видео"):
|
||
self.assertIn(sentence, source)
|
||
|
||
def test_the_hash_the_review_prints_is_the_one_the_app_shows(self):
|
||
from lihont_ltp import review
|
||
folders, expected = [], {}
|
||
for folder in sorted(p for p in (ROOT / "plugins").iterdir() if p.is_dir() and (p / "plugin.json").is_file()):
|
||
ltp = self.work / (folder.name + ".ltp")
|
||
with zipfile.ZipFile(ltp, "w") as archive:
|
||
archive.writestr("plugin.json", (folder / "plugin.json").read_bytes())
|
||
if (folder / "assets").is_dir():
|
||
for asset in sorted((folder / "assets").glob("*")):
|
||
archive.writestr("assets/" + asset.name, asset.read_bytes())
|
||
expected[folder.name] = review.plugin_hash(ltp)
|
||
folders.append(folder)
|
||
done = subprocess.run([self.java, "-Dfile.encoding=UTF-8", "-cp", str(self.classes), "lihont.two.plugin.GuardDump",
|
||
"--hash"] + [str(f) for f in folders], capture_output=True, encoding="utf-8", cwd=str(ROOT))
|
||
self.assertEqual(done.returncode, 0, done.stderr)
|
||
java = {}
|
||
for block in done.stdout.split("=====")[1:]:
|
||
name, _, text = block.partition("\n")
|
||
java[name.strip()] = text.strip()
|
||
self.assertGreaterEqual(len(expected), 6)
|
||
for name, value in expected.items():
|
||
self.assertEqual(java[name], value, name)
|
||
|
||
def test_plugins_made_with_the_library_get_identical_words_and_the_app_accepts_them(self):
|
||
made = {}
|
||
|
||
def make(key, plugin):
|
||
made[key] = build(plugin)
|
||
|
||
p = Plugin("a", author="В", id="v.a")
|
||
p.video(hashtag("fyp"), hide)
|
||
make("narrow", p)
|
||
p = Plugin("b", author="В", id="v.b")
|
||
p.video(hide)
|
||
p.video(between("22:00", "07:00"), hide, title="ночью")
|
||
make("hide-all", p)
|
||
p = Plugin("c", author="В", id="v.c")
|
||
p.name(always, rename("Аноним"))
|
||
p.name(person("123456"), rename("Ыы"), title="этот")
|
||
p.name(me & morning, before("*"), after("!"))
|
||
make("names", p)
|
||
p = Plugin("d", author="В", id="v.d")
|
||
p.video(word("a", "b", "c", "d", "e", "f", "g") & ~hashtag("x") & author("y", "self") | weekday("sat", "fri"),
|
||
say("t"), limit=15)
|
||
make("deep", p)
|
||
p = Plugin("e", author="В", id="v.e")
|
||
p.screen(picture("star.png", size=320, movable=False, on_tap=[wiggle, like], pet="star.png"))
|
||
p.screen(picture("star.png", size=120, on_tap=[]), title="пустая")
|
||
make("pictures", p)
|
||
p = Plugin("f", author="В", id="v.f")
|
||
p.screen(download("https://cdn.example.com/a/cat.png", "cat.png"),
|
||
download("https://img.example.org/dog.gif", "dog.gif", sha256="ab" * 32), picture("cat.png"))
|
||
make("online", p)
|
||
p = Plugin("g", author="В", id="v.g")
|
||
p.screen(download("https://cdn.example.com/cat.png", "cat.png", sha256="cd" * 32), picture("cat.png"),
|
||
say("загружено"))
|
||
make("online-pinned", p)
|
||
folders = [self.folder_of(key, manifest, assets) for key, (manifest, assets, _r) in made.items()]
|
||
java = self.java_says(folders)
|
||
for key, (_m, _a, report) in made.items():
|
||
self.assertNotIn("REFUSED", java[key], "%s: %s" % (key, java[key]))
|
||
self.assertEqual(java[key], report.text(), key)
|
||
|
||
def test_what_the_library_refuses_the_app_refuses_too(self):
|
||
bad = {
|
||
"hide-in-names": {"title": "t", "when": "name.show", "do": [{"feed.hide": True}]},
|
||
"overlay-in-video": {"title": "t", "when": "feed.item", "do": [{"overlay": {"image": "star.png"}}]},
|
||
"empty-do": {"title": "t", "when": "feed.item", "do": []},
|
||
"bad-time": {"title": "t", "when": "feed.item", "if": {"time": "25:00-07:00"}, "do": [{"feed.hide": True}]},
|
||
"bad-limit": {"title": "t", "when": "feed.item", "limit": 99, "do": [{"notice": "x"}]},
|
||
"two-keys": {"title": "t", "when": "feed.item", "if": {"text": ["a"], "uid": ["b"]}, "do": [{"feed.hide": True}]},
|
||
"bad-likes": {"title": "t", "when": "feed.item", "if": {"likes": [5]}, "do": [{"feed.hide": True}]},
|
||
"bad-chance": {"title": "t", "when": "feed.item", "if": {"chance": 0}, "do": [{"feed.hide": True}]},
|
||
"bad-flag": {"title": "t", "when": "feed.item", "if": {"verified": False}, "do": [{"feed.hide": True}]},
|
||
"bad-bounds": {"title": "t", "when": "feed.item", "if": {"age": [10, 5]}, "do": [{"feed.hide": True}]},
|
||
}
|
||
folders = []
|
||
for key, rule in bad.items():
|
||
manifest = {"ltp": 1, "id": "bad." + key, "name": "x", "version": "1", "author": "a",
|
||
"permissions": ["feed.hide", "ui.notice", "ui.overlay"], "rules": [rule]}
|
||
with self.assertRaises(LtpError, msg=key):
|
||
validate.check_manifest(manifest, {"star.png": (SDK / "examples" / "files" / "star.png").read_bytes()})
|
||
folders.append(self.folder_of(key, manifest, {}))
|
||
java = self.java_says(folders)
|
||
for key in bad:
|
||
self.assertIn("REFUSED", java[key], key)
|
||
|
||
def test_what_is_wrong_in_a_download_is_refused_by_both(self):
|
||
def manifest(net, *downloads, rights=("net.download", "ui.overlay")):
|
||
do = [{"download": d} for d in downloads] + [{"overlay": {"image": "cat.png"}}]
|
||
out = {"ltp": 1, "id": "net.case", "name": "x", "version": "1", "author": "a", "permissions": list(rights),
|
||
"rules": [{"title": "t", "when": "screen.show", "do": do}]}
|
||
if net is not None:
|
||
out["net"] = net
|
||
return out
|
||
|
||
good = {"url": "https://cdn.example.com/cat.png", "as": "cat.png"}
|
||
cdn = {"hosts": ["cdn.example.com"]}
|
||
cases = {
|
||
"no-net": manifest(None, good),
|
||
"net-no-right": manifest(cdn, good, rights=("ui.overlay",)),
|
||
"empty-hosts": manifest({"hosts": []}, good),
|
||
"unused-host": manifest({"hosts": ["cdn.example.com", "x.example.org"]}, good),
|
||
"other-host": manifest({"hosts": ["x.example.org"]}, good),
|
||
"double-host": manifest({"hosts": ["cdn.example.com", "cdn.example.com"]}, good),
|
||
"extra-key": manifest({"hosts": ["cdn.example.com"], "x": 1}, good),
|
||
"http": manifest(cdn, dict(good, url="http://cdn.example.com/cat.png")),
|
||
"port": manifest(cdn, dict(good, url="https://cdn.example.com:81/cat.png")),
|
||
"login": manifest(cdn, dict(good, url="https://u@cdn.example.com/cat.png")),
|
||
"ip": manifest({"hosts": ["10.0.0.1"]}, {"url": "https://10.0.0.1/cat.png", "as": "cat.png"}),
|
||
"upper": manifest({"hosts": ["Cdn.Example.com"]}, good),
|
||
"no-path": manifest(cdn, dict(good, url="https://cdn.example.com")),
|
||
"dots": manifest(cdn, dict(good, url="https://cdn.example.com/../cat.png")),
|
||
"fragment": manifest(cdn, dict(good, url="https://cdn.example.com/cat.png#x")),
|
||
"space": manifest(cdn, dict(good, url="https://cdn.example.com/cat png")),
|
||
"txt": manifest(cdn, dict(good, **{"as": "cat.txt"})),
|
||
"bad-hash": manifest(cdn, dict(good, sha256="abc")),
|
||
"twice": manifest(cdn, good, dict(good, url="https://cdn.example.com/b.png")),
|
||
"extra-field": manifest(cdn, dict(good, post=1)),
|
||
"no-as": manifest(cdn, {"url": "https://cdn.example.com/cat.png"}),
|
||
}
|
||
folders = []
|
||
for key, case in cases.items():
|
||
with self.assertRaises(LtpError, msg=key):
|
||
validate.check_manifest(case, {})
|
||
folders.append(self.folder_of(key, case, {}))
|
||
# a file that is also in the plugin cannot be fetched under the same name
|
||
clash = manifest(cdn, good)
|
||
star = (SDK / "examples" / "files" / "star.png").read_bytes()
|
||
clash["rules"][0]["do"][-1] = {"overlay": {"image": "cat.png"}}
|
||
with self.assertRaises(LtpError):
|
||
validate.check_manifest(clash, {"cat.png": star})
|
||
folders.append(self.folder_of("clash", clash, {"cat.png": star}))
|
||
# and the good one passes both
|
||
validate.check_manifest(manifest(cdn, good), {})
|
||
folders.append(self.folder_of("fine", manifest(cdn, good), {}))
|
||
java = self.java_says(folders)
|
||
for key in list(cases) + ["clash"]:
|
||
self.assertIn("REFUSED", java[key], "%s: %s" % (key, java[key]))
|
||
self.assertNotIn("REFUSED", java["fine"])
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|