LichessStatTgWeb/tests/bot/test_events.py
vrubelroman 6351e18795 admin bot: /status redesigned around health, growth and activity; raw counters moved to /counters
- /status: verdict line (✅/⚠️, UTC time), 🩺 health (errors today/yesterday,
  Lichess 429 per 24 h from /health, age of the last player-status refresh,
  closed/not-found players, users who blocked the bot in 7 days), 📈 growth
  table (users/gamers/subscriptions: total, +today, +yesterday, +7 days,
  users without gamers), ⚡ activity today vs yesterday (commands, active
  users, notifications, Lichess requests). Flags: errors >= 10, any 429,
  status older than 30 min, no SUMMARY for yesterday, journal missing.
  Blocks fail independently (only a DB failure breaks the whole message).
- /counters: all raw command counters sorted by total + last SUMMARY as is.
- Database.get_admin_overview replaces get_admin_stats.
- events.summarize_days (one pass over events.log.1 + events.log, extra
  keys active_users/blocked/status_refresh_failed/cmd_by_name/lines),
  last_summary(); last_summary_line reads the rotated backup too.
- LichessAPI.get_service_health(timeout).
- Designer spec in docs/design/admin_status.md; README, CURRENT_STATE,
  CHANGELOG (Unreleased) updated; 25 new tests (61 bot tests total).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-21 06:16:53 +00:00

223 lines
12 KiB
Python

"""events.py: line format of event()/summary(), parse_event_line, summarize_days / summarize_day, last_summary."""
from tests.bot import _env # noqa: F401 (DATABASE_PATH must be set before events/config import)
import logging
import os
import re
import tempfile
import unittest
import events
class LineFormatTests(unittest.TestCase):
def test_fmt_value(self):
f = events._fmt_value
self.assertEqual("12", f(12))
self.assertEqual("0", f(0))
self.assertEqual("1", f(True))
self.assertEqual("0", f(False))
self.assertEqual("-", f(None))
self.assertEqual("2.5", f(2.46))
self.assertEqual("Magnus", f("Magnus"))
self.assertEqual("'a b'", f("a b")) # space -> repr-quoted
self.assertEqual("'k=v'", f("k=v")) # '=' -> repr-quoted
self.assertEqual("''", f(""))
self.assertEqual("x" * events.MAX_STR_LEN, f("x" * (events.MAX_STR_LEN + 20))) # truncated
def test_format_line(self):
line = events._format_line("EVT", "check", {'uid': 5, 'decision': 'request', 'games': None,
'notified': True, 'took_s': 1.25, 'err': 'a b'})
self.assertRegex(line, r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ EVT check uid=5 decision=request games=- "
r"notified=1 took_s=1\.2 err='a b'$")
line = events._format_line("SUMMARY", "", {'date': '2026-10-20', 'checks': 3})
self.assertRegex(line, r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ SUMMARY date=2026-10-20 checks=3$")
def test_event_writes_to_file(self):
"""event() and summary() append one formatted line each to EVENTS_LOG_PATH."""
tmp = tempfile.mkdtemp()
path = os.path.join(tmp, "events.log")
old_path, old_logger = events.EVENTS_LOG_PATH, events._events_logger
lg = logging.getLogger("events")
old_handlers = list(lg.handlers)
for h in old_handlers:
lg.removeHandler(h)
events.EVENTS_LOG_PATH, events._events_logger = path, None
try:
events.event('cmd', uid=1, name='start')
events.event('text', uid=1, len=3, in_flow=False)
events.summary(date='2026-10-20', checks=0)
with open(path, encoding="utf-8") as f:
lines = f.read().splitlines()
finally:
for h in list(lg.handlers):
lg.removeHandler(h)
h.close()
for h in old_handlers:
lg.addHandler(h)
events.EVENTS_LOG_PATH, events._events_logger = old_path, old_logger
self.assertEqual(3, len(lines))
self.assertTrue(lines[0].endswith(" EVT cmd uid=1 name=start"))
self.assertTrue(lines[1].endswith(" EVT text uid=1 len=3 in_flow=0"))
self.assertTrue(lines[2].endswith(" SUMMARY date=2026-10-20 checks=0"))
class ParseTests(unittest.TestCase):
def test_parse_event_line(self):
parsed = events.parse_event_line(
"2026-10-20T22:15:12Z EVT tg_error uid=5 handler='/start' error=\"RuntimeError('x=1 y')\" next=ok\n")
self.assertEqual(("2026-10-20", "EVT", "tg_error",
{'uid': '5', 'handler': "'/start'", 'error': "\"RuntimeError('x=1 y')\"", 'next': 'ok'}),
parsed)
self.assertEqual(("2026-10-21", "SUMMARY", "", {'date': '2026-10-20', 'checks': '3'}),
events.parse_event_line("2026-10-21T00:00:00Z SUMMARY date=2026-10-20 checks=3"))
self.assertEqual(("2026-10-20", "EVT", "ping", {}), events.parse_event_line("2026-10-20T00:00:00Z EVT ping"))
self.assertIsNone(events.parse_event_line("garbage line"))
self.assertIsNone(events.parse_event_line("2026-10-20T00:00:00Z WHAT x=1"))
self.assertIsNone(events.parse_event_line(""))
SYNTHETIC_LOG = """\
2026-10-19T23:59:59Z EVT check uid=1 gamer=A decision=request reason=- window_s=3600 stale=0 games=1 puzzles=- notified=1 lag_s=3
2026-10-20T00:00:00Z SUMMARY date=2026-10-19 users=1 checks=1
2026-10-20T01:00:00Z EVT user_start uid=1 new=1 lang=ru tg_lang=ru
2026-10-20T01:00:01Z EVT cmd uid=1 name=start
2026-10-20T01:00:02Z EVT cmd uid=1 name=addgamer
2026-10-20T01:00:03Z EVT user_start uid=2 new=0 lang=en tg_lang=-
2026-10-20T01:01:00Z EVT gamer_added uid=1 gamer=A gamer_id=1 new_gamer=1 via=addgamer
2026-10-20T02:00:00Z EVT check uid=1 gamer=A decision=request reason=- window_s=3600 stale=0 games=2 puzzles=- notified=1 lag_s=3
2026-10-20T03:00:00Z EVT check uid=1 gamer=A decision=request reason=- window_s=3600 stale=0 games=0 puzzles=- notified=0 lag_s=3
2026-10-20T04:00:00Z EVT check uid=1 gamer=A decision=skip_unchanged reason=- window_s=3600 stale=0 games=- puzzles=- notified=0 lag_s=3
2026-10-20T05:00:00Z EVT check uid=2 gamer=B decision=skip_closed reason=not_found window_s=3600 stale=0 games=- puzzles=- notified=0 lag_s=3
2026-10-20T06:00:00Z EVT check_error uid=1 gamer=A error="RuntimeError('Games period API returned no data')" consecutive=1
2026-10-20T06:00:01Z EVT tg_error uid=- handler=Update error='NetworkError(\"x\")'
2026-10-20T06:00:02Z EVT admin_notify kind=new_user ok=1
2026-10-20T07:00:00Z EVT callback uid=4 data=lang:ru
2026-10-20T07:00:01Z EVT text uid=1 len=3 in_flow=0
2026-10-20T07:30:00Z EVT blocked uid=2 gamer=B
2026-10-20T08:00:00Z EVT status_refresh tracked=3 answered=0 closed=0 not_found=0 took_s=1.0 ok=0
2026-10-20T08:15:00Z EVT status_refresh tracked=3 answered=3 closed=0 not_found=0 took_s=1.0 ok=1
this is not an event line
2026-10-21T00:00:01Z EVT check uid=1 gamer=A decision=request reason=- window_s=3600 stale=0 games=1 puzzles=- notified=1 lag_s=3
"""
ROTATED_LOG = """\
2026-10-20T00:30:00Z EVT cmd uid=3 name=today
2026-10-20T00:31:00Z EVT check uid=3 gamer=C decision=request reason=- window_s=3600 stale=0 games=5 puzzles=2 notified=1 lag_s=1
2026-10-19T12:00:00Z EVT gamer_added uid=3 gamer=C gamer_id=3 new_gamer=1 via=addtoken
"""
class SummarizeDayTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
self.path = os.path.join(self.tmp, "events.log")
with open(self.path, "w", encoding="utf-8") as f:
f.write(SYNTHETIC_LOG)
with open(self.path + ".1", "w", encoding="utf-8") as f:
f.write(ROTATED_LOG)
def test_counts_one_day_across_both_files(self):
self.assertEqual({
'checks': 3, # 02:00, 03:00 (events.log) + 00:31 (events.log.1)
'skipped': 2, # skip_unchanged + skip_closed
'notifications': 2, # 02:00 + 00:31
'errors': 2, # check_error + tg_error
'users_started': 2,
'new_users': 1,
'gamers_added': 1,
'commands': 3, # start, addgamer (events.log) + today (events.log.1)
}, events.summarize_day("2026-10-20", path=self.path))
def test_other_days_and_missing_file(self):
self.assertEqual(1, events.summarize_day("2026-10-19", path=self.path)['checks'])
self.assertEqual(1, events.summarize_day("2026-10-19", path=self.path)['gamers_added'])
empty = {k: 0 for k in events.SUMMARY_COUNTERS}
self.assertEqual(empty, events.summarize_day("2026-10-18", path=self.path))
self.assertEqual(empty, events.summarize_day("2026-10-20", path=os.path.join(self.tmp, "nope.log")))
def test_summary_keys_are_the_documented_ones(self):
self.assertEqual(('checks', 'skipped', 'notifications', 'errors',
'users_started', 'new_users', 'gamers_added', 'commands'), events.SUMMARY_COUNTERS)
# summarize_day is what the SUMMARY line is built from: documented keys only
self.assertEqual(set(events.SUMMARY_COUNTERS), set(events.summarize_day("2026-10-20", path=self.path)))
class SummarizeDaysTests(SummarizeDayTests):
"""summarize_days: the SUMMARY counters plus the /status extras, several days in one pass."""
def test_extra_keys_for_one_day(self):
days = events.summarize_days(["2026-10-20"], path=self.path)
self.assertEqual(["2026-10-20"], list(days))
d = days["2026-10-20"]
self.assertEqual(3, d['checks']) # SUMMARY counters still there
self.assertEqual(2, d['errors'])
self.assertEqual(4, d['active_users']) # uid 1 (user_start/cmd/text), 2 (user_start), 3 (cmd in .1), 4 (callback)
self.assertEqual(1, d['blocked'])
self.assertEqual(1, d['status_refresh_failed']) # ok=0 counted, ok=1 not
self.assertEqual({'start': 1, 'addgamer': 1, 'today': 1}, d['cmd_by_name'])
self.assertEqual(19, d['lines']) # 17 EVT lines in events.log + 2 in events.log.1 (SUMMARY/garbage not counted)
def test_several_days_and_an_empty_one(self):
days = events.summarize_days(["2026-10-18", "2026-10-19", "2026-10-20", "2026-10-21"], path=self.path)
self.assertEqual(2, days["2026-10-19"]['lines']) # check (events.log) + gamer_added (events.log.1)
self.assertEqual(1, days["2026-10-19"]['gamers_added'])
self.assertEqual(0, days["2026-10-19"]['active_users'])
self.assertEqual(1, days["2026-10-21"]['lines'])
# a day without a single line: zeros, lines=0 (the caller shows "—", not 0)
empty = days["2026-10-18"]
self.assertEqual(0, empty['lines'])
self.assertEqual(0, empty['active_users'])
self.assertEqual({}, empty['cmd_by_name'])
self.assertTrue(all(empty[k] == 0 for k in events.SUMMARY_COUNTERS))
def test_missing_file_is_none_not_zeros(self):
self.assertIsNone(events.summarize_days(["2026-10-20"], path=os.path.join(self.tmp, "nope.log")))
# ... while the SUMMARY wrapper keeps counting a missing file as empty
self.assertEqual({k: 0 for k in events.SUMMARY_COUNTERS},
events.summarize_day("2026-10-20", path=os.path.join(self.tmp, "nope.log")))
def test_rotated_backup_alone_is_enough(self):
os.remove(self.path)
days = events.summarize_days(["2026-10-20"], path=self.path)
self.assertEqual(2, days["2026-10-20"]['lines'])
class LastSummaryTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
self.old_path = events.EVENTS_LOG_PATH
events.EVENTS_LOG_PATH = os.path.join(self.tmp, "events.log")
def tearDown(self):
events.EVENTS_LOG_PATH = self.old_path
def test_last_summary_fields(self):
with open(events.EVENTS_LOG_PATH, "w", encoding="utf-8") as f:
f.write(SYNTHETIC_LOG)
f.write("2026-10-21T00:00:00Z SUMMARY date=2026-10-20 users=2 gamers=1 pairs_active=1 lichess_429=- errors=2\n")
f.write("2026-10-21T00:00:05Z EVT cmd uid=1 name=today\n")
self.assertEqual({'date': '2026-10-20', 'users': '2', 'gamers': '1', 'pairs_active': '1',
'lichess_429': '-', 'errors': '2'}, events.last_summary())
def test_no_summary_or_no_file(self):
self.assertIsNone(events.last_summary()) # no file
with open(events.EVENTS_LOG_PATH, "w", encoding="utf-8") as f:
f.write("2026-10-21T00:00:05Z EVT cmd uid=1 name=today\n")
self.assertIsNone(events.last_summary()) # file without SUMMARY
def test_summary_only_in_rotated_backup(self):
# after a rotation later in the day the midnight SUMMARY is in events.log.1 only
with open(events.EVENTS_LOG_PATH + ".1", "w", encoding="utf-8") as f:
f.write("2026-10-21T00:00:00Z SUMMARY date=2026-10-20 users=2 gamers=1\n")
with open(events.EVENTS_LOG_PATH, "w", encoding="utf-8") as f:
f.write("2026-10-21T00:00:05Z EVT cmd uid=1 name=today\n")
self.assertEqual('2026-10-20', events.last_summary()['date'])
# the current file wins when both have one
with open(events.EVENTS_LOG_PATH, "a", encoding="utf-8") as f:
f.write("2026-10-22T00:00:00Z SUMMARY date=2026-10-21 users=3 gamers=1\n")
self.assertEqual('2026-10-21', events.last_summary()['date'])
if __name__ == '__main__':
unittest.main()