LichessStatTgWeb/tests/service/test_stats_service.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

134 lines
6.4 KiB
Python

"""StatsService helpers, the by_finish lookback with a mocked Lichess client, 429 routing, and /health."""
import asyncio
import types
import unittest
from unittest.mock import AsyncMock
from stats_service import StatsService, FINISH_LOOKBACK_SECONDS
from lichess_client import LichessClient
def game(**fields):
g = {'id': 'x', 'rated': True, 'speed': 'blitz', 'perf': 'blitz', 'status': 'mate',
'players': {'white': {'user': {'name': 'u'}, 'rating': 1500, 'ratingDiff': 5},
'black': {'user': {'name': 'v'}, 'rating': 1500, 'ratingDiff': -5}},
'winner': 'white', 'createdAt': 1000}
g.update(fields)
return g
class FinishedInTests(unittest.TestCase):
def test_boundaries(self):
since, until = 1000, 2000
games = [
game(id='at_since', lastMoveAt=1000), # excluded: half-open on the left
game(id='just_in', lastMoveAt=1001),
game(id='at_until', lastMoveAt=2000), # included: closed on the right
game(id='after', lastMoveAt=2001),
game(id='fallback', createdAt=1500), # no lastMoveAt: createdAt is used
game(id='fallback_out', createdAt=999),
game(id='bad', lastMoveAt='1500', createdAt=None), # non-int: dropped
]
kept = [g['id'] for g in StatsService._finished_in(games, since, until)]
self.assertEqual(['just_in', 'at_until', 'fallback'], kept)
class GamesTotalTests(unittest.TestCase):
def test_sums_games_without_puzzle_and_junk(self):
perfs = {'blitz': {'games': 3}, 'rapid': {'games': 4}, 'puzzle': {'games': 100},
'storm': {'runs': 5}, 'bullet': 'x', 'classical': {'games': '7'}, 'ultraBullet': {}}
self.assertEqual(7, StatsService._games_total_from_perfs(perfs))
self.assertEqual(0, StatsService._games_total_from_perfs({}))
self.assertEqual(0, StatsService._games_total_from_perfs(None))
class ByFinishLookbackTests(unittest.TestCase):
SINCE, UNTIL = 1_800_000_000, 1_800_003_600 # seconds
def service_with(self, games):
svc = StatsService()
svc.lichess_client.get_games_of_period = AsyncMock(return_value=games)
return svc
def test_lookback_and_filter(self):
since_ms, until_ms = self.SINCE * 1000, self.UNTIL * 1000
games = [
game(id='old', createdAt=since_ms - 7_000_000, lastMoveAt=since_ms - 1), # finished before window
game(id='crossing', createdAt=since_ms - 600_000, lastMoveAt=since_ms + 60_000), # started before, finished in
game(id='inside', createdAt=since_ms + 1000, lastMoveAt=since_ms + 2000),
]
svc = self.service_with(games)
result = asyncio.run(svc.get_games_of_period('u', self.SINCE, self.UNTIL, rated_only=False, by_finish=True))
call = svc.lichess_client.get_games_of_period.await_args
self.assertEqual(('u', since_ms - FINISH_LOOKBACK_SECONDS * 1000, until_ms), call.args)
self.assertTrue(result.success)
self.assertEqual(2, result.games_count)
def test_without_by_finish_since_is_passed_unchanged(self):
svc = self.service_with([])
result = asyncio.run(svc.get_games_of_period('u', self.SINCE, self.UNTIL, rated_only=False))
call = svc.lichess_client.get_games_of_period.await_args
self.assertEqual(('u', self.SINCE * 1000, self.UNTIL * 1000), call.args)
self.assertTrue(result.success)
self.assertEqual(0, result.games_count)
def test_user_not_found_is_not_success(self):
svc = self.service_with(None)
result = asyncio.run(svc.get_games_of_period('gone', self.SINCE, self.UNTIL))
self.assertFalse(result.success)
self.assertEqual(StatsService.USER_NOT_FOUND, result.message)
self.assertEqual(0, result.games_count)
def test_client_exception_is_not_success_either(self):
svc = StatsService()
svc.lichess_client.get_games_of_period = AsyncMock(side_effect=RuntimeError("boom"))
result = asyncio.run(svc.get_games_of_period('u', self.SINCE, self.UNTIL))
self.assertFalse(result.success)
self.assertNotEqual(StatsService.USER_NOT_FOUND, result.message)
class Handle429Tests(unittest.TestCase):
def setUp(self):
self.client = LichessClient()
self.pauses = []
self.client.shared_token_gate = types.SimpleNamespace(pause=lambda seconds: self.pauses.append(seconds))
def response(self, text):
return types.SimpleNamespace(text=text)
def test_routing_and_counters(self):
self.client._handle_429('a', self.response('{"error":"Please only run 2 requests at a time"}'), endpoint='games')
self.assertEqual([], self.pauses) # concurrency: no pause
self.client._handle_429('b', self.response('<html>Too many requests. Read https://http.lichess.org/429</html>'))
self.assertEqual([60], self.pauses) # burst: a minute
self.client._handle_429('c', self.response(''))
self.assertEqual([60, 60], self.pauses) # unknown body: also a minute
self.assertEqual(3, self.client.count_429())
self.assertEqual(3, self.client.count_429(24 * 3600))
self.assertEqual(3, self.client.lichess_429_total)
self.assertEqual(0, self.client.count_429(-1)) # everything older than "now + 1 s"
self.assertEqual(3, self.client.lichess_429_total) # the total never shrinks
def test_fresh_client_has_no_429(self):
self.assertEqual(0, self.client.count_429())
self.assertEqual(0, self.client.lichess_429_total)
class HealthEndpointTests(unittest.TestCase):
def test_health_reports_429_counters(self):
from fastapi.testclient import TestClient
import main
with TestClient(main.app) as client:
body = client.get('/health').json()
self.assertEqual('healthy', body['status'])
self.assertEqual(0, body['lichess_429_24h'])
self.assertEqual(0, body['lichess_429_total'])
main.stats_service.lichess_client._handle_429(
'x', types.SimpleNamespace(text='{"error":"Please only run 2 requests at a time"}'))
body = client.get('/health').json()
self.assertEqual(1, body['lichess_429_24h'])
self.assertEqual(1, body['lichess_429_total'])
if __name__ == '__main__':
unittest.main()