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

165 lines
9.1 KiB
Python

"""Database on a temporary synthetic SQLite file: migrations, merges, counts, gamer_status, cascade."""
from tests.bot import _env # noqa: F401 (environment before bot imports)
import os
import shutil
import sqlite3
import tempfile
import unittest
from datetime import datetime, timezone
from database import Database
def build_synthetic_db(path: str) -> None:
"""Three users, three gamers, four links; user 3 tracks nobody."""
db = Database(path)
db.add_or_get_telegram_user(1, 'alice', 'Alice', None, 'ru')
db.add_or_get_telegram_user(2, 'bob', 'Bob', None, 'en')
db.add_or_get_telegram_user(3, None, 'Nobody', None, None)
a = db.add_gamer('Alpha')
b = db.add_gamer('Bravo')
c = db.add_gamer('Charlie')
db.add_user_gamer(1, a)
db.add_user_gamer(1, b, token='tok')
db.add_user_gamer(2, b)
db.add_user_gamer(2, c)
for uid, gid in ((1, a), (1, b), (2, b), (2, c)):
db.set_user_gamer_period(uid, gid, 60)
class DatabaseTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.mkdtemp()
cls.master = os.path.join(cls.tmp, "master.db")
build_synthetic_db(cls.master)
def setUp(self):
# Every test works on its own copy of the synthetic DB
self.path = os.path.join(self.tmp, f"{self._testMethodName}.db")
shutil.copyfile(self.master, self.path)
self.db = Database(self.path)
def ids(self):
with sqlite3.connect(self.path) as conn:
return dict(conn.execute("SELECT username, id FROM gamers").fetchall())
def test_init_is_idempotent(self):
before = self.db.get_counts()
Database(self.path)
Database(self.path)
self.assertEqual(before, self.db.get_counts())
with sqlite3.connect(self.path) as conn:
cols = {row[1] for row in conn.execute("PRAGMA table_info(gamer_status)")}
self.assertTrue({'missing_count', 'not_found', 'checked_at'} <= cols)
def test_migration_adds_status_columns_to_old_schema(self):
old = os.path.join(self.tmp, "old_schema.db")
with sqlite3.connect(old) as conn:
conn.execute("CREATE TABLE gamer_status (gamer_id INTEGER PRIMARY KEY, disabled INTEGER NOT NULL DEFAULT 0, "
"seen_at INTEGER, games_total INTEGER, checked_at INTEGER NOT NULL)")
conn.execute("INSERT INTO gamer_status VALUES (7, 0, NULL, 5, 100)")
db = Database(old)
self.assertEqual({'disabled': False, 'seen_at': None, 'games_total': 5, 'checked_at': 100,
'missing_count': 0, 'not_found': False}, db.get_gamer_status(7))
def test_case_duplicate_merge(self):
with sqlite3.connect(self.path) as conn:
conn.execute("DROP INDEX idx_gamers_username_nocase")
conn.execute("INSERT INTO gamers (username) VALUES ('alpha')") # duplicate of 'Alpha'
dup_id = conn.execute("SELECT id FROM gamers WHERE username = 'alpha'").fetchone()[0]
# user 2 tracks only the duplicate; user 1 tracks both spellings (checkpoint only on the dup)
conn.execute("INSERT INTO user_gamers (user_id, gamer_id, period_minutes) VALUES (2, ?, 30)", (dup_id,))
conn.execute("INSERT INTO user_gamers (user_id, gamer_id, period_minutes, last_period_end_ts) "
"VALUES (1, ?, 0, 12345)", (dup_id,))
db = Database(self.path) # runs _merge_case_duplicate_gamers
ids = self.ids()
self.assertIn('Alpha', ids)
self.assertNotIn('alpha', ids)
keep = ids['Alpha']
user2 = {g['username']: g for g in db.get_user_gamers(2)}
self.assertEqual(30, user2['Alpha']['period_minutes']) # link re-pointed
user1 = [g for g in db.get_user_gamers(1) if g['id'] == keep]
self.assertEqual(1, len(user1)) # one link, not two
self.assertEqual(60, user1[0]['period_minutes']) # enabled period kept
self.assertEqual(12345, db.get_period_checkpoint(1, keep)) # checkpoint merged in
with sqlite3.connect(self.path) as conn, self.assertRaises(sqlite3.IntegrityError):
conn.execute("INSERT INTO gamers (username) VALUES ('ALPHA')") # index back in place
def test_gamer_exists_is_case_insensitive(self):
self.assertTrue(self.db.gamer_exists('Alpha'))
self.assertTrue(self.db.gamer_exists('ALPHA'))
self.assertFalse(self.db.gamer_exists('Delta'))
def test_get_counts(self):
self.assertEqual({'users': 3, 'gamers': 3}, self.db.get_counts())
def test_get_admin_stats(self):
today = datetime.now(timezone.utc).date().isoformat() # created_at defaults are UTC
self.assertEqual({'users': 3, 'users_today': 3, 'users_without_gamers': 1,
'gamers': 3, 'gamers_today': 3}, self.db.get_admin_stats(today))
self.assertEqual({'users': 3, 'users_today': 0, 'users_without_gamers': 1,
'gamers': 3, 'gamers_today': 0}, self.db.get_admin_stats('2000-01-01'))
def test_tracked_gamers_and_pairs(self):
tracked = {g['username'] for g in self.db.get_all_tracked_gamers()}
self.assertEqual({'Alpha', 'Bravo', 'Charlie'}, tracked)
self.assertEqual(4, len(self.db.get_all_gamers_with_periods()))
self.db.set_user_gamer_period(2, self.ids()['Charlie'], 0)
self.assertEqual({'Alpha', 'Bravo'}, {g['username'] for g in self.db.get_all_tracked_gamers()})
def test_gamer_status_upsert_missing_and_not_found(self):
a, b = self.ids()['Alpha'], self.ids()['Bravo']
self.assertIsNone(self.db.get_gamer_status(a))
self.db.upsert_gamer_statuses([{'gamer_id': a, 'disabled': False, 'seen_at': 5, 'games_total': 10, 'checked_at': 100}])
self.assertEqual({'disabled': False, 'seen_at': 5, 'games_total': 10, 'checked_at': 100,
'missing_count': 0, 'not_found': False}, self.db.get_gamer_status(a))
# first miss: counted, not yet flagged; games_total kept
self.assertEqual(0, self.db.mark_gamer_statuses_missing([a, b], 200))
self.assertEqual({'disabled': False, 'seen_at': 5, 'games_total': 10, 'checked_at': 200,
'missing_count': 1, 'not_found': False}, self.db.get_gamer_status(a))
self.assertEqual({'disabled': False, 'seen_at': None, 'games_total': None, 'checked_at': 200,
'missing_count': 1, 'not_found': False}, self.db.get_gamer_status(b)) # row created
# second consecutive miss: flagged
self.assertEqual(2, self.db.mark_gamer_statuses_missing([a, b], 300))
self.assertEqual(2, self.db.get_gamer_status(a)['missing_count'])
self.assertTrue(self.db.get_gamer_status(a)['not_found'])
self.assertTrue(self.db.get_gamer_status(b)['not_found'])
# third miss: still flagged, counter keeps growing, only the given ids are counted
self.assertEqual(1, self.db.mark_gamer_statuses_missing([a], 400))
self.assertEqual(3, self.db.get_gamer_status(a)['missing_count'])
self.assertEqual(2, self.db.get_gamer_status(b)['missing_count'])
# present again: both reset, a closed account stays closed but found
self.db.upsert_gamer_statuses([{'gamer_id': a, 'disabled': True, 'seen_at': None, 'games_total': 10, 'checked_at': 500}])
self.assertEqual({'disabled': True, 'seen_at': None, 'games_total': 10, 'checked_at': 500,
'missing_count': 0, 'not_found': False}, self.db.get_gamer_status(a))
self.assertEqual(0, self.db.mark_gamer_statuses_missing([], 600))
def test_pair_check_state(self):
a = self.ids()['Alpha']
self.assertEqual({'last_games_total': None, 'closed_notice_sent': False}, self.db.get_pair_check_state(1, a))
self.db.set_pair_last_games_total(1, a, 42)
self.db.set_pair_closed_notice_sent(1, a, True)
self.assertEqual({'last_games_total': 42, 'closed_notice_sent': True}, self.db.get_pair_check_state(1, a))
self.assertEqual({'last_games_total': None, 'closed_notice_sent': False}, self.db.get_pair_check_state(9, a))
def test_remove_user_gamer_cascade(self):
ids = self.ids()
a, b = ids['Alpha'], ids['Bravo']
self.db.upsert_gamer_statuses([{'gamer_id': a, 'disabled': False, 'seen_at': None, 'games_total': 1, 'checked_at': 1},
{'gamer_id': b, 'disabled': False, 'seen_at': None, 'games_total': 1, 'checked_at': 1}])
# Bravo is tracked by users 1 and 2: unlinking one keeps the gamer and its status
self.assertTrue(self.db.remove_user_gamer(1, b))
self.assertTrue(self.db.gamer_exists('Bravo'))
self.assertIsNotNone(self.db.get_gamer_status(b))
# Alpha is tracked by user 1 only: unlinking removes gamer + status row
self.assertTrue(self.db.remove_user_gamer(1, a))
self.assertFalse(self.db.gamer_exists('Alpha'))
self.assertIsNone(self.db.get_gamer_status(a))
self.assertFalse(self.db.remove_user_gamer(1, a)) # nothing left to delete
self.assertEqual({'users': 3, 'gamers': 2}, self.db.get_counts())
if __name__ == '__main__':
unittest.main()