File size: 4,940 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
"""Liveness has to tell a park being replaced apart from a dead desktop.

The supervisor stops the engine and starts the next one between tries, so
openrct2 is briefly missing while the session is fine. Reading that gap as a
dead runtime ends the agent's session at the very moment it earned its second
try, so the gap is waited out only while the supervisor still owes a try, and
only for as long as a reset can honestly take. Harbor is stubbed when it is not
importable from this interpreter; only the adapter is under test.
"""
import asyncio
import json
import sys
import types
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]/"scripts"))
try:
    import harbor.agents.computer_1.runtime  # noqa: F401
except ImportError:
    agent = types.ModuleType("harbor.agents.computer_1")
    agent.Computer1 = type("Computer1", (), {})
    runtime = types.ModuleType("harbor.agents.computer_1.runtime")
    runtime.Computer1Session = type("Computer1Session", (), {})
    runtime.RuntimeRequestError = type("RuntimeRequestError", (Exception,), {})
    for name in ("harbor", "harbor.agents"):
        sys.modules.setdefault(name, types.ModuleType(name))
    sys.modules[agent.__name__] = agent
    sys.modules[runtime.__name__] = runtime

import computer_agent  # noqa: E402
from computer_agent import GameSession  # noqa: E402

FINISHED = {"try": 3, "tries": 3, "history": [{"try": 1, "reason": "objective_failed"},
                                              {"try": 2, "reason": "objective_failed"},
                                              {"try": 3, "reason": "objective_failed"}]}
COMPLETED = {"try": 2, "tries": 3, "history": [{"try": 1, "reason": "objective_failed"},
                                               {"try": 2, "reason": "objective_complete"}]}
MID = {"try": 1, "tries": 3, "history": [{"try": 1, "reason": "objective_failed"}]}


class Desktop(GameSession):
    """A GameSession whose only shell is a script of answers."""

    def __init__(self, engine, supervisor=(0, MID)):
        self.engine = list(engine)
        self.supervisor = supervisor
        self.engine_checks = 0
        self.supervisor_checks = 0

    async def _raw_exec(self, command, timeout_sec=None):
        if "pgrep -x openrct2" in command:
            self.engine_checks += 1
            running = self.engine[min(self.engine_checks-1, len(self.engine)-1)]
            return types.SimpleNamespace(return_code=0 if running else 1, stdout="")
        if "try-supervisor.py" in command:
            self.supervisor_checks += 1
            code, state = self.supervisor
            body = state if isinstance(state, str) else json.dumps(state)
            return types.SimpleNamespace(return_code=code, stdout="" if code else body)
        raise AssertionError(f"Unexpected command: {command}")


class Liveness(unittest.TestCase):
    def setUp(self):
        self.grace = computer_agent.RESET_GRACE_SEC
        self.poll = computer_agent.RESET_POLL_SEC
        computer_agent.RESET_GRACE_SEC = 0.5
        computer_agent.RESET_POLL_SEC = 0.01

    def tearDown(self):
        computer_agent.RESET_GRACE_SEC = self.grace
        computer_agent.RESET_POLL_SEC = self.poll

    def alive(self, desktop):
        return asyncio.run(desktop.is_session_alive())

    def test_running_engine_is_alive(self):
        desktop = Desktop([True])
        self.assertTrue(self.alive(desktop))
        # A healthy engine answers on its own; nothing else is consulted.
        self.assertEqual((desktop.engine_checks, desktop.supervisor_checks), (1, 0))

    def test_reset_gap_is_waited_out(self):
        desktop = Desktop([False, False, False, True])
        self.assertTrue(self.alive(desktop))
        self.assertEqual(desktop.engine_checks, 4)

    def test_finished_campaign_engine_loss_is_death(self):
        desktop = Desktop([False], supervisor=(0, FINISHED))
        self.assertFalse(self.alive(desktop))

    def test_completed_objective_engine_loss_is_death(self):
        desktop = Desktop([False], supervisor=(0, COMPLETED))
        self.assertFalse(self.alive(desktop))

    def test_first_try_still_counts_as_pending(self):
        desktop = Desktop([False, True], supervisor=(0, {"try": 1, "tries": 3, "history": []}))
        self.assertTrue(self.alive(desktop))

    def test_no_supervisor_is_death(self):
        desktop = Desktop([False], supervisor=(1, ""))
        self.assertFalse(self.alive(desktop))

    def test_unreadable_state_is_death(self):
        desktop = Desktop([False], supervisor=(0, "half a json"))
        self.assertFalse(self.alive(desktop))

    def test_engine_that_never_returns_gives_up(self):
        desktop = Desktop([False])
        self.assertFalse(self.alive(desktop))
        # It waited rather than answering at once, but it did stop waiting.
        self.assertGreater(desktop.engine_checks, 1)


if __name__ == "__main__":
    unittest.main()