Files
SteamBase/tests/test_db.py
T
2026-11-06 20:34:19 +03:00

188 lines
7.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Tests for schema initialization and versioned migrations."""
import os
import sqlite3
import sys
import tempfile
import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
import db
LEGACY_SCHEMA = """
CREATE TABLE schema_meta (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE games (
appid INTEGER PRIMARY KEY,
name TEXT NOT NULL,
type TEXT,
release_date TEXT,
metacritic INTEGER,
review_pct INTEGER,
updated_at TEXT
);
CREATE TABLE game_details (
appid INTEGER PRIMARY KEY REFERENCES games(appid) ON DELETE CASCADE,
short_description TEXT,
about TEXT,
header_image TEXT,
developers TEXT,
publishers TEXT,
release_date TEXT,
lang TEXT,
fetched_at TEXT,
status TEXT
);
INSERT INTO games (appid, name, type) VALUES (100, 'Legacy', 'game');
INSERT INTO game_details (appid, short_description, status)
VALUES (100, 'Old description', 'ok');
"""
class SchemaVersionTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.path = os.path.join(self.tmp.name, "test.db")
def _version(self, con):
row = con.execute("SELECT value FROM schema_meta WHERE key='schema_version'").fetchone()
return row[0] if row else None
def _columns(self, con, table):
return {row[1] for row in con.execute(f"PRAGMA table_info({table})")}
def test_migrations_cover_current_version(self):
self.assertEqual(set(db.MIGRATIONS), set(range(1, db.SCHEMA_VERSION + 1)))
def test_new_database_is_stamped(self):
con = db.connect(self.path)
self.addCleanup(con.close)
db.init(con)
self.assertEqual(self._version(con), str(db.SCHEMA_VERSION))
self.assertIn("source_appid", self._columns(con, "game_details"))
tables = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
self.assertIn("personal", tables)
self.assertIn("game_translations", tables)
self.assertIn("reco_feedback", tables)
self.assertIn("game_fts", tables)
self.assertIn("estimated_hours", self._columns(con, "games"))
def test_legacy_database_is_migrated_and_data_preserved(self):
con = sqlite3.connect(self.path)
con.executescript(LEGACY_SCHEMA)
con.commit()
con.close()
con = db.connect(self.path)
self.addCleanup(con.close)
self.assertNotIn("source_appid", self._columns(con, "game_details"))
db.init(con)
self.assertEqual(self._version(con), str(db.SCHEMA_VERSION))
self.assertIn("source_appid", self._columns(con, "game_details"))
row = con.execute("SELECT name FROM games WHERE appid=100").fetchone()
self.assertEqual(row["name"], "Legacy")
details = con.execute("SELECT short_description, source_appid FROM game_details WHERE appid=100").fetchone()
self.assertEqual(details["short_description"], "Old description")
self.assertIsNone(details["source_appid"])
self.assertIn("estimated_hours", self._columns(con, "games"))
fts_tables = {r[0] for r in con.execute(
"SELECT name FROM sqlite_master WHERE name='game_fts'")}
self.assertEqual(fts_tables, {"game_fts"})
def test_init_is_idempotent(self):
con = db.connect(self.path)
self.addCleanup(con.close)
db.init(con)
con.execute("INSERT INTO games (appid, name, type) VALUES (1, 'One', 'game')")
con.commit()
db.init(con)
self.assertEqual(self._version(con), str(db.SCHEMA_VERSION))
self.assertEqual(con.execute("SELECT COUNT(*) c FROM games").fetchone()["c"], 1)
def test_parse_release_date(self):
self.assertEqual(db.parse_release_date("1 янв. 2000 г."), "2000-01-01")
self.assertEqual(db.parse_release_date("19 ноя. 1998 г."), "1998-11-19")
self.assertEqual(db.parse_release_date("Nov 16, 2004"), "2004-11-16")
self.assertEqual(db.parse_release_date("2023"), "2023")
self.assertEqual(db.parse_release_date("Q4 2024"), "2024")
self.assertIsNone(db.parse_release_date("Coming soon"))
self.assertIsNone(db.parse_release_date(None))
def test_backfill_release_dates(self):
con = db.connect(self.path)
self.addCleanup(con.close)
db.init(con)
con.execute("INSERT INTO games (appid, name, type) VALUES (1, 'Old', 'game')")
con.execute("INSERT INTO game_details (appid, release_date, status) "
"VALUES (1, '1 янв. 2000 г.', 'ok')")
con.commit()
self.assertEqual(db.backfill_release_dates(con), 1)
self.assertEqual(
con.execute("SELECT release_date FROM games WHERE appid=1").fetchone()[0],
"2000-01-01")
self.assertEqual(db.backfill_release_dates(con), 0)
def test_duration_estimate(self):
self.assertEqual(db.estimate_hours({"RPG"}, set()), 30)
self.assertEqual(db.estimate_hours({"RPG"}, {"Short"}), 5)
self.assertEqual(db.estimate_hours({"Adventure"}, {"Open World", "Short"}), 5)
self.assertEqual(db.estimate_hours(set(), {"City Builder"}), 28)
self.assertEqual(db.estimate_hours(set(), {"MMORPG"}), 80)
self.assertEqual(db.estimate_hours(set(), set()), 12)
self.assertEqual(db.estimate_hours({"Casual"}, set()), 6)
def test_search_index_rebuild_and_single_game_refresh(self):
con = db.connect(self.path)
self.addCleanup(con.close)
db.init(con)
con.executemany(
"INSERT INTO games (appid, name, type) VALUES (?, ?, ?)",
[(1, "Alpha Quest", "game"), (2, "Toolbox", "tool")])
con.execute("INSERT INTO game_details (appid, short_description, about, status) "
"VALUES (1, 'Short', '<p>Deep dungeon</p>', 'ok')")
con.execute("INSERT INTO game_translations (appid, lang, short_description) "
"VALUES (1, 'ru', 'Краткое описание')")
con.execute("INSERT INTO tag_names (tag_id, name) VALUES (10, 'RPG')")
con.execute("INSERT INTO game_tags (appid, tag_id) VALUES (1, 10)")
con.commit()
db.refresh_search_index(con)
def match(term):
return [r[0] for r in con.execute(
"SELECT appid FROM game_fts WHERE game_fts MATCH ? ORDER BY appid", (term,))]
self.assertEqual(match("alpha*"), [1])
self.assertEqual(match("dungeon*"), [1])
self.assertEqual(match("краткое*"), [1])
self.assertEqual(match("rpg*"), [1])
self.assertEqual(match("toolbox*"), [])
con.execute("INSERT INTO games (appid, name, type) VALUES (3, 'Beta Game', 'game')")
db.refresh_search_game(con, 3)
self.assertEqual(match("beta*"), [3])
con.execute("UPDATE games SET type='tool' WHERE appid=3")
db.refresh_search_game(con, 3)
self.assertEqual(match("beta*"), [])
def test_newer_database_is_rejected(self):
con = db.connect(self.path)
self.addCleanup(con.close)
con.execute("CREATE TABLE schema_meta (key TEXT PRIMARY KEY, value TEXT)")
con.execute("INSERT INTO schema_meta (key, value) VALUES ('schema_version', '999')")
con.commit()
with self.assertRaises(RuntimeError):
db.init(con)
if __name__ == "__main__":
unittest.main()