"""admin_bot: /status and /counters text builders (pure functions, no Telegram), number/age helpers.""" from tests.bot import _env # noqa: F401 (environment before bot imports) import re import unittest from datetime import datetime, timezone import admin_bot from admin_bot import build_counters_text, build_status_text, fmt_age, fmt_int, fmt_pair NOW = datetime(2026, 10, 21, 14, 32, 5, tzinfo=timezone.utc) TODAY, YESTERDAY = "2026-10-21", "2026-10-20" WEEK = ["2026-10-21", "2026-10-20", "2026-10-19", "2026-10-18", "2026-10-17", "2026-10-16", "2026-10-15"] MAX_WIDTH = 34 EMERGENCY_LINE = "⚠️ 429 от Lichess за 24 ч: — (stats-сервис не отвечает)" def day(**overrides) -> dict: d = {'checks': 1012, 'skipped': 60, 'notifications': 131, 'errors': 0, 'users_started': 3, 'new_users': 1, 'gamers_added': 1, 'commands': 14, 'active_users': 11, 'players_played': 37, 'blocked': 0, 'status_refresh_failed': 0, 'cmd_by_name': {'today': 3}, 'lines': 1200} d.update(overrides) return d def overview(**overrides) -> dict: o = {'users': {'total': 624, 'today': 1, 'yesterday': 1, 'week': 9}, 'gamers': {'total': 493, 'today': 0, 'yesterday': 0, 'week': 4}, 'pairs': {'active': 441, 'today': 0, 'yesterday': 1, 'week': 3}, 'users_without_gamers': 350, 'status': {'closed': 7, 'not_found': 2, 'last_checked_at': int(NOW.timestamp()) - 12 * 60}} o.update(overrides) return o def normal_inputs(): """Mockup 2.1: a quiet day.""" days = {d: day(blocked=0) for d in WEEK} days[TODAY] = day(commands=14, active_users=9, notifications=143, players_played=41, checks=1012, errors=0) days[YESTERDAY] = day(commands=14, active_users=11, notifications=131, checks=1012, errors=0) return overview(), days, {'status': 'ok', 'lichess_429_24h': 0, 'lichess_429_total': 3}, {'date': YESTERDAY}, NOW def bad_inputs(): """Mockup 2.2: errors, 429s, stale status, a blocked user, no midnight SUMMARY.""" days = {d: day() for d in WEEK} days[TODAY] = day(commands=14, active_users=9, notifications=12, checks=4318, errors=37) days[YESTERDAY] = day(commands=14, active_users=11, notifications=131, checks=1012, errors=2) days["2026-10-18"] = day(blocked=1) ov = overview(status={'closed': 7, 'not_found': 2, 'last_checked_at': int(NOW.timestamp()) - 112 * 60}) return ov, days, {'status': 'ok', 'lichess_429_24h': 4, 'lichess_429_total': 9}, {'date': "2026-10-19"}, NOW def empty_inputs(): """Mockup 2.3: fresh DB, no journal, stats service up with no 429s.""" ov = {'users': {'total': 0, 'today': 0, 'yesterday': 0, 'week': 0}, 'gamers': {'total': 0, 'today': 0, 'yesterday': 0, 'week': 0}, 'pairs': {'active': 0, 'today': 0, 'yesterday': 0, 'week': 0}, 'users_without_gamers': 0, 'status': {'closed': 0, 'not_found': 0, 'last_checked_at': None}} return ov, None, {'status': 'ok', 'lichess_429_24h': 0, 'lichess_429_total': 0}, None, NOW def plain_lines(text: str) -> list: """The message as the phone shows it: HTML tags stripped.""" return re.sub(r"", "", text).split("\n") class HelperTests(unittest.TestCase): def test_fmt_int(self): self.assertEqual("0", fmt_int(0)) self.assertEqual("624", fmt_int(624)) self.assertEqual("1 012", fmt_int(1012)) self.assertEqual("65 370", fmt_int(65370)) self.assertEqual("1 234 567", fmt_int(1234567)) self.assertEqual("—", fmt_int(None)) def test_fmt_age(self): self.assertEqual("<1 мин", fmt_age(0)) self.assertEqual("<1 мин", fmt_age(59)) self.assertEqual("<1 мин", fmt_age(-5)) # clock skew: never negative self.assertEqual("1 мин", fmt_age(60)) self.assertEqual("12 мин", fmt_age(12 * 60 + 30)) self.assertEqual("179 мин", fmt_age(179 * 60 + 59)) self.assertEqual("3 ч", fmt_age(180 * 60)) self.assertEqual("47 ч", fmt_age(47 * 3600 + 3599)) self.assertEqual("2 дн.", fmt_age(48 * 3600)) self.assertEqual("10 дн.", fmt_age(10 * 86400 + 5)) def test_fmt_pair(self): self.assertEqual("1 012 (вчера 1 012)", fmt_pair(1012, 1012)) self.assertEqual("— (вчера —)", fmt_pair(None, None)) self.assertEqual("0 (вчера —)", fmt_pair(0, None)) def test_constants(self): self.assertEqual(10, admin_bot.ERRORS_WARN) self.assertEqual(2 * 15 * 60, admin_bot.STATUS_STALE_SECONDS) class StatusTextTests(unittest.TestCase): def assert_fits_phone(self, text: str): for line in plain_lines(text): if line == EMERGENCY_LINE: continue self.assertLessEqual(len(line), MAX_WIDTH, f"too wide: {line!r}") def test_normal_day_matches_mockup(self): text = build_status_text(*normal_inputs()) self.assert_fits_phone(text) self.assertEqual([ "✅ Всё в порядке · 14:32 UTC", "", "🩺 Здоровье", "Ошибок сегодня: 0 (вчера 0)", "429 от Lichess за 24 ч: 0", "Статус игроков: 12 мин назад", "Игроков закрыто 7, не найдено 2", "Заблокировали бота: 0 за 7 дн.", "", "📈 Рост", " всего +сег +вч +7д", "Пользователи 624 1 1 9", "Игроки 493 0 0 4", "Подписки 441 0 1 3", "Без игроков: 350 из 624 (56%)", "", "⚡ Активность", "Команд: 14 (вчера 14)", "Активных людей: 9 (вчера 11)", "Уведомлений: 143 (вчера 131)", "Играли игроков: 41 (вчера 37)", "Проверок: 1 012 (вчера 1 012)", "", "Ещё: /counters · /events 30 _error", ], plain_lines(text)) # HTML: bold verdict and block titles, the growth table in
        self.assertIn("✅ Всё в порядке · 14:32 UTC", text)
        self.assertIn("🩺 Здоровье", text)
        self.assertIn("📈 Рост\n
             всего +сег +вч +7д\n", text)
        self.assertIn("Подписки       441    0   1   3
\nБез игроков", text) self.assertNotIn("⚠️", text) def test_bad_day_matches_mockup(self): text = build_status_text(*bad_inputs()) self.assert_fits_phone(text) lines = plain_lines(text) self.assertEqual("⚠️ Есть проблемы · 14:32 UTC", lines[0]) self.assertEqual([ "🩺 Здоровье", "⚠️ Ошибок сегодня: 37 (вчера 2)", "⚠️ 429 от Lichess за 24 ч: 4", "⚠️ Статус игроков: 112 мин назад", "Игроков закрыто 7, не найдено 2", "Заблокировали бота: 1 за 7 дн.", "⚠️ Нет сводки за вчера", ], lines[2:9]) self.assertIn("Уведомлений: 12 (вчера 131)", lines) self.assertIn("Проверок: 4 318 (вчера 1 012)", lines) self.assertEqual("Ещё: /counters · /events 30 _error", lines[-1]) def test_empty_state_matches_mockup(self): text = build_status_text(*empty_inputs()) self.assert_fits_phone(text) self.assertEqual([ "⚠️ Есть проблемы · 14:32 UTC", "", "🩺 Здоровье", "⚠️ Журнал событий ещё пуст", "429 от Lichess за 24 ч: 0", "⚠️ Статус игроков: нет данных", "Игроков закрыто 0, не найдено 0", "Заблокировали бота: — за 7 дн.", "", "📈 Рост", " всего +сег +вч +7д", "Пользователи 0 0 0 0", "Игроки 0 0 0 0", "Подписки 0 0 0 0", "Без игроков: 0 из 0 (—)", "", "⚡ Активность", "Команд: — (вчера —)", "Активных людей: — (вчера —)", "Уведомлений: — (вчера —)", "Играли игроков: — (вчера —)", "Проверок: — (вчера —)", "", "Ещё: /counters · /events 30 _error", ], plain_lines(text)) self.assertNotIn("Нет сводки", text) # replaced by "Журнал событий ещё пуст" def test_stats_service_down_only_breaks_its_own_line(self): ov, days, _, summary, now = normal_inputs() text = build_status_text(ov, days, None, summary, now) lines = plain_lines(text) self.assertEqual("⚠️ Есть проблемы · 14:32 UTC", lines[0]) self.assertIn(EMERGENCY_LINE, lines) self.assertIn("Ошибок сегодня: 0 (вчера 0)", lines) # the rest still renders self.assertIn("Проверок: 1 012 (вчера 1 012)", lines) # a /health body without the counter counts as "did not answer" too self.assertIn(EMERGENCY_LINE, plain_lines(build_status_text(ov, days, {'status': 'ok'}, summary, now))) def test_day_without_lines_is_dash_not_zero(self): ov, days, health, summary, now = normal_inputs() days[TODAY] = day(lines=0, errors=0, commands=0) # journal exists, nothing logged today yet lines = plain_lines(build_status_text(ov, days, health, summary, now)) self.assertIn("Ошибок сегодня: — (вчера 0)", lines) self.assertIn("Команд: — (вчера 14)", lines) self.assertEqual("✅ Всё в порядке · 14:32 UTC", lines[0]) # unknown is not an error def test_flags_thresholds(self): ov, days, health, summary, now = normal_inputs() days[TODAY] = day(errors=admin_bot.ERRORS_WARN - 1) self.assertIn("\nОшибок сегодня: 9 (вчера 0)", build_status_text(ov, days, health, summary, now)) days[TODAY] = day(errors=admin_bot.ERRORS_WARN) self.assertIn("\n⚠️ Ошибок сегодня: 10 (вчера 0)", build_status_text(ov, days, health, summary, now)) # status age exactly at the threshold is fine, one second more is stale ov['status']['last_checked_at'] = int(now.timestamp()) - admin_bot.STATUS_STALE_SECONDS self.assertIn("\nСтатус игроков: 30 мин назад", build_status_text(ov, days, health, summary, now)) ov['status']['last_checked_at'] -= 1 self.assertIn("\n⚠️ Статус игроков: 30 мин назад", build_status_text(ov, days, health, summary, now)) # SUMMARY of a different day / missing: flagged; of yesterday: not self.assertIn("⚠️ Нет сводки за вчера", build_status_text(ov, days, health, None, now)) self.assertIn("⚠️ Нет сводки за вчера", build_status_text(ov, days, health, {'date': TODAY}, now)) self.assertNotIn("Нет сводки", build_status_text(ov, days, health, {'date': YESTERDAY}, now)) def test_growth_table_width(self): ov, days, health, summary, now = normal_inputs() ov['users'] = {'total': 12345, 'today': 1234, 'yesterday': 999, 'week': 999} text = build_status_text(ov, days, health, summary, now) table = re.search(r"
(.*?)
", text, re.S).group(1).split("\n") self.assertEqual(4, len(table)) self.assertTrue(all(len(row) <= 31 for row in table[1:]), table) self.assertEqual("Пользователи12 3451 234 999 999", table[1]) # 5-digit totals still line up def test_blocked_sums_the_whole_week(self): ov, days, health, summary, now = normal_inputs() for d in WEEK: days[d]['blocked'] = 1 days["2026-10-14"] = day(blocked=50) # outside the 7-day window: ignored self.assertIn("Заблокировали бота: 7 за 7 дн.", build_status_text(ov, days, health, summary, now)) class CountersTextTests(unittest.TestCase): def test_table_sorted_by_total_then_summary(self): by_command = {'addgamer': {'total': 1180, 'today': 0}, 'periodic_notification': {'total': 65370, 'today': 143}, 'today': {'total': 1792, 'today': 3}, 'lang': {'total': 12, 'today': 0}, 'gamer_added': {'total': 0, 'today': 0}, 'resetlang': {'total': 3, 'today': 0}} summary = "2026-10-21T00:00:00Z SUMMARY date=2026-10-20 users=624 gamers=493 pairs_active=441 checks=1012" text = build_counters_text(by_command, summary) self.assertEqual([ "🔢 Счётчики: всего / сегодня", "periodic_notification 65 370 143", "today 1 792 3", "addgamer 1 180 0", "lang 12 0", "resetlang 3 0", "gamer_added 0 0", "", "Последняя сводка (SUMMARY):", "date=2026-10-20 users=624 gamers=493 pairs_active=441 checks=1012", ], plain_lines(text)) self.assertIn("
periodic_notification", text)
        self.assertTrue(all(len(l) <= 33 for l in plain_lines(text)[1:7]))

    def test_empty_states(self):
        self.assertEqual(["🔢 Счётчики: всего / сегодня", "Счётчиков пока нет", "",
                          "Последняя сводка (SUMMARY):", "Сводок пока нет"], plain_lines(build_counters_text({}, "")))


if __name__ == '__main__':
    unittest.main()