Files
LihonT/tests/test_accounts.py
cheb0chik 5df4cddf7d LihonT 3 Luna pre-alpha: the streak pet becomes an animal
A pair of people can have a kitten, a puppy or a lion cub in place of TikTok's streak creature: it grows with the days of the
streak (cub, teen, adult, elder), goes grey while the streak is about to burn out, can be dragged in the chat and is also shown
on the big streak screen. An animal is given by a link (lihont.space/pet) that the friend accepts. The drawings are made by
scripts/make_pet_designs.py and served as strips of frames. Also here: the promo video scripts (make_pet_video.py on top of
make_store_video.py), a retry pause for strips that failed to load, stricter checks in the answer to a gift.

Work in progress: the gift service is not switched on for everyone yet and there is no public build with the animals.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 15:14:48 +03:00

306 lines
16 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.
import base64
import hashlib
import time as real_time
import importlib.util
import io
import tempfile
import unittest
from pathlib import Path
from PIL import Image
ROOT = Path(__file__).resolve().parents[1] / "services" / "members"
SPEC = importlib.util.spec_from_file_location("members_server", ROOT / "server.py")
server = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(server)
import authbot # noqa: E402 (server.py put the folder on sys.path)
ALICE, BOB = "6812345678901234", "6899999999999999"
INST_A, INST_B = "a" * 64, "b" * 64
OWNER = 777
def sha(value):
return hashlib.sha256(value.encode("ascii")).hexdigest()
def picture(shade):
out = io.BytesIO()
Image.new("RGBA", (120, 80), (shade, 40, 90, 255)).save(out, "PNG")
return base64.b64encode(out.getvalue()).decode("ascii")
class FakeTelegram:
def __init__(self):
self.sent = []
self.fail = {}
def call(self, method, fields=None, files=None, timeout=40):
if method == "sendMessage":
if fields["chat_id"] in self.fail:
raise RuntimeError(self.fail[fields["chat_id"]])
self.sent.append((fields["chat_id"], fields["text"]))
return []
class AccountsTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.now = int(real_time.time()) # the bans of TikTok accounts are judged by the database clock, so the test clock starts now
self.who = ALICE
self.inst = INST_A
self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now,
fetcher=lambda unique_id: (self.who, self.registry.code(self.who, sha(self.inst))))
self.acc = self.registry.accounts
self.telegram = FakeTelegram()
self.bot = authbot.AuthBot(self.registry, self.telegram, OWNER, clock=lambda: self.now)
# -- helpers --
def sign_in(self, tg_id, installation, handle):
token = self.acc.call("tg_start", {"installation": installation})["token"]
self.assertTrue(self.acc.bot_link(token, tg_id)["ok"])
reply = self.acc.call("tg_poll", {"installation": installation, "token": token})
self.assertEqual("linked", reply["status"])
self.acc.call("tg_register", {"installation": installation, "handle": handle})
def prove(self, uid, installation):
self.who, self.inst = uid, installation
self.assertTrue(self.registry.shape(uid, installation, "flower", "someone")["published"])
def publish_approved(self, uid, installation, name="Венок", shade=10):
self.who, self.inst = uid, installation
art = self.registry.catalog.call("publish", {"uid": uid, "installation": installation, "unique_id": "someone", "kind": "frame",
"name": name, "description": "", "png": picture(shade)})["id"]
self.registry.art_decide(art, "approved")
return art
# -- signing in --
def test_the_link_belongs_to_the_installation_that_asked_and_works_once(self):
start = self.acc.call("tg_start", {"installation": INST_A})
self.assertTrue(start["link"].startswith("https://t.me/lihonTauthbot?start="))
token = start["token"]
self.assertEqual("waiting", self.acc.call("tg_poll", {"installation": INST_A, "token": token})["status"])
self.assertEqual("expired", self.acc.call("tg_poll", {"installation": INST_B, "token": token})["status"]) # another phone learns nothing
self.assertTrue(self.acc.bot_link(token, 111)["ok"])
reply = self.acc.call("tg_poll", {"installation": INST_A, "token": token})
self.assertEqual(("linked", False), (reply["status"], reply["registered"]))
self.assertFalse(self.acc.bot_link(token, 222)["ok"]) # the token is spent: a second person cannot take the session
def test_a_link_runs_out(self):
token = self.acc.call("tg_start", {"installation": INST_A})["token"]
self.now += 901
self.assertEqual("expired", self.acc.bot_link(token, 111)["reason"])
def test_open_links_are_limited(self):
for _ in range(5):
self.acc.call("tg_start", {"installation": INST_A})
with self.assertRaises(ValueError):
self.acc.call("tg_start", {"installation": INST_A})
def test_nicknames(self):
token = self.acc.call("tg_start", {"installation": INST_A})["token"]
self.acc.bot_link(token, 111)
self.acc.call("tg_poll", {"installation": INST_A, "token": token})
for bad in ("ab", "x" * 21, "Привет", "has space", "admin", "lihont_official", "moderator1", "root"):
with self.assertRaises(ValueError, msg=bad):
self.acc.call("tg_register", {"installation": INST_A, "handle": bad})
self.assertEqual("masha", self.acc.call("tg_register", {"installation": INST_A, "handle": "@Masha"})["handle"])
self.sign_in(222, INST_B, "vova")
with self.assertRaises(ValueError): # taken, whatever the case
self.acc.call("tg_register", {"installation": INST_B, "handle": "MASHA"})
with self.assertRaises(ValueError): # only once in 30 days
self.acc.call("tg_register", {"installation": INST_A, "handle": "masha2"})
self.now += 31 * 86400
self.assertEqual("masha2", self.acc.call("tg_register", {"installation": INST_A, "handle": "masha2"})["handle"])
def test_member_calls_need_a_session_and_a_nickname(self):
with self.assertRaises(ValueError):
self.acc.call("following", {"installation": INST_A})
token = self.acc.call("tg_start", {"installation": INST_A})["token"]
self.acc.bot_link(token, 111)
self.acc.call("tg_poll", {"installation": INST_A, "token": token})
with self.assertRaises(ValueError): # signed in, no nickname yet
self.acc.call("following", {"installation": INST_A})
# -- the author level --
def test_the_tiktok_link_needs_this_installations_proof(self):
self.sign_in(111, INST_A, "alice")
with self.assertRaises(ValueError):
self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})
self.prove(ALICE, INST_A)
self.assertEqual(ALICE, self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})["uid"])
self.assertEqual("author", self.acc.call("tg_me", {"installation": INST_A})["level"])
self.sign_in(222, INST_B, "mallory")
with self.assertRaises(ValueError): # someone else's proven account is not theirs
self.acc.call("tg_link_tiktok", {"installation": INST_B, "uid": ALICE})
# -- follows and the inbox --
def test_follow_counts_lists_and_limits(self):
self.sign_in(111, INST_A, "alice")
self.prove(ALICE, INST_A)
self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})
self.publish_approved(ALICE, INST_A)
self.sign_in(222, INST_B, "bob")
with self.assertRaises(ValueError): # nobody by that number
self.acc.call("follow", {"installation": INST_B, "uid": "6877777777777777"})
self.assertEqual(1, self.acc.call("follow", {"installation": INST_B, "uid": ALICE})["followers"])
self.assertEqual(1, self.acc.call("follow", {"installation": INST_B, "uid": ALICE})["followers"]) # twice is once
with self.assertRaises(ValueError):
self.acc.call("follow", {"installation": INST_A, "uid": ALICE}) # not oneself
self.assertEqual({"followers": 1, "following": True}, self.acc.call("follow_info", {"uid": ALICE, "installation": INST_B}))
self.assertEqual({"followers": 1}, self.acc.call("follow_info", {"uid": ALICE})) # the public sees a number and no names
self.assertEqual(["bob"], [i["handle"] for i in self.acc.call("followers", {"installation": INST_A})["items"]]) # the owner sees names
self.assertEqual([ALICE], [i["uid"] for i in self.acc.call("following", {"installation": INST_B})["items"]])
self.assertEqual({"items": [], "count": 0}, self.acc.call("followers", {"installation": INST_B})) # bob has no followers to show
self.assertEqual(0, self.acc.call("unfollow", {"installation": INST_B, "uid": ALICE})["followers"])
def test_the_inbox_holds_only_followed_approved_work_and_counts_the_unread(self):
self.sign_in(222, INST_B, "bob")
first = self.publish_approved(ALICE, INST_A, "Первая", 10)
self.acc.call("follow", {"installation": INST_B, "uid": ALICE})
self.publish_approved(BOB, INST_B, "Чужая", 20) # not followed
self.who, self.inst = ALICE, INST_A
self.registry.catalog.call("publish", {"uid": ALICE, "installation": INST_A, "unique_id": "someone", "kind": "frame",
"name": "Не принята", "description": "", "png": picture(30)}) # not approved
box = self.acc.call("inbox", {"installation": INST_B})
self.assertEqual([first], [i["id"] for i in box["items"]])
self.assertEqual(1, box["unread"])
self.now += 10
self.acc.call("inbox_seen", {"installation": INST_B})
self.now += 10
self.assertEqual(0, self.acc.call("inbox", {"installation": INST_B})["unread"])
self.publish_approved(ALICE, INST_A, "Новая", 40)
self.assertEqual(1, self.acc.call("inbox", {"installation": INST_B})["unread"])
def test_follow_limit(self):
self.sign_in(222, INST_B, "bob")
self.acc.FOLLOW_LIMIT = 1
import accounts as module
saved, module.FOLLOW_LIMIT = module.FOLLOW_LIMIT, 1
self.addCleanup(setattr, module, "FOLLOW_LIMIT", saved)
self.publish_approved(ALICE, INST_A)
self.publish_approved(BOB, INST_B, "Другая", 50)
self.acc.call("follow", {"installation": INST_B, "uid": ALICE})
with self.assertRaises(ValueError):
self.acc.call("follow", {"installation": INST_B, "uid": BOB})
# -- hidden ids and bans --
def test_hidden_ids_are_stable_and_join_when_the_accounts_are_linked(self):
self.sign_in(111, INST_A, "alice")
tg_pid = self.acc.pid_for_tg(111)
uid_pid = self.acc.pid_for_uid(ALICE) # an author is known by number first
self.assertNotEqual(tg_pid, uid_pid)
self.assertEqual(uid_pid, self.acc.pid_for_uid(ALICE))
self.assertRegex(uid_pid, r"\A[A-Z2-9]{3}-[A-Z2-9]{3}\Z")
self.prove(ALICE, INST_A)
self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})
self.assertEqual(uid_pid, self.acc.pid_for_uid(ALICE)) # the id the owner already knows stays
def test_a_ban_closes_both_accounts_for_the_days_and_then_runs_out(self):
self.sign_in(111, INST_A, "alice")
self.prove(ALICE, INST_A)
self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})
art = self.publish_approved(ALICE, INST_A)
pid = self.acc.pid_for_uid(ALICE)
result = self.acc.ban(pid, 7, "spam")
self.assertEqual((True, True), (result["tg"], result["tiktok"]))
with self.assertRaises(ValueError):
self.acc.call("tg_me", {"installation": INST_A}) # the session is gone
self.assertEqual([], self.registry.catalog.call("catalog", {})["items"]) # the work is hidden
with self.assertRaises(ValueError):
self.registry.catalog.call("unpublish", {"uid": ALICE, "installation": INST_A, "id": art}) # no rights on the TikTok side
token = self.acc.call("tg_start", {"installation": INST_A})["token"]
self.assertEqual("banned", self.acc.bot_link(token, 111)["reason"])
self.assertTrue(self.acc.who(pid)["banned"])
self.acc.unban(pid)
self.assertFalse(self.acc.who(pid)["banned"])
self.assertTrue(self.acc.bot_link(token, 111)["ok"])
def test_a_timed_ban_of_a_tiktok_account_ends_by_itself(self):
self.publish_approved(ALICE, INST_A)
pid = self.acc.pid_for_uid(ALICE)
with self.registry.connect() as db:
db.execute("INSERT INTO blocked(uid, until) VALUES(?, ?) ON CONFLICT(uid) DO UPDATE SET until=excluded.until",
(ALICE, int(real_time.time()) + 3600))
self.assertEqual([], self.registry.catalog.call("catalog", {})["items"])
with self.registry.connect() as db:
db.execute("UPDATE blocked SET until=? WHERE uid=?", (int(real_time.time()) - 5, ALICE))
self.assertEqual(1, len(self.registry.catalog.call("catalog", {})["items"]))
self.assertTrue(pid)
def test_ban_input_is_checked(self):
with self.assertRaises(ValueError):
self.acc.ban("nonsense", 1)
with self.assertRaises(ValueError):
self.acc.ban("AAA-AAA", 1) # unknown
pid = self.acc.pid_for_uid(ALICE)
with self.assertRaises(ValueError):
self.acc.ban(pid, -1)
with self.assertRaises(ValueError):
self.acc.ban(pid, 100000)
# -- the bot --
def say(self, user_id, text, chat_type="private"):
self.bot.handle({"message": {"from": {"id": user_id}, "chat": {"id": user_id, "type": chat_type}, "text": text}})
def test_the_bot_links_a_person_and_explains_a_stale_link(self):
token = self.acc.call("tg_start", {"installation": INST_A})["token"]
self.say(111, "/start " + token)
self.assertIn("выберите себе ник", self.telegram.sent[-1][1])
self.say(222, "/start " + token) # a copy of the link in other hands
self.assertIn("устарела", self.telegram.sent[-1][1])
def test_only_the_owner_bans_and_only_in_a_private_chat(self):
pid = self.acc.pid_for_uid(ALICE)
self.say(555, "/ban %s 3" % pid)
self.assertFalse(self.acc.who(pid)["banned"]) # a stranger gets the help text and nothing happens
self.say(OWNER, "/ban %s 3" % pid, chat_type="group")
self.assertFalse(self.acc.who(pid)["banned"])
self.say(OWNER, "/ban %s 3 плохая картинка" % pid)
self.assertTrue(self.acc.who(pid)["banned"])
self.assertIn("Забанен", self.telegram.sent[-1][1])
self.say(OWNER, "/who " + pid)
self.assertIn("Бан: да", self.telegram.sent[-1][1])
self.say(OWNER, "/unban " + pid)
self.assertFalse(self.acc.who(pid)["banned"])
self.say(OWNER, "/ban nonsense 3")
self.assertIn("Не получилось", self.telegram.sent[-1][1])
def test_delete_needs_a_second_message_and_removes_the_follows(self):
self.sign_in(222, INST_B, "bob")
self.publish_approved(ALICE, INST_A)
self.acc.call("follow", {"installation": INST_B, "uid": ALICE})
self.say(222, "/delete yes") # not asked first
self.assertEqual(1, self.acc.call("follow_info", {"uid": ALICE})["followers"])
self.say(222, "/delete")
self.say(222, "/delete yes")
self.assertEqual(0, self.acc.call("follow_info", {"uid": ALICE})["followers"])
with self.assertRaises(ValueError):
self.acc.call("tg_me", {"installation": INST_B})
def test_notifications_go_to_followers_who_want_them_and_a_blocked_bot_is_muted(self):
self.sign_in(111, INST_A, "alice")
self.prove(ALICE, INST_A)
self.acc.call("tg_link_tiktok", {"installation": INST_A, "uid": ALICE})
art = self.publish_approved(ALICE, INST_A, "Венок")
self.sign_in(222, INST_B, "bob")
self.sign_in(333, "c" * 64, "carol")
self.sign_in(444, "d" * 64, "dave")
for inst in (INST_B, "c" * 64, "d" * 64):
self.acc.call("follow", {"installation": inst, "uid": ALICE})
self.acc.call("tg_notify", {"installation": "c" * 64, "on": False})
self.telegram.fail[444] = "Forbidden: bot was blocked by the user"
sent = self.bot.notify_new(self.registry.art(art))
self.assertEqual(1, sent)
self.assertEqual([222], [chat for chat, _ in self.telegram.sent if "Венок" in _])
self.assertIn("@alice", self.telegram.sent[-1][1])
self.assertEqual([], self.acc.followers_to_notify(ALICE, 10)[1:]) # dave is muted now: only bob is left
self.say(222, "/stop")
self.assertEqual([], self.acc.followers_to_notify(ALICE))
if __name__ == "__main__":
unittest.main()