Initial
This commit is contained in:
commit
2ca7a264b3
53 files changed
+7113
No files matched your search
@@ -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)
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Round-trip a local game at every decision, including pending choices."""
|
||||
import random
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.extend([str(ROOT / "game"), str(ROOT / "demo")])
|
||||
import local_game as local
|
||||
|
||||
|
||||
class BrowserSave(unittest.TestCase):
|
||||
def test_resumes_with_same_decisions(self):
|
||||
for bots in (3, 4, 5):
|
||||
rng = random.Random(bots)
|
||||
game = local.e.new_game(bots, rng=rng)
|
||||
for _ in range(3000):
|
||||
token = local.encode(game)
|
||||
self.assertLess(len(token), 3500)
|
||||
restored = local.decode(token)
|
||||
self.assertEqual(token, local.encode(restored))
|
||||
self.assertEqual(local.e.actions(game), local.e.actions(restored))
|
||||
if game["winner"] is not None:
|
||||
break
|
||||
view = local.e.observation(game, local.e.actor(game))
|
||||
choice = local.decide(dict(view=view, actions=local.e.actions(game)))
|
||||
local.e.Turn(game, lambda *_: None, rng).apply(choice["command"])
|
||||
self.assertIsNotNone(game["winner"])
|
||||
@@ -0,0 +1,196 @@
|
||||
import copy
|
||||
import random
|
||||
import unittest
|
||||
from collections import Counter
|
||||
|
||||
from game import engine as e
|
||||
from game.strategy import decide
|
||||
|
||||
|
||||
class Rules(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.rng = random.Random(215)
|
||||
self.s = e.new_game(3, "purple", self.rng)
|
||||
self.s["active"] = 0
|
||||
self.log = []
|
||||
self.t = e.Turn(self.s, lambda s, k, d: self.log.append((k, d)), self.rng)
|
||||
self.own = [key for key, p in self.s["planes"].items() if p["owner"] == 0]
|
||||
|
||||
def test_setup_and_full_games(self):
|
||||
for bots in (3, 4, 5):
|
||||
s = e.new_game(bots, rng=self.rng)
|
||||
self.assertEqual(len(s["deck"]), 146 - (bots + 1) * 9)
|
||||
self.assertEqual(len(set(s["colors"])), bots + 1)
|
||||
|
||||
def audit(state, kind, data):
|
||||
cards = [*state["deck"], *state["discard"]]
|
||||
for h in state["hands"]:
|
||||
cards.extend(h)
|
||||
cards.extend(x for x in (state["weather"], state["transit"]) if x)
|
||||
self.assertEqual(Counter(cards), Counter(e.CAT["cards"]))
|
||||
positions = [
|
||||
p["pos"]
|
||||
for p in state["planes"].values()
|
||||
if p["pos"] not in ("H", "F")
|
||||
]
|
||||
self.assertEqual(len(positions), len(set(positions)))
|
||||
|
||||
while s["winner"] is None and s["turn"] < 1800:
|
||||
cmd = decide(
|
||||
dict(view=e.observation(s, e.actor(s)), actions=e.actions(s))
|
||||
)["command"]
|
||||
e.Turn(s, audit, self.rng).apply(cmd)
|
||||
self.assertIsNotNone(s["winner"])
|
||||
self.assertTrue(
|
||||
all(
|
||||
p["pos"] == "F"
|
||||
for p in s["planes"].values()
|
||||
if p["owner"] == s["winner"]
|
||||
)
|
||||
)
|
||||
|
||||
def test_snow_and_captain(self):
|
||||
key = self.own[0]
|
||||
self.s["planes"][key]["pos"] = "A:B1"
|
||||
self.s["hands"][0] = ["B", "B", "LC", "LC"]
|
||||
self.s["weather"] = "SN"
|
||||
cmd = dict(kind="move", plane=key, to="B:B1", cards=["B", "B", "LC"])
|
||||
prev = copy.deepcopy(self.s)
|
||||
with self.assertRaises(ValueError):
|
||||
self.t.apply(cmd)
|
||||
self.assertEqual(prev, self.s)
|
||||
cmd["cards"].append("LC")
|
||||
self.t.apply(cmd)
|
||||
self.assertEqual(self.s["planes"][key]["pos"], "B:B1")
|
||||
|
||||
def test_exchange_pauses_then_continues(self):
|
||||
s = self.s
|
||||
for i, key in enumerate(self.own[:2]):
|
||||
s["planes"][key]["pos"] = "A:B" + str(i + 1)
|
||||
s["deck"].extend(["B", "DLY", "A", "FG"])
|
||||
self.t.apply(dict(kind="exchange", cards=s["hands"][0][:2]))
|
||||
self.assertEqual(e.actor(s), 1)
|
||||
self.assertEqual(s["deck"][-1], "B")
|
||||
self.assertEqual(s["owed"], 1)
|
||||
self.assertEqual(s["weather"], "FG")
|
||||
self.assertEqual(len(e.actions(s)), 2)
|
||||
self.t.apply(e.actions(s)[0])
|
||||
self.assertEqual(s["known"][0], {"A": 1, "B": 1})
|
||||
self.assertEqual(s["planes"][self.own[0]]["pos"], "H")
|
||||
self.assertEqual(s["turn"], 2)
|
||||
|
||||
def test_private_draw(self):
|
||||
self.s["hands"][0] = ["SC"] * 7 + ["A", "A"]
|
||||
self.s["deck"].extend(["FG", "DLY", "ICE"])
|
||||
self.t.apply(dict(kind="weather", cards=["SC"]))
|
||||
self.assertEqual(self.s["weather"], "SC")
|
||||
self.assertIn("ICE", self.s["hands"][0])
|
||||
self.assertEqual(self.s["known"][0], {})
|
||||
|
||||
def test_vip_and_runway_choice(self):
|
||||
key = self.own[0]
|
||||
s = self.s
|
||||
s["hands"][0][0] = "VIP"
|
||||
self.t.apply(dict(kind="move", plane=key, to="V1:31L", cards=["VIP"]))
|
||||
self.assertEqual(s["planes"][key]["pos"], "V1:31L")
|
||||
s["active"] = 0
|
||||
self.t.finish()
|
||||
self.assertEqual(s["planes"][key]["pos"], "V2:31L")
|
||||
s["active"] = 0
|
||||
self.t.finish()
|
||||
self.assertTrue(s["pending"])
|
||||
self.t.apply(dict(kind="runway", plane=key, to="D:31R:0"))
|
||||
self.assertEqual(s["planes"][key]["pos"], "D:31R:0")
|
||||
s["active"] = 0
|
||||
self.t.finish()
|
||||
self.assertEqual(s["planes"][key]["pos"], "F")
|
||||
|
||||
def test_two_takeoffs_and_no_chain(self):
|
||||
for key, pos in zip(self.own, ["D:31L:0", "D:31R:0", "D:31R:1"]):
|
||||
self.s["planes"][key]["pos"] = pos
|
||||
self.t.finish()
|
||||
self.assertEqual(
|
||||
[self.s["planes"][k]["pos"] for k in self.own[:3]], ["F", "F", "D:31R:0"]
|
||||
)
|
||||
|
||||
def test_crosswind_snow_ice_and_closed(self):
|
||||
for weather in ["FG", "31L", "CW", "SN", "ICE", "SC"]:
|
||||
for size in (1, 2, 3):
|
||||
s = copy.deepcopy(self.s)
|
||||
head, follower = self.own[:2]
|
||||
s["planes"][head].update(pos="D:31L:0", size=size)
|
||||
s["planes"][follower]["pos"] = "D:31L:1"
|
||||
s["weather"] = weather
|
||||
e.Turn(s, lambda *args: None).finish()
|
||||
expected = (
|
||||
"D:31L:0"
|
||||
if weather in ("FG", "31L")
|
||||
else "D:31L:1"
|
||||
if weather == "ICE" or (weather, size) in (("CW", 1), ("SN", 3))
|
||||
else "F"
|
||||
)
|
||||
self.assertEqual(s["planes"][head]["pos"], expected)
|
||||
self.s["weather"] = "ICE"
|
||||
for n, lane in enumerate(e.LANES):
|
||||
self.s["planes"][self.own[n]]["pos"] = f"D:{lane}:0"
|
||||
self.s["hands"][0] = ["AI"] * 9
|
||||
self.t.apply(dict(kind="ice", plane=self.own[0], cards=["AI"] * 3))
|
||||
self.assertEqual(self.s["planes"][self.own[1]]["pos"], "D:31R:0")
|
||||
|
||||
def test_invisible_redistribution(self):
|
||||
s = self.s
|
||||
for pending in [None, dict(seat=1, card="DLY", targets=self.own[:2])]:
|
||||
s["pending"] = pending
|
||||
seat = e.actor(s)
|
||||
other = (seat + 1) % len(s["hands"])
|
||||
altered = copy.deepcopy(s)
|
||||
altered["deck"].reverse()
|
||||
h = altered["hands"][other]
|
||||
h[0], altered["deck"][-1] = altered["deck"][-1], h[0]
|
||||
|
||||
def req(game):
|
||||
return dict(view=e.observation(game, seat), actions=e.actions(game))
|
||||
|
||||
self.assertEqual(req(s), req(altered))
|
||||
self.assertEqual(decide(req(s)), decide(req(altered)))
|
||||
|
||||
def test_blocked_stand_and_frozen_queue(self):
|
||||
key = self.own[0]
|
||||
self.s["planes"][key]["pos"] = "C:C1"
|
||||
self.s["hands"][0] = ["A"] * 9
|
||||
self.assertFalse(any(c.get("to") == "A:C1" for c in e.actions(self.s)))
|
||||
self.s["weather"] = "FG"
|
||||
self.s["planes"][key]["pos"] = "D:31L:2"
|
||||
self.t.compact()
|
||||
self.assertEqual(e.tail(self.s, "31L"), "D:31L:3")
|
||||
self.t.weather("SC")
|
||||
self.assertEqual(self.s["planes"][key]["pos"], "D:31L:0")
|
||||
|
||||
def test_attack_targets_and_refill(self):
|
||||
enemy = next(k for k, p in self.s["planes"].items() if p["owner"] == 1)
|
||||
self.s["planes"][enemy]["pos"] = "D:31L:0"
|
||||
self.s["hands"][0] = ["DLY", "FLR"] + ["A"] * 7
|
||||
commands = e.actions(self.s)
|
||||
flr = dict(kind="attack", plane=enemy, cards=["FLR"])
|
||||
self.assertIn(flr, commands)
|
||||
self.assertNotIn(dict(kind="attack", plane=enemy, cards=["DLY"]), commands)
|
||||
self.t.apply(flr)
|
||||
self.assertEqual(self.s["planes"][enemy]["pos"], "H")
|
||||
self.s["active"] = 0
|
||||
self.s["deck"] = ["A"]
|
||||
self.s["discard"] = ["B", "B", "C"]
|
||||
self.s["weather"] = "ICE"
|
||||
self.t.apply(dict(kind="exchange", cards=["A", "A"]))
|
||||
self.assertEqual(len(self.s["hands"][0]), 9)
|
||||
self.assertEqual(self.s["weather"], "ICE")
|
||||
self.assertIn("shuffle", [kind for kind, _ in self.log])
|
||||
|
||||
def test_closed_hand_can_hold_trouble_and_weather(self):
|
||||
s = self.s
|
||||
key = self.own[0]
|
||||
s["hands"][0] = ["A"] * 9
|
||||
s["deck"].extend(["FG", "DLY", "SN"])
|
||||
self.t.apply(dict(kind="move", plane=key, to="A:B1", cards=["A"] * 3))
|
||||
self.assertIsNone(s["weather"])
|
||||
self.assertEqual(s["planes"][key]["pos"], "A:B1")
|
||||
self.assertTrue({"FG", "DLY", "SN"}.issubset(s["hands"][0]))
|
||||
@@ -0,0 +1,69 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { airfield } from "../game/static/airfield.js";
|
||||
import { cardFace } from "../game/static/cards.js";
|
||||
|
||||
const catalog = JSON.parse(
|
||||
readFileSync(new URL("../game/catalog.json", import.meta.url)),
|
||||
);
|
||||
const empty = {
|
||||
geometry: catalog.board,
|
||||
markers: {},
|
||||
selected: "",
|
||||
pickable: new Set(),
|
||||
destinations: new Set(),
|
||||
weather: null,
|
||||
};
|
||||
|
||||
test("A labelled vector face exists for each card in the rules catalog", () => {
|
||||
for (const code of Object.keys(catalog.cards)) {
|
||||
const card = cardFace(code, 0, true, true);
|
||||
assert.ok(card.includes('data-code="' + code + '"'));
|
||||
for (const cls of ["fc-title", "fc-en", "fc-effect"])
|
||||
assert.match(card, new RegExp('class="' + cls + '"[^>]*>[^<]+<'));
|
||||
assert.match(card, /<svg[^>]*>.*<path/s);
|
||||
assert.match(card, /aria-pressed="true"/);
|
||||
assert.doesNotMatch(card, /undefined/);
|
||||
assert.doesNotMatch(cardFace(code, 0, false, false), /data-act=/);
|
||||
}
|
||||
});
|
||||
test("Positions are unique and all six positions on each runway have a marker", () => {
|
||||
const svg = airfield(empty);
|
||||
const ids = Array.from(svg.matchAll(/data-position="([^"]+)"/g), (m) => m[1]);
|
||||
assert.equal(ids.length, new Set(ids).size);
|
||||
const b = catalog.board;
|
||||
assert.equal(
|
||||
ids.length,
|
||||
b.ab_stands +
|
||||
b.b_stands +
|
||||
2 * b.ac_stands +
|
||||
b.vip_lanes * 2 +
|
||||
b.runways.length * b.queue_capacity,
|
||||
);
|
||||
for (const lane of b.runways)
|
||||
for (let i = 0; i < b.queue_capacity; i++)
|
||||
assert.ok(ids.includes("D:" + lane + ":" + i));
|
||||
});
|
||||
test("Only supplied targets are interactive; the preview is read-only", () => {
|
||||
assert.doesNotMatch(airfield(empty), /data-act=/);
|
||||
const svg = airfield({
|
||||
...empty,
|
||||
markers: {
|
||||
"A:B2": {
|
||||
key: "blue-1",
|
||||
caption: "С1",
|
||||
size: 3,
|
||||
color: "#345",
|
||||
name: "Синяя",
|
||||
},
|
||||
},
|
||||
pickable: new Set(["blue-1"]),
|
||||
destinations: new Set(["B:B3"]),
|
||||
selected: "blue-1",
|
||||
});
|
||||
assert.match(svg, /data-act="pick" data-val="blue-1"/);
|
||||
assert.match(svg, /data-act="mapdest" data-val="B:B3"/);
|
||||
assert.equal([...svg.matchAll(/data-act=/g)].length, 2);
|
||||
assert.match(svg, /href="#jet3"/);
|
||||
});
|
||||
Reference in new issue
Block a user