- 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>
328 lines
18 KiB
Python
328 lines
18 KiB
Python
"""
|
||
The report (StatsFormatter.format_report, docs/design/product_concepts.md 2.5)
|
||
and the shared builders: exact texts for 1, 5 and 12 games, puzzles, puzzles
|
||
only, bullet only, two modes, a long window, missing accuracy / ratingDiff /
|
||
side, HTML-escaped name, the English locale, and the 34-character rule of
|
||
test_onboarding (an emoji counts as 2) for every line except the one with
|
||
the name. Also /today blocks and headers (2.8), /year and the ratings table.
|
||
"""
|
||
from tests.bot import _env # noqa: F401 (environment before bot imports)
|
||
|
||
import unittest
|
||
from datetime import datetime
|
||
|
||
from formatters import StatsFormatter, MAX_REPORT_ROWS
|
||
from i18n import t
|
||
from tests.bot.test_onboarding import long_lines, visual_len
|
||
|
||
NAME = 'DrNykterstein'
|
||
|
||
|
||
def row(result='1-0', white=True, diff=8, acc=91.0, opp=2990, opp_acc=79.0, ts=1):
|
||
"""A GameRow as the stats service serialises it, from the tracked player's point of view."""
|
||
return {
|
||
'white_name': NAME if white else 'Opp', 'black_name': 'Opp' if white else NAME,
|
||
'white_rating': 3100 if white else opp, 'black_rating': opp if white else 3100,
|
||
'white_accuracy': acc if white else opp_acc, 'black_accuracy': opp_acc if white else acc,
|
||
'result': result, 'created_at': ts, 'tracked_is_white': white, 'tracked_rating_diff': diff,
|
||
}
|
||
|
||
|
||
def mode(games, rating, change, wins, losses=0, draws=0, rows=None):
|
||
return {'games_played': games, 'wins': wins, 'losses': losses, 'draws': draws,
|
||
'rating_change': change, 'rating': rating, 'accuracy': None, 'games': rows or []}
|
||
|
||
|
||
def games_data(**modes):
|
||
data = {m: mode(0, None, 0, 0) for m in ('bullet', 'blitz', 'rapid', 'classical', 'correspondence')}
|
||
data.update(modes)
|
||
total = sum(s['games_played'] for s in data.values())
|
||
data['total'] = mode(total, None, 0, 0)
|
||
return {'message': 'ok', 'success': True, 'username': NAME, 'period_start': 0, 'period_end': 1,
|
||
'games_count': total, 'data': data}
|
||
|
||
|
||
def puzzles_data(solved=14, total=17):
|
||
return {'message': 'ok', 'puzzles_in_period': total,
|
||
'data': {'total_attempts': total, 'solved': solved, 'failed': total - solved, 'success_rate': 0.0}}
|
||
|
||
|
||
FIVE_ROWS = [
|
||
row('1-0', True, 8, 91, 2990, 79, 1),
|
||
row('0-1', False, 7, 88, 3011, 84, 2),
|
||
row('0-1', True, -9, 79, 3080, 92, 3),
|
||
row('1/2-1/2', False, 0, None, 3102, None, 4),
|
||
row('1-0', True, 6, 93, 2950, 71, 5),
|
||
]
|
||
FIVE_GAMES = games_data(blitz=mode(5, 3105, 12, 3, 1, 1, FIVE_ROWS))
|
||
|
||
RU_FIVE = (
|
||
"♟️ <b>DrNykterstein</b> — 5 партий\n"
|
||
"🔥 Blitz 3105 (+12) · 3 из 5 побед\n"
|
||
"\n"
|
||
"<pre> ± цвет точн. соперник\n"
|
||
"🟢 +8 белые 91 % 2990 · 79 %\n"
|
||
"🟢 +7 чёрные 88 % 3011 · 84 %\n"
|
||
"🔴 -9 белые 79 % 3080 · 92 %\n"
|
||
"⚪ 0 чёрные — 3102 · —\n"
|
||
"🟢 +6 белые 93 % 2950 · 71 %</pre>\n"
|
||
"\n"
|
||
"/today — весь день"
|
||
)
|
||
EN_FIVE = (
|
||
"♟️ <b>DrNykterstein</b> — 5 games\n"
|
||
"🔥 Blitz 3105 (+12) · 3 of 5 won\n"
|
||
"\n"
|
||
"<pre> ± colour acc. opponent\n"
|
||
"🟢 +8 white 91 % 2990 · 79 %\n"
|
||
"🟢 +7 black 88 % 3011 · 84 %\n"
|
||
"🔴 -9 white 79 % 3080 · 92 %\n"
|
||
"⚪ 0 black — 3102 · —\n"
|
||
"🟢 +6 white 93 % 2950 · 71 %</pre>\n"
|
||
"\n"
|
||
"/today — the whole day"
|
||
)
|
||
|
||
|
||
MODE_PREFIXES = ('⚡', '🔥', '🐇', '♟️')
|
||
|
||
|
||
def report_lines_ok(text, mode_lines=True):
|
||
"""
|
||
Lines over 34 (emoji = 2), ignoring the one with the name. With
|
||
mode_lines=False the mode lines are ignored too: the owner-approved
|
||
"· N из M побед" tail does not fit 34 for two-digit counts or Classical
|
||
("♟️ Classical 2257 (+45) · 3 из 5 побед" is 38) — these are plain-text
|
||
lines, Telegram wraps them, nothing breaks.
|
||
"""
|
||
lines = [line for line in text.split('\n') if '<b>' not in line]
|
||
if not mode_lines:
|
||
lines = [line for line in lines if not line.startswith(MODE_PREFIXES)]
|
||
return long_lines("\n".join(lines))
|
||
|
||
|
||
class ReportTests(unittest.TestCase):
|
||
def test_five_games_ru_matches_the_mockup(self):
|
||
self.assertEqual(RU_FIVE, StatsFormatter.format_report(NAME, FIVE_GAMES, None, 60, 'ru'))
|
||
|
||
def test_five_games_en(self):
|
||
self.assertEqual(EN_FIVE, StatsFormatter.format_report(NAME, FIVE_GAMES, None, 60, 'en'))
|
||
|
||
def test_longest_row_is_32_and_header_aligns(self):
|
||
text = StatsFormatter.format_report(NAME, FIVE_GAMES, None, 60, 'ru')
|
||
self.assertEqual(34, visual_len("🔥 Blitz 3105 (+12) · 3 из 5 побед"))
|
||
rows = [line for line in text.split('\n') if line.startswith(('🟢', '🔴', '⚪'))]
|
||
self.assertEqual(32, max(visual_len(r) for r in rows))
|
||
header = next(line for line in text.split('\n') if 'соперник' in line).replace('<pre>', '')
|
||
self.assertEqual(" ± цвет точн. соперник", header)
|
||
# "соперник" starts where "2990" does (the emoji is 2 wide on screen)
|
||
self.assertEqual(header.index('соперник'), rows[0].index('2990') + 1)
|
||
self.assertEqual([], report_lines_ok(text))
|
||
|
||
def test_one_game_no_wins_part(self):
|
||
data = games_data(blitz=mode(1, 3105, 8, 1, rows=[row()]))
|
||
self.assertEqual(
|
||
"♟️ <b>DrNykterstein</b> — 1 партия\n"
|
||
"🔥 Blitz 3105 (+8)\n"
|
||
"\n"
|
||
"<pre> ± цвет точн. соперник\n"
|
||
"🟢 +8 белые 91 % 2990 · 79 %</pre>\n"
|
||
"\n"
|
||
"/today — весь день",
|
||
StatsFormatter.format_report(NAME, data, None, 60, 'ru'))
|
||
|
||
def test_twelve_games_cut_at_ten_with_the_rest_outside_pre(self):
|
||
rows = [row(ts=i, diff=i) for i in range(1, 13)]
|
||
data = games_data(blitz=mode(12, 3200, 78, 12, rows=rows))
|
||
text = StatsFormatter.format_report(NAME, data, None, 60, 'ru')
|
||
self.assertEqual(MAX_REPORT_ROWS, sum(1 for line in text.split('\n') if line.startswith('🟢')))
|
||
self.assertIn("</pre>\n…и ещё 2 партии — /today\n\n/today — весь день", text)
|
||
self.assertIn("12 партий", text.split('\n')[0])
|
||
self.assertIn("· 12 из 12 побед", text)
|
||
self.assertEqual([], report_lines_ok(text, mode_lines=False))
|
||
self.assertEqual(36, visual_len("🔥 Blitz 3200 (+78) · 12 из 12 побед")) # the known exception
|
||
en = StatsFormatter.format_report(NAME, data, None, 60, 'en')
|
||
self.assertIn("…and 2 games more — /today", en)
|
||
|
||
def test_rows_are_chronological(self):
|
||
rows = [row(ts=3, diff=3), row(ts=1, diff=1), row(ts=2, diff=2)]
|
||
text = StatsFormatter.format_report(NAME, games_data(blitz=mode(3, 3105, 6, 3, rows=rows)), None, 60, 'ru')
|
||
diffs = [line.split()[1] for line in text.split('\n') if line.startswith('🟢')]
|
||
self.assertEqual(['+1', '+2', '+3'], diffs)
|
||
|
||
def test_puzzles_with_games(self):
|
||
data = games_data(blitz=mode(2, 3105, 3, 1, 1, rows=[row(), row('1-0', False, -5, None, 3080, None, 2)]))
|
||
text = StatsFormatter.format_report(NAME, data, puzzles_data(), 60, 'ru')
|
||
self.assertEqual(
|
||
"♟️ <b>DrNykterstein</b> — 2 партии\n"
|
||
"🔥 Blitz 3105 (+3) · 1 из 2 побед\n"
|
||
"\n"
|
||
"<pre> ± цвет точн. соперник\n"
|
||
"🟢 +8 белые 91 % 2990 · 79 %\n"
|
||
"🔴 -5 чёрные — 3080 · —</pre>\n"
|
||
"\n"
|
||
"🧩 Пазлы: 14 из 17 решены\n"
|
||
"\n"
|
||
"/today — весь день", text)
|
||
self.assertIn("🧩 Puzzles: 14 of 17 solved", StatsFormatter.format_report(NAME, data, puzzles_data(), 60, 'en'))
|
||
|
||
def test_puzzles_only(self):
|
||
self.assertEqual("🧩 <b>DrNykterstein</b> — пазлы: 14 из 17\n\n/today — весь день",
|
||
StatsFormatter.format_report(NAME, games_data(), puzzles_data(), 60, 'ru'))
|
||
self.assertEqual("🧩 <b>DrNykterstein</b> — puzzles: 14 of 17\n\n/today — the whole day",
|
||
StatsFormatter.format_report(NAME, None, puzzles_data(), 60, 'en'))
|
||
# zero attempts is not activity
|
||
self.assertEqual(t('no_activity', 'ru'), StatsFormatter.format_report(NAME, None, puzzles_data(0, 0), 60, 'ru'))
|
||
|
||
def test_bullet_only_has_no_rows(self):
|
||
data = games_data(bullet=mode(3, 2800, -15, 1, 2))
|
||
self.assertEqual("♟️ <b>DrNykterstein</b> — 3 партии\n⚡ Bullet 2800 (−15) · 1 из 3 побед\n\n/today — весь день",
|
||
StatsFormatter.format_report(NAME, data, None, 60, 'ru'))
|
||
|
||
def test_two_modes_rows_grouped_in_mode_order(self):
|
||
data = games_data(rapid=mode(1, 2890, -4, 0, 1, rows=[row('0-1', True, -4, 85, 2900, 80, 1)]),
|
||
blitz=mode(5, 3105, 12, 3, 1, 1, FIVE_ROWS))
|
||
text = StatsFormatter.format_report(NAME, data, None, 60, 'ru')
|
||
lines = text.split('\n')
|
||
self.assertEqual("♟️ <b>DrNykterstein</b> — 6 партий", lines[0])
|
||
self.assertEqual("🔥 Blitz 3105 (+12) · 3 из 5 побед", lines[1])
|
||
self.assertEqual("🐇 Rapid 2890 (−4)", lines[2])
|
||
circles = [line[0] for line in lines if line.startswith(('🟢', '🔴', '⚪'))]
|
||
self.assertEqual(['🟢', '🟢', '🔴', '⚪', '🟢', '🔴'], circles) # blitz rows (ts 1-5) then the rapid one
|
||
self.assertNotIn("Blitz:", text) # no sub-headings
|
||
self.assertEqual([], report_lines_ok(text))
|
||
|
||
def test_long_window_note(self):
|
||
data = games_data(blitz=mode(1, 3105, 8, 1, rows=[row()]))
|
||
self.assertNotIn("за последние", StatsFormatter.format_report(NAME, data, None, 359, 'ru'))
|
||
text = StatsFormatter.format_report(NAME, data, None, 360, 'ru')
|
||
self.assertEqual("за последние 6 часов", text.split('\n')[1])
|
||
self.assertEqual("over the last 6 hours", StatsFormatter.format_report(NAME, data, None, 360, 'en').split('\n')[1])
|
||
self.assertEqual("за последние 21 час", StatsFormatter.format_report(NAME, data, None, 21 * 60, 'ru').split('\n')[1])
|
||
self.assertEqual("за последние 2 дня", StatsFormatter.format_report(NAME, data, None, 48 * 60, 'ru').split('\n')[1])
|
||
self.assertEqual("over the last 5 days", StatsFormatter.format_report(NAME, data, None, 5 * 1440, 'en').split('\n')[1])
|
||
# puzzles only, long window: the note still comes second
|
||
self.assertEqual("🧩 <b>DrNykterstein</b> — пазлы: 14 из 17\nза последние 7 часов\n\n/today — весь день",
|
||
StatsFormatter.format_report(NAME, None, puzzles_data(), 7 * 60, 'ru'))
|
||
|
||
def test_missing_values(self):
|
||
unknown_side = row('1-0', True, None, None, None, None, 1)
|
||
unknown_side['tracked_is_white'] = None
|
||
rows = [unknown_side, row('1-0', True, 100, 100.0, 1000, 100.0, 2)]
|
||
data = games_data(blitz=mode(2, 3105, 100, 2, rows=rows))
|
||
text = StatsFormatter.format_report(NAME, data, None, 60, 'ru')
|
||
# wider ± and accuracy columns, the header follows them
|
||
self.assertIn("<pre> ± цвет точн. соперник\n"
|
||
"⚪ ? ? — — · —\n"
|
||
"🟢 +100 белые 100 % 1000 · 100 %</pre>", text)
|
||
self.assertIn("(+100)", text)
|
||
# a 3-digit diff next to two "100 %" is the one row shape wider than 34 (36); Telegram scrolls <pre>
|
||
self.assertEqual([36], [n for n, _ in report_lines_ok(text, mode_lines=False)])
|
||
|
||
def test_rating_unknown_and_zero_change(self):
|
||
data = games_data(blitz=mode(1, None, 0, 0, 0, 1, rows=[row('1/2-1/2', True, 0, 50, 2000, 50)]))
|
||
self.assertIn("🔥 Blitz — (0)", StatsFormatter.format_report(NAME, data, None, 60, 'ru'))
|
||
|
||
def test_name_is_escaped(self):
|
||
data = games_data(blitz=mode(1, 3105, 8, 1, rows=[row()]))
|
||
text = StatsFormatter.format_report('<b>x</b>&', data, None, 60, 'ru')
|
||
self.assertTrue(text.startswith("♟️ <b><b>x</b>&</b> — 1 партия"), text)
|
||
|
||
def test_no_activity(self):
|
||
self.assertEqual(t('no_activity', 'ru'), StatsFormatter.format_report(NAME, games_data(), None, 60, 'ru'))
|
||
self.assertEqual(t('no_activity', 'en'), StatsFormatter.format_report(NAME, None, None, 60, 'en'))
|
||
|
||
def test_plural_titles(self):
|
||
for n, word in ((1, "1 партия"), (2, "2 партии"), (4, "4 партии"), (5, "5 партий"), (11, "11 партий"),
|
||
(14, "14 партий"), (21, "21 партия"), (25, "25 партий")):
|
||
data = games_data(bullet=mode(n, 2800, 1, n))
|
||
self.assertIn(f"— {word}", StatsFormatter.format_report(NAME, data, None, 60, 'ru').split('\n')[0], n)
|
||
|
||
|
||
class TodayBlockTests(unittest.TestCase):
|
||
ACTIVITY = {'message': 'ok', 'data': {
|
||
'username': NAME,
|
||
'tasks': {'total': 17, 'solved': 14, 'unsolved': 3},
|
||
'games': {
|
||
'bullet': {'games_played': 0, 'rating_change': 0, 'final_rating': 0, 'wins': 0, 'losses': 0, 'draws': 0},
|
||
'blitz': {'games_played': 5, 'rating_change': 12, 'final_rating': 3105, 'wins': 3, 'losses': 1, 'draws': 1},
|
||
'rapid': {'games_played': 0, 'rating_change': 0, 'final_rating': 0, 'wins': 0, 'losses': 0, 'draws': 0},
|
||
'classical': {'games_played': 0, 'rating_change': 0, 'final_rating': 0, 'wins': 0, 'losses': 0, 'draws': 0},
|
||
}}}
|
||
|
||
def test_compact_block_with_rows_and_puzzles(self):
|
||
self.assertEqual(
|
||
"<b>DrNykterstein</b> — 5 партий\n"
|
||
"🔥 Blitz 3105 (+12) · 3 из 5 побед\n"
|
||
"<pre> ± цвет точн. соперник\n"
|
||
"🟢 +8 белые 91 % 2990 · 79 %\n"
|
||
"🟢 +7 чёрные 88 % 3011 · 84 %\n"
|
||
"🔴 -9 белые 79 % 3080 · 92 %\n"
|
||
"⚪ 0 чёрные — 3102 · —\n"
|
||
"🟢 +6 белые 93 % 2950 · 71 %</pre>\n"
|
||
"🧩 Пазлы: 14 из 17 решены",
|
||
StatsFormatter.format_player_stats(NAME, self.ACTIVITY, FIVE_GAMES, True, 'ru'))
|
||
|
||
def test_week_has_no_rows_and_no_extra_is_fine(self):
|
||
self.assertEqual(
|
||
"<b>DrNykterstein</b> — 5 партий\n🔥 Blitz 3105 (+12) · 3 из 5 побед\n🧩 Пазлы: 14 из 17 решены",
|
||
StatsFormatter.format_player_stats(NAME, self.ACTIVITY, FIVE_GAMES, False, 'ru'))
|
||
self.assertEqual(
|
||
"<b>DrNykterstein</b> — 5 games\n🔥 Blitz 3105 (+12) · 3 of 5 won\n🧩 Puzzles: 14 of 17 solved",
|
||
StatsFormatter.format_player_stats(NAME, self.ACTIVITY, None, True, 'en'))
|
||
|
||
def test_puzzles_only_and_nothing(self):
|
||
act = {'message': 'ok', 'data': {'username': NAME, 'tasks': {'total': 3, 'solved': 1, 'unsolved': 2}, 'games': {}}}
|
||
self.assertEqual("<b>DrNykterstein</b> — пазлы: 1 из 3", StatsFormatter.format_player_stats(NAME, act, None, True, 'ru'))
|
||
self.assertIsNone(StatsFormatter.format_player_stats(NAME, {'message': 'x', 'data': None}, None, True, 'ru'))
|
||
self.assertIsNone(StatsFormatter.format_player_stats(NAME, None, None, True, 'ru'))
|
||
|
||
def test_headers(self):
|
||
now = datetime(2026, 10, 21, 15, 0)
|
||
self.assertEqual("📊 Сегодня, 21 октября", StatsFormatter.format_stats_header('today', 'ru', now))
|
||
self.assertEqual("📊 Вчера, 20 октября", StatsFormatter.format_stats_header('yesterday', 'ru', now))
|
||
self.assertEqual("📊 Неделя, 15–21 октября", StatsFormatter.format_stats_header('week', 'ru', now))
|
||
self.assertEqual("📊 Today, 21 October", StatsFormatter.format_stats_header('today', 'en', now))
|
||
self.assertEqual("📊 Week, 15–21 October", StatsFormatter.format_stats_header('week', 'en', now))
|
||
self.assertEqual("📊 Неделя, 28 сентября – 4 октября",
|
||
StatsFormatter.format_stats_header('week', 'ru', datetime(2026, 10, 4, 1, 0)))
|
||
|
||
|
||
class YearTests(unittest.TestCase):
|
||
DATA = {'games_count': 523, 'period_start': 1_700_000_000, 'period_end': 1_760_000_000,
|
||
'earliest_game_ts': 1_730_000_000,
|
||
'data': {'blitz': {'games_played': 523, 'wins': 250, 'losses': 230, 'draws': 43, 'rating_change': 45,
|
||
'rating': 2257, 'accuracy': 78.4},
|
||
'bullet': {'games_played': 3, 'wins': 1, 'losses': 2, 'draws': 0, 'rating_change': -10, 'rating': 2000}}}
|
||
|
||
def test_ru_text_within_34(self):
|
||
text = StatsFormatter.format_last_year_or_1000(self.DATA, NAME, 'ru')
|
||
lines = text.split('\n')
|
||
self.assertEqual("📈 <b>DrNykterstein</b>: за год, 523 партии", lines[0])
|
||
self.assertRegex(lines[1], r"^\d\d\.\d\d\.\d{4}–\d\d\.\d\d\.\d{4}, рейтинговые$")
|
||
self.assertIn("⚡ Bullet 2000 (−10)\n 3 партии · +1 −2 =0\n\n🔥 Blitz 2257 (+45)\n 523 партии · +250 −230 =43\n точность 78 %", text)
|
||
self.assertEqual([], report_lines_ok(text))
|
||
self.assertNotIn("last year", text)
|
||
|
||
def test_en_and_1000(self):
|
||
data = dict(self.DATA, games_count=1000)
|
||
text = StatsFormatter.format_last_year_or_1000(data, NAME, 'en')
|
||
self.assertTrue(text.startswith("📈 <b>DrNykterstein</b>: last 1000 games\nsince "), text)
|
||
self.assertIn(", rated\n\n", text)
|
||
self.assertIn(" accuracy 78 %", text)
|
||
self.assertEqual([], report_lines_ok(text))
|
||
|
||
|
||
class GamersTableTests(unittest.TestCase):
|
||
def test_dash_for_missing(self):
|
||
table = StatsFormatter.format_gamers_table([
|
||
{'username': 'Ab', 'bullet': None, 'blitz': 1500, 'rapid': 1600},
|
||
{'username': 'Longname', 'bullet': 2000, 'blitz': None, 'rapid': None},
|
||
])
|
||
self.assertEqual("Ab ⚡ — 🔥1500 🐇1600\nLongname ⚡2000 🔥 — 🐇 —", table)
|
||
self.assertNotIn("N/A", table)
|
||
self.assertEqual("", StatsFormatter.format_gamers_table([]))
|
||
|
||
|
||
if __name__ == '__main__':
|
||
unittest.main()
|