File size: 10,896 Bytes
3eae4cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
"""
tests/test_phase2_api.py
Phase 2 API: FastAPI endpoints /health /reset /step /state /grade /sessions
Run (server must be running on localhost:7860):
    pytest tests/test_phase2_api.py -v
OR against the TestClient (no server needed):
    pytest tests/test_phase2_api.py -v --use-testclient
"""
import pytest
import sys

# ── Use TestClient by default β€” no running server needed ─────────────────────
try:
    from fastapi.testclient import TestClient
    from app.main import app
    client = TestClient(app)
    USE_TESTCLIENT = True
except Exception:
    import requests
    BASE = "http://localhost:7860"
    USE_TESTCLIENT = False


def post(path: str, body: dict) -> dict:
    if USE_TESTCLIENT:
        r = client.post(path, json=body)
    else:
        import requests
        r = requests.post(f"{BASE}{path}", json=body)
    return r.status_code, r.json()


def get(path: str, params: dict = None) -> dict:
    if USE_TESTCLIENT:
        r = client.get(path, params=params)
    else:
        import requests
        r = requests.get(f"{BASE}{path}", params=params)
    return r.status_code, r.json()


def delete(path: str) -> dict:
    if USE_TESTCLIENT:
        r = client.delete(path)
    else:
        import requests
        r = requests.delete(f"{BASE}{path}")
    return r.status_code, r.json()


# ─── /health ──────────────────────────────────────────────────────────────────
class TestHealth:
    def test_health_returns_200(self):
        code, body = get("/health")
        assert code == 200

    def test_health_status_ok(self):
        _, body = get("/health")
        assert body.get("status") == "ok"

    def test_health_has_version(self):
        _, body = get("/health")
        assert "version" in body

    def test_health_has_active_sessions(self):
        _, body = get("/health")
        assert "active_sessions" in body
        assert isinstance(body["active_sessions"], int)


# ─── POST /reset ──────────────────────────────────────────────────────────────
class TestReset:
    def test_reset_returns_200(self):
        code, _ = post("/reset", {"task_id": "district_backlog_easy"})
        assert code == 200

    def test_reset_returns_session_id(self):
        _, body = post("/reset", {"task_id": "district_backlog_easy"})
        assert "session_id" in body
        assert isinstance(body["session_id"], str)
        assert len(body["session_id"]) > 0

    def test_reset_returns_observation(self):
        _, body = post("/reset", {"task_id": "district_backlog_easy"})
        assert "observation" in body
        obs = body["observation"]
        assert obs["day"] == 0
        assert obs["task_id"] == "district_backlog_easy"

    def test_reset_returns_info_dict(self):
        _, body = post("/reset", {"task_id": "district_backlog_easy"})
        assert "info" in body
        assert isinstance(body["info"], dict)

    def test_reset_with_seed(self):
        code, body = post("/reset", {"task_id": "district_backlog_easy", "seed": 42})
        assert code == 200
        assert "session_id" in body

    def test_reset_different_tasks(self):
        for tid in ["district_backlog_easy", "mixed_urgency_medium", "cross_department_hard"]:
            code, body = post("/reset", {"task_id": tid})
            assert code == 200, f"Reset failed for task {tid}"
            assert body["observation"]["task_id"] == tid

    def test_two_resets_give_different_session_ids(self):
        _, b1 = post("/reset", {"task_id": "district_backlog_easy"})
        _, b2 = post("/reset", {"task_id": "district_backlog_easy"})
        assert b1["session_id"] != b2["session_id"]


# ─── POST /step ───────────────────────────────────────────────────────────────
class TestStep:
    def _session(self):
        _, body = post("/reset", {"task_id": "district_backlog_easy", "seed": 42})
        return body["session_id"]

    def test_step_returns_200(self):
        sid = self._session()
        code, _ = post("/step", {
            "session_id": sid,
            "action": {"action_type": "advance_time"},
        })
        assert code == 200

    def test_step_returns_all_fields(self):
        sid = self._session()
        _, body = post("/step", {
            "session_id": sid,
            "action": {"action_type": "advance_time"},
        })
        assert "observation" in body
        assert "reward" in body
        assert "terminated" in body
        assert "truncated" in body
        assert "info" in body

    def test_step_reward_is_number(self):
        sid = self._session()
        _, body = post("/step", {
            "session_id": sid,
            "action": {"action_type": "advance_time"},
        })
        assert isinstance(body["reward"], (int, float))

    def test_step_observation_day_increments(self):
        sid = self._session()
        _, b = post("/step", {"session_id": sid,
                              "action": {"action_type": "advance_time"}})
        assert b["observation"]["day"] == 1

    def test_step_set_priority_mode(self):
        sid = self._session()
        _, body = post("/step", {
            "session_id": sid,
            "action": {"action_type": "set_priority_mode",
                       "priority_mode": "urgent_first"},
        })
        assert body["info"]["invalid_action"] is False

    def test_step_invalid_action_flagged(self):
        sid = self._session()
        _, body = post("/step", {
            "session_id": sid,
            "action": {"action_type": "set_priority_mode"},  # missing priority_mode
        })
        assert body["info"]["invalid_action"] is True

    def test_step_on_unknown_session_returns_404(self):
        code, _ = post("/step", {
            "session_id": "no-such-session-xyz",
            "action": {"action_type": "advance_time"},
        })
        assert code == 404

    def test_step_terminated_episode_returns_409(self):
        sid = self._session()
        # Run until termination
        for _ in range(200):
            _, b = post("/step", {"session_id": sid,
                                  "action": {"action_type": "advance_time"}})
            if b.get("terminated") or b.get("truncated"):
                break
        # One more step should be 409
        code, _ = post("/step", {
            "session_id": sid,
            "action": {"action_type": "advance_time"},
        })
        assert code in [409, 422]


# ─── GET/POST /state ──────────────────────────────────────────────────────────
class TestState:
    def _session(self):
        _, body = post("/reset", {"task_id": "district_backlog_easy", "seed": 42})
        return body["session_id"]

    def test_state_post_returns_200(self):
        sid = self._session()
        code, _ = post("/state", {"session_id": sid})
        assert code == 200

    def test_state_get_returns_200(self):
        sid = self._session()
        code, _ = get("/state", {"session_id": sid})
        assert code == 200

    def test_state_has_episode_state(self):
        sid = self._session()
        _, body = post("/state", {"session_id": sid})
        assert "state" in body

    def test_state_day_zero_at_start(self):
        sid = self._session()
        _, body = post("/state", {"session_id": sid})
        assert body["state"]["day"] == 0

    def test_state_unknown_session_404(self):
        code, _ = post("/state", {"session_id": "ghost-session"})
        assert code == 404

    def test_state_action_history_excluded_by_default(self):
        sid = self._session()
        _, body = post("/state", {"session_id": sid,
                                  "include_action_history": False})
        state = body["state"]
        assert "action_history" not in state or state.get("action_history") is None


# ─── POST /grade ──────────────────────────────────────────────────────────────
class TestGrade:
    def _run_session(self, steps=5):
        _, body = post("/reset", {"task_id": "district_backlog_easy", "seed": 42})
        sid = body["session_id"]
        for _ in range(steps):
            r = post("/step", {"session_id": sid,
                               "action": {"action_type": "advance_time"}})
            if r[1].get("terminated") or r[1].get("truncated"):
                break
        return sid

    def test_grade_returns_200(self):
        sid = self._run_session()
        code, _ = post("/grade", {"session_id": sid})
        assert code == 200

    def test_grade_score_in_range(self):
        sid = self._run_session()
        _, body = post("/grade", {"session_id": sid})
        assert 0.0 <= body["score"] <= 1.0

    def test_grade_has_grader_name(self):
        sid = self._run_session()
        _, body = post("/grade", {"session_id": sid})
        assert "grader_name" in body
        assert isinstance(body["grader_name"], str)

    def test_grade_has_metrics(self):
        sid = self._run_session()
        _, body = post("/grade", {"session_id": sid})
        assert "metrics" in body

    def test_grade_unknown_session_404(self):
        code, _ = post("/grade", {"session_id": "dead-session"})
        assert code == 404


# ─── GET /sessions / DELETE /sessions/{id} ───────────────────────────────────
class TestSessions:
    def test_list_sessions_returns_200(self):
        code, _ = get("/sessions")
        assert code == 200

    def test_list_sessions_has_count(self):
        _, body = get("/sessions")
        assert "active_sessions" in body

    def test_delete_session(self):
        _, r = post("/reset", {"task_id": "district_backlog_easy"})
        sid = r["session_id"]
        code, body = delete(f"/sessions/{sid}")
        assert code == 200
        assert body.get("deleted") == sid

    def test_delete_nonexistent_session_404(self):
        code, _ = delete("/sessions/nonexistent-id-xyz")
        assert code == 404

    def test_session_count_increases_after_reset(self):
        _, b1 = get("/sessions")
        count_before = b1["active_sessions"]
        post("/reset", {"task_id": "district_backlog_easy"})
        _, b2 = get("/sessions")
        count_after = b2["active_sessions"]
        assert count_after >= count_before