LichessStatTgWeb/tests/bot/_fakes.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

179 lines
6 KiB
Python

"""
Minimal stand-ins for python-telegram-bot's Update / Context and for the bot's
outgoing side, so handler tests (and the onboarding dry run) can call
LichessBot methods directly and read the exact outgoing text, parse mode,
preview flag and inline buttons — no network, no Telegram objects to build.
Also a LichessBot factory with the network-facing parts replaced: Lichess
lookups answer from a dict, the admin notifier and the periodic monitor are
no-ops, and every events.event() call is recorded for assertions.
"""
from tests.bot import _env # noqa: F401 (environment before bot imports)
import os
import tempfile
from types import SimpleNamespace
import bot as bot_module
from bot import LichessBot
from database import Database
def buttons(kwargs):
"""[[(label, callback_data), ...], ...] of the reply_markup in a captured call, or None."""
markup = kwargs.get('reply_markup')
if markup is None:
return None
return [[(b.text, b.callback_data) for b in row] for row in markup.inline_keyboard]
class FakeMessage:
def __init__(self, outbox, text=None, photo=None):
self.text = text
self.photo = photo
self._outbox = outbox
async def reply_text(self, text, **kwargs):
self._outbox.append(('text', text, kwargs))
return FakeMessage(self._outbox, text=text)
async def reply_photo(self, photo, **kwargs):
self._outbox.append(('photo', kwargs.get('caption'), kwargs))
async def edit_text(self, text, **kwargs):
self._outbox.append(('edit', text, kwargs))
async def delete(self):
pass
class FakeQuery:
def __init__(self, outbox, data, user, message):
self.data = data
self.from_user = user
self.message = message
self._outbox = outbox
async def answer(self):
pass
async def edit_message_text(self, text, **kwargs):
self._outbox.append(('edit', text, kwargs))
def make_user(uid=1, lang_code='ru'):
return SimpleNamespace(id=uid, username=f"tg{uid}", first_name="Test", last_name=None, language_code=lang_code)
def make_update(outbox, uid=1, text=None, lang_code='ru', callback=None, photo=False):
"""A text message (text=...), a non-text message (photo=True) or a callback (callback='data')."""
user = make_user(uid, lang_code)
chat = SimpleNamespace(id=uid, type='private')
message = FakeMessage(outbox, text=text, photo=[object()] if photo else None)
query = FakeQuery(outbox, callback, user, message) if callback else None
return SimpleNamespace(effective_user=user, effective_chat=chat, message=message, callback_query=query)
def make_context():
return SimpleNamespace(user_data={}, args=[])
class FakeLichess:
"""
Stand-in for lichess_api.LichessAPI (both the direct lichess.org calls and
the local stats service). Every call is recorded in `calls` as
(method, username) so a test can assert that a screen made no request.
- check_user_exists answers from `accounts` (lowercase name -> dict | False | None);
- get_today_stats / get_yesterday_stats / get_week_stats answer from
`activity` (name -> the /stats/{u}/<period> payload, None, or an
Exception instance to raise);
- get_games_period answers from `games_period` (name -> payload or None);
- get_user_ratings answers from `ratings` (name -> {'perfs': ...} or None);
- tokens never reach Lichess.
"""
def __init__(self, accounts, activity=None, games_period=None, ratings=None):
self.accounts = accounts
self.activity = activity or {}
self.games_period = games_period or {}
self.ratings = ratings or {}
self.calls = []
async def check_user_exists(self, username):
self.calls.append(username)
return self.accounts.get(username.lower(), False)
async def get_user_profile(self, token):
raise AssertionError("get_user_profile must not be called in this test")
def _activity(self, method, username):
self.calls.append((method, username))
answer = self.activity.get(username)
if isinstance(answer, Exception):
raise answer
return answer
async def get_today_stats(self, username):
return self._activity('today', username)
async def get_yesterday_stats(self, username):
return self._activity('yesterday', username)
async def get_week_stats(self, username):
return self._activity('week', username)
async def get_games_period(self, username, since, until, **kwargs):
self.calls.append(('games_period', username))
return self.games_period.get(username)
async def get_user_ratings(self, username):
self.calls.append(('ratings', username))
return self.ratings.get(username)
class FakeNotifier:
async def notify_new_user(self, **kwargs):
pass
async def notify_new_player(self, *args, **kwargs):
pass
class FakeMonitor:
application = None
def __init__(self):
self.stopped = []
async def start_periodic_task(self, *args, **kwargs):
pass
async def stop_periodic_task(self, gamer_id, user_id):
self.stopped.append((gamer_id, user_id))
def make_bot(accounts=None, db_path=None, activity=None, games_period=None, ratings=None):
"""
A LichessBot on a fresh temporary DB with the network parts replaced.
Returns (bot, events): `events` collects every events.event() call made by
bot.py as (name, fields) while this bot is in use (module-level patch —
restore with restore_events()).
"""
if db_path is None:
db_path = os.path.join(tempfile.mkdtemp(prefix="lichess-handlers-"), "bot.db")
bot = LichessBot()
bot.db = Database(db_path)
bot.lichess_api = FakeLichess(accounts or {}, activity=activity, games_period=games_period, ratings=ratings)
bot.notifier = FakeNotifier()
bot.monitor = FakeMonitor()
events = []
bot_module.event = lambda _name, **fields: events.append((_name, fields))
return bot, events
_ORIGINAL_EVENT = bot_module.event
def restore_events():
bot_module.event = _ORIGINAL_EVENT