This commit is contained in:
latypov committed 2026-11-23 23:55:37 +07:00
commit 2ca7a264b3
53 files changed
+7113

No files matched your search

+125
View File
@@ -0,0 +1,125 @@
import random
import tempfile
import unittest
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from unittest.mock import patch
from fastapi.testclient import TestClient
from game import api, engine
from game.store import Database
from game.strategy import decide
class Contract(unittest.TestCase):
def setUp(self):
self.folder = tempfile.TemporaryDirectory()
self.addCleanup(self.folder.cleanup)
store = Database()
store.dsn = None
store.path = str(Path(self.folder.name) / "games.db")
mock = patch.object(api, "db", store)
mock.start()
self.addCleanup(mock.stop)
store.init()
self.c = TestClient(api.app)
self.addCleanup(self.c.close)
self.c.get("/api/games")
new_game = engine.new_game
def fixture(bots, color):
state = new_game(bots, color, random.Random(42))
state["active"] = 0
return state
with patch.object(engine, "new_game", fixture):
response = self.c.post("/api/games", json={"bots": 3, "color": "red"})
self.assertEqual(response.status_code, 201)
self.url = "/api/games/" + response.json()["id"]
def test_private_views(self):
v = self.c.get(self.url).json()["view"]
self.assertNotIn("hands", v)
self.assertNotIn("deck", v)
self.assertEqual(self.c.get(self.url + "/export").status_code, 403)
self.assertEqual(
self.c.get(self.url + "/replay?perspective=full").status_code, 403
)
self.assertEqual(
self.c.get(self.url + "/replay?perspective=1").status_code, 403
)
other = TestClient(api.app)
self.addCleanup(other.close)
self.assertEqual(other.get(self.url).status_code, 404)
self.assertEqual(other.get("/api/games").json(), [])
def test_competing_requests_and_restart(self):
s = self.c.get(self.url).json()
cmd = decide(s)["command"]
base = dict(command=cmd, expected_version=s["version"])
packets = [dict(**base, command_id=str(uuid.uuid4())) for _ in range(2)]
with ThreadPoolExecutor(max_workers=2) as pool:
answers = list(
pool.map(lambda p: self.c.post(self.url + "/commands", json=p), packets)
)
self.assertEqual(sorted(r.status_code for r in answers), [200, 409])
i = next(i for i, r in enumerate(answers) if r.status_code == 200)
self.assertEqual(
self.c.post(self.url + "/commands", json=packets[i]).json(),
answers[i].json(),
)
changed = {**packets[i], "command": {"kind": "bad"}}
self.assertEqual(
self.c.post(self.url + "/commands", json=changed).status_code, 409
)
new_store = Database()
new_store.dsn = None
new_store.path = api.db.path
with patch.object(api, "db", new_store):
new_store.init()
self.assertEqual(self.c.get(self.url).json()["version"], s["version"] + 1)
def test_archive_step_privacy(self):
doc = self.c.get("/api/reference/export").json()
ev = next(r for r in doc["events"] if r["kind"] == "decision")
for eye in ["full", str(ev["data"]["seat"]), "0"]:
r = self.c.get(
"/api/reference/replay", params={"perspective": eye, "seq": ev["seq"]}
).json()
self.assertEqual("hands" in r["view"], eye == "full")
self.assertEqual(
"alternatives" in r["timeline"][r["seq"] - 1]["data"], eye != "0"
)
self.assertTrue(all(not x["data"] for x in r["timeline"][r["seq"] :]))
if eye == "full":
self.assertEqual(r["view"]["deck"], list(reversed(ev["state"]["deck"])))
self.assertEqual(doc["events"][-1]["kind"], "winner")
def test_archive_cleanup(self):
def create():
return self.c.post("/api/games",json={"bots":3}).json()["id"]
done, other_done, active = create(),create(),create()
foreign = TestClient(api.app)
self.addCleanup(foreign.close)
foreign_id = foreign.post("/api/games", json={"bots":4}).json()["id"]
active2 = self.url.split("/")[-1]
with api.db.transaction(True) as run:
for gid in (done,other_done,foreign_id):
run("UPDATE games SET winner=0,next_actor=NULL WHERE id=?", (gid,))
run("INSERT INTO commands VALUES (?,?,?,?)",(gid,"test","{}","{}"))
def remove(ids,active=False):
return self.c.post("/api/archive/remove",json={"ids":ids,"allow_active":active})
self.assertEqual(remove([done,active],True).status_code,422)
self.assertEqual(remove([done,done,other_done,foreign_id,active]).json(),{"removed":2})
self.assertEqual(remove([done]).json(),{"removed":0})
self.assertEqual(remove([foreign_id], True).json(),{"removed":0})
self.assertEqual(remove([active],True).json(),{"removed":1})
with api.db.transaction() as run:
for table,col in (("events","game_id"),("commands","game_id"),("games","id")):
self.assertEqual(run(f"SELECT COUNT(*) FROM {table} WHERE {col} IN (?,?,?)",
(done,other_done,active)).fetchone()[0],0)
self.assertGreater(run(f"SELECT COUNT(*) FROM {table} WHERE {col}=?",(foreign_id,)).fetchone()[0],0)
self.assertEqual([g["id"] for g in self.c.get("/api/games").json()],[active2])
self.assertEqual(self.c.get("/api/reference/replay").status_code,200)