Files
cwshed-clone/tests/test_vk_conversation.py
T

440 lines
24 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 unittest
from datetime import datetime
from tempfile import TemporaryDirectory
from app.belki.identity import Identity, IdentityDirectory
from app.belki.vk_bot import HELP_TEXT, BelkiDialog, inspect_bulk_text, parse_text_command
class VkConversationTests(unittest.TestCase):
@staticmethod
def add_screenshot(dialog, actor_id):
dialog.queue_attachments(actor_id, [{"type": "photo", "url": "https://example.test/screenshot.jpg"}])
return dialog.handle(actor_id, "готово")
def test_help_is_a_neutral_faq(self):
self.assertIn("Беличья нора", HELP_TEXT)
self.assertIn("Два способа ввести данные", HELP_TEXT)
self.assertIn("/отмена", HELP_TEXT)
self.assertNotIn("Для детей", HELP_TEXT)
self.assertIn("Одной строкой", HELP_TEXT)
def test_goal_dialog_rejects_non_finite_and_unbounded_values(self):
dialog = BelkiDialog()
self.assertIn("баллов", dialog.handle(110, "/цель").lower())
self.assertIn("конечным", dialog.handle(110, "NaN").lower())
dialog.handle(110, "0")
dialog.handle(110, "10")
self.assertIn("от 1 до 1440", dialog.handle(110, "1441"))
def test_step_by_step_coaching_dialog(self):
dialog = BelkiDialog()
self.assertIn("дат", dialog.handle(77, "/лу").lower())
self.assertIn("начал", dialog.handle(77, "15.08").lower())
self.assertIn("конец", dialog.handle(77, "11:00").lower())
self.assertIn("сопровождающ", dialog.handle(77, "11:20").lower())
self.assertIn("котён", dialog.handle(77, "Дикая Вишня [1604614]").lower())
self.assertIn("самостоятель", dialog.handle(77, "Серолап [1617140]").lower())
self.assertIn("скриншот", dialog.handle(77, "самостоятельно").lower())
confirmation = self.add_screenshot(dialog, 77)
self.assertIn("подтверд", confirmation.lower())
report = dialog.handle(77, "да")
self.assertIn("Баллы белки: 4 балла.", report)
def test_step_by_step_coaching_accepts_comma_separated_kittens(self):
dialog = BelkiDialog()
dialog.handle(78, "/лу")
for answer in ("15.08", "11:00", "11:20", "Белка [1]"):
dialog.handle(78, answer)
response = dialog.handle(78, "Беззубик [1566767], Малыш [123456]")
self.assertIn("самостоятель", response.lower())
self.assertEqual(dialog._states[78]["extra_kittens"], [("Малыш", 123456, "самостоятельно")])
def test_comma_separated_example_accepts_trailing_period(self):
dialog = BelkiDialog()
dialog.handle(79, "/лу")
for answer in ("15.08", "11:00", "16:41", "Дикая Вишня [1604614]"):
dialog.handle(79, answer)
response = dialog.handle(79, "Беззубик [1566767], Малыш [123456].")
self.assertIn("самостоятель", response.lower())
self.assertEqual(dialog._states[79]["kitten_id"], 1566767)
self.assertEqual(dialog._states[79]["extra_kittens"][0][1], 123456)
def test_confirmation_numbers_kittens_and_normalizes_spaced_id(self):
dialog = BelkiDialog()
dialog.handle(80, "/лу")
for answer in ("15.08", "11:00", "16:41", "Дикая Вишня [1604614]"):
dialog.handle(80, answer)
response = dialog.handle(80, "Беззубик [1 566767], Малыш [123456].")
dialog.handle(80, "сам, сам")
self.assertIn("Котёнок 1: Беззубик [1566767]", dialog._confirmation(dialog._states[80]))
self.assertIn("Котёнок 2: Малыш [123456]", dialog._confirmation(dialog._states[80]))
self.assertIn("самостоятель", response.lower())
def test_lu_allows_one_nonself_kitten(self):
dialog = BelkiDialog()
dialog.handle(81, "/лу")
for answer in ("15.08", "11:00", "12:00", "Дикая Вишня [1604614]"):
dialog.handle(81, answer)
response = dialog.handle(81, "Беззубик [1] самостоятельно, Малыш [2] несамостоятельно")
self.assertIn("скриншот", response.lower())
def test_bulk_input_is_detected_and_confirmed(self):
dialog = BelkiDialog()
confirmation = dialog.handle(
88,
"/лу 15.08 11:00 11:20 | Дикая Вишня [1604614] | Серолап [1617140] | самостоятельно",
)
self.assertIn("скриншот", confirmation.lower())
confirmation = self.add_screenshot(dialog, 88)
self.assertIn("распознал", confirmation.lower())
self.assertIn("11:00", confirmation)
self.assertIn("подтверд", confirmation.lower())
report = dialog.handle(88, "да")
self.assertIn("#лазание", report)
def test_bulk_without_skill_requests_clarification(self):
dialog = BelkiDialog()
response = dialog.handle(99, "15.08 11:00 11:20 | Белка [1] | Котёнок [2]")
self.assertIn("ЛУ", response)
self.assertIn("ЗУ", response)
def test_cancel_clears_dialog(self):
dialog = BelkiDialog()
dialog.handle(1, "/лу")
self.assertIn("отмен", dialog.handle(1, "/отмена").lower())
def test_person_input_rejects_a_non_positive_id(self):
dialog = BelkiDialog()
dialog.handle(1, "/лу")
dialog.handle(1, "15.08")
dialog.handle(1, "ЛУ")
dialog.handle(1, "11:00")
dialog.handle(1, "11:20")
self.assertIn("положительным", dialog.handle(1, "Белка [0]").lower())
def test_bulk_inspector_returns_fields_and_missing_questions(self):
inspected = inspect_bulk_text("/лу 15.08 11:00 11:20 | Белка [1] | Котёнок [2]")
self.assertEqual(inspected["status"], "needs_clarification")
self.assertIn("skill", inspected["fields"])
self.assertIn("самостоятель", " ".join(inspected["questions"]).lower())
def test_bulk_inspector_detects_plain_text_without_skill(self):
inspected = inspect_bulk_text("15.08 11:00 11:20 | Белка [1] | Котёнок [2]")
self.assertEqual(inspected["status"], "needs_clarification")
self.assertIn("ЛУ", " ".join(inspected["questions"]))
def test_natural_bulk_input_needs_no_pipes(self):
dialog = BelkiDialog()
response = dialog.handle(101, "15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140")
self.assertIn("ЛУ", response)
self.assertIn("ЗУ", response)
response = dialog.handle(101, "ЛУ")
self.assertIn("самостоятель", response.lower())
response = dialog.handle(101, "самостоятельно")
self.assertIn("скриншот", response.lower())
def test_natural_bulk_input_extracts_people_before_time_range(self):
for text in (
"24.08 ЛУ Дикая Вишня 1604614 Серопопик 1346767 21:00-22:00 сам",
"24.08 ЛУ Дикая Вишня [1604614], Серопопик [1346767] 21:00-22:00 сам",
):
inspected = inspect_bulk_text(text)
self.assertEqual(inspected["fields"]["escort_name"], "Дикая Вишня")
self.assertEqual(inspected["fields"]["escort_id"], 1604614)
self.assertEqual(inspected["fields"]["kitten_name"], "Серопопик")
self.assertEqual(inspected["fields"]["kitten_id"], 1346767)
self.assertEqual(inspected["fields"]["start"], "21:00")
self.assertEqual(inspected["fields"]["end"], "22:00")
def test_natural_bulk_input_prioritizes_explicit_mentor_and_student_labels(self):
inspected = inspect_bulk_text(
"24.08 ЛУ ученик: Серопопик [1346767], сопровождающая: Дикая Вишня [1604614] 21:00-22:00 несам"
)
self.assertEqual(inspected["fields"]["escort_name"], "Дикая Вишня")
self.assertEqual(inspected["fields"]["escort_id"], 1604614)
self.assertEqual(inspected["fields"]["kitten_name"], "Серопопик")
self.assertEqual(inspected["fields"]["kitten_id"], 1346767)
self.assertEqual(inspected["fields"]["kitten_independence"], "несамостоятельно")
def test_natural_bulk_input_assigns_statuses_to_labelled_individual_kittens(self):
inspected = inspect_bulk_text(
"24.08 ЛУ 21:00-22:00 сопровождающая Дикая Вишня [1604614]; "
"ученик Серопопик [1346767] — несам; бельчонок Тучка [1604615] — сам"
)
self.assertEqual(inspected["status"], "complete")
self.assertEqual(inspected["fields"]["kitten_independence"], "несамостоятельно")
self.assertEqual(inspected["fields"]["extra_kittens"], [("Тучка", 1604615, "самостоятельно")])
def test_natural_bulk_input_normalizes_flexible_punctuation_ids_and_role_typos(self):
inspected = inspect_bulk_text(
"лу; 24-08; 21.00 - 22 ч 00. ученика: Серопопик [1 346 767]; сопроваждающая Дикая Вишня id 1 604 614; несам."
)
self.assertEqual(inspected["fields"]["date"], "24.08")
self.assertEqual((inspected["fields"]["start"], inspected["fields"]["end"]), ("21:00", "22:00"))
self.assertEqual((inspected["fields"]["escort_name"], inspected["fields"]["escort_id"]), ("Дикая Вишня", 1604614))
self.assertEqual((inspected["fields"]["kitten_name"], inspected["fields"]["kitten_id"]), ("Серопопик", 1346767))
def test_natural_bulk_input_normalizes_russian_written_dates(self):
for date_text, expected in (("24 августа", "24.08"), ("1-го сент", "1.09")):
with self.subTest(date_text=date_text):
inspected = inspect_bulk_text(
f"ЛУ {date_text} 21:00-22:00 Дикая Вишня [1604614] Серопопик [1346767] сам"
)
self.assertEqual(inspected["fields"]["date"], expected)
def test_natural_zu_with_nonself_status_becomes_a_clarification_not_an_exception(self):
inspected = inspect_bulk_text("24.08 ЗУ 21:00 22:00 Белка [1] Ученик [2] несам")
self.assertEqual(inspected["status"], "needs_clarification")
self.assertNotIn("kitten_independence", inspected["fields"])
self.assertIn("Для ЗУ", " ".join(inspected["questions"]))
def test_training_supports_stepwise_and_natural_bulk(self):
dialog = BelkiDialog()
self.assertIn("сопровождающ", dialog.handle(102, "/урок").lower())
self.assertIn("котён", dialog.handle(102, "Дикая Вишня [1604614]").lower())
self.assertIn("скриншот", dialog.handle(102, "Серолап [1617140]").lower())
confirmation = self.add_screenshot(dialog, 102)
self.assertIn("25", confirmation)
self.assertIn("#урок", dialog.handle(102, "да"))
natural = dialog.handle(103, "урок Дикая Вишня 1604614 Серолап 1617140")
self.assertIn("скриншот", natural.lower())
natural = self.add_screenshot(dialog, 103)
self.assertIn("25", natural)
self.assertIn("подтверд", natural.lower())
def test_inspection_supports_stepwise_and_id_only_character(self):
directory = IdentityDirectory([Identity("Серолап", 1617140)])
dialog = BelkiDialog(directory)
self.assertIn("место", dialog.handle(104, "/осмотр").lower())
self.assertIn("сколько", dialog.handle(104, "дупло").lower())
self.assertIn("персонаж", dialog.handle(104, "6").lower())
self.assertIn("ресурс", dialog.handle(104, "1617140").lower())
self.assertIn("скриншот", dialog.handle(104, "без ресурсов").lower())
confirmation = self.add_screenshot(dialog, 104)
self.assertIn("Серолап", confirmation)
self.assertIn("подтверд", confirmation.lower())
def test_inspection_character_without_directory_offers_pairing(self):
dialog = BelkiDialog(IdentityDirectory())
dialog.handle(105, "/осмотр")
dialog.handle(105, "дупло")
dialog.handle(105, "1")
response = dialog.handle(105, "1617140")
self.assertIn("связк", response.lower())
dialog.handle(105, "Серолап")
dialog.handle(105, "без ресурсов")
confirmation = self.add_screenshot(dialog, 105)
self.assertIn("Серолап", confirmation)
def test_inspection_resources_use_signed_amount_before_name(self):
dialog = BelkiDialog()
dialog.handle(106, "/осмотр")
dialog.handle(106, "дупло")
dialog.handle(106, "6")
dialog.handle(106, "Серолап [1617140]")
self.assertIn("скриншот", dialog.handle(106, "+1 вьюнок, + 3 паук").lower())
confirmation = self.add_screenshot(dialog, 106)
self.assertIn("вьюнок=1", confirmation)
self.assertIn("паук=3", confirmation)
def test_queued_photo_is_saved_in_confirmed_state(self):
dialog = BelkiDialog()
dialog.queue_attachments(107, [{"type": "photo", "url": "https://example.test/photo.jpg"}])
dialog.handle(107, "/урок")
dialog.handle(107, "Белка [1]")
self.assertIn("скриншот", dialog.handle(107, "Котёнок [2]").lower())
confirmation = self.add_screenshot(dialog, 107)
self.assertIn("подтверд", confirmation.lower())
self.assertEqual(dialog._states[107]["attachments"][0]["url"], "https://example.test/photo.jpg")
def test_six_photos_are_kept_on_active_report(self):
dialog = BelkiDialog()
dialog.handle(109, "/урок")
dialog.handle(109, "Белка [1]")
dialog.handle(109, "Котёнок [2]")
dialog.queue_attachments(109, [{"type": "photo", "attachment": f"photo1_{index}", "url": f"https://example.test/{index}.jpg"} for index in range(6)])
confirmation = dialog.handle(109, "готово")
self.assertIn("подтверд", confirmation.lower())
self.assertEqual(len(dialog._states[109]["attachments"]), 6)
def test_photo_is_mirrored_before_history_save(self):
mirrored = []
def mirror(photo):
mirrored.append(photo["url"])
return "https://img.nyan404.ru/photo/abc.jpg"
dialog = BelkiDialog(attachment_mirror=mirror)
dialog.queue_attachments(108, [{"type": "photo", "url": "https://vk.example/photo.jpg"}])
dialog.handle(108, "/урок")
dialog.handle(108, "Белка [1]")
dialog.handle(108, "Котёнок [2]")
self.add_screenshot(dialog, 108)
dialog.handle(108, "да")
self.assertEqual(mirrored[0], "https://vk.example/photo.jpg")
def test_natural_inspection_accepts_character_id_without_name(self):
inspected = inspect_bulk_text("осмотр дупло 6 1617140 без ресурсов")
self.assertEqual(inspected["fields"]["character_id"], 1617140)
self.assertIn("имени", " ".join(inspected["questions"]).lower())
def test_explicit_inspection_command_accepts_count_before_place(self):
parsed = parse_text_command("/осмотр 6 расщелина Серолап [1617140] | паутина=2")
self.assertEqual(parsed["place"], "расщелина")
self.assertEqual(parsed["inspections"], 6)
self.assertEqual(parsed["resources"], [["паутина", 2]])
def test_explicit_coaching_command_accepts_a_time_range_and_written_date(self):
parsed = parse_text_command("/лу 24 августа 21:00–22:00 | Белка [1] | Ученик [2] | сам")
self.assertEqual((parsed["date"], parsed["start"], parsed["end"]), ("24.08", "21:00", "22:00"))
def test_natural_inspection_does_not_confuse_date_or_id_with_count(self):
inspected = inspect_bulk_text(
"24.08 осмотр расщелина: 6 раз; персонаж Серолап id 1 617 140; +2 паутина, +1 паук"
)
self.assertEqual(inspected["fields"]["inspections"], 6)
self.assertEqual((inspected["fields"]["character_name"], inspected["fields"]["character_id"]), ("Серолап", 1617140))
self.assertEqual(inspected["fields"]["resources"], [["паутина", 2], ["паук", 1]])
def test_natural_inspection_accepts_legacy_resource_assignments_without_count_noise(self):
inspected = inspect_bulk_text("осмотр дупло 6 раз Серолап [1617140]; паутина=2, паук: 1")
self.assertEqual(inspected["fields"]["resources"], [["паутина", 2], ["паук", 1]])
def test_identity_directory_persists_pairs_in_sqlite(self):
with TemporaryDirectory() as directory:
path = f"{directory}/identities.sqlite3"
first = IdentityDirectory(db_path=path)
first.remember(name="Серолап", character_id=1617140)
second = IdentityDirectory(db_path=path)
self.assertEqual(second.resolve(character_id=1617140).name, "Серолап")
self.assertEqual(second.resolve(name="Серолап").character_id, 1617140)
def test_onboarding_remembers_author_and_greets_by_name(self):
with TemporaryDirectory() as directory:
identities = IdentityDirectory(db_path=f"{directory}/identities.sqlite3")
dialog = BelkiDialog(identities, onboarding=True)
self.assertIn("представься", dialog.handle(500, "/лу", user_id=700).lower())
welcome = dialog.handle(500, "Дикая Вишня [1604614]", user_id=700)
self.assertIn("Привет, Дикая Вишня", welcome)
self.assertIn("/осмотр", welcome)
self.assertIn("дат", dialog.handle(500, "/лу", user_id=700).lower())
restarted = BelkiDialog(IdentityDirectory(db_path=f"{directory}/identities.sqlite3"), onboarding=True)
self.assertIn("дат", restarted.handle(500, "/лу", user_id=700).lower())
def test_saved_author_is_used_as_coaching_escort(self):
identities = IdentityDirectory()
identities.remember_profile(actor_id=700, name="Дикая Вишня", character_id=1604614)
dialog = BelkiDialog(identities)
response = dialog.handle(501, "/лу", user_id=700)
self.assertIn("дат", response.lower())
self.assertNotIn("сопровождающего", response.lower())
self.assertEqual(dialog._states[700]["escort_id"], 1604614)
def test_inspection_reuses_onboarded_author_character(self):
with TemporaryDirectory() as directory:
identities = IdentityDirectory(db_path=f"{directory}/identities.sqlite3")
dialog = BelkiDialog(identities, onboarding=True)
dialog.handle(510, "/осмотр", user_id=710)
dialog.handle(510, "Дикая Вишня [1604614]", user_id=710)
self.assertIn("место", dialog.handle(510, "/осмотр", user_id=710).lower())
dialog.handle(510, "дупло", user_id=710)
self.assertIn("ресурс", dialog.handle(510, "1", user_id=710).lower())
self.assertNotIn("персонаж", dialog.handle(510, "без ресурсов", user_id=710).lower())
def test_independence_accepts_adjectival_forms(self):
dialog = BelkiDialog()
dialog.handle(501, "/лу")
for answer in ("15.08", "11:00", "11:20", "Дикая Вишня [1604614]", "Серолап [1617140]"):
dialog.handle(501, answer)
self.assertIn("скриншот", dialog.handle(501, "Самостоятельный").lower())
confirmation = self.add_screenshot(dialog, 501)
self.assertIn("самостоятельно", confirmation.lower())
dialog.handle(502, "/лу")
for answer in ("15.08", "11:00", "11:20", "Дикая Вишня [1604614]", "Серолап [1617140]"):
dialog.handle(502, answer)
self.assertIn("скриншот", dialog.handle(502, "несам").lower())
def test_compact_zu_command_rejects_non_self_variants(self):
for value in (
("сам", "самостоятельно"),
("самостоятельный", "самостоятельно"),
("самостоятельно", "самостоятельно"),
):
parsed = parse_text_command(
f"/зу 16.08 10:00 10:10 | Белка [1] | Малыш [2] | {value[0]}"
)
self.assertEqual(parsed["kitten_independence"], value[1])
for value in (
("несам", "несамостоятельно"),
("несамостоятельный", "несамостоятельно"),
("несамостоятельно", "несамостоятельно"),
):
with self.assertRaisesRegex(ValueError, "Для ЗУ все котята должны быть самостоятельными"):
parse_text_command(
f"/зу 16.08 10:00 10:10 | Белка [1] | Малыш [2] | {value[0]}"
)
def test_keyboard_changes_with_dialog_state(self):
dialog = BelkiDialog()
menu = dialog.keyboard_for(503)
labels = [button["action"]["label"] for row in menu["buttons"] for button in row]
self.assertIn("Прокачка ЛУ", labels)
dialog.handle(503, "/лу")
for answer in ("15.08", "11:00", "11:20", "Дикая Вишня [1604614]", "Серолап [1617140]"):
dialog.handle(503, answer)
labels = [button["action"]["label"] for row in dialog.keyboard_for(503)["buttons"] for button in row]
self.assertEqual(labels[:2], ["Сам", "Несам"])
dialog.handle(503, "сам")
labels = [button["action"]["label"] for row in dialog.keyboard_for(503)["buttons"] for button in row]
self.assertIn("Готово", labels)
def test_quick_buttons_cover_safe_choices(self):
dialog = BelkiDialog()
dialog.handle(504, "15.08 11:00 11:20 Белка 1 Котёнок 2")
labels = [button["action"]["label"] for row in dialog.keyboard_for(504)["buttons"] for button in row]
self.assertIn("ЛУ", labels)
dialog = BelkiDialog()
dialog.handle(504, "/лу")
labels = [button["action"]["label"] for row in dialog.keyboard_for(504)["buttons"] for button in row]
self.assertIn("Сегодня", labels)
response = dialog.handle(504, "__today__")
self.assertIn("начал", response.lower())
self.assertEqual(dialog._states[504]["date"], datetime.now().strftime("%d.%m"))
inspection = BelkiDialog()
inspection.handle(505, "/осмотр")
labels = [button["action"]["label"] for row in inspection.keyboard_for(505)["buttons"] for button in row]
self.assertEqual(labels[:2], ["Дупло", "Расщелина"])
inspection.handle(505, "дупло")
inspection.handle(505, "0")
inspection.handle(505, "Серолап [2]")
labels = [button["action"]["label"] for row in inspection.keyboard_for(505)["buttons"] for button in row]
self.assertIn("Без ресурсов", labels)
def test_goal_calculator_is_available_from_vk_menu_and_is_interactive(self):
dialog = BelkiDialog()
menu = dialog.keyboard_for(901)
labels = [button["action"]["label"] for row in menu["buttons"] for button in row]
self.assertIn("Калькулятор цели", labels)
self.assertIn("баллов", dialog.handle(901, "/цель").lower())
dialog.handle(901, "10")
dialog.handle(901, "34")
dialog.handle(901, "20")
self.assertIn("самостоятель", dialog.handle(901, "ЛУ").lower())
dialog.handle(901, "сам")
confirmation = dialog.handle(901, "1")
self.assertIn("Осталось добрать: 24", confirmation)
self.assertIn("подтвердить", confirmation.lower())
self.assertIn("Нужно заходов: 6", dialog.handle(901, "да"))
if __name__ == "__main__":
unittest.main()
"""End-to-end dialog tests for the interactive VK application flow."""