LichessStatTgWeb/tests/service/test_stats_service.py
vrubelroman df6b582376 iteration 1: report with game table, /getgamers state screen, silent-30-days prompt, /today as one message, stats port bound to localhost
- periodic report rebuilt in HTML: title with games count, mode lines, one <pre>
  table (± · colour · accuracy · opponent rating · opponent accuracy), 10-row cap,
  span note after catch-up; stats service returns tracked_rating_diff per game
- /getgamers shows player state from the DB (played today / N days quiet /
  closed / not found, report period) without Lichess calls; ratings on a button
- "player silent 30 days — keep?" prompt with keep/delete buttons, repeat 90 days
- /today, /yesterday, /week: one message edited into the result, nav buttons
- /year localised; active-gamer leftovers and N/A removed; one period wording
- docker-compose.prod.yml: stats port 8002 bound to 127.0.0.1
- product review docs: user journeys, concepts, Mini App feasibility, proposal

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

155 lines
7.7 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 BuildGameRowTests(unittest.TestCase):
def test_tracked_rating_diff_follows_the_tracked_side(self):
svc = StatsService()
g = game(players={'white': {'user': {'name': 'Me'}, 'rating': 1500, 'ratingDiff': 7},
'black': {'user': {'name': 'Them'}, 'rating': 1600, 'ratingDiff': -7}})
row = svc._build_game_row(g, 'me')
self.assertTrue(row.tracked_is_white)
self.assertEqual(7, row.tracked_rating_diff)
row = svc._build_game_row(g, 'THEM')
self.assertFalse(row.tracked_is_white)
self.assertEqual(-7, row.tracked_rating_diff)
# side unknown -> None; field missing -> None; the row is still built
self.assertIsNone(svc._build_game_row(g, 'nobody').tracked_rating_diff)
self.assertIsNone(svc._build_game_row(g, 'nobody').tracked_is_white)
g2 = game(players={'white': {'user': {'name': 'Me'}, 'rating': 1500}, 'black': {'user': {'name': 'Them'}, 'rating': 1600}})
self.assertIsNone(svc._build_game_row(g2, 'me').tracked_rating_diff)
self.assertEqual(1500, svc._build_game_row(g2, 'me').white_rating)
# serialised: the field is present and optional (old clients ignore it)
self.assertIn('tracked_rating_diff', row.model_dump() if hasattr(row, 'model_dump') else row.dict())
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()