feat: add tests, CI and P0 reliability features

This commit is contained in:
strsv committed 2026-11-06 07:43:30 +03:00
1 parent 0754065dae
commit 626650e44a
22 files changed
+1576 -49

No files matched your search

View File
Whitespace-only changes.
+339
View File
@@ -0,0 +1,339 @@
"""HTTP API smoke tests against a temporary database."""
import json
import os
import sqlite3
import sys
import tempfile
import threading
import time
import unittest
import urllib.error
import urllib.request
from http.server import ThreadingHTTPServer
from unittest import mock
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
sys.path.insert(0, os.path.join(ROOT, "web"))
import db
import server
class _NoDetails:
def enqueue_many(self, appids):
pass
def fetch_now(self, appid):
pass
class ApiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.db_path = os.path.join(cls.tmp.name, "api.db")
cls.con = db.connect(cls.db_path)
db.init(cls.con)
db.seed_moods(cls.con)
cls._seed(cls.con)
cls.con.close()
cls.db_patch = mock.patch.object(db, "DEFAULT_DB", cls.db_path)
cls.db_patch.start()
cls.details_patch = mock.patch.object(server, "DETAILS", _NoDetails())
cls.details_patch.start()
cls.httpd = ThreadingHTTPServer(("127.0.0.1", 0), server.Handler)
cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
cls.thread.start()
@classmethod
def tearDownClass(cls):
cls.httpd.shutdown()
cls.httpd.server_close()
cls.thread.join(timeout=5)
cls.details_patch.stop()
cls.db_patch.stop()
cls.tmp.cleanup()
@staticmethod
def _seed(con):
games = [
(1, "Alpha", "game", "2020-05-01", 90, 90),
(2, "Beta", "game", "2019-02-02", 85, 85),
(3, "Gamma", "game", None, 70, 70),
(4, "Tool", "tool", "2018-01-01", 99, 99),
]
con.executemany(
"""INSERT INTO games (appid, name, type, release_date, metacritic, review_pct)
VALUES (?,?,?,?,?,?)""", games)
playtime = [(1, 120, "2026-01-01"), (2, 0, None), (3, 30, None), (4, 0, None)]
con.executemany("INSERT INTO game_playtime (appid, minutes, last_played) VALUES (?,?,?)", playtime)
installs = [(1, 1, 1024 * 1024 * 1024, "C:/Steam"), (2, 0, None, None)]
con.executemany(
"INSERT INTO game_install (appid, installed, size_bytes, library_path) VALUES (?,?,?,?)",
installs)
personal = [
(1, "playing", 9, 1, "заметка"),
(2, "backlog", None, 0, None),
]
con.executemany(
"INSERT INTO personal (appid, status, rating, favorite, notes) VALUES (?,?,?,?,?)", personal)
con.executemany(
"INSERT INTO game_genres (appid, genre) VALUES (?,?)",
[(1, "RPG"), (1, "Adventure"), (2, "RPG"), (3, "Horror"), (4, "RPG")])
con.executemany(
"INSERT INTO game_tags (appid, tag_id) VALUES (?,?)",
[(1, 1), (1, 2), (2, 1), (2, 2), (3, 3)])
con.executemany(
"INSERT INTO tag_names (tag_id, name) VALUES (?,?)",
[(1, "RPG"), (2, "Party-Based RPG"), (3, "Horror")])
con.execute(
"""INSERT INTO game_details (appid, short_description, about, header_image, developers,
publishers, release_date, lang, fetched_at, status)
VALUES (1, 'Short text', '<p>About text</p>', 'http://img', 'Dev', 'Pub',
'2020-05-01', 'en', '2026-01-01', 'ok')""")
con.execute(
"""INSERT INTO game_translations (appid, lang, short_description, provider, translated_at)
VALUES (1, 'ru', 'Кратко', 'google', '2026-01-01')""")
con.execute("INSERT INTO attributes (appid, key, value) VALUES (1, 'mood', 'calm')")
con.commit()
def get(self, path, expect=200):
try:
with urllib.request.urlopen(self.base + path, timeout=10) as resp:
status = resp.status
body = resp.read().decode("utf-8")
except urllib.error.HTTPError as exc:
status = exc.code
body = exc.read().decode("utf-8")
self.assertEqual(status, expect, body)
return json.loads(body) if body else None
def raw_get(self, path, expect=200):
try:
with urllib.request.urlopen(self.base + path, timeout=10) as resp:
status = resp.status
body = resp.read()
headers = resp.headers
except urllib.error.HTTPError as exc:
status = exc.code
body = exc.read()
headers = exc.headers
self.assertEqual(status, expect, body)
return body, headers.get("Content-Type"), headers
def post(self, path, payload, expect=200):
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
self.base + path, data=data, method="POST",
headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=10) as resp:
status = resp.status
body = resp.read().decode("utf-8")
except urllib.error.HTTPError as exc:
status = exc.code
body = exc.read().decode("utf-8")
self.assertEqual(status, expect, body)
return json.loads(body) if body else None
def test_meta(self):
data = self.get("/api/meta")
self.assertEqual(data["total"], 3)
self.assertEqual(data["installed"], 1)
self.assertEqual(data["played"], 2)
self.assertEqual(data["hours"], 2)
self.assertEqual(data["cached"], 1)
self.assertEqual(data["missing"], 0)
self.assertEqual(data["pending"], 2)
self.assertEqual(data["translated"], 1)
self.assertEqual(data["translate_pending"], 0)
self.assertEqual(data["statuses"], {"playing": 1, "backlog": 1})
genres = {g["name"]: g["count"] for g in data["genres"]}
self.assertEqual(genres["RPG"], 2)
tags = {t["name"]: t["count"] for t in data["tags"]}
self.assertEqual(tags["RPG"], 2)
def test_games_list_and_serialization(self):
data = self.get("/api/games")
self.assertEqual(data["total"], 3)
names = [g["name"] for g in data["items"]]
self.assertEqual(names, ["Alpha", "Beta", "Gamma"])
alpha = data["items"][0]
self.assertEqual(alpha["appid"], 1)
self.assertEqual(alpha["year"], 2020)
self.assertEqual(alpha["review"], 90)
self.assertEqual(alpha["hours"], 2.0)
self.assertTrue(alpha["installed"])
self.assertEqual(alpha["status"], "playing")
self.assertEqual(alpha["rating"], 9)
self.assertTrue(alpha["favorite"])
self.assertEqual(alpha["notes"], "заметка")
self.assertEqual(alpha["genres"], ["Adventure", "RPG"])
self.assertEqual(alpha["tags"], ["Party-Based RPG", "RPG"])
self.assertEqual(alpha["description"], "Кратко")
self.assertEqual(alpha["desc_status"], "ok")
self.assertEqual(alpha["developers"], "Dev")
self.assertEqual(alpha["publishers"], "Pub")
def test_games_filters(self):
self.assertEqual([g["appid"] for g in self.get("/api/games?q=alph")["items"]], [1])
self.assertEqual({g["appid"] for g in self.get("/api/games?genre=RPG")["items"]}, {1, 2})
self.assertEqual({g["appid"] for g in self.get("/api/games?tag=RPG")["items"]}, {1, 2})
self.assertEqual([g["appid"] for g in self.get("/api/games?status=playing")["items"]], [1])
self.assertEqual([g["appid"] for g in self.get("/api/games?installed=1")["items"]], [1])
self.assertEqual({g["appid"] for g in self.get("/api/games?unplayed=1")["items"]}, {2})
self.assertEqual([g["appid"] for g in self.get("/api/games?favorite=1")["items"]], [1])
def test_games_sort_and_pagination(self):
self.assertEqual([g["appid"] for g in self.get("/api/games?sort=review")["items"]], [1, 2, 3])
self.assertEqual([g["appid"] for g in self.get("/api/games?sort=hours")["items"]], [1, 3, 2])
page2 = self.get("/api/games?per_page=12&page=2")
self.assertEqual(page2["page"], 2)
self.assertEqual(page2["items"], [])
def test_game_card(self):
data = self.get("/api/game/1")
self.assertEqual(data["name"], "Alpha")
self.assertEqual(data["about"], "<p>About text</p>")
self.assertEqual(data["size_gb"], 1.0)
self.assertEqual(data["steam_url"], "https://store.steampowered.com/app/1/")
self.assertEqual(data["attributes"], [{"key": "mood", "value": "calm"}])
self.assertTrue(data["similar"])
self.assertEqual(data["similar"][0]["appid"], 2)
def test_unknown_game(self):
data = self.get("/api/game/999", expect=404)
self.assertEqual(data["error"], "unknown appid")
def test_descriptions(self):
data = self.get("/api/descriptions?ids=1,2")
self.assertEqual(data["1"], "Кратко")
self.assertIsNone(data["2"])
def test_moods(self):
data = self.get("/api/moods")
names = {m["name"] for m in data["moods"]}
self.assertIn("dark-fantasy", names)
mood = next(m for m in data["moods"] if m["name"] == "dark-fantasy")
self.assertIn("Dark Fantasy", mood["tags"])
self.assertEqual(mood["genres"], ["RPG", "Adventure", "Action"])
def test_recommend_preset_and_text(self):
data = self.post("/api/recommend", {"preset": "dark-fantasy", "limit": 5})
self.assertEqual(data["mood"]["preset"], "dark-fantasy")
self.assertTrue(data["results"])
data = self.post("/api/recommend", {"mood": "рпг приключение", "limit": 5})
self.assertEqual(data["mood"]["description"], "рпг приключение")
self.assertIn("RPG", data["mood"]["tags"])
def test_recommend_unknown_mood(self):
data = self.post("/api/recommend", {"preset": "no-such-mood"}, expect=400)
self.assertEqual(data["error"], "unknown mood")
def test_personal_update(self):
try:
data = self.post("/api/personal/3", {
"status": "played", "rating": 7, "favorite": True, "notes": "ok"})
self.assertEqual(data["status"], "played")
self.assertEqual(data["rating"], 7)
self.assertEqual(data["favorite"], 1)
self.assertEqual(data["notes"], "ok")
fresh = self.get("/api/game/3")
self.assertEqual(fresh["status"], "played")
self.assertEqual(fresh["rating"], 7)
finally:
con = db.connect(self.db_path)
try:
con.execute("DELETE FROM personal WHERE appid = 3")
con.commit()
finally:
con.close()
def test_personal_errors(self):
self.assertEqual(self.post("/api/personal/999", {"rating": 5}, expect=404)["error"],
"unknown appid")
self.assertEqual(self.post("/api/personal/2", {}, expect=400)["error"],
"nothing to update")
self.assertEqual(self.post("/api/personal/2", {"status": "bogus"}, expect=400)["error"],
"nothing to update")
def test_cover_negative_cache(self):
with tempfile.TemporaryDirectory() as covers, \
mock.patch.object(server, "CACHE_DIR", covers), \
mock.patch.object(server, "LIB_CACHE", None), \
mock.patch.object(server.Handler, "_download_cover", return_value=None) as download:
self.get("/api/cover/3", expect=404)
calls = download.call_count
self.assertEqual(calls, len(server.CDN_COVER_NAMES))
marker = os.path.join(covers, "3", ".missing")
self.assertTrue(os.path.isfile(marker))
self.get("/api/cover/3", expect=404)
self.assertEqual(download.call_count, calls, "fresh negative cache should avoid downloads")
old = time.time() - server.COVER_MISSING_TTL - 1
os.utime(marker, (old, old))
self.get("/api/cover/3", expect=404)
self.assertEqual(download.call_count, calls * 2, "expired marker should retry")
def test_cached_cover_clears_negative_marker(self):
with tempfile.TemporaryDirectory() as covers, \
mock.patch.object(server, "CACHE_DIR", covers):
app_dir = os.path.join(covers, "1")
os.makedirs(app_dir)
with open(os.path.join(app_dir, "header.jpg"), "wb") as fh:
fh.write(b"image-bytes")
marker = os.path.join(app_dir, ".missing")
with open(marker, "w", encoding="utf-8") as fh:
fh.write("0")
body, content_type, _ = self.raw_get("/api/cover/1")
self.assertEqual(body, b"image-bytes")
self.assertTrue(content_type.startswith("image/jpeg"))
self.assertFalse(os.path.exists(marker))
def test_backup_download(self):
body, content_type, headers = self.raw_get("/api/backup")
self.assertEqual(content_type, "application/octet-stream")
disposition = headers.get("Content-Disposition")
self.assertIn("attachment", disposition)
self.assertIn(".db", disposition)
self.assertTrue(body.startswith(b"SQLite format 3\x00"))
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "backup.db")
with open(path, "wb") as fh:
fh.write(body)
con = sqlite3.connect(path)
try:
self.assertEqual(con.execute("PRAGMA integrity_check").fetchone()[0], "ok")
self.assertEqual(con.execute("SELECT COUNT(*) FROM games").fetchone()[0], 4)
self.assertEqual(
con.execute("SELECT value FROM schema_meta WHERE key='schema_version'").fetchone()[0],
str(db.SCHEMA_VERSION))
finally:
con.close()
def test_unknown_api(self):
self.assertEqual(self.get("/api/nope", expect=404)["error"], "not found")
def test_job_status(self):
data = self.get("/api/job")
self.assertIn("running", data)
self.assertIn("cancelled", data)
self.assertFalse(data["running"])
def test_job_cancel_without_job(self):
data = self.post("/api/job/cancel", {}, expect=200)
self.assertFalse(data["cancelled"])
if __name__ == "__main__":
unittest.main()
+113
View File
@@ -0,0 +1,113 @@
"""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)
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"])
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_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()
+207
View File
@@ -0,0 +1,207 @@
"""Tests for the library import: full, incremental and data preservation."""
import contextlib
import io
import os
import sys
import tempfile
import unittest
from unittest import mock
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
import db
import import_steam
import steam_source
STEAMID = "76561198000000000"
def game_info(name, genres=None, tags=None, metacritic=None, review=None, release=None):
return {
"name": name,
"type": "game",
"genres": genres or {},
"tags": tags or {},
"metacritic": metacritic,
"review_pct": review,
"release": release,
}
class ImportSteamTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = self.tmp.name
self.db_path = os.path.join(self.root, "test.db")
def _run(self, appinfo, playtime=None, installed=None, lib_ids=None,
incremental=False, no_network=True):
playtime = playtime or {}
installed = installed or {}
lib_ids = lib_ids if lib_ids is not None else list(appinfo)
argv = [
"import_steam.py",
"--db", self.db_path,
"--steam-root", self.root,
"--steamid", STEAMID,
]
if incremental:
argv.append("--incremental")
if no_network:
argv.append("--no-network")
patches = [
mock.patch.object(sys, "argv", argv),
mock.patch.object(steam_source, "read_users", return_value=[
{"steamid": STEAMID, "account": "user", "persona": "User", "most_recent": True},
]),
mock.patch.object(steam_source, "library_roots", return_value=[self.root]),
mock.patch.object(steam_source, "library_appids", return_value=lib_ids),
mock.patch.object(steam_source, "read_appinfo", return_value=appinfo),
mock.patch.object(steam_source, "read_playtime", return_value=playtime),
mock.patch.object(steam_source, "installed_apps", return_value=installed),
]
with contextlib.ExitStack() as stack:
for patch in patches:
stack.enter_context(patch)
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
import_steam.main()
con = db.connect(self.db_path)
self.addCleanup(con.close)
return con
def _game(self, con, appid):
return con.execute("SELECT * FROM games WHERE appid = ?", (appid,)).fetchone()
def _personal(self, con, appid):
return con.execute("SELECT * FROM personal WHERE appid = ?", (appid,)).fetchone()
def test_full_import_writes_all_tables(self):
appinfo = {
100: game_info("Alpha", genres={"0": 25, "1": 3, "2": 30}, tags={"0": 10, "1": 20},
metacritic=90, review=95, release=1600000000),
200: game_info("Beta", genres={"0": 23}, tags={"0": 10}, review=80),
}
playtime = {100: {"minutes": 120, "last_played": 1700000000}}
installed = {200: {"name": "Beta", "size_bytes": 1024,
"last_played": "0", "library_path": self.root}}
con = self._run(appinfo, playtime, installed)
alpha = self._game(con, 100)
self.assertEqual(alpha["name"], "Alpha")
self.assertEqual(alpha["type"], "game")
self.assertEqual(alpha["release_date"], "2020-09-13")
self.assertEqual(alpha["metacritic"], 90)
self.assertEqual(alpha["review_pct"], 95)
self.assertEqual({r["genre"] for r in con.execute(
"SELECT genre FROM game_genres WHERE appid = 100")}, {"Adventure", "RPG"})
self.assertEqual({r["tag_id"] for r in con.execute(
"SELECT tag_id FROM game_tags WHERE appid = 100")}, {10, 20})
pt = con.execute("SELECT * FROM game_playtime WHERE appid = 100").fetchone()
self.assertEqual(pt["minutes"], 120)
self.assertEqual(pt["last_played"], "2023-11-14")
self.assertEqual(self._personal(con, 100)["status"], "played")
self.assertEqual(self._personal(con, 200)["status"], "backlog")
alpha_install = con.execute("SELECT * FROM game_install WHERE appid = 100").fetchone()
beta_install = con.execute("SELECT * FROM game_install WHERE appid = 200").fetchone()
self.assertEqual(alpha_install["installed"], 0)
self.assertEqual(beta_install["installed"], 1)
self.assertEqual(beta_install["size_bytes"], 1024)
meta = {r["key"]: r["value"] for r in con.execute("SELECT * FROM schema_meta")}
self.assertEqual(meta["steamid"], STEAMID)
self.assertEqual(meta["steam_root"], self.root)
self.assertIn("imported_at", meta)
def test_incremental_keeps_metadata_and_preserves_personal(self):
con = self._run({100: game_info("Old Name", review=80)})
con.execute(
"UPDATE personal SET status='ignore', rating=8, favorite=1, notes='keep me' WHERE appid=100")
con.commit()
self._run(
{
100: game_info("New Name", review=99),
300: game_info("Gamma", review=70),
},
playtime={100: {"minutes": 600, "last_played": 0}},
installed={100: {"name": "New Name", "size_bytes": 2048,
"last_played": "0", "library_path": self.root}},
incremental=True,
)
con = db.connect(self.db_path)
self.addCleanup(con.close)
self.assertEqual(self._game(con, 100)["name"], "Old Name")
self.assertEqual(self._game(con, 100)["review_pct"], 80)
self.assertEqual(con.execute(
"SELECT minutes FROM game_playtime WHERE appid = 100").fetchone()["minutes"], 600)
self.assertEqual(con.execute(
"SELECT installed FROM game_install WHERE appid = 100").fetchone()["installed"], 1)
personal = self._personal(con, 100)
self.assertEqual(personal["status"], "ignore")
self.assertEqual(personal["rating"], 8)
self.assertEqual(personal["favorite"], 1)
self.assertEqual(personal["notes"], "keep me")
self.assertEqual(self._game(con, 300)["name"], "Gamma")
self.assertEqual(self._personal(con, 300)["status"], "backlog")
def test_full_import_preserves_personal_attributes_and_translations(self):
con = self._run({100: game_info("Initial", review=80)})
con.execute(
"UPDATE personal SET status='playing', rating=9, favorite=1, notes='mine' WHERE appid=100")
con.execute("INSERT INTO attributes (appid, key, value) VALUES (100, 'mood', 'nostalgia')")
con.execute("""INSERT INTO game_translations
(appid, lang, short_description, about, provider, translated_at)
VALUES (100, 'ru', 'Кратко', 'Полно', 'google', '2026-01-01')""")
con.commit()
self._run({100: game_info("Renamed", review=95)})
con = db.connect(self.db_path)
self.addCleanup(con.close)
self.assertEqual(self._game(con, 100)["name"], "Renamed")
personal = self._personal(con, 100)
self.assertEqual(personal["status"], "playing")
self.assertEqual(personal["rating"], 9)
self.assertEqual(personal["favorite"], 1)
self.assertEqual(personal["notes"], "mine")
self.assertEqual(con.execute(
"SELECT value FROM attributes WHERE appid=100 AND key='mood'").fetchone()["value"],
"nostalgia")
translation = con.execute("SELECT * FROM game_translations WHERE appid=100").fetchone()
self.assertEqual(translation["short_description"], "Кратко")
self.assertEqual(translation["about"], "Полно")
def test_tag_names_downloaded_when_network_enabled(self):
with mock.patch.object(import_steam, "fetch_tag_names", return_value={10: "RPG"}):
con = self._run({100: game_info("Alpha")}, no_network=False)
self.assertEqual(
con.execute("SELECT name FROM tag_names WHERE tag_id=10").fetchone()["name"], "RPG")
class IsoFromUnixTests(unittest.TestCase):
def test_none_and_zero(self):
self.assertIsNone(import_steam.iso_from_unix(None))
self.assertIsNone(import_steam.iso_from_unix(0))
def test_utc_date(self):
self.assertEqual(import_steam.iso_from_unix(1700000000), "2023-11-14")
if __name__ == "__main__":
unittest.main()
+45
View File
@@ -0,0 +1,45 @@
"""Tests for the background job manager."""
import os
import sys
import time
import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
sys.path.insert(0, os.path.join(ROOT, "web"))
import server
class JobManagerTests(unittest.TestCase):
def wait_for(self, predicate, timeout=5):
deadline = time.time() + timeout
while time.time() < deadline:
if predicate():
return True
time.sleep(0.05)
return False
def test_start_cancel_and_finish(self):
jobs = server.JobManager()
self.assertTrue(jobs.start("test", ["-c", "import time; time.sleep(30)"]))
try:
self.assertTrue(self.wait_for(lambda: jobs.status()["running"]))
self.assertFalse(jobs.start("test", ["-c", "pass"]), "only one job at a time")
self.assertTrue(jobs.cancel())
self.assertTrue(self.wait_for(lambda: not jobs.status()["running"]))
state = jobs.status()
self.assertTrue(state["cancelled"])
self.assertIsNotNone(state["finished_at"])
self.assertFalse(jobs.cancel(), "nothing left to cancel")
finally:
jobs.cancel()
def test_cancel_without_job(self):
jobs = server.JobManager()
self.assertFalse(jobs.cancel())
if __name__ == "__main__":
unittest.main()
+179
View File
@@ -0,0 +1,179 @@
"""Tests for mood parsing, recommendations and similar games."""
import os
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
import reco
class RecoFixture(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.con = db.connect(os.path.join(self.tmp.name, "reco.db"))
self.addCleanup(self.con.close)
db.init(self.con)
db.seed_moods(self.con)
self._seed()
def _seed(self):
con = self.con
games = [
# appid, name, type, review, metacritic, release
(1, "Alpha", "game", 90, 90, "2020-05-01"),
(2, "Beta", "game", 85, 85, "2019-01-01"),
(3, "Gamma", "game", 95, 95, "2018-01-01"),
(4, "Delta", "game", 70, 70, "2021-01-01"),
(5, "Ignored", "game", 99, 99, "2017-01-01"),
(6, "Unknown", "game", None, None, None),
(7, "Tool", "tool", 99, 99, "2016-01-01"),
(8, "NoTags", "game", 80, 80, "2015-01-01"),
]
con.executemany(
"INSERT INTO games (appid, name, type, review_pct, metacritic, release_date) VALUES (?,?,?,?,?,?)",
games,
)
playtime = [
(1, 0, None), (2, 0, None), (3, 0, None), (4, 600, "2026-01-01"),
(5, 0, None), (6, 0, None), (7, 0, None), (8, 0, None),
]
con.executemany("INSERT INTO game_playtime (appid, minutes, last_played) VALUES (?,?,?)", playtime)
con.execute("INSERT INTO game_install (appid, installed) VALUES (1, 1)")
personal = [(5, "ignore", None, 0), (4, "played", 8, 0), (1, "backlog", None, 0)]
con.executemany(
"INSERT INTO personal (appid, status, rating, favorite) VALUES (?,?,?,?)", personal)
tags = {1: [1, 2, 3], 2: [1, 2], 3: [4], 4: [1, 2, 3],
5: [1, 2, 3], 6: [1, 2, 3], 7: [1, 2, 3]}
con.executemany(
"INSERT INTO game_tags (appid, tag_id) VALUES (?,?)",
[(appid, tag) for appid, ids in tags.items() for tag in ids])
con.executemany(
"INSERT INTO tag_names (tag_id, name) VALUES (?,?)",
[(1, "RPG"), (2, "Party-Based RPG"), (3, "Dungeon Crawler"), (4, "Horror")])
genres = {1: ["RPG", "Adventure"], 2: ["RPG"], 3: ["Horror"], 4: ["RPG"],
5: ["RPG"], 6: ["RPG"], 7: ["RPG"]}
con.executemany(
"INSERT INTO game_genres (appid, genre) VALUES (?,?)",
[(appid, genre) for appid, names in genres.items() for genre in names])
con.commit()
def mood(self):
return {
"description": "test",
"genres": ["RPG", "Adventure"],
"tags": {"RPG": 1.0, "Party-Based RPG": 1.3, "Dungeon Crawler": 1.2},
}
def names(self, results):
return [g["name"] for g in results]
class MoodTests(RecoFixture):
def test_russian_text(self):
mood = reco.mood_from_text("рпг про подземелья и отряд")
self.assertEqual(mood["tags"]["RPG"], 1.0)
self.assertEqual(mood["tags"]["Dungeon Crawler"], 1.2)
self.assertEqual(mood["tags"]["Party-Based RPG"], 1.3)
self.assertEqual(mood["genres"], ["RPG", "Adventure"])
def test_english_text(self):
mood = reco.mood_from_text("dark fantasy coop horror")
self.assertIn("Dark Fantasy", mood["tags"])
self.assertIn("Co-op", mood["tags"])
self.assertIn("Horror", mood["tags"])
self.assertEqual(mood["description"], "dark fantasy coop horror")
def test_empty_text(self):
mood = reco.mood_from_text("")
self.assertEqual(mood, {"description": "", "genres": [], "tags": {}})
def test_load_preset(self):
mood = reco.load_mood(self.con, preset="dark-fantasy")
self.assertEqual(mood["preset"], "dark-fantasy")
self.assertIn("Dark Fantasy", mood["tags"])
def test_load_missing_preset(self):
with self.assertRaises(KeyError):
reco.load_mood(self.con, preset="nope")
def test_load_text_and_empty(self):
mood = reco.load_mood(self.con, text="кооп")
self.assertIn("Co-op", mood["tags"])
with self.assertRaises(ValueError):
reco.load_mood(self.con)
class RecommendTests(RecoFixture):
def test_default_excludes_unknown_ignored_and_non_games(self):
_, results = reco.recommend(self.con, self.mood(), limit=10)
names = self.names(results)
self.assertEqual(names[0], "Alpha")
self.assertEqual(set(names), {"Alpha", "Beta", "Gamma", "Delta", "NoTags"})
self.assertNotIn("Ignored", names)
self.assertNotIn("Unknown", names)
self.assertNotIn("Tool", names)
alpha = results[0]
self.assertEqual(alpha["matched"], ["RPG", "Party-Based RPG", "Dungeon Crawler"])
self.assertTrue(alpha["installed"])
self.assertEqual(alpha["review"], 90)
self.assertEqual(alpha["hours"], 0.0)
def test_unplayed_only(self):
_, results = reco.recommend(self.con, self.mood(), unplayed_only=True)
self.assertEqual(set(self.names(results)), {"Alpha", "Beta", "Gamma", "NoTags"})
def test_min_review(self):
_, results = reco.recommend(self.con, self.mood(), min_review=95)
self.assertEqual(self.names(results), ["Gamma"])
def test_allowed_statuses(self):
_, results = reco.recommend(self.con, self.mood(), allowed_statuses=["ignore"])
self.assertEqual(self.names(results), ["Ignored"])
def test_allow_unknown(self):
_, results = reco.recommend(self.con, self.mood(), allow_unknown=True, limit=10)
self.assertIn("Unknown", self.names(results))
def test_limit(self):
_, results = reco.recommend(self.con, self.mood(), limit=2)
self.assertEqual(len(results), 2)
def test_no_eligible_games(self):
mood, results = reco.recommend(self.con, self.mood(), allowed_statuses=["tribute"])
self.assertEqual(mood["description"], "test")
self.assertEqual(results, [])
class SimilarGamesTests(RecoFixture):
def test_similar_games_by_shared_tags(self):
results = reco.similar_games(self.con, 1, limit=6)
ids = [g["appid"] for g in results]
self.assertEqual(ids[0], 4)
self.assertEqual(set(ids), {2, 4, 6})
self.assertNotIn(1, ids)
self.assertNotIn(5, ids)
self.assertNotIn(7, ids)
delta = results[0]
self.assertEqual(delta["matched"], ["RPG", "Party-Based RPG", "Dungeon Crawler"])
self.assertEqual(delta["year"], 2021)
self.assertEqual(delta["hours"], 10.0)
def test_requires_two_shared_tags(self):
ids = [g["appid"] for g in reco.similar_games(self.con, 3)]
self.assertEqual(ids, [])
def test_unknown_or_untagged_game(self):
self.assertEqual(reco.similar_games(self.con, 999), [])
self.assertEqual(reco.similar_games(self.con, 8), [])
if __name__ == "__main__":
unittest.main()
+257
View File
@@ -0,0 +1,257 @@
"""Tests for the Steam file readers."""
import os
import struct
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 steam_source
class VdfBuilder:
"""Build a binary VDF blob in the appinfo.vdf v29 format."""
def __init__(self):
self._strings = []
self._index = {}
def _idx(self, value):
if value not in self._index:
self._index[value] = len(self._strings)
self._strings.append(value)
return self._index[value]
def _entry(self, kind, key, payload=b""):
return struct.pack("<BI", kind, self._idx(key)) + payload
def obj(self, key, payload):
return self._entry(0x00, key, payload + b"\x08")
def string(self, key, value):
return self._entry(0x01, key, value.encode("utf-8") + b"\x00")
def int32(self, key, value):
return self._entry(0x02, key, struct.pack("<i", value))
def float32(self, key, value):
return self._entry(0x03, key, struct.pack("<f", value))
def uint32(self, key, value, kind=0x04):
return self._entry(kind, key, struct.pack("<I", value))
def uint64(self, key, value):
return self._entry(0x07, key, struct.pack("<Q", value))
def int64(self, key, value):
return self._entry(0x0A, key, struct.pack("<q", value))
def _unique(values):
seen = set()
out = []
for value in values:
if value not in seen:
seen.add(value)
out.append(value)
return out
def make_app(appid, common_payload):
builder = VdfBuilder()
body = builder.obj(
"appinfo",
builder.uint32("appid", appid) + builder.obj("common", common_payload(builder)),
) + b"\x08"
return appid, body, builder._strings
def build_appinfo_from_apps(apps, magic=0x07564429):
"""Return bytes for a synthetic appinfo.vdf built from make_app() records."""
records = b""
strings = []
for appid, payload, app_strings in apps:
records += struct.pack("<II", appid, len(payload) + 60) + b"\x00" * 60 + payload
strings.extend(app_strings)
records += b"\x00" * 8
strings = _unique(strings)
string_table = struct.pack("<I", len(strings))
for value in strings:
string_table += value.encode("utf-8") + b"\x00"
table_offset = 16 + len(records)
header = struct.pack("<IIQ", magic, 0, table_offset)
return header + records + string_table
class AppinfoStringsTests(unittest.TestCase):
def test_reads_count_and_utf8_strings(self):
data = struct.pack("<I", 3) + b"alpha\x00beta\x00\xd0\xb8\xd0\xb3\xd1\x80\xd0\xb0\x00"
self.assertEqual(steam_source._appinfo_strings(data, 0), ["alpha", "beta", "игра"])
def test_empty_table(self):
self.assertEqual(steam_source._appinfo_strings(struct.pack("<I", 0), 0), [])
class AppinfoKvTests(unittest.TestCase):
def _parse(self, payload):
builder = VdfBuilder()
body = builder.obj("root", payload(builder)) + b"\x08"
return steam_source._appinfo_kv(body, 0, builder._strings)[0]["root"]
def test_all_scalar_types(self):
result = self._parse(lambda b: (
b.string("text", "value")
+ b.int32("signed", -7)
+ b.float32("ratio", 1.5)
+ b.uint32("pointer", 11, 0x04)
+ b.uint32("uint", 12, 0x05)
+ b.uint32("color", 13, 0x06)
+ b.uint64("big", 2**40)
+ b.int64("huge", -(2**40))
))
self.assertEqual(result["text"], "value")
self.assertEqual(result["signed"], -7)
self.assertAlmostEqual(result["ratio"], 1.5)
self.assertEqual(result["pointer"], 11)
self.assertEqual(result["uint"], 12)
self.assertEqual(result["color"], 13)
self.assertEqual(result["big"], 2**40)
self.assertEqual(result["huge"], -(2**40))
def test_nested_objects(self):
result = self._parse(lambda b: b.obj("outer", b.string("inner", "x") + b.obj("deep", b.uint32("id", 5))))
self.assertEqual(result["outer"]["inner"], "x")
self.assertEqual(result["outer"]["deep"]["id"], 5)
def test_unknown_type_raises(self):
data = b"\x63" + struct.pack("<I", 0)
with self.assertRaises(ValueError):
steam_source._appinfo_kv(data, 0, ["key"])
class ReadAppinfoTests(unittest.TestCase):
def test_parses_synthetic_file(self):
apps = [
make_app(100, lambda b: (
b.string("name", "Тестовая игра")
+ b.string("type", "Game")
+ b.obj("genres", b.uint32("0", 25) + b.uint32("1", 3))
+ b.obj("store_tags", b.uint32("0", 122) + b.uint32("1", 4747))
+ b.uint32("metacritic_score", 96)
+ b.uint32("review_percentage", 91)
+ b.uint32("steam_release_date", 1691074800)
)),
make_app(200, lambda b: b.string("name", "Tool") + b.string("type", "Tool")),
]
data = build_appinfo_from_apps(apps)
with tempfile.TemporaryDirectory() as root:
os.makedirs(os.path.join(root, "appcache"))
with open(os.path.join(root, "appcache", "appinfo.vdf"), "wb") as fh:
fh.write(data)
result = steam_source.read_appinfo(root)
self.assertEqual(set(result), {100, 200})
game = result[100]
self.assertEqual(game["name"], "Тестовая игра")
self.assertEqual(game["type"], "Game")
self.assertEqual(game["genres"], {"0": 25, "1": 3})
self.assertEqual(game["tags"], {"0": 122, "1": 4747})
self.assertEqual(game["metacritic"], 96)
self.assertEqual(game["review_pct"], 91)
self.assertEqual(game["release"], 1691074800)
self.assertEqual(result[200]["tags"], {})
def test_skips_malformed_records_and_continues(self):
good = make_app(300, lambda b: b.string("name", "Good"))
junk = (301, b"\x63" + struct.pack("<I", 0), [])
data = build_appinfo_from_apps([junk, good])
with tempfile.TemporaryDirectory() as root:
os.makedirs(os.path.join(root, "appcache"))
with open(os.path.join(root, "appcache", "appinfo.vdf"), "wb") as fh:
fh.write(data)
result = steam_source.read_appinfo(root)
self.assertEqual(set(result), {300})
self.assertEqual(result[300]["name"], "Good")
def test_missing_file_returns_empty(self):
with tempfile.TemporaryDirectory() as root:
self.assertEqual(steam_source.read_appinfo(root), {})
def test_rejects_unsupported_version(self):
data = build_appinfo_from_apps([], magic=0x07564428)
with tempfile.TemporaryDirectory() as root:
os.makedirs(os.path.join(root, "appcache"))
with open(os.path.join(root, "appcache", "appinfo.vdf"), "wb") as fh:
fh.write(data)
with self.assertRaises(SystemExit):
steam_source.read_appinfo(root)
def test_real_steam_file(self):
try:
root = steam_source.find_steam_root()
except SystemExit:
self.skipTest("Steam is not installed")
path = os.path.join(root, "appcache", "appinfo.vdf")
if not os.path.isfile(path):
self.skipTest("appinfo.vdf is not present")
result = steam_source.read_appinfo(root)
self.assertIsInstance(result, dict)
self.assertTrue(result, "real appinfo.vdf should contain apps")
expected_keys = {"name", "type", "genres", "tags", "metacritic", "review_pct", "release"}
for appid, info in result.items():
self.assertIsInstance(appid, int)
self.assertEqual(set(info), expected_keys)
self.assertIsInstance(info["genres"], dict)
self.assertIsInstance(info["tags"], dict)
self.assertTrue(any(info["name"] for info in result.values()))
named_genres = [info for info in result.values() if info["genres"]]
self.assertTrue(named_genres, "real appinfo.vdf should contain genres")
for info in named_genres:
self.assertTrue(all(isinstance(v, int) for v in info["genres"].values()))
class FindCoverTests(unittest.TestCase):
def _touch(self, path):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as fh:
fh.write(b"x")
def test_flat_layout(self):
with tempfile.TemporaryDirectory() as cache:
self._touch(os.path.join(cache, "10", "header.jpg"))
self.assertEqual(steam_source.find_cover(10, cache), os.path.join(cache, "10", "header.jpg"))
def test_hashed_layout(self):
with tempfile.TemporaryDirectory() as cache:
path = os.path.join(cache, "11", "abcdef", "library_capsule.jpg")
self._touch(path)
self.assertEqual(steam_source.find_cover(11, cache), path)
def test_prefers_best_cover_across_layouts(self):
with tempfile.TemporaryDirectory() as cache:
self._touch(os.path.join(cache, "12", "hash", "header.jpg"))
best = os.path.join(cache, "12", "library_600x900.jpg")
self._touch(os.path.join(cache, "12", "library_capsule.jpg"))
self._touch(best)
self.assertEqual(steam_source.find_cover(12, cache), best)
def test_missing_cover_returns_none(self):
with tempfile.TemporaryDirectory() as cache:
self.assertIsNone(steam_source.find_cover(13, cache))
self.assertIsNone(steam_source.find_cover(13, None))
self.assertIsNone(steam_source.find_cover(13, os.path.join(cache, "nope")))
if __name__ == "__main__":
unittest.main()