Files
SteamBase/tests/test_api.py
T
strsv 528fcb7474
CI / test (push) Successful in 32s
feat: link DLC and soundtracks to parent games
Add games.parent_appid (schema v9), parse appinfo parent links, show addons and parent game in the card, and add import_steam.py --refresh-parents for existing databases.
2026-11-07 01:36:26 +03:00

807 lines
39 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.
"""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 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.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.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)")
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.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.assertFalse(data["steam_api"])
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_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"], ["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_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_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"), {2})
self.assertEqual(ids("/api/games?duration=long"), {1})
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(" "), "")
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"]], [1, 3, 2])
self.assertEqual([g["appid"] for g in self.get("/api/games?sort=genre&dir=desc")["items"]], [2, 3, 1])
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"], ["Adventure", "RPG"])
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"], "<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.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_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_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}]):
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)
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"}]):
data = self.get("/api/steam/friends/76561198000000001")
self.assertEqual(data["common_count"], 1)
self.assertEqual(data["common"][0]["appid"], 1)
self.assertEqual(data["common"][0]["status"], "playing")
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_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"])
if __name__ == "__main__":
unittest.main()