New math fixes, again
This commit is contained in:
1 parent
92605e7a4d
commit
ec5a1a197a
5 files changed
+130
-62
No files matched your search
+10
-10
@@ -73,6 +73,8 @@ class CoachingSession:
|
|||||||
_positive_id(kitten_id, "ID дополнительного котёнка")
|
_positive_id(kitten_id, "ID дополнительного котёнка")
|
||||||
if independence not in ("самостоятельно", "несамостоятельно"):
|
if independence not in ("самостоятельно", "несамостоятельно"):
|
||||||
raise ValueError("Некорректный статус самостоятельности")
|
raise ValueError("Некорректный статус самостоятельности")
|
||||||
|
if any(independence != self.kitten_independence for _, _, independence in self.extra_kittens):
|
||||||
|
raise ValueError("Все котята в одном отчёте должны быть либо самостоятельными, либо несамостоятельными")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def duration_minutes(start: str, end: str) -> int:
|
def duration_minutes(start: str, end: str) -> int:
|
||||||
@@ -95,26 +97,24 @@ def calculate_coaching(session: CoachingSession) -> CoachingResult:
|
|||||||
if minutes <= 0:
|
if minutes <= 0:
|
||||||
raise ValueError("Продолжительность захода должна быть больше нуля")
|
raise ValueError("Продолжительность захода должна быть больше нуля")
|
||||||
|
|
||||||
# The multiplier belongs to the escort (Krylan/Belka), not to the kitten.
|
|
||||||
# ZU is always treated as independent according to the calculator rules.
|
|
||||||
independence_multiplier = (
|
|
||||||
1.5
|
|
||||||
if session.skill == "ЛУ" and session.kitten_independence == "несамостоятельно"
|
|
||||||
else 1.0
|
|
||||||
)
|
|
||||||
kitten_count = 1 + len(session.extra_kittens)
|
kitten_count = 1 + len(session.extra_kittens)
|
||||||
# Several wards share one report: the second ward pays 1.5x, and each
|
# Several wards share one report: the second ward pays 1.5x, and each
|
||||||
# following ward adds a further 1.15x multiplier instead of another full
|
# following ward adds a further 1.15x multiplier instead of another full
|
||||||
# base payout.
|
# base payout.
|
||||||
ward_multiplier = 1.0 if kitten_count == 1 else 1.5 * (1.15 ** (kitten_count - 2))
|
ward_multiplier = 1.0 if kitten_count == 1 else 1.5 * (1.15 ** (kitten_count - 2))
|
||||||
escort_multiplier = independence_multiplier * ward_multiplier
|
# The independence bonus applies to every skill, including зоркость (ЗУ),
|
||||||
|
# and is calculated separately for each non-independent kitten.
|
||||||
|
nonself_count = (session.kitten_independence == "несамостоятельно") + sum(
|
||||||
|
independence == "несамостоятельно" for _, _, independence in session.extra_kittens
|
||||||
|
)
|
||||||
|
nonself_bonus = minutes * 0.5 * nonself_count / 5
|
||||||
|
|
||||||
return CoachingResult(
|
return CoachingResult(
|
||||||
minutes=minutes,
|
minutes=minutes,
|
||||||
escort_points=_points(minutes * escort_multiplier / 5),
|
escort_points=_points(minutes * ward_multiplier / 5 + nonself_bonus),
|
||||||
kitten_points=_points(minutes / 5),
|
kitten_points=_points(minutes / 5),
|
||||||
kitten_count=kitten_count,
|
kitten_count=kitten_count,
|
||||||
escort_multiplier=round(escort_multiplier, 4),
|
escort_multiplier=round(ward_multiplier, 4),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+52
-17
@@ -65,7 +65,7 @@ def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]:
|
|||||||
result = []
|
result = []
|
||||||
for item in re.split(r"\s*,\s*", value):
|
for item in re.split(r"\s*,\s*", value):
|
||||||
independence = "самостоятельно"
|
independence = "самостоятельно"
|
||||||
status = re.search(r"(?i)(?:;|\s+)\s*(самостоятельно|несамостоятельно|сам|несам)\s*$", item)
|
status = re.search(r"(?i)(?:;|\s+)\s*(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|сам|несам)\s*$", item)
|
||||||
if status:
|
if status:
|
||||||
independence = "несамостоятельно" if status.group(1).lower().startswith("несам") else "самостоятельно"
|
independence = "несамостоятельно" if status.group(1).lower().startswith("несам") else "самостоятельно"
|
||||||
item = item[:status.start()].strip()
|
item = item[:status.start()].strip()
|
||||||
@@ -74,6 +74,23 @@ def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]:
|
|||||||
return tuple(result)
|
return tuple(result)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_uniform_independence(primary: str, extras: tuple[tuple[str, int, str], ...] | list[tuple[str, int, str]]) -> None:
|
||||||
|
if any(independence != primary for _, _, independence in extras):
|
||||||
|
raise ValueError("Все котята в одном отчёте должны быть либо самостоятельными, либо несамостоятельными")
|
||||||
|
|
||||||
|
|
||||||
|
def _kitten_entry(value: str) -> tuple[str, int, str | None]:
|
||||||
|
"""Parse one kitten and an optional per-kitten independence status."""
|
||||||
|
value = value.strip().rstrip(".!?").strip()
|
||||||
|
status = None
|
||||||
|
match = re.search(r"(?i)\s+(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|сам|несам)\s*$", value)
|
||||||
|
if match:
|
||||||
|
status = "несамостоятельно" if match.group(1).lower().startswith("несам") else "самостоятельно"
|
||||||
|
value = value[:match.start()].strip()
|
||||||
|
name, kitten_id = _person(value)
|
||||||
|
return name, kitten_id, status
|
||||||
|
|
||||||
|
|
||||||
def parse_text_command(text: str) -> dict[str, Any]:
|
def parse_text_command(text: str) -> dict[str, Any]:
|
||||||
text = text.strip()
|
text = text.strip()
|
||||||
if text.lower() in ("/help", "help", "/start", "start"):
|
if text.lower() in ("/help", "help", "/start", "start"):
|
||||||
@@ -89,24 +106,27 @@ def parse_text_command(text: str) -> dict[str, Any]:
|
|||||||
raise ValueError("Формат: /лу ДД.ММ HH:MM HH:MM | Имя [ID] | Котёнок [ID] | статус")
|
raise ValueError("Формат: /лу ДД.ММ HH:MM HH:MM | Имя [ID] | Котёнок [ID] | статус")
|
||||||
date, start, end = parts[0].split()
|
date, start, end = parts[0].split()
|
||||||
escort_name, escort_id = _person(parts[1])
|
escort_name, escort_id = _person(parts[1])
|
||||||
kitten_entries = [_person(item) for item in parts[2].split(",") if item.strip()]
|
kitten_entries = [_kitten_entry(item) for item in parts[2].split(",") if item.strip()]
|
||||||
if not kitten_entries:
|
if not kitten_entries:
|
||||||
raise ValueError("Укажите имя котёнка или котят через запятую в формате Имя [ID].")
|
raise ValueError("Укажите имя котёнка или котят через запятую в формате Имя [ID].")
|
||||||
kitten_name, kitten_id = kitten_entries[0]
|
kitten_name, kitten_id, primary_status = kitten_entries[0]
|
||||||
extras = [(name, kitten_id, "самостоятельно") for name, kitten_id in kitten_entries[1:]]
|
extras = [(name, kitten_id, status) for name, kitten_id, status in kitten_entries[1:]]
|
||||||
status_part = parts[3] if len(parts) > 3 else ""
|
status_part = parts[3] if len(parts) > 3 else ""
|
||||||
status_value = status_part.lower()
|
status_value = status_part.lower()
|
||||||
status_is_valid = status_value in ("сам", "самостоятельно", "несам", "несамостоятельно")
|
status_is_valid = status_value in ("сам", "самостоятельно", "самостоятельный", "несам", "несамостоятельно", "несамостоятельный")
|
||||||
extra_parts = parts[4:] if status_is_valid else parts[3:]
|
extra_parts = parts[4:] if status_is_valid else parts[3:]
|
||||||
for extra_part in extra_parts:
|
for extra_part in extra_parts:
|
||||||
if extra_part.strip().lower().startswith(("доп", "нет")) or "[" in extra_part:
|
if extra_part.strip().lower().startswith(("доп", "нет")) or "[" in extra_part:
|
||||||
extras.extend(_extra_kittens(extra_part))
|
extras.extend(_extra_kittens(extra_part))
|
||||||
|
primary_independence = ("несамостоятельно" if status_part.lower().startswith("несам") else "самостоятельно") if status_is_valid else (primary_status or "самостоятельно")
|
||||||
|
extras = [(name, kitten_id, status or primary_independence) for name, kitten_id, status in extras]
|
||||||
|
_validate_uniform_independence(primary_independence, extras)
|
||||||
return {
|
return {
|
||||||
"mode": "coaching", "date": date, "skill": "ЛУ", "start": start, "end": end,
|
"mode": "coaching", "date": date, "skill": "ЛУ", "start": start, "end": end,
|
||||||
"escort_name": escort_name, "escort_id": escort_id,
|
"escort_name": escort_name, "escort_id": escort_id,
|
||||||
"kitten_name": kitten_name, "kitten_id": kitten_id,
|
"kitten_name": kitten_name, "kitten_id": kitten_id,
|
||||||
"kitten_independence": ("несамостоятельно" if status_part.lower().startswith("несам") else "самостоятельно") if status_is_valid else "самостоятельно",
|
"kitten_independence": primary_independence,
|
||||||
"_independence_provided": status_is_valid,
|
"_independence_provided": status_is_valid or primary_status is not None,
|
||||||
"extra_kittens": tuple(extras),
|
"extra_kittens": tuple(extras),
|
||||||
}
|
}
|
||||||
if command in ("/зу", "/зоркость"):
|
if command in ("/зу", "/зоркость"):
|
||||||
@@ -261,9 +281,10 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None:
|
|||||||
questions.append("Не вижу котёнка в формате Имя и ID.")
|
questions.append("Не вижу котёнка в формате Имя и ID.")
|
||||||
if len(people) > 2:
|
if len(people) > 2:
|
||||||
fields["extra_kittens"] = [(name, kitten_id, "самостоятельно") for name, kitten_id in people[2:]]
|
fields["extra_kittens"] = [(name, kitten_id, "самостоятельно") for name, kitten_id in people[2:]]
|
||||||
independence_match = re.search(r"(?i)\b(самостоятельно|несамостоятельно)\b", text)
|
independence_match = re.search(r"(?i)\b(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|сам|несам)\b", text)
|
||||||
if independence_match:
|
if independence_match:
|
||||||
fields["kitten_independence"] = independence_match.group(1).lower()
|
value = independence_match.group(1).lower()
|
||||||
|
fields["kitten_independence"] = "несамостоятельно" if value.startswith("несам") else "самостоятельно"
|
||||||
else:
|
else:
|
||||||
questions.append("Котёнок самостоятельный или несамостоятельный?")
|
questions.append("Котёнок самостоятельный или несамостоятельный?")
|
||||||
return fields, questions
|
return fields, questions
|
||||||
@@ -424,7 +445,7 @@ class BelkiDialog:
|
|||||||
("start", "Укажите время начала в формате HH:MM."),
|
("start", "Укажите время начала в формате HH:MM."),
|
||||||
("end", "Укажите время конца (конец захода) в формате HH:MM."),
|
("end", "Укажите время конца (конец захода) в формате HH:MM."),
|
||||||
("escort", "Укажите сопровождающего в формате Имя [ID]."),
|
("escort", "Укажите сопровождающего в формате Имя [ID]."),
|
||||||
("kitten", "Укажите имя котёнка или котят через запятую в формате Имя [ID].\nНапример: Беззубик [1566767], Малыш [123456]."),
|
("kitten", "Укажите имя котёнка или котят через запятую в формате Имя [ID].\nНапример: Беззубик [1566767], Малыш [123456].\nДля нескольких котят укажите один общий статус: все самостоятельные или все несамостоятельные."),
|
||||||
("independence", "Котёнок самостоятельный или несамостоятельный?"),
|
("independence", "Котёнок самостоятельный или несамостоятельный?"),
|
||||||
),
|
),
|
||||||
"training": (
|
"training": (
|
||||||
@@ -622,12 +643,12 @@ class BelkiDialog:
|
|||||||
f"Ресурсы: {resources}\n"
|
f"Ресурсы: {resources}\n"
|
||||||
"Подтвердить? Ответьте «да» или «нет»."
|
"Подтвердить? Ответьте «да» или «нет»."
|
||||||
)
|
)
|
||||||
kittens = [(state["kitten_name"], state["kitten_id"])] + [
|
kittens = [(state["kitten_name"], state["kitten_id"], state["kitten_independence"])] + [
|
||||||
(name, kitten_id) for name, kitten_id, _ in state.get("extra_kittens", [])
|
(name, kitten_id, independence) for name, kitten_id, independence in state.get("extra_kittens", [])
|
||||||
]
|
]
|
||||||
kitten_lines = "\n".join(
|
kitten_lines = "\n".join(
|
||||||
f"Котёнок {index}: {name} [{kitten_id}]"
|
f"Котёнок {index}: {name} [{kitten_id}] — {independence}"
|
||||||
for index, (name, kitten_id) in enumerate(kittens, start=1)
|
for index, (name, kitten_id, independence) in enumerate(kittens, start=1)
|
||||||
)
|
)
|
||||||
return (
|
return (
|
||||||
"Я распознал данные:\n"
|
"Я распознал данные:\n"
|
||||||
@@ -739,12 +760,17 @@ class BelkiDialog:
|
|||||||
state[key] = True
|
state[key] = True
|
||||||
elif key == "kitten":
|
elif key == "kitten":
|
||||||
try:
|
try:
|
||||||
kittens = [_person(item) for item in text.split(",") if item.strip()]
|
kittens = [_kitten_entry(item) for item in text.split(",") if item.strip()]
|
||||||
if not kittens:
|
if not kittens:
|
||||||
raise ValueError("Укажите имя котёнка или котят через запятую в формате Имя [ID].")
|
raise ValueError("Укажите имя котёнка или котят через запятую в формате Имя [ID].")
|
||||||
state["kitten_name"], state["kitten_id"] = kittens[0]
|
state["kitten_name"], state["kitten_id"], primary_status = kittens[0]
|
||||||
|
if primary_status is not None:
|
||||||
|
state["kitten_independence"] = primary_status
|
||||||
if state.get("mode") == "coaching" and len(kittens) > 1:
|
if state.get("mode") == "coaching" and len(kittens) > 1:
|
||||||
state["extra_kittens"] = [(*item, "самостоятельно") for item in kittens[1:]]
|
primary = primary_status or state.get("kitten_independence") or "самостоятельно"
|
||||||
|
extras = [(name, kitten_id, status or primary) for name, kitten_id, status in kittens[1:]]
|
||||||
|
_validate_uniform_independence(primary, extras)
|
||||||
|
state["extra_kittens"] = extras
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
return str(exc)
|
return str(exc)
|
||||||
state[key] = True
|
state[key] = True
|
||||||
@@ -753,6 +779,9 @@ class BelkiDialog:
|
|||||||
if value is None:
|
if value is None:
|
||||||
return "Ответьте «самостоятельный» или «несамостоятельный» (подойдут и другие формы слова)."
|
return "Ответьте «самостоятельный» или «несамостоятельный» (подойдут и другие формы слова)."
|
||||||
state["kitten_independence"] = value
|
state["kitten_independence"] = value
|
||||||
|
state["extra_kittens"] = [
|
||||||
|
(name, kitten_id, value) for name, kitten_id, _ in state.get("extra_kittens", [])
|
||||||
|
]
|
||||||
state[key] = True
|
state[key] = True
|
||||||
elif key == "place":
|
elif key == "place":
|
||||||
value = text.lower()
|
value = text.lower()
|
||||||
@@ -854,6 +883,12 @@ class BelkiDialog:
|
|||||||
except (ValueError, IndexError) as exc:
|
except (ValueError, IndexError) as exc:
|
||||||
return f"Не удалось добавить котят: {exc}"
|
return f"Не удалось добавить котят: {exc}"
|
||||||
state["extra_kittens"] = list(state.get("extra_kittens", ()))
|
state["extra_kittens"] = list(state.get("extra_kittens", ()))
|
||||||
|
primary = state.get("kitten_independence", "самостоятельно")
|
||||||
|
additions = [(name, kitten_id, status or primary) for name, kitten_id, status in additions]
|
||||||
|
try:
|
||||||
|
_validate_uniform_independence(primary, state["extra_kittens"] + additions)
|
||||||
|
except ValueError as exc:
|
||||||
|
return str(exc)
|
||||||
state["extra_kittens"].extend(additions)
|
state["extra_kittens"].extend(additions)
|
||||||
return (
|
return (
|
||||||
f"Добавлено дополнительных котят: {len(additions)}. "
|
f"Добавлено дополнительных котят: {len(additions)}. "
|
||||||
|
|||||||
@@ -106,13 +106,9 @@ independence = dependent
|
|||||||
|
|
||||||
### Зоркость
|
### Зоркость
|
||||||
|
|
||||||
Если прокачивается `ЗУ`/зоркость, в калькуляторе всегда используется значение:
|
Для `ЗУ`/зоркости статус самостоятельности также учитывается. Все котята в
|
||||||
|
одном отчёте должны иметь одинаковый статус: либо все самостоятельные, либо
|
||||||
```text
|
все несамостоятельные. Смешанный вариант не принимается.
|
||||||
independence = independent
|
|
||||||
```
|
|
||||||
|
|
||||||
То есть надбавка за несамостоятельное лазание к ЗУ не применяется.
|
|
||||||
|
|
||||||
### Урок
|
### Урок
|
||||||
|
|
||||||
@@ -373,28 +369,10 @@ count_multiplier(n) = 1.5 * 1.15^(n - 2), n >= 3
|
|||||||
|
|
||||||
## 10. Несколько котят + несамостоятельность
|
## 10. Несколько котят + несамостоятельность
|
||||||
|
|
||||||
Скриншоты подтверждают отдельно:
|
Множитель второго и последующих котят применяется к базовым баллам
|
||||||
|
сопровождающего. Если все котята несамостоятельные, за каждого добавляется
|
||||||
```text
|
отдельная надбавка `minutes * 0.5 / 5`. Смешивать статусы в одном отчёте
|
||||||
1 несамостоятельный котёнок -> ×1.5
|
нельзя. Правило одинаково для `ЛУ` и `ЗУ`.
|
||||||
2 самостоятельных котёнка -> ×1.5
|
|
||||||
```
|
|
||||||
|
|
||||||
Но предоставленные материалы не показывают числовой пример, где одновременно выполняются оба условия, например:
|
|
||||||
|
|
||||||
```text
|
|
||||||
2 котёнка, один из которых несамостоятельный
|
|
||||||
```
|
|
||||||
|
|
||||||
Поэтому нельзя молча выбирать один из вариантов:
|
|
||||||
|
|
||||||
```text
|
|
||||||
×1.5
|
|
||||||
×1.5 ×1.5
|
|
||||||
другая формула
|
|
||||||
```
|
|
||||||
|
|
||||||
До проверки исходной формулы таблицы такой случай должен считаться **неуточнённым правилом**, а не догадкой расчётного ядра.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+38
-5
@@ -47,7 +47,7 @@ class CalculationTests(unittest.TestCase):
|
|||||||
self.assertEqual(result.kitten_points, 12)
|
self.assertEqual(result.kitten_points, 12)
|
||||||
|
|
||||||
def test_non_self_kitten_and_extra_companion(self):
|
def test_non_self_kitten_and_extra_companion(self):
|
||||||
result = calculate_coaching(
|
with self.assertRaisesRegex(ValueError, "Все котята"):
|
||||||
CoachingSession(
|
CoachingSession(
|
||||||
date="15.08",
|
date="15.08",
|
||||||
skill="ЗУ",
|
skill="ЗУ",
|
||||||
@@ -63,9 +63,6 @@ class CalculationTests(unittest.TestCase):
|
|||||||
("Третий", 4, "самостоятельно"),
|
("Третий", 4, "самостоятельно"),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
)
|
|
||||||
self.assertEqual(result.escort_points, 20.7)
|
|
||||||
self.assertEqual(result.kitten_points, 12)
|
|
||||||
|
|
||||||
def test_non_self_30_minutes_matches_calculator(self):
|
def test_non_self_30_minutes_matches_calculator(self):
|
||||||
result = calculate_coaching(
|
result = calculate_coaching(
|
||||||
@@ -81,7 +78,7 @@ class CalculationTests(unittest.TestCase):
|
|||||||
kitten_independence="несамостоятельно",
|
kitten_independence="несамостоятельно",
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.assertEqual(result.escort_points, 6)
|
self.assertEqual(result.escort_points, 9)
|
||||||
self.assertEqual(result.kitten_points, 6)
|
self.assertEqual(result.kitten_points, 6)
|
||||||
|
|
||||||
def test_non_self_60_minutes_gives_adult_18_and_kitten_12(self):
|
def test_non_self_60_minutes_gives_adult_18_and_kitten_12(self):
|
||||||
@@ -113,6 +110,42 @@ class CalculationTests(unittest.TestCase):
|
|||||||
self.assertEqual(result.escort_multiplier, 1.725)
|
self.assertEqual(result.escort_multiplier, 1.725)
|
||||||
self.assertEqual(result.escort_points, 20.7)
|
self.assertEqual(result.escort_points, 20.7)
|
||||||
|
|
||||||
|
def test_nonself_additional_ward_adds_half_base_bonus(self):
|
||||||
|
result = calculate_coaching(
|
||||||
|
CoachingSession(
|
||||||
|
"15.08", "ЛУ", "10:00", "10:55", "Белка", 1, "Первый", 2,
|
||||||
|
kitten_independence="несамостоятельно",
|
||||||
|
extra_kittens=(("Второй", 3, "несамостоятельно"),),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.assertEqual(result.escort_points, 27.5)
|
||||||
|
self.assertEqual(result.kitten_points, 11)
|
||||||
|
|
||||||
|
def test_two_nonself_wards_add_two_bonuses(self):
|
||||||
|
result = calculate_coaching(
|
||||||
|
CoachingSession(
|
||||||
|
"15.08", "ЛУ", "10:00", "10:55", "Белка", 1, "Первый", 2,
|
||||||
|
kitten_independence="несамостоятельно",
|
||||||
|
extra_kittens=(("Второй", 3, "несамостоятельно"),),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.assertEqual(result.escort_points, 27.5)
|
||||||
|
|
||||||
|
def test_zu_independence_matrix_matches_reported_values(self):
|
||||||
|
def points(primary, extra):
|
||||||
|
return calculate_coaching(
|
||||||
|
CoachingSession(
|
||||||
|
"16.08", "ЗУ", "10:00", "11:00", "Белка", 1, "Первый", 2,
|
||||||
|
kitten_independence=primary,
|
||||||
|
extra_kittens=(("Второй", 3, extra),),
|
||||||
|
)
|
||||||
|
).escort_points
|
||||||
|
|
||||||
|
self.assertEqual(points("самостоятельно", "самостоятельно"), 18)
|
||||||
|
with self.assertRaisesRegex(ValueError, "Все котята"):
|
||||||
|
points("самостоятельно", "несамостоятельно")
|
||||||
|
self.assertEqual(points("несамостоятельно", "несамостоятельно"), 30)
|
||||||
|
|
||||||
def test_training_is_fixed(self):
|
def test_training_is_fixed(self):
|
||||||
self.assertEqual(calculate_training(TrainingSession("Белка", 1, "Котёнок", 2)).points, 25)
|
self.assertEqual(calculate_training(TrainingSession("Белка", 1, "Котёнок", 2)).points, 25)
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ from datetime import datetime
|
|||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
|
|
||||||
from app.belki.identity import Identity, IdentityDirectory
|
from app.belki.identity import Identity, IdentityDirectory
|
||||||
from app.belki.vk_bot import HELP_TEXT, BelkiDialog, inspect_bulk_text
|
from app.belki.vk_bot import HELP_TEXT, BelkiDialog, inspect_bulk_text, parse_text_command
|
||||||
|
|
||||||
|
|
||||||
class VkConversationTests(unittest.TestCase):
|
class VkConversationTests(unittest.TestCase):
|
||||||
@@ -62,6 +62,14 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
self.assertIn("Котёнок 2: Малыш [123456]", dialog._confirmation(dialog._states[80]))
|
self.assertIn("Котёнок 2: Малыш [123456]", dialog._confirmation(dialog._states[80]))
|
||||||
self.assertIn("самостоятель", response.lower())
|
self.assertIn("самостоятель", response.lower())
|
||||||
|
|
||||||
|
def test_multiple_kittens_reject_mixed_independence_status(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)
|
||||||
|
|
||||||
def test_bulk_input_is_detected_and_confirmed(self):
|
def test_bulk_input_is_detected_and_confirmed(self):
|
||||||
dialog = BelkiDialog()
|
dialog = BelkiDialog()
|
||||||
confirmation = dialog.handle(
|
confirmation = dialog.handle(
|
||||||
@@ -255,6 +263,20 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
dialog.handle(502, answer)
|
dialog.handle(502, answer)
|
||||||
self.assertIn("скриншот", dialog.handle(502, "несам").lower())
|
self.assertIn("скриншот", dialog.handle(502, "несам").lower())
|
||||||
|
|
||||||
|
def test_compact_command_accepts_all_independence_variants(self):
|
||||||
|
for value, expected in (
|
||||||
|
("сам", "самостоятельно"),
|
||||||
|
("самостоятельный", "самостоятельно"),
|
||||||
|
("самостоятельно", "самостоятельно"),
|
||||||
|
("несам", "несамостоятельно"),
|
||||||
|
("несамостоятельный", "несамостоятельно"),
|
||||||
|
("несамостоятельно", "несамостоятельно"),
|
||||||
|
):
|
||||||
|
parsed = parse_text_command(
|
||||||
|
f"/зу 16.08 10:00 10:10 | Белка [1] | Малыш [2] | {value}"
|
||||||
|
)
|
||||||
|
self.assertEqual(parsed["kitten_independence"], expected)
|
||||||
|
|
||||||
def test_keyboard_changes_with_dialog_state(self):
|
def test_keyboard_changes_with_dialog_state(self):
|
||||||
dialog = BelkiDialog()
|
dialog = BelkiDialog()
|
||||||
menu = dialog.keyboard_for(503)
|
menu = dialog.keyboard_for(503)
|
||||||
|
|||||||
Reference in new issue
Block a user