import unittest import json from app.belki.vk_bot import ( BelkiDialog, HELP_TEXT, HELP_REQUEST_TEMPLATE, build_message_request, parse_text_command, BelkiBot, extract_photo_attachments, ) from app.belki.vk_callback import process_callback class VkBotTests(unittest.TestCase): def test_callback_confirmation_requires_valid_secret_and_group(self): handler = lambda event: None response = process_callback( {"type": "confirmation", "group_id": 1}, secret="", expected_secret="secret", group_id=1, confirmation="confirm-me", claim_event=None, release_event=None, handle_event=handler, ) self.assertEqual((response.status, response.body), (200, "confirm-me")) self.assertEqual( process_callback( {"type": "message_new", "group_id": 1, "secret": "wrong"}, secret="wrong", expected_secret="secret", group_id=1, confirmation="confirm-me", claim_event=None, release_event=None, handle_event=handler, ).status, 403, ) def test_callback_event_is_claimed_once(self): handled = [] claimed = set() def claim(event_id, event_type): if event_id in claimed: return False claimed.add(event_id) return True payload = {"type": "message_new", "group_id": 1, "secret": "secret", "event_id": "evt-1"} kwargs = dict(secret="secret", expected_secret="secret", group_id=1, confirmation="confirm-me", claim_event=claim, release_event=None, handle_event=handled.append) self.assertEqual(process_callback(payload, **kwargs).body, "ok") self.assertEqual(process_callback(payload, **kwargs).body, "ok") self.assertEqual(handled, [payload]) def test_callback_rejects_secret_longer_than_vk_limit(self): response = process_callback( {"type": "message_new", "group_id": 1}, secret="x" * 51, expected_secret="x" * 51, group_id=1, confirmation="confirm-me", claim_event=None, release_event=None, handle_event=lambda event: None, ) self.assertEqual(response.status, 403) def test_message_event_callback_is_normalized_to_button_message(self): class Client: def __init__(self): self.sent = [] def send(self, *args, **kwargs): self.sent.append((args, kwargs)) bot = BelkiBot.__new__(BelkiBot) bot.client = Client() bot.group_id = 1 bot.application_dialog = type("ApplicationDialog", (), {"is_application_command": lambda *_: False, "handle": lambda *_: None, "keyboard_for": lambda *_: None})() bot.dialog = type("Dialog", (), {"handle": lambda *_args, **_kwargs: "Ответ", "keyboard_for": lambda *_: None})() bot.conversation_store = type("Store", (), {})() bot.handle_event({"type": "message_event", "object": { "peer_id": 42, "user_id": 42, "payload": '{"command":"menu:help"}', }}) self.assertEqual(bot.client.sent[0][0][0], 42) self.assertEqual(bot.client.sent[0][0][1], "Ответ") def test_public_chat_messages_are_ignored_but_invite_is_registered(self): class Client: def __init__(self): self.sent = [] def call(self, method, params): return {"title": "Тестовая беседа"} def send(self, *args, **kwargs): self.sent.append((args, kwargs)) class Store: def __init__(self): self.items = [] def upsert_conversation(self, **kwargs): self.items.append(kwargs) bot = BelkiBot.__new__(BelkiBot) bot.client = Client(); bot.conversation_store = Store() bot.application_dialog = bot.dialog = object() bot.handle_event({"type": "message_new", "object": {"message": { "peer_id": 2000000007, "from_id": 42, "text": "/help", "action": {"type": "chat_invite_user"}, }}}) self.assertEqual(bot.client.sent, []) self.assertEqual(bot.conversation_store.items[0]["title"], "Тестовая беседа") def test_parse_coaching_command(self): command = parse_text_command( "/лу 15.08 11:00 11:20 | Дикая Вишня [1604614] | Серолап [1617140] | самостоятельно" ) self.assertEqual(command["mode"], "coaching") self.assertEqual(command["escort_id"], 1604614) self.assertEqual(command["kitten_id"], 1617140) def test_parse_coaching_command_with_additional_wards(self): command = parse_text_command( "/лу 15.08 11:00 11:20 | Белка [1] | Первый [2] | сам | доп. котята: Второй [3], Третий [4]" ) self.assertEqual(command["extra_kittens"], (("Второй", 3, "самостоятельно"), ("Третий", 4, "самостоятельно"))) def test_zu_command_accepts_non_self_kittens(self): command = parse_text_command( "/зу 15.08 11:00 11:20 | Белка [1] | Первый [2], Второй [3] | несам" ) self.assertEqual(command["kitten_independence"], "несамостоятельно") self.assertEqual(command["extra_kittens"], (("Второй", 3, "несамостоятельно"),)) def test_parse_help(self): self.assertEqual(parse_text_command("/help"), {"mode": "help"}) self.assertIn("/лу", HELP_TEXT) self.assertIn("Беличья нора", HELP_TEXT) self.assertIn("Все змеи приносят по 1 баллу", HELP_TEXT) def test_help_and_exit_templates_are_copyable(self): dialog = BelkiDialog() self.assertEqual(dialog.handle(900, "/помощь"), HELP_REQUEST_TEMPLATE) self.assertEqual( dialog.handle(900, "/выход Дикая Вишня [1604614] ущелье 2"), "#выход\nДикая Вишня [1604614] ущелье 2", ) self.assertIn("от 2 до 6", dialog.handle(900, "/выход Белка [1] уступы 1")) def test_message_request_never_omits_random_id(self): request = build_message_request(123, "Готово", "secret", "5.199", random_id=77) self.assertEqual(request["peer_id"], 123) self.assertEqual(request["random_id"], 77) self.assertEqual(request["access_token"], "secret") self.assertEqual(request["v"], "5.199") def test_message_request_serializes_vk_keyboard(self): keyboard = {"one_time": False, "buttons": []} request = build_message_request(123, "Меню", "secret", "5.199", random_id=77, keyboard=keyboard) self.assertEqual(json.loads(request["keyboard"]), keyboard) def test_button_payload_maps_to_command(self): self.assertEqual(BelkiBot._button_text({"payload": "menu:lu"}), "/лу") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"menu:my_reports"}'}), "/мои-отчёты") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"points:coaching"}'}), "прокачка") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"points:training"}'}), "тренировка") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"points:inspection"}'}), "осмотр") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"confirm:yes"}'}), "да") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"quick:inscription"}'}), "+1 надпись") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"application:flying"}'}), "/летяга") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"application:practice-no"}'}), "нет") def test_points_choice_has_clickable_activity_menu_and_accepts_cases(self): dialog = BelkiDialog() dialog.handle(901, "/цель") keyboard = dialog.keyboard_for(901) payloads = [ json.loads(button["action"]["payload"])["command"] for row in keyboard["buttons"] for button in row ] self.assertEqual(payloads[:3], ["points:coaching", "points:training", "points:inspection"]) for activity in ("прокачка", "прокачку", "тренировка", "тренировку"): current = BelkiDialog() current.handle(902, "/цель") response = current.handle(902, activity) self.assertNotIn("Выберите: прокачка, тренировка или осмотр.", response) def test_keyboard_button_payloads_are_valid_json(self): keyboard = BelkiDialog().keyboard_for(503) for row in keyboard["buttons"]: for button in row: payload = json.loads(button["action"]["payload"]) self.assertIsInstance(payload, dict) self.assertIn("command", payload) def test_my_reports_menu_shows_only_current_vk_sender_history(self): class Store: def list_vk_reports(self, actor_id, *, limit=100): self.actor_id = actor_id return [{"id": 7, "mode": "training", "message": "Малыш [123] — тренировка.", "created_at": "2026-10-18T12:00:00+00:00"}] store = Store() dialog = BelkiDialog(calculation_store=store) response = dialog.handle(900, "/мои-отчёты", user_id=501) self.assertEqual(store.actor_id, 501) self.assertIn("Малыш [123]", response) self.assertIn("№7", response) def test_my_reports_button_is_in_main_menu(self): keyboard = BelkiDialog().keyboard_for(503) commands = [ json.loads(button["action"]["payload"])["command"] for row in keyboard["buttons"] for button in row ] self.assertIn("menu:my_reports", commands) def test_extract_photo_attachment_keeps_largest_size_and_vk_reference(self): photos = extract_photo_attachments({"attachments": [{"type": "photo", "photo": { "owner_id": -10, "id": 42, "access_key": "secret", "sizes": [{"width": 100, "height": 100, "url": "small"}, {"width": 1000, "height": 800, "url": "large"}], }}]}) self.assertEqual(photos[0]["url"], "large") self.assertEqual(photos[0]["attachment"], "photo-10_42_secret") if __name__ == "__main__": unittest.main() """VK transport and command parser regression tests."""