"""The try loop, driven against a stub engine. What matters here is not the game but the sequencing around it: every try starts from an empty park, a try's evidence is collected before that park is thrown away, a completed try is never reset, and there is never a fourth try. The stub engine stands in for game-process.py and reports the outcomes the test asks for. """ import importlib.util import json import os import shutil import sys import tempfile import unittest from pathlib import Path TASK = Path(__file__).resolve().parents[1] NOTES_TEXT = "try 1: cheap flat rides paid, coaster did not\n" STUB_ENGINE = ''' import json, os, sys, time from pathlib import Path profile = Path(os.environ["T37_STUB_PROFILE"]) attempt = int(os.environ["T37_TRY"]) plan = json.loads(os.environ["T37_STUB_PLAN"])[attempt-1] # What this try inherited: the loop is supposed to hand over an empty park. Path(os.environ["T37_STUB_LOG"]).open("a").write(json.dumps({ "try": attempt, "inherited": sorted(p.name for p in (profile/"save").glob("*"))})+"\\n") (profile/"save").mkdir(parents=True, exist_ok=True) (profile/"save").joinpath(f"try-{attempt}.park").write_text("park") if plan == "engine_exit": sys.exit(3) beat = Path(os.environ["T37_TRY_HEARTBEAT"]) quiet = plan in ("silent", "stall") # "silent" never reports at all; "stall" reports once and then goes quiet, the # way the controller does when the agent quits the park to the title screen. if plan != "silent": beat.write_text("beat") if not quiet: Path(os.environ["T37_TRY_OUTCOME"]).write_text(plan) # The real engine stays up until the supervisor stops it; this one outlives the # decision it is meant to provoke and then goes away, so the final try's wait # for the engine ends and the test does not. deadline = time.time() + (float(os.environ["T37_STUB_QUIET_LIFETIME"]) if quiet else float(os.environ["T37_STUB_LIFETIME"])) while time.time() < deadline: if not quiet: beat.write_text("beat") time.sleep(0.02) ''' STUB_COLLECT = ''' import json, os, sys from pathlib import Path state = json.loads((Path(os.environ["T37_STUB_STATE"])/"current.json").read_text()) profile = Path(os.environ["T37_STUB_PROFILE"]) Path(os.environ["T37_STUB_COLLECTED"]).open("a").write(json.dumps({ "try": state["try"], "saves": sorted(p.name for p in (profile/"save").glob("*"))})+"\\n") ''' def load(tries, folder): """A fresh copy of the supervisor, wired to this test's directories.""" os.environ["T37_AUDIT_DIR"] = str(folder/"audit") os.environ["T37_TRIES"] = str(tries) spec = importlib.util.spec_from_file_location( "try_supervisor_"+str(tries)+folder.name, TASK/"environment/try-supervisor.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) lib = folder/"lib" lib.mkdir() (lib/"game-process.py").write_text(STUB_ENGINE) (lib/"collect.py").write_text(STUB_COLLECT) (lib/"observer.js").write_text("var CONTROLLER = 1;\n") module.LIB = lib module.STATE = folder/"tries" module.PROFILE = folder/"profile" module.SEED = folder/"seed.park" module.SEED.write_text("seed") # The agent's notes are the one thing a reset must not take away. module.NOTES = folder/"notes" module.NOTES.mkdir(exist_ok=True) (module.NOTES/"micropark-notes.txt").write_text(NOTES_TEXT) # The real graces leave a settled park on screen for minutes; the loop's # ordering is what is under test, not its patience. module.FAILURE_GRACE = module.COMPLETION_GRACE = 0 module.POLL = 0.05 module.HEARTBEAT_TIMEOUT = 0.5 module.STARTUP_TIMEOUT = 0.5 return module class Loop(unittest.TestCase): def setUp(self): self.folder = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.folder, True) self.saved_environment = dict(os.environ) self.addCleanup(lambda: (os.environ.clear(), os.environ.update(self.saved_environment))) def play(self, *plan): """Run the loop with one planned outcome per try; return its records.""" module = load(len(plan), self.folder) os.environ.update({ "T37_STUB_PLAN": json.dumps(list(plan)), "T37_STUB_PROFILE": str(module.PROFILE), "T37_STUB_STATE": str(module.STATE), "T37_STUB_LOG": str(self.folder/"engine.jsonl"), "T37_STUB_COLLECTED": str(self.folder/"collected.jsonl"), "T37_STUB_LIFETIME": "0.4", "T37_STUB_QUIET_LIFETIME": "3", }) sys.argv = ["try-supervisor.py"] with self.assertRaises(SystemExit): module.main() return (self.lines(module.AUDIT/"game.jsonl"), self.lines(self.folder/"engine.jsonl"), self.lines(self.folder/"collected.jsonl")) def lines(self, path): if not Path(path).exists(): return [] return [json.loads(line) for line in Path(path).read_text().splitlines() if line] def test_a_failed_try_is_followed_by_another(self): audit, engine, _ = self.play("objective_failed", "objective_failed") self.assertEqual([r["kind"] for r in audit], ["try_started", "try_ended", "try_started", "try_ended", "campaign_finished"]) self.assertEqual([r["try"] for r in engine], [1, 2]) def test_every_try_starts_from_an_empty_park(self): _, engine, _ = self.play("objective_failed", "objective_failed", "objective_failed") self.assertEqual([r["inherited"] for r in engine], [[], [], []]) def test_a_completed_try_ends_the_session(self): audit, engine, _ = self.play("objective_complete", "objective_failed", "objective_failed") self.assertEqual([r["try"] for r in engine], [1]) ended = [r for r in audit if r["kind"] == "try_ended"] self.assertEqual(len(ended), 1) self.assertEqual(ended[0]["reason"], "objective_complete") self.assertTrue(ended[0]["final"]) def test_the_last_try_is_final_even_when_it_fails(self): audit, engine, _ = self.play("objective_failed", "objective_failed", "objective_failed") self.assertEqual([r["try"] for r in engine], [1, 2, 3]) self.assertTrue([r for r in audit if r["kind"] == "try_ended"][-1]["final"]) self.assertEqual([r for r in audit if r["kind"] == "campaign_finished"][0] ["tries_played"], 3) def test_evidence_is_collected_before_the_park_is_thrown_away(self): _, _, collected = self.play("objective_failed", "objective_failed") self.assertEqual(collected, [{"try": 1, "saves": ["try-1.park"]}, {"try": 2, "saves": ["try-2.park"]}]) def test_the_controller_is_told_which_try_it_is(self): module = load(3, self.folder) module.install_plugin(2) installed = (module.PROFILE/"plugin/t37-observer.js").read_text() self.assertTrue(installed.startswith("var T37_TRY=2,T37_TRIES=3;")) self.assertIn("var CONTROLLER = 1;", installed) def test_a_park_closed_by_the_agent_ends_its_try_and_no_more(self): audit, engine, _ = self.play("stall", "objective_failed") self.assertEqual([r for r in audit if r["kind"] == "try_ended"][0]["reason"], "park_closed") self.assertEqual([r["try"] for r in engine], [1, 2]) def test_an_engine_that_never_reports_does_not_hang_the_session(self): audit, engine, _ = self.play("silent", "objective_failed") self.assertEqual([r for r in audit if r["kind"] == "try_ended"][0]["reason"], "engine_stalled") self.assertEqual([r["try"] for r in engine], [1, 2]) def test_a_crashed_engine_does_not_consume_the_remaining_tries(self): audit, engine, _ = self.play("engine_exit", "objective_failed") self.assertEqual([r for r in audit if r["kind"] == "try_ended"][0]["reason"], "engine_exit") self.assertEqual([r["try"] for r in engine], [1, 2]) def test_notes_survive_every_reset(self): audit, _, _ = self.play("objective_failed", "objective_failed", "objective_failed") # Two resets happened between these three tries; the notes went through # both of them untouched, which is what makes a retry worth anything. self.assertEqual((self.folder/"notes/micropark-notes.txt").read_text(), NOTES_TEXT) self.assertEqual([r["notes_bytes"] for r in audit if r["kind"] == "try_ended"], [len(NOTES_TEXT)]*3) def test_every_try_is_measured_at_its_start_as_well(self): # The grader needs the size before the agent touched anything to tell # the seeded file from the agent's own writing, so try_started carries it. audit, _, _ = self.play("objective_failed", "objective_failed", "objective_failed") self.assertEqual([r["notes_bytes"] for r in audit if r["kind"] == "try_started"], [len(NOTES_TEXT)]*3) def test_clearing_the_park_leaves_the_notes_alone(self): module = load(3, self.folder) (module.PROFILE/"save").mkdir(parents=True, exist_ok=True) (module.PROFILE/"save/try-1.park").write_text("park") module.clear_park() self.assertEqual(list((module.PROFILE/"save").iterdir()), []) self.assertEqual((module.NOTES/"micropark-notes.txt").read_text(), NOTES_TEXT) def test_the_live_try_is_published_for_the_collector(self): module = load(3, self.folder) module.publish(2, [{"try": 1, "reason": "objective_failed"}]) state = json.loads((module.STATE/"current.json").read_text()) self.assertEqual((state["try"], state["tries"]), (2, 3)) self.assertEqual(state["history"][0]["reason"], "objective_failed") if __name__ == "__main__": unittest.main()