"""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.parse import urllib.request from http.server import ThreadingHTTPServer from types import SimpleNamespace 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) db.refresh_search_index(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.steam_patch = mock.patch.object(server.steam_api, "has_key", return_value=False) cls.steam_patch.start() cls.server_config = os.path.join(cls.tmp.name, "server.json") cls.server_patch = mock.patch.object(server, "SERVER_CONFIG", cls.server_config) cls.server_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.server_patch.stop() cls.steam_patch.stop() 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) con.execute("INSERT INTO games (appid, name, type, parent_appid) " "VALUES (5, 'Alpha DLC', 'dlc', 1)") con.execute("INSERT INTO game_playtime (appid, minutes) VALUES (5, 0)") con.execute("INSERT INTO game_ownership (appid, owned, checked_at) " "VALUES (1, 1, '2026-01-01')") con.execute("INSERT INTO game_ownership (appid, owned, checked_at) " "VALUES (2, 0, '2026-01-01')") 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.executemany( "INSERT INTO game_tags (appid, tag_id) VALUES (?,?)", [(2, 100 + i) for i in range(12)]) con.executemany( "INSERT INTO tag_names (tag_id, name) VALUES (?,?)", [(100 + i, f"Tag {i:02d}") for i in range(12)]) con.execute( """INSERT INTO game_details (appid, short_description, about, header_image, developers, publishers, release_date, lang, fetched_at, status) VALUES (1, 'Short text', '
About text
', '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.execute("""UPDATE games SET estimated_hours = CASE appid WHEN 1 THEN 30 WHEN 2 THEN 10 WHEN 3 THEN 5 ELSE NULL END""") con.execute("""UPDATE games SET hltb_main = 23.5, hltb_extra = 30.0, hltb_complete = 50.0, hltb_checked_at = '2026-01-01', hltb_match = 1 WHERE appid = 1""") con.execute("""UPDATE games SET hltb_checked_at = '2026-01-02', hltb_match = 0 WHERE appid = 2""") con.commit() def get(self, path, expect=200): url = self.base + urllib.parse.quote(path, safe="/?=&%:,") try: with urllib.request.urlopen(url, 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 delete(self, path, expect=200): req = urllib.request.Request(self.base + path, method="DELETE") 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 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}) self.assertEqual(data["signals"], 1) self.assertEqual(data["hltb_checked"], 2) self.assertEqual(data["hltb_matched"], 1) self.assertEqual(data["unnamed_tags"], 0) self.assertEqual(data["owned"], 1) self.assertEqual(data["shared"], 1) self.assertRegex(data["version"], r"^\d+\.\d+\.\d+") self.assertFalse(data["steam_api"]) genres = {g["name"]: g["count"] for g in data["genres"]} self.assertEqual(genres["Ролевые игры"], 2) tags = {t["name"]: t["count"] for t in data["tags"]} self.assertEqual(tags["RPG"], 2) def test_hltb_status_page(self): data = self.get("/api/hltb/status") self.assertEqual(data["checked"], 2) self.assertEqual(data["matched"], 1) self.assertEqual(data["total"], 2) statuses = {item["appid"]: item["status"] for item in data["items"]} self.assertEqual(statuses, {1: "match", 2: "miss"}) only_match = self.get("/api/hltb/status?status=match") self.assertEqual(only_match["total"], 1) self.assertEqual(only_match["items"][0]["appid"], 1) self.assertEqual(only_match["items"][0]["main"], 23.5) only_miss = self.get("/api/hltb/status?status=miss") self.assertEqual(only_miss["items"][0]["appid"], 2) self.assertEqual(self.get("/api/hltb/status?q=Alpha")["total"], 1) self.assertEqual(self.get("/api/hltb/status?limit=1&offset=1")["items"][0]["appid"], 1) 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.assertEqual(alpha["duration"], 30) 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"], ["Приключенческие игры", "Ролевые игры"]) 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_multi_value_filters(self): self.assertEqual( {g["appid"] for g in self.get("/api/games?genre=RPG&genre=Horror")["items"]}, {1, 2, 3}) self.assertEqual( {g["appid"] for g in self.get("/api/games?genre=RPG,Horror")["items"]}, {1, 2, 3}) self.assertEqual( {g["appid"] for g in self.get("/api/games?tag=RPG&tag=Horror")["items"]}, {1, 2, 3}) self.assertEqual( {g["appid"] for g in self.get("/api/games?genre=RPG&tag=Party-Based%20RPG")["items"]}, {1, 2}) self.assertEqual( server.multi_values({"genre": ["RPG, Horror", "RPG"]}, "genre"), ["RPG", "Horror"]) def test_search_by_name_description_tags_and_translation(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?q=Short")["items"]], [1]) self.assertEqual([g["appid"] for g in self.get("/api/games?q=About")["items"]], [1]) self.assertEqual([g["appid"] for g in self.get("/api/games?q=Party")["items"]], [1, 2]) self.assertEqual([g["appid"] for g in self.get("/api/games?q=Кратко")["items"]], [1]) self.assertEqual(self.get("/api/games?q=заметка")["items"], []) self.assertEqual(self.get("/api/games?q=%%%")["items"], []) def test_search_name_only(self): self.assertEqual( [g["appid"] for g in self.get("/api/games?q=Alpha&name_only=1")["items"]], [1]) self.assertEqual( self.get("/api/games?q=Short&name_only=1")["items"], []) self.assertEqual( [g["appid"] for g in self.get("/api/games?q=Short")["items"]], [1]) def test_range_filters(self): def ids(query): return {g["appid"] for g in self.get(query)["items"]} self.assertEqual(ids("/api/games?min_hours=1"), {1}) self.assertEqual(ids("/api/games?max_hours=0.6"), {2, 3}) self.assertEqual(ids("/api/games?min_year=2020"), {1}) self.assertEqual(ids("/api/games?max_year=2019"), {2}) self.assertEqual(ids("/api/games?min_year=2019&max_year=2020"), {1, 2}) self.assertEqual(ids("/api/games?min_review=80"), {1, 2}) self.assertEqual(ids("/api/games?max_review=85"), {2, 3}) self.assertEqual(ids("/api/games?min_review=80&max_hours=1"), {2}) self.assertEqual(ids("/api/games?min_hours=oops&min_review="), {1, 2, 3}) self.assertEqual(ids("/api/games?duration=short"), {3}) self.assertEqual(ids("/api/games?duration=medium"), {1, 2}) self.assertEqual(ids("/api/games?duration=long"), set()) self.assertEqual(ids("/api/games?min_duration=10"), {1, 2}) self.assertEqual(ids("/api/games?max_duration=6"), {3}) self.assertEqual(ids("/api/games?min_duration=10&max_duration=24"), {1, 2}) self.assertEqual(server.number_param({"x": ["bad"]}, "x", int), None) self.assertEqual(server.number_param({"x": ["7"]}, "x", int), 7) def test_release_year_parser(self): self.assertEqual(server.release_year("1 янв. 2000 г."), 2000) self.assertEqual(server.release_year("2023-05-01"), 2023) self.assertIsNone(server.release_year("Coming soon")) self.assertIsNone(server.release_year(None)) def test_fts_query_builder(self): self.assertEqual(server.fts_query("Baldur's Gate"), '"baldur"* "gate"*') self.assertEqual(server.fts_query("Bullet Heaven", name_only=True), 'name : "bullet"* "heaven"*') self.assertEqual(server.fts_query(" "), "") self.assertEqual(server.fts_query("!!! ???"), "") 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]) self.assertEqual([g["appid"] for g in self.get("/api/games?sort=duration")["items"]], [3, 2, 1]) self.assertEqual([g["appid"] for g in self.get("/api/games?sort=review&dir=asc")["items"]], [3, 2, 1]) self.assertEqual([g["appid"] for g in self.get("/api/games?sort=name&dir=desc")["items"]], [3, 2, 1]) self.assertEqual([g["appid"] for g in self.get("/api/games?sort=favorite")["items"]], [1, 2, 3]) self.assertEqual([g["appid"] for g in self.get("/api/games?sort=genre")["items"]], [3, 1, 2]) self.assertEqual([g["appid"] for g in self.get("/api/games?sort=genre&dir=desc")["items"]], [2, 1, 3]) page2 = self.get("/api/games?per_page=12&page=2") self.assertEqual(page2["page"], 2) self.assertEqual(page2["items"], []) def test_feedback_and_exclusion(self): try: data = self.post("/api/feedback", { "appid": 1, "verdict": "dislike", "preset": "dark-fantasy"}) self.assertTrue(data["saved"]) self.assertEqual(data["key"], "preset:dark-fantasy") rec = self.post("/api/recommend", {"preset": "dark-fantasy", "limit": 20}) self.assertNotIn(1, [g["appid"] for g in rec["results"]]) data = self.post("/api/feedback", { "appid": 3, "verdict": "played", "preset": "dark-fantasy"}) self.assertTrue(data["saved"]) self.assertEqual(self.get("/api/game/3")["status"], "played") data = self.post("/api/feedback", {"appid": 2, "verdict": "like", "mood": "рпг"}) self.assertTrue(data["key"].startswith("text:")) self.assertEqual(self.post("/api/feedback", {"appid": "x", "verdict": "like"}, expect=400)["error"], "invalid appid") self.assertEqual(self.post("/api/feedback", {"appid": 1, "verdict": "wat"}, expect=400)["error"], "unknown verdict") self.assertEqual(self.post("/api/feedback", {"appid": 1, "verdict": "like"}, expect=400)["error"], "unknown mood") self.assertEqual(self.post("/api/feedback", {"appid": 999, "verdict": "like", "preset": "dark-fantasy"}, expect=404)["error"], "unknown appid") finally: con = db.connect(self.db_path) try: con.execute("DELETE FROM reco_feedback") con.execute("DELETE FROM personal WHERE appid = 3") con.commit() finally: con.close() def test_export_library(self): body, content_type, headers = self.raw_get("/api/export?format=csv") self.assertTrue(content_type.startswith("text/csv")) self.assertIn("attachment", headers.get("Content-Disposition")) text = body.decode("utf-8-sig") lines = text.splitlines() self.assertEqual(len(lines), 4) self.assertTrue(lines[0].startswith("appid,name,type,year")) self.assertIn("Alpha", text) self.assertNotIn("Tool", text) data = self.get("/api/export?format=json") self.assertEqual(len(data), 3) self.assertEqual({item["appid"] for item in data}, {1, 2, 3}) self.assertEqual(data[0]["genres"], ["Приключенческие игры", "Ролевые игры"]) filtered = self.get("/api/export?format=json&genre=RPG") self.assertEqual({item["appid"] for item in filtered}, {1, 2}) self.assertEqual(self.get("/api/export?format=xml", expect=400)["error"], "unknown format") def test_game_card(self): data = self.get("/api/game/1") self.assertEqual(data["name"], "Alpha") self.assertEqual(data["about"], "About text
") 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.assertEqual(data["hltb"], {"main": 23.5, "extra": 30.0, "complete": 50.0}) self.assertTrue(data["similar"]) self.assertEqual(data["similar"][0]["appid"], 2) def test_game_card_returns_all_tags(self): data = self.get("/api/game/2") self.assertEqual(len(data["tags"]), 14) self.assertIn("Tag 11", data["tags"]) def test_games_list_caps_tags(self): data = self.get("/api/games") beta = next(g for g in data["items"] if g["appid"] == 2) self.assertEqual(len(beta["tags"]), 10) def test_localized_tag_names(self): con = db.connect(self.db_path) try: con.execute("UPDATE tag_names SET name_ru='Хоррор' WHERE tag_id=3") con.commit() self.assertEqual(self.get("/api/game/3")["tags"], ["Хоррор"]) meta = {t["name"] for t in self.get("/api/meta")["tags"]} self.assertIn("Хоррор", meta) self.assertNotIn("Horror", meta) self.assertEqual( [g["appid"] for g in self.get("/api/games?tag=Хоррор")["items"]], [3]) self.assertEqual( [g["appid"] for g in self.get("/api/games?tag=Horror")["items"]], [3]) finally: con.execute("UPDATE tag_names SET name_ru=NULL WHERE tag_id=3") con.commit() con.close() def test_mood_tags_localized_and_canonicalized(self): con = db.connect(self.db_path) try: con.execute("UPDATE tag_names SET name_ru='Ролевая игра' WHERE name='RPG'") con.commit() moods = {m["name"]: m for m in self.get("/api/moods")["moods"]} self.assertIn("Ролевая игра", moods["dark-fantasy"]["tags_display"]) self.assertIn("RPG", moods["dark-fantasy"]["tags"]) created = self.post( "/api/moods", {"name": "loc-test", "tags": {"Ролевая игра": 1.5}}) self.assertEqual(created["mood"]["tags"], {"RPG": 1.5}) self.delete("/api/moods/loc-test") finally: con.execute("UPDATE tag_names SET name_ru=NULL WHERE name='RPG'") con.commit() con.close() def test_localized_genres(self): self.assertEqual( {g["appid"] for g in self.get("/api/games?genre=Ролевые игры")["items"]}, {1, 2}) self.assertEqual( {g["appid"] for g in self.get("/api/games?genre=RPG")["items"]}, {1, 2}) meta = {g["name"] for g in self.get("/api/meta")["genres"]} self.assertIn("Ролевые игры", meta) self.assertNotIn("RPG", meta) def test_mood_genres_localized_and_canonicalized(self): moods = {m["name"]: m for m in self.get("/api/moods")["moods"]} self.assertIn("Ролевые игры", moods["dark-fantasy"]["genres_display"]) self.assertIn("RPG", moods["dark-fantasy"]["genres"]) created = self.post( "/api/moods", {"name": "loc-genre", "genres": ["Ролевые игры"], "tags": {"RPG": 1.0}}) self.assertEqual(created["mood"]["genres"], ["RPG"]) self.delete("/api/moods/loc-genre") 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"]) self.assertIsInstance(data["results"][0]["reasons"], list) data = self.post("/api/recommend", {"mood": "рпг приключение", "limit": 5}) self.assertEqual(data["mood"]["description"], "рпг приключение") self.assertIn("RPG", data["mood"]["tags"]) data = self.post("/api/recommend", {"preset": "dark-fantasy", "session": "short", "limit": 5}) self.assertTrue(data["results"]) data = self.post("/api/recommend", {"preset": "horror-night", "time_of_day": "night", "limit": 5}) self.assertTrue(data["results"]) def test_custom_mood_crud(self): try: data = self.post("/api/moods", { "name": "test-cozy", "description": "Тестовый профиль", "genres": ["Simulation"], "tags": {"Cozy": 1.5, "Relaxing": 1.0}}) self.assertFalse(data["builtin"]) self.assertEqual(data["mood"]["tags"]["Cozy"], 1.5) moods = {mood["name"]: mood for mood in self.get("/api/moods")["moods"]} self.assertIn("test-cozy", moods) self.assertFalse(moods["test-cozy"]["builtin"]) self.assertTrue(moods["dark-fantasy"]["builtin"]) updated = self.post("/api/moods", { "name": "test-cozy", "description": "Обновлён", "genres": [], "tags": {"Cozy": 2.0}}) self.assertEqual(updated["mood"]["description"], "Обновлён") self.assertEqual(self.post("/api/moods", {"name": "dark-fantasy", "tags": {"Cozy": 1}}, expect=400)["error"], "builtin profile") self.assertEqual(self.post("/api/moods", {"name": "Bad Name", "tags": {"Cozy": 1}}, expect=400)["error"], "invalid name") self.assertEqual(self.post("/api/moods", {"name": "empty-profile"}, expect=400)["error"], "empty profile") self.assertTrue(self.delete("/api/moods/test-cozy")["deleted"]) moods = {mood["name"] for mood in self.get("/api/moods")["moods"]} self.assertNotIn("test-cozy", moods) self.assertEqual(self.delete("/api/moods/dark-fantasy", expect=400)["error"], "builtin profile") self.assertEqual(self.delete("/api/moods/missing", expect=404)["error"], "unknown profile") finally: con = db.connect(self.db_path) try: con.execute("DELETE FROM moods WHERE name = 'test-cozy'") con.commit() finally: con.close() def test_mood_export_import(self): try: self.post("/api/moods", { "name": "export-one", "description": "Экспорт", "genres": ["RPG"], "tags": {"Cozy": 1.5}}) data = self.get("/api/moods/export") self.assertEqual(data["version"], 1) names = {mood["name"] for mood in data["moods"]} self.assertIn("export-one", names) self.assertIn("dark-fantasy", names) custom = self.get("/api/moods/export?custom=1") custom_names = {mood["name"] for mood in custom["moods"]} self.assertIn("export-one", custom_names) self.assertNotIn("dark-fantasy", custom_names) result = self.post("/api/moods/import", {"moods": [ {"name": "import-one", "description": "Импорт", "genres": ["RPG"], "tags": {"Cozy": 1.2}}, {"name": "export-one", "description": "Обновлён", "genres": [], "tags": {"Relaxing": 1.0}}, {"name": "dark-fantasy", "tags": {"Cozy": 1.0}}, {"name": "Bad Name", "tags": {"Cozy": 1.0}}, "not-a-dict", ]}) self.assertEqual(result["imported"], 1) self.assertEqual(result["updated"], 1) self.assertEqual(len(result["skipped"]), 3) moods = {mood["name"]: mood for mood in self.get("/api/moods")["moods"]} self.assertIn("import-one", moods) self.assertEqual(moods["export-one"]["description"], "Обновлён") self.assertEqual(self.post("/api/moods/import", {"not": "a list"}, expect=400)["error"], "expected list of moods") finally: con = db.connect(self.db_path) try: con.execute("DELETE FROM moods WHERE name IN ('export-one', 'import-one')") con.commit() finally: con.close() def test_ownership_filter_and_card(self): self.assertEqual([g["appid"] for g in self.get("/api/games?ownership=owned")["items"]], [1]) self.assertEqual([g["appid"] for g in self.get("/api/games?ownership=shared")["items"]], [2]) self.assertEqual(self.get("/api/game/1")["owned"], 1) self.assertEqual(self.get("/api/game/2")["owned"], 0) self.assertIsNone(self.get("/api/game/3")["owned"]) def test_game_addons_and_parent(self): game = self.get("/api/game/1") self.assertEqual(game["addons"], [ {"appid": 5, "name": "Alpha DLC", "type": "dlc"}]) self.assertIsNone(game["parent"]) dlc = self.get("/api/game/5") self.assertEqual(dlc["parent"]["appid"], 1) self.assertEqual(dlc["parent"]["name"], "Alpha") def test_steam_friends(self): self.assertEqual(self.get("/api/steam/friends", expect=400)["error"], "Steam API key is not configured") self.assertEqual(self.get("/api/steam/friends/123", expect=400)["error"], "invalid steamid") with mock.patch.object(server.steam_api, "has_key", return_value=True), \ mock.patch.object(server.steam_api, "steam_id", return_value="765"), \ mock.patch.object(server.steam_api, "friends", return_value=[{"steamid": "1", "friend_since": 10}]), \ mock.patch.object(server.steam_api, "player_summaries", return_value=[{ "steamid": "1", "personaname": "Ann", "avatarmedium": "a", "profileurl": "u", "personastate": 1, "lastlogoff": 1700000000, "timecreated": 1200000000}]): data = self.get("/api/steam/friends") self.assertEqual(data["total"], 1) self.assertEqual(data["friends"][0]["name"], "Ann") self.assertEqual(data["friends"][0]["state"], 1) self.assertEqual(data["friends"][0]["lastlogoff"], 1700000000) self.assertEqual(data["friends"][0]["created"], 1200000000) def test_steam_friend_compare(self): with mock.patch.object(server.steam_api, "has_key", return_value=True), \ mock.patch.object(server.steam_api, "owned_games", return_value=[ {"appid": 1, "name": "Alpha", "playtime_forever": 120}, {"appid": 999, "name": "Other", "playtime_forever": 60}]), \ mock.patch.object(server.steam_api, "player_summaries", return_value=[{ "steamid": "76561198000000001", "personaname": "Ann", "personastate": 0, "lastlogoff": 1700000000, "timecreated": 1200000000}]): data = self.get("/api/steam/friends/76561198000000001") self.assertEqual(data["state"], 0) self.assertEqual(data["lastlogoff"], 1700000000) self.assertEqual(data["created"], 1200000000) self.assertEqual(data["common_count"], 1) self.assertEqual(data["common"][0]["appid"], 1) self.assertEqual(data["common"][0]["status"], "playing") self.assertEqual(data["common"][0]["local_hours"], 2.0) self.assertTrue(data["common"][0]["installed"]) self.assertEqual(data["friend_only_count"], 1) self.assertEqual(data["friend_only"][0]["appid"], 999) def test_steam_achievements(self): self.assertEqual(self.get("/api/steam/achievements/1", expect=400)["error"], "Steam API key is not configured") self.assertEqual(self.get("/api/steam/achievements/abc", expect=400)["error"], "invalid appid") payload = {"total": 2, "achieved": 1, "percent": 50.0, "achievements": []} with mock.patch.object(server.steam_api, "has_key", return_value=True), \ mock.patch.object(server.steam_api, "steam_id", return_value="765"), \ mock.patch.object(server.steam_api, "achievements", return_value=payload): self.assertEqual(self.get("/api/steam/achievements/1"), payload) with mock.patch.object(server.steam_api, "has_key", return_value=True), \ mock.patch.object(server.steam_api, "steam_id", return_value="765"), \ mock.patch.object(server.steam_api, "achievements", return_value=None): self.get("/api/steam/achievements/1", expect=404) def test_update_check(self): payload = {"current": "1.0.0", "latest": "v1.1.0", "update_available": True, "url": "https://example/tag", "checked_at": "2026-01-01", "tags": []} with mock.patch.object(server.check_updates, "check", return_value=payload): self.assertEqual(self.get("/api/update"), payload) with mock.patch.object(server.check_updates, "check", side_effect=RuntimeError("offline")): self.assertEqual(self.get("/api/update", expect=502)["error"], "offline") def test_server_config(self): data = self.get("/api/server") self.assertFalse(data["configured"]) self.assertFalse(data["token_set"]) self.assertNotIn("token", data) data = self.post("/api/server", { "url": "https://steambase.example/", "handle": "tester", "token": "secret-token"}) self.assertTrue(data["configured"]) self.assertTrue(data["token_set"]) self.assertEqual(data["url"], "https://steambase.example") self.assertNotIn("token", data) data = self.get("/api/server") self.assertTrue(data["token_set"]) self.assertNotIn("secret-token", json.dumps(data)) data = self.post("/api/server", { "url": "https://steambase.example", "handle": "tester", "token": ""}) self.assertTrue(data["token_set"]) self.assertEqual(self.post("/api/server", { "url": "ftp://bad", "handle": "tester"}, expect=400)["error"], "invalid URL") self.assertEqual(self.post("/api/server", { "url": "https://x", "handle": "Bad Name"}, expect=400)["error"], "invalid handle") data = self.post("/api/server", { "url": "https://steambase.example", "handle": "tester", "clear_token": True}) self.assertFalse(data["token_set"]) self.assertEqual(self.post("/api/server/upload", {}, expect=400)["error"], "server is not configured") def test_server_test(self): self.post("/api/server", { "url": "https://steambase.example", "handle": "tester", "token": "secret"}) class FakeResponse: status = 200 def __enter__(self): return self def __exit__(self, *args): pass original = urllib.request.urlopen def fake_open(request, *args, **kwargs): url = request.full_url if hasattr(request, "full_url") else str(request) if url.startswith("https://steambase.example"): return FakeResponse() return original(request, *args, **kwargs) with mock.patch("urllib.request.urlopen", side_effect=fake_open): data = self.post("/api/server/test", {}) self.assertTrue(data["ok"]) self.assertEqual(data["health"], 200) self.assertEqual(data["ready"], 200) def test_server_upload(self): self.post("/api/server", { "url": "https://steambase.example", "handle": "tester", "token": "secret"}) with mock.patch.object(server.JOBS, "start", return_value=True) as start: data = self.post("/api/server/upload", { "no_notes": True, "include_dlc": True}) self.assertTrue(data["started"]) args = start.call_args.args self.assertEqual(args[0], "snapshot") self.assertIn("--handle", args[1]) self.assertIn("tester", args[1]) self.assertIn("--no-notes", args[1]) self.assertIn("--include-dlc", args[1]) with mock.patch.object(server.JOBS, "start", return_value=False): self.post("/api/server/upload", {}, expect=409) def test_activity_heatmap(self): data = self.get("/api/activity?year=2026") self.assertEqual(data["year"], "2026") self.assertIn("2026", data["years"]) day = next(item for item in data["days"] if item["date"] == "2026-01-01") self.assertEqual(day["games"], 1) self.assertEqual(day["hours"], 2.0) self.assertGreaterEqual(data["max_games"], 1) self.assertEqual(self.get("/api/activity?year=20", expect=400)["error"], "invalid year") def test_recommend_taste_profile(self): data = self.post("/api/recommend", { "preset": "dark-fantasy", "limit": 5, "taste_profile": "solo"}) self.assertIsInstance(data["results"], list) self.assertEqual(self.post("/api/recommend", { "preset": "dark-fantasy", "taste_profile": "nope"}, expect=400)["error"], "unknown taste profile") def test_compare_presets(self): data = self.get("/api/compare?a=dark-fantasy&b=story-heavy&limit=5") self.assertEqual(data["a"], "dark-fantasy") self.assertEqual(data["b"], "story-heavy") self.assertGreaterEqual(data["jaccard"], 0.0) self.assertLessEqual(data["jaccard"], 1.0) common = {game["appid"] for game in data["common"]} only_a = {game["appid"] for game in data["only_a"]} only_b = {game["appid"] for game in data["only_b"]} self.assertFalse(common & only_a) self.assertFalse(common & only_b) self.assertFalse(only_a & only_b) self.assertEqual(self.get("/api/compare?a=dark-fantasy", expect=400)["error"], "two presets required") self.get("/api/compare?a=dark-fantasy&b=missing-preset", expect=404) 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_bulk_update(self): try: data = self.post("/api/personal/bulk", { "appids": [1, 1, 2], "status": "ignore", "favorite": True}) self.assertEqual(data["updated"], 2) previous = {item["appid"]: item for item in data["previous"]} self.assertEqual(previous[1]["status"], "playing") self.assertEqual(previous[2]["status"], "backlog") for appid in (1, 2): item = self.get(f"/api/game/{appid}") self.assertEqual(item["status"], "ignore") self.assertTrue(item["favorite"]) self.assertEqual(self.get("/api/game/1")["rating"], 9) self.assertEqual(self.get("/api/game/1")["notes"], "заметка") restored = self.post("/api/personal/restore", {"items": data["previous"]}) self.assertEqual(restored["updated"], 2) self.assertEqual(self.get("/api/game/1")["status"], "playing") self.assertEqual(self.get("/api/game/2")["status"], "backlog") self.assertEqual(self.post("/api/personal/restore", {"items": []}, expect=400)["error"], "no items") self.assertEqual(self.post("/api/personal/restore", { "items": [{"appid": 1, "status": "bogus"}]}, expect=400)["error"], "no items") self.assertEqual(self.post("/api/personal/restore", { "items": [{"appid": 999, "status": "played"}]}, expect=404)["error"], "unknown appids") self.assertEqual(self.post("/api/personal/bulk", {"appids": []}, expect=400)["error"], "no appids") self.assertEqual(self.post("/api/personal/bulk", {"appids": [1]}, expect=400)["error"], "nothing to update") self.assertEqual(self.post("/api/personal/bulk", {"appids": [999], "status": "played"}, expect=404)["error"], "unknown appids") finally: con = db.connect(self.db_path) try: con.execute("""UPDATE personal SET status='playing', rating=9, favorite=1, notes='заметка' WHERE appid=1""") con.execute("""UPDATE personal SET status='backlog', rating=NULL, favorite=0, notes=NULL WHERE appid=2""") con.commit() finally: con.close() def test_hide_scope_by_tag_and_undo(self): try: data = self.post("/api/personal/hide-scope", {"scope": "tag", "tag": "Horror"}) self.assertEqual(data["updated"], 1) self.assertEqual(data["appids"], [3]) self.assertEqual(self.get("/api/game/3")["status"], "ignore") restored = self.post("/api/personal/restore", {"items": data["previous"]}) self.assertEqual(restored["updated"], 1) self.assertEqual(self.get("/api/game/3")["status"], "backlog") self.assertEqual(self.post("/api/personal/hide-scope", {"scope": "bad"}, expect=400)["error"], "unknown scope") self.assertEqual(self.post("/api/personal/hide-scope", { "scope": "tag", "tag": ""}, expect=400)["error"], "empty tag") self.assertEqual(self.post("/api/personal/hide-scope", { "scope": "series", "appid": 999}, expect=404)["error"], "unknown appid") 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_cover_prefers_webp_preview(self): with tempfile.TemporaryDirectory() as covers_dir, \ mock.patch.object(server, "CACHE_DIR", covers_dir): app_dir = os.path.join(covers_dir, "1") os.makedirs(app_dir) with open(os.path.join(app_dir, "header.jpg"), "wb") as fh: fh.write(b"jpeg-bytes") with open(os.path.join(app_dir, "preview.webp"), "wb") as fh: fh.write(b"webp-bytes") body, content_type, _ = self.raw_get("/api/cover/1") self.assertEqual(body, b"webp-bytes") self.assertEqual(content_type, "image/webp") 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_pwa_assets(self): body, content_type, _ = self.raw_get("/static/site.webmanifest") self.assertTrue(content_type.startswith("application/manifest+json")) manifest = json.loads(body) self.assertEqual(manifest["name"], "SteamBase") self.assertEqual(manifest["start_url"], "/") sizes = {icon["sizes"] for icon in manifest["icons"]} self.assertEqual(sizes, {"192x192", "512x512"}) body, content_type, _ = self.raw_get("/sw.js") self.assertTrue(content_type.startswith("application/javascript")) self.assertIn(b"addEventListener", body) body, content_type, _ = self.raw_get("/static/icon-192.png") self.assertEqual(content_type, "image/png") self.assertTrue(body.startswith(b"\x89PNG\r\n\x1a\n")) html, _, _ = self.raw_get("/") self.assertIn(b"site.webmanifest", html) self.assertIn(b'id="themeToggle"', html) 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], 5) 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"]) self.assertFalse(self.post("/api/job/pause", {}, expect=200)["paused"]) self.assertFalse(self.post("/api/job/resume", {}, expect=200)["paused"]) def test_job_retry_without_job(self): data = self.post("/api/job/retry", {}, expect=200) self.assertFalse(data["started"]) def test_hltb_requires_optional_package(self): with mock.patch.object(server.importlib.util, "find_spec", return_value=None): data = self.post("/api/hltb", {"limit": 5}, expect=400) self.assertIn("howlongtobeatpy", data["error"]) def test_hltb_manual_match(self): entry = SimpleNamespace(main_story=10.0, main_extra=12.0, completionist=15.0, game_id=999) class FakeSearch: def search_from_id(self, hltb_id): return entry if hltb_id == 999 else None try: with mock.patch.object(server.importlib.util, "find_spec", return_value=object()), \ mock.patch.object(server.fetch_hltb, "HowLongToBeat", return_value=FakeSearch()): data = self.post("/api/hltb/match", {"appid": 2, "hltb_id": 999}) self.assertEqual(data["estimated_hours"], 10.0) self.assertEqual(self.post("/api/hltb/match", { "appid": 2, "hltb_id": 0}, expect=400)["error"], "invalid HLTB id") self.post("/api/hltb/match", {"appid": 2, "hltb_id": 123}, expect=404) con = db.connect(self.db_path) try: row = con.execute( "SELECT hltb_main, hltb_match, hltb_id FROM games WHERE appid = 2" ).fetchone() finally: con.close() self.assertEqual(row["hltb_main"], 10.0) self.assertEqual(row["hltb_match"], 1) self.assertEqual(row["hltb_id"], 999) finally: con = db.connect(self.db_path) try: con.execute( """UPDATE games SET hltb_main = NULL, hltb_extra = NULL, hltb_complete = NULL, hltb_id = NULL, hltb_checked_at = '2026-01-02', hltb_match = 0, hltb_updated_at = NULL, estimated_hours = 10 WHERE appid = 2""") con.commit() finally: con.close() def test_server_config_hides_token(self): with mock.patch.object( server, "read_server_config", return_value={"url": "https://s", "token": "secret", "handle": "h"}): data = self.get("/api/server") self.assertEqual(data["url"], "https://s") self.assertEqual(data["handle"], "h") self.assertTrue(data["token_set"]) self.assertTrue(data["configured"]) self.assertNotIn("token", data) self.assertNotIn("secret", json.dumps(data)) def test_server_config_requires_token(self): with mock.patch.object( server, "read_server_config", return_value={"url": "https://s", "handle": "h"}): data = self.get("/api/server") self.assertFalse(data["configured"]) self.assertFalse(data["token_set"]) def test_server_save_keeps_existing_token(self): saved = {} with mock.patch.object(server, "read_server_config", return_value={"token": "old"}), \ mock.patch.object(server, "write_server_config", side_effect=saved.update): data = self.post("/api/server", {"url": "https://s/", "handle": "strsv"}) self.assertEqual(saved["url"], "https://s") self.assertEqual(saved["token"], "old") self.assertEqual(saved["handle"], "strsv") self.assertTrue(data["configured"]) def test_server_save_clear_token(self): saved = {} with mock.patch.object(server, "read_server_config", return_value={"token": "old"}), \ mock.patch.object(server, "write_server_config", side_effect=saved.update): data = self.post("/api/server", { "url": "https://s", "handle": "strsv", "clear_token": True}) self.assertNotIn("token", saved) self.assertFalse(data["configured"]) def test_server_save_rejects_bad_url(self): with mock.patch.object(server, "read_server_config", return_value={}), \ mock.patch.object(server, "write_server_config"): self.post("/api/server", {"url": "ftp://x"}, expect=400) def test_server_upload_requires_config(self): with mock.patch.object(server, "read_server_config", return_value={}): self.post("/api/server/upload", {}, expect=400) def test_server_upload_starts_job(self): with mock.patch.object( server, "read_server_config", return_value={"url": "https://s", "token": "t", "handle": "tester"}), \ mock.patch.object(server.JOBS, "start", return_value=True) as start: data = self.post("/api/server/upload", {}) self.assertTrue(data["started"]) self.assertEqual(start.call_args.args[0], "snapshot") def test_server_test_endpoint(self): class _Response: status = 200 def __enter__(self): return self def __exit__(self, *args): return False real_urlopen = urllib.request.urlopen base = self.base def routing_urlopen(request, *args, **kwargs): url = getattr(request, "full_url", str(request)) if url.startswith(base): return real_urlopen(request, *args, **kwargs) return _Response() with mock.patch.object( server, "read_server_config", return_value={"url": "https://s", "token": "t", "handle": "h"}), \ mock.patch.object(server.urllib.request, "urlopen", side_effect=routing_urlopen): data = self.post("/api/server/test", {}) self.assertTrue(data["ok"]) self.assertEqual(data["health"], 200) self.assertEqual(data["ready"], 200) if __name__ == "__main__": unittest.main()