340 lines
14 KiB
Python
340 lines
14 KiB
Python
"""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()
|