LichessStatTgWeb/tests/bot/test_database.py

233 lines
14 KiB
Python
Raw Normal View History

"""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, timedelta, 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_overview(self):
today = datetime.now(timezone.utc).date() # created_at defaults are UTC
yesterday = today - timedelta(days=1)
week_start = today - timedelta(days=6)
iso = lambda d: d.isoformat()
# everything in the synthetic DB was created "now" -> today and week, not yesterday
self.assertEqual({
'users': {'total': 3, 'today': 3, 'yesterday': 0, 'week': 3},
'gamers': {'total': 3, 'today': 3, 'yesterday': 0, 'week': 3},
'pairs': {'active': 4, 'today': 4, 'yesterday': 0, 'week': 4},
'users_without_gamers': 1,
'status': {'closed': 0, 'not_found': 0, 'last_checked_at': None},
}, self.db.get_admin_overview(iso(today), iso(yesterday), iso(week_start)))
# rows created yesterday / 10 days ago: in "yesterday" and "week" / in neither
a, b = self.ids()['Alpha'], self.ids()['Bravo']
with sqlite3.connect(self.path) as conn:
conn.execute("INSERT INTO telegram_users (user_id, first_name, created_at) VALUES (4, 'Y', ?)",
(f"{iso(yesterday)} 12:00:00",))
conn.execute("INSERT INTO telegram_users (user_id, first_name, created_at) VALUES (5, 'Old', ?)",
(f"{iso(today - timedelta(days=10))} 12:00:00",))
conn.execute("INSERT INTO user_gamers (user_id, gamer_id, period_minutes, created_at) VALUES (3, ?, 0, ?)",
(a, f"{iso(yesterday)} 12:00:00"))
# a paused subscription (period 0) is counted as created but not as active
self.db.set_user_gamer_period(2, self.ids()['Charlie'], 0)
# status: Alpha closed, Bravo missing twice -> not_found; last_checked_at = the newest checked_at
self.db.upsert_gamer_statuses([{'gamer_id': a, 'disabled': True, 'seen_at': None, 'games_total': 1, 'checked_at': 100}])
self.db.mark_gamer_statuses_missing([b], 200)
self.db.mark_gamer_statuses_missing([b], 300)
overview = self.db.get_admin_overview(iso(today), iso(yesterday), iso(week_start))
self.assertEqual({'total': 5, 'today': 3, 'yesterday': 1, 'week': 4}, overview['users'])
self.assertEqual({'total': 3, 'today': 3, 'yesterday': 0, 'week': 3}, overview['gamers'])
self.assertEqual({'active': 3, 'today': 4, 'yesterday': 1, 'week': 5}, overview['pairs'])
self.assertEqual(2, overview['users_without_gamers']) # user 3 now tracks Alpha; 4 and 5 track nobody
self.assertEqual({'closed': 1, 'not_found': 1, 'last_checked_at': 300}, overview['status'])
# a week that starts today excludes yesterday's rows
overview = self.db.get_admin_overview(iso(today), iso(yesterday), iso(today))
self.assertEqual({'total': 5, 'today': 3, 'yesterday': 1, 'week': 3}, overview['users'])
self.assertEqual({'active': 3, 'today': 4, 'yesterday': 1, 'week': 4}, overview['pairs'])
# a day with nothing: zeros, never None
overview = self.db.get_admin_overview('2000-01-01', '1999-12-31', '2000-01-01')
self.assertEqual({'total': 5, 'today': 0, 'yesterday': 0, 'week': 5}, overview['users'])
def test_get_admin_overview_empty_db(self):
empty = Database(os.path.join(self.tmp, "empty.db"))
self.assertEqual({
'users': {'total': 0, 'today': 0, 'yesterday': 0, 'week': 0},
'gamers': {'total': 0, 'today': 0, 'yesterday': 0, 'week': 0},
'pairs': {'active': 0, 'today': 0, 'yesterday': 0, 'week': 0},
'users_without_gamers': 0,
'status': {'closed': 0, 'not_found': 0, 'last_checked_at': None},
}, empty.get_admin_overview('2026-10-21', '2026-10-20', '2026-10-15'))
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']
empty = {'last_games_total': None, 'closed_notice_sent': False, 'silent_prompt_at': None}
self.assertEqual(empty, 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.db.set_pair_silent_prompt_at(1, a, 1_800_000_000)
self.assertEqual({'last_games_total': 42, 'closed_notice_sent': True, 'silent_prompt_at': 1_800_000_000},
self.db.get_pair_check_state(1, a))
self.db.set_pair_silent_prompt_at(1, a, None)
self.assertIsNone(self.db.get_pair_check_state(1, a)['silent_prompt_at'])
self.assertEqual(empty, self.db.get_pair_check_state(9, a))
with sqlite3.connect(self.path) as conn:
cols = {row[1] for row in conn.execute("PRAGMA table_info(user_gamers)")}
self.assertIn('silent_prompt_at', cols)
def test_gamer_statuses_bulk_and_username(self):
ids = self.ids()
a, b, c = ids['Alpha'], ids['Bravo'], ids['Charlie']
self.assertEqual({}, self.db.get_gamer_statuses([]))
self.assertEqual({}, self.db.get_gamer_statuses([a, b]))
self.db.upsert_gamer_statuses([{'gamer_id': a, 'disabled': False, 'seen_at': 5, 'games_total': 10, 'checked_at': 100},
{'gamer_id': c, 'disabled': True, 'seen_at': None, 'games_total': 1, 'checked_at': 100}])
statuses = self.db.get_gamer_statuses([a, b, c])
self.assertEqual({a, c}, set(statuses)) # Bravo has no row
self.assertEqual(self.db.get_gamer_status(a), statuses[a])
self.assertEqual(self.db.get_gamer_status(c), statuses[c])
self.assertEqual('Alpha', self.db.get_gamer_username(a))
self.assertIsNone(self.db.get_gamer_username(10 ** 6))
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()