File size: 10,162 Bytes
5463b45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
"""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()