LichessStatTgWeb/tests/bot/test_events.py
vrubelroman a7571f13c1
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 16s
v1.5.1: not-found players paused, tests in repo + CI, log-based daily summary, docs pruned
- players absent from two consecutive bulk answers (deleted/renamed on Lichess) are paused
  like closed accounts with their own notice; ❓ mark; stats service answers 404 instead
  of "0 games" for unknown users
- /getgamers table stays unmarked, a legend line under it lists closed / not-found players
- daily SUMMARY is computed from events.log (survives restarts); lichess_429 comes from the
  stats service /health, which now exposes lichess_429_24h / lichess_429_total
- admin /status reads its numbers through Database.get_admin_stats
- tests/: 36 bot + 15 service unittest cases, run_tests.sh runs them inside the real images,
  CI runs them after the build and before pushing/deploying
- docs: USER_GUIDE/about/API_DOCUMENTATION rewritten for the current code, ARCHITECTURE.md and
  two sub-READMEs removed, 7 obsolete helper scripts removed, CURRENT_STATE updated
- .claude/agents/designer.md: Telegram-aware designer role

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

140 lines
7.1 KiB
Python

"""events.py: line format of event()/summary(), parse_event_line, summarize_day."""
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
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)
if __name__ == '__main__':
unittest.main()