dsh-project-dept 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,644 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Tests for ``scripts/run_evals.py`` (the project-dept evals runner).
3
+
4
+ Deliberately stdlib-only ``unittest``: the runner is driven as a real subprocess so the
5
+ tests check exit codes and stdout exactly the way a user / CI would. The real
6
+ ``evals/evals.json`` is only read, never modified: every bad-schema case is a temp copy.
7
+
8
+ Run:
9
+ python -m unittest tests.test_run_evals -v
10
+ python -m unittest discover -s tests -v
11
+ """
12
+
13
+ import importlib.util
14
+ import json
15
+ import os
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import unittest
20
+
21
+ HERE = os.path.dirname(os.path.abspath(__file__))
22
+ SKILL_ROOT = os.path.dirname(HERE)
23
+ RUNNER = os.path.join(SKILL_ROOT, "scripts", "run_evals.py")
24
+ REAL_EVALS = os.path.join(SKILL_ROOT, "evals", "evals.json")
25
+
26
+ for _stream in (sys.stdout, sys.stderr):
27
+ try:
28
+ _stream.reconfigure(encoding="utf-8", errors="replace")
29
+ except Exception: # noqa: BLE001
30
+ pass
31
+
32
+
33
+ def load_json(path=REAL_EVALS):
34
+ with open(path, encoding="utf-8-sig") as fh:
35
+ return json.load(fh)
36
+
37
+
38
+ def gold_answer(case):
39
+ """A synthetic answer that contains every must_include and no must_exclude."""
40
+ return "\n".join(case["assertions"]["must_include"])
41
+
42
+
43
+ def run_runner(*args):
44
+ env = dict(os.environ)
45
+ env["PYTHONIOENCODING"] = "utf-8"
46
+ return subprocess.run(
47
+ [sys.executable, RUNNER, *args],
48
+ capture_output=True,
49
+ text=True,
50
+ encoding="utf-8",
51
+ errors="replace",
52
+ env=env,
53
+ cwd=SKILL_ROOT,
54
+ )
55
+
56
+
57
+ def import_runner():
58
+ spec = importlib.util.spec_from_file_location("run_evals_under_test", RUNNER)
59
+ module = importlib.util.module_from_spec(spec)
60
+ spec.loader.exec_module(module)
61
+ return module
62
+
63
+
64
+ class TempEvalsMixin:
65
+ def setUp(self):
66
+ self._tmpdir = tempfile.TemporaryDirectory(prefix="pd_evals_")
67
+ self.tmp = self._tmpdir.name
68
+
69
+ def tearDown(self):
70
+ self._tmpdir.cleanup()
71
+
72
+ def write_variant(self, mutate, name="evals.json"):
73
+ data = load_json()
74
+ mutate(data)
75
+ path = os.path.join(self.tmp, name)
76
+ with open(path, "w", encoding="utf-8") as fh:
77
+ json.dump(data, fh, ensure_ascii=False)
78
+ return path
79
+
80
+ def static(self, *extra):
81
+ return run_runner("--mode", "static", *extra)
82
+
83
+
84
+ class TestStaticRealPackage(unittest.TestCase):
85
+ def test_real_evals_static_passes_and_prints_seven_briefs(self):
86
+ proc = run_runner("--mode", "static")
87
+ self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
88
+ self.assertIn("static 校验通过", proc.stdout)
89
+ cases = load_json()["evals"]
90
+ self.assertEqual(len(cases), 7)
91
+ for case in cases:
92
+ self.assertIn("CASE: " + case["id"], proc.stdout)
93
+ self.assertEqual(proc.stdout.count("【给 judge 的评分要求"), 7)
94
+ self.assertEqual(proc.stdout.count("token 预算提示"), 7)
95
+
96
+ def test_default_mode_is_static(self):
97
+ proc = run_runner()
98
+ self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
99
+ self.assertIn("static 校验通过", proc.stdout)
100
+
101
+ def test_gold_expected_output_passes_its_own_assertions(self):
102
+ # Derivation invariant: every include is in expected_output, no exclude is. If this
103
+ # breaks, the assertions were not extracted from the frozen criterion.
104
+ for case in load_json()["evals"]:
105
+ gold = case["expected_output"]
106
+ for item in case["assertions"]["must_include"]:
107
+ self.assertIn(item, gold, "%s: include '%s'" % (case["id"], item))
108
+ for item in case["assertions"]["must_exclude"]:
109
+ self.assertNotIn(item, gold, "%s: exclude '%s'" % (case["id"], item))
110
+
111
+
112
+ class TestStaticBadSchema(TempEvalsMixin, unittest.TestCase):
113
+ def assert_invalid(self, path, needle):
114
+ proc = self.static("--evals", path)
115
+ self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr)
116
+ self.assertIn(needle, proc.stdout)
117
+ self.assertIn("exit 2", proc.stdout)
118
+
119
+ def test_missing_assertions_named(self):
120
+ def mutate(data):
121
+ del data["evals"][0]["assertions"]
122
+ self.assert_invalid(self.write_variant(mutate), "assertions")
123
+
124
+ def test_duplicate_id_named(self):
125
+ def mutate(data):
126
+ data["evals"][1]["id"] = data["evals"][0]["id"]
127
+ self.assert_invalid(self.write_variant(mutate), "id 重复")
128
+
129
+ def test_tautological_include_rejected(self):
130
+ def mutate(data):
131
+ data["evals"][0]["assertions"]["must_include"].append("的")
132
+ self.assert_invalid(self.write_variant(mutate), "恒真串")
133
+
134
+ def test_include_not_extractable_from_expected_output(self):
135
+ def mutate(data):
136
+ data["evals"][0]["assertions"]["must_include"].append("这句判据里根本没有")
137
+ self.assert_invalid(self.write_variant(mutate), "expected_output 里找不到")
138
+
139
+ def test_exclude_present_in_expected_output_rejected(self):
140
+ def mutate(data):
141
+ data["evals"][0]["assertions"]["must_exclude"].append("验收标准")
142
+ self.assert_invalid(self.write_variant(mutate), "出现在 expected_output 里")
143
+
144
+ def test_too_few_assertions_rejected(self):
145
+ def mutate(data):
146
+ data["evals"][2]["assertions"]["must_include"] = ["三段式"]
147
+ data["evals"][2]["assertions"]["must_exclude"] = ["跳过 L2"]
148
+ self.assert_invalid(self.write_variant(mutate), "至少")
149
+
150
+ def test_bad_axis_value_named(self):
151
+ def mutate(data):
152
+ data["evals"][0]["assertions"]["axes"]["rigor"] = "super-critical"
153
+ self.assert_invalid(self.write_variant(mutate), "不是 manifest.yaml 的真实轴值")
154
+
155
+ def test_bad_step_named(self):
156
+ def mutate(data):
157
+ data["evals"][0]["assertions"]["steps"] = ["0-gate", "9-invented"]
158
+ self.assert_invalid(self.write_variant(mutate), "不是六步编号")
159
+
160
+ def test_missing_budget_named(self):
161
+ def mutate(data):
162
+ del data["evals"][0]["budget_hint"]
163
+ self.assert_invalid(self.write_variant(mutate), "budget_hint")
164
+
165
+ def test_utf8_bom_rejected(self):
166
+ path = self.write_variant(lambda data: None, name="bom.json")
167
+ with open(path, "rb") as fh:
168
+ raw = fh.read()
169
+ with open(path, "wb") as fh:
170
+ fh.write(b"\xef\xbb\xbf" + raw)
171
+ self.assert_invalid(path, "BOM")
172
+
173
+ def test_broken_json_named(self):
174
+ path = os.path.join(self.tmp, "broken.json")
175
+ with open(path, "w", encoding="utf-8") as fh:
176
+ fh.write("{not json,")
177
+ self.assert_invalid(path, "不是合法 JSON")
178
+
179
+
180
+ class TestGradeMode(TempEvalsMixin, unittest.TestCase):
181
+ def grade(self, case_id, text):
182
+ answer = os.path.join(self.tmp, "answer.md")
183
+ with open(answer, "w", encoding="utf-8") as fh:
184
+ fh.write(text)
185
+ return run_runner("--mode", "grade", "--case", case_id, "--answer", answer)
186
+
187
+ def test_gold_answer_passes_for_every_case(self):
188
+ for case in load_json()["evals"]:
189
+ proc = self.grade(case["id"], gold_answer(case))
190
+ self.assertEqual(proc.returncode, 0, case["id"] + "\n" + proc.stdout)
191
+ self.assertEqual(proc.stdout.strip().splitlines()[-1],
192
+ "CASE %s PASS" % case["id"])
193
+ self.assertEqual(proc.stdout.count("[x]"), 0,
194
+ "%s: no assertion should fail\n%s" % (case["id"], proc.stdout))
195
+
196
+ def test_missing_one_include_fails_with_marker(self):
197
+ case = load_json()["evals"][0]
198
+ answer = "\n".join(case["assertions"]["must_include"][1:])
199
+ proc = self.grade(case["id"], answer)
200
+ self.assertEqual(proc.returncode, 1, proc.stdout)
201
+ self.assertIn("[x]", proc.stdout)
202
+ self.assertIn(case["assertions"]["must_include"][0], proc.stdout)
203
+ self.assertEqual(proc.stdout.strip().splitlines()[-1], "CASE %s FAIL" % case["id"])
204
+
205
+ def test_present_exclude_fails_even_with_all_includes(self):
206
+ case = load_json()["evals"][1]
207
+ answer = gold_answer(case) + "\n" + case["assertions"]["must_exclude"][0]
208
+ proc = self.grade(case["id"], answer)
209
+ self.assertEqual(proc.returncode, 1, proc.stdout)
210
+ self.assertIn("直接 FAIL", proc.stdout)
211
+ self.assertEqual(proc.stdout.strip().splitlines()[-1], "CASE %s FAIL" % case["id"])
212
+
213
+ def test_unknown_case_exits_2(self):
214
+ proc = self.grade("no-such-case", "whatever")
215
+ self.assertEqual(proc.returncode, 2, proc.stdout)
216
+ self.assertIn("不存在", proc.stdout)
217
+
218
+ def test_missing_answer_file_exits_2(self):
219
+ proc = run_runner("--mode", "grade", "--case", "full-package",
220
+ "--answer", os.path.join(self.tmp, "nope.md"))
221
+ self.assertEqual(proc.returncode, 2, proc.stdout)
222
+
223
+ def test_empty_answer_fails_not_crashes(self):
224
+ proc = self.grade("mechanism-choice", "")
225
+ self.assertEqual(proc.returncode, 1, proc.stdout)
226
+ self.assertEqual(proc.stdout.strip().splitlines()[-1],
227
+ "CASE mechanism-choice FAIL")
228
+
229
+ def test_without_required_args_exits_2(self):
230
+ self.assertEqual(run_runner("--mode", "grade").returncode, 2)
231
+ self.assertEqual(run_runner("--mode", "grade", "--case", "full-package").returncode, 2)
232
+
233
+
234
+ class TestCompareMode(TempEvalsMixin, unittest.TestCase):
235
+ def make_side(self, name, break_case=None):
236
+ root = os.path.join(self.tmp, name)
237
+ for case in load_json()["evals"]:
238
+ case_dir = os.path.join(root, case["id"])
239
+ os.makedirs(case_dir, exist_ok=True)
240
+ answer = gold_answer(case)
241
+ if case["id"] == break_case:
242
+ answer = "\n".join(case["assertions"]["must_include"][1:])
243
+ with open(os.path.join(case_dir, "answer.md"), "w", encoding="utf-8") as fh:
244
+ fh.write(answer)
245
+ return root
246
+
247
+ def test_both_sides_graded_and_counts_printed(self):
248
+ with_dir = self.make_side("with")
249
+ without_dir = self.make_side("without", break_case="full-package")
250
+ proc = run_runner("--mode", "compare", "--with", with_dir, "--without", without_dir)
251
+ self.assertEqual(proc.returncode, 0, proc.stdout)
252
+ self.assertIn("WITH", proc.stdout)
253
+ self.assertIn("WITHOUT", proc.stdout)
254
+ self.assertIn("TOTAL PASS", proc.stdout)
255
+ self.assertIn("7/7", proc.stdout)
256
+ self.assertIn("6/7", proc.stdout)
257
+ self.assertIn("不能当等价性证明", proc.stdout)
258
+
259
+ def test_failure_on_with_side_exits_1(self):
260
+ with_dir = self.make_side("with_bad", break_case="checker-must-fail")
261
+ without_dir = self.make_side("without_ok")
262
+ proc = run_runner("--mode", "compare", "--with", with_dir, "--without", without_dir)
263
+ self.assertEqual(proc.returncode, 1, proc.stdout)
264
+ self.assertIn("FAIL", proc.stdout)
265
+
266
+ def test_unreadable_directory_exits_2(self):
267
+ proc = run_runner("--mode", "compare",
268
+ "--with", os.path.join(self.tmp, "missing-a"),
269
+ "--without", os.path.join(self.tmp, "missing-b"))
270
+ self.assertEqual(proc.returncode, 2, proc.stdout)
271
+ self.assertIn("目录不可读", proc.stdout)
272
+
273
+ def test_missing_answer_file_is_reported_not_crashed(self):
274
+ empty_dir = os.path.join(self.tmp, "empty")
275
+ os.makedirs(empty_dir)
276
+ with_dir = self.make_side("with")
277
+ proc = run_runner("--mode", "compare", "--with", with_dir, "--without", empty_dir)
278
+ self.assertEqual(proc.returncode, 0, proc.stdout)
279
+ self.assertIn("MISSING", proc.stdout)
280
+
281
+
282
+ class TestResolveAnswerPath(unittest.TestCase):
283
+ def test_single_case_falls_back_to_answer_md(self):
284
+ runner = import_runner()
285
+ with tempfile.TemporaryDirectory(prefix="pd_evals_") as root:
286
+ path = os.path.join(root, "answer.md")
287
+ with open(path, "w", encoding="utf-8") as fh:
288
+ fh.write("x")
289
+ self.assertEqual(runner.resolve_answer_path(root, "solo", 1), path)
290
+ self.assertIsNone(runner.resolve_answer_path(root, "solo", 7))
291
+
292
+
293
+ JUDGE_CASES = ("baseline-is-wrong", "executor-self-complete", "mechanism-choice")
294
+
295
+
296
+ def real_case(case_id):
297
+ for case in load_json()["evals"]:
298
+ if case["id"] == case_id:
299
+ return case
300
+ raise KeyError(case_id)
301
+
302
+
303
+ def answer_body(case_id, arm, rep):
304
+ """Unique body text with no arm name in it (so leaking an arm is detectable)."""
305
+ index = (0 if arm == "with" else 2) + rep
306
+ return "正文标记 %s-%d" % (case_id, index)
307
+
308
+
309
+ def make_answers(root, cases=JUDGE_CASES, reps=(1, 2)):
310
+ for case_id in cases:
311
+ for arm in ("with", "without"):
312
+ for rep in reps:
313
+ path = os.path.join(root, "%s-%s-r%d.txt" % (case_id, arm, rep))
314
+ with open(path, "w", encoding="utf-8", newline="\n") as fh:
315
+ fh.write(answer_body(case_id, arm, rep) + "\n")
316
+
317
+
318
+ def read_text(path):
319
+ with open(path, encoding="utf-8-sig") as fh:
320
+ return fh.read()
321
+
322
+
323
+ def write_pair(root, case_key, mapping, scores, items=None):
324
+ if items is None:
325
+ items = [{"id": "R%d" % (index + 1), "text": "要点 %d" % (index + 1)}
326
+ for index in range(4)]
327
+ payload = {"case": case_key, "items": items, "scores": scores}
328
+ for name, data in (("scores_%s.json" % case_key, payload),
329
+ ("map_%s.json" % case_key, mapping)):
330
+ with open(os.path.join(root, name), "w", encoding="utf-8", newline="\n") as fh:
331
+ json.dump(data, fh, ensure_ascii=False, indent=2)
332
+
333
+
334
+ def parse_stdout_json(proc):
335
+ return json.loads(proc.stdout)
336
+
337
+
338
+ class TestJudgeMode(unittest.TestCase):
339
+ def setUp(self):
340
+ self._tmpdir = tempfile.TemporaryDirectory(prefix="pd_judge_")
341
+ self.tmp = self._tmpdir.name
342
+ self.answers = os.path.join(self.tmp, "answers")
343
+ self.out = os.path.join(self.tmp, "out")
344
+ os.makedirs(self.answers)
345
+
346
+ def tearDown(self):
347
+ self._tmpdir.cleanup()
348
+
349
+ def judge(self, *extra):
350
+ return run_runner("--mode", "judge", "--answers", self.answers,
351
+ "--out", self.out, *extra)
352
+
353
+ def test_end_to_end_writes_prompt_template_and_map(self):
354
+ make_answers(self.answers)
355
+ proc = self.judge("--seed", "7")
356
+ self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
357
+ for case_id in JUDGE_CASES:
358
+ prompt_path = os.path.join(self.out, "judge_prompt_%s.md" % case_id)
359
+ template_path = os.path.join(self.out, "scores_template_%s.json" % case_id)
360
+ map_path = os.path.join(self.out, "map_%s.json" % case_id)
361
+ self.assertTrue(os.path.isfile(prompt_path), prompt_path)
362
+ self.assertTrue(os.path.isfile(template_path), template_path)
363
+ self.assertTrue(os.path.isfile(map_path), map_path)
364
+ prompt = read_text(prompt_path).lower()
365
+ self.assertNotIn("with", prompt, "%s: prompt leaks an arm name" % case_id)
366
+ self.assertNotIn("without", prompt, "%s: prompt leaks an arm name" % case_id)
367
+ self.assertEqual(prompt.count("===== 答复 ".lower()), 8) # 4 blocks, start + end
368
+ self.assertEqual(prompt.count("开始 =====".lower()), 4)
369
+ for arm in ("with", "without"):
370
+ for rep in (1, 2):
371
+ self.assertIn(answer_body(case_id, arm, rep).lower(), prompt)
372
+ template = load_json(template_path)
373
+ mapping = load_json(map_path)
374
+ self.assertEqual(template["case"], case_id)
375
+ self.assertEqual(len(template["items"]), 4)
376
+ self.assertEqual(sorted(template["scores"]), ["A", "B", "C", "D"])
377
+ self.assertEqual(sorted(mapping), ["A", "B", "C", "D"])
378
+ self.assertEqual(set(mapping.values()),
379
+ {"with-r1", "with-r2", "without-r1", "without-r2"})
380
+ self.assertEqual(set(template["scores"]), set(mapping))
381
+ for row in template["scores"].values():
382
+ self.assertEqual(row, [None, None, None, None])
383
+
384
+ def test_anonymised_order_is_not_the_file_order(self):
385
+ make_answers(self.answers)
386
+ proc = self.judge("--seed", "7")
387
+ self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
388
+ canonical = ["with-r1", "with-r2", "without-r1", "without-r2"]
389
+ orders = []
390
+ for case_id in JUDGE_CASES:
391
+ mapping = load_json(os.path.join(self.out, "map_%s.json" % case_id))
392
+ orders.append([mapping[label] for label in sorted(mapping)])
393
+ self.assertTrue(any(order != canonical for order in orders),
394
+ "every case kept the original arm/rep order: %s" % orders)
395
+
396
+ def test_same_seed_gives_identical_anonymisation(self):
397
+ make_answers(self.answers)
398
+ self.assertEqual(self.judge("--seed", "7").returncode, 0)
399
+ first = {cid: read_text(os.path.join(self.out, "map_%s.json" % cid))
400
+ for cid in JUDGE_CASES}
401
+ second_out = os.path.join(self.tmp, "out2")
402
+ proc = run_runner("--mode", "judge", "--answers", self.answers,
403
+ "--out", second_out, "--seed", "7")
404
+ self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
405
+ for case_id in JUDGE_CASES:
406
+ self.assertEqual(first[case_id],
407
+ read_text(os.path.join(second_out, "map_%s.json" % case_id)))
408
+
409
+ def test_bad_answer_filename_exits_2_and_names_it(self):
410
+ make_answers(self.answers, cases=("baseline-is-wrong",))
411
+ bad = os.path.join(self.answers, "notes.txt")
412
+ with open(bad, "w", encoding="utf-8", newline="\n") as fh:
413
+ fh.write("not an answer\n")
414
+ proc = self.judge()
415
+ self.assertEqual(proc.returncode, 2, proc.stdout)
416
+ self.assertIn("notes.txt", proc.stdout + proc.stderr)
417
+ self.assertIn("不符合", proc.stdout + proc.stderr)
418
+
419
+ def test_unequal_arm_counts_exit_2(self):
420
+ for rep in (1, 2):
421
+ path = os.path.join(self.answers, "baseline-is-wrong-with-r%d.txt" % rep)
422
+ with open(path, "w", encoding="utf-8", newline="\n") as fh:
423
+ fh.write(answer_body("baseline-is-wrong", "with", rep) + "\n")
424
+ path = os.path.join(self.answers, "baseline-is-wrong-without-r1.txt")
425
+ with open(path, "w", encoding="utf-8", newline="\n") as fh:
426
+ fh.write(answer_body("baseline-is-wrong", "without", 1) + "\n")
427
+ proc = self.judge()
428
+ self.assertEqual(proc.returncode, 2, proc.stdout)
429
+ self.assertIn("不一致", proc.stdout + proc.stderr)
430
+
431
+ def test_case_selector_filters_output(self):
432
+ make_answers(self.answers)
433
+ proc = self.judge("--case", "mech")
434
+ self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
435
+ written = sorted(os.listdir(self.out))
436
+ self.assertEqual(written, [
437
+ "judge_prompt_mechanism-choice.md",
438
+ "map_mechanism-choice.json",
439
+ "scores_template_mechanism-choice.json",
440
+ ])
441
+
442
+ def test_rubric_derived_from_must_include_has_four_items(self):
443
+ runner = import_runner()
444
+ case = real_case("baseline-is-wrong")
445
+ case.pop("rubric", None) # v1.3.5 起真 case 自带 rubric;这里专测「没有 rubric 时怎么派生」
446
+ rubric = runner.build_rubric(case)
447
+ self.assertEqual(len(rubric), 4)
448
+ joined = "\n".join(rubric)
449
+ for item in case["assertions"]["must_include"]:
450
+ self.assertIn(item, joined)
451
+ self.assertNotIn(case["expected_output"], joined)
452
+ for item in rubric:
453
+ self.assertTrue(item.startswith("要点:"), item)
454
+
455
+ def test_explicit_rubric_overrides_derivation(self):
456
+ data = load_json()
457
+ target = data["evals"][0]
458
+ custom = ["自定义要点一", "自定义要点二", "自定义要点三", "自定义要点四"]
459
+ target["rubric"] = custom
460
+ evals_path = os.path.join(self.tmp, "evals_rubric.json")
461
+ with open(evals_path, "w", encoding="utf-8", newline="\n") as fh:
462
+ json.dump(data, fh, ensure_ascii=False)
463
+ make_answers(self.answers, cases=(target["id"],))
464
+ proc = self.judge("--evals", evals_path, "--case", target["id"])
465
+ self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
466
+ template = load_json(os.path.join(self.out, "scores_template_%s.json" % target["id"]))
467
+ self.assertEqual([item["text"] for item in template["items"]], custom)
468
+
469
+
470
+ class TestRubricField(unittest.TestCase):
471
+ """v1.3.5:evals.json 自带 rubric 必须被优先采用;抄参考答案/条数不对要被静态校验抓住。"""
472
+
473
+ def test_real_cases_use_explicit_rubric(self):
474
+ runner = import_runner()
475
+ for cid in ("full-package", "baseline-is-wrong", "mechanism-choice"):
476
+ case = real_case(cid)
477
+ self.assertIn("rubric", case, cid)
478
+ self.assertEqual(len(case["rubric"]), 4, cid)
479
+ self.assertEqual(runner.build_rubric(case), case["rubric"], cid)
480
+
481
+ def test_rubric_copied_from_expected_output_is_rejected(self):
482
+ runner = import_runner()
483
+ data = load_json()
484
+ case = data["evals"][0]
485
+ case["rubric"] = [case["expected_output"][:20]] + case["rubric"][1:]
486
+ errors, _warnings = runner.validate(data, runner.load_manifest_axes())
487
+ joined = "\n".join(errors)
488
+ self.assertIn("rubric", joined)
489
+ self.assertTrue(("逐字抄" in joined) or ("参考答案" in joined), joined)
490
+
491
+ def test_rubric_wrong_length_is_rejected(self):
492
+ runner = import_runner()
493
+ data = load_json()
494
+ case = data["evals"][0]
495
+ case["rubric"] = case["rubric"][:3]
496
+ errors, _warnings = runner.validate(data, runner.load_manifest_axes())
497
+ self.assertTrue(any("rubric" in e for e in errors), errors)
498
+
499
+
500
+ class TestTallyMode(unittest.TestCase):
501
+ def setUp(self):
502
+ self._tmpdir = tempfile.TemporaryDirectory(prefix="pd_tally_")
503
+ self.tmp = self._tmpdir.name
504
+
505
+ def tearDown(self):
506
+ self._tmpdir.cleanup()
507
+
508
+ def tally(self, *extra):
509
+ return run_runner("--mode", "tally", "--out", self.tmp, *extra)
510
+
511
+ def test_hand_computed_paired_statistics(self):
512
+ # with totals 4+4=8, without totals 2+3=5 (4 rubric items x 2 reps each).
513
+ write_pair(
514
+ self.tmp, "c1",
515
+ {"A": "with-r1", "B": "without-r1", "C": "with-r2", "D": "without-r2"},
516
+ {"A": [1, 1, 1, 1], "B": [0, 1, 0, 1],
517
+ "C": [1, 1, 1, 1], "D": [1, 1, 0, 1]})
518
+ proc = self.tally("--json")
519
+ self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
520
+ stats = parse_stdout_json(proc)
521
+ self.assertEqual(stats["per_arm"]["with"], 8)
522
+ self.assertEqual(stats["per_arm"]["without"], 5)
523
+ self.assertEqual(stats["per_arm"]["max"], 8)
524
+ self.assertEqual(stats["cases"][0]["with"], 8)
525
+ self.assertEqual(stats["cases"][0]["without"], 5)
526
+ pairs = stats["per_arm"]["pairs"]
527
+ self.assertEqual(pairs["n"], 2)
528
+ self.assertEqual(pairs["with_better"], 2)
529
+ self.assertEqual(pairs["without_better"], 0)
530
+ self.assertEqual(pairs["tie"], 0)
531
+ self.assertEqual(pairs["win_rate"], 1.0)
532
+ self.assertAlmostEqual(stats["wilson"]["lower"], 1.0 / (1.0 + 1.96 ** 2 / 2.0), places=6)
533
+ self.assertAlmostEqual(stats["wilson"]["lower"], 0.342, places=3)
534
+ self.assertAlmostEqual(stats["wilson"]["upper"], 1.0, places=6)
535
+ self.assertEqual(stats["wilson"]["n"], 2)
536
+ self.assertTrue(any("方向性" in warning for warning in stats["warnings"]))
537
+ item_hits = {row["item"]: (row["with"], row["without"]) for row in stats["items"]}
538
+ self.assertEqual(item_hits["R3"], (2, 0))
539
+
540
+ def test_null_score_exits_2_and_names_the_cell(self):
541
+ write_pair(self.tmp, "c1",
542
+ {"A": "with-r1", "B": "without-r1"},
543
+ {"A": [1, None, 1, 1], "B": [1, 1, 1, 1]})
544
+ proc = self.tally()
545
+ self.assertEqual(proc.returncode, 2, proc.stdout)
546
+ combined = proc.stdout + proc.stderr
547
+ self.assertIn("null", combined)
548
+ self.assertIn("R2", combined)
549
+ self.assertIn("标签 A", combined)
550
+ self.assertIn("c1", combined)
551
+
552
+ def test_blanks_in_every_case_are_named_together(self):
553
+ """v1.3.1(c1 轻微项):多个 case 半填时,要一次点名所有受影响的 case。
554
+
555
+ 旧行为是遇到第一个 case 就抛错,后面的 case 空格永远不会被报出来。
556
+ """
557
+ write_pair(self.tmp, "c1",
558
+ {"A": "with-r1", "B": "without-r1"},
559
+ {"A": [1, None, 1, 1], "B": [1, 1, 1, 1]})
560
+ write_pair(self.tmp, "c2",
561
+ {"A": "with-r1", "B": "without-r1"},
562
+ {"A": [1, 1, 1, 1], "B": [1, 1, None, 1]})
563
+ proc = self.tally()
564
+ self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr)
565
+ combined = proc.stdout + proc.stderr
566
+ self.assertIn("null", combined)
567
+ self.assertIn("c1", combined)
568
+ self.assertIn("c2", combined)
569
+ self.assertIn("2 个 case", combined)
570
+
571
+ def test_unequal_arm_counts_exit_2(self):
572
+ write_pair(self.tmp, "c1",
573
+ {"A": "with-r1", "B": "without-r1", "C": "with-r2"},
574
+ {"A": [1, 1, 1, 1], "B": [1, 1, 1, 1], "C": [1, 1, 1, 1]})
575
+ proc = self.tally()
576
+ self.assertEqual(proc.returncode, 2, proc.stdout)
577
+ self.assertIn("两臂 rep 不一致", proc.stdout + proc.stderr)
578
+
579
+ def test_json_stdout_is_a_single_document(self):
580
+ write_pair(self.tmp, "c1",
581
+ {"A": "with-r1", "B": "without-r1"},
582
+ {"A": [1, 1, 1, 1], "B": [0, 0, 0, 0]})
583
+ proc = self.tally("--json")
584
+ self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
585
+ stats = json.loads(proc.stdout) # must parse whole stdout, no banner mixed in
586
+ for key in ("cases", "items", "pairs", "per_arm", "wilson", "warnings"):
587
+ self.assertIn(key, stats)
588
+ self.assertTrue(proc.stdout.lstrip().startswith("{"), proc.stdout[:80])
589
+ self.assertNotIn("===", proc.stdout)
590
+
591
+ def test_unpaired_files_exit_2(self):
592
+ write_pair(self.tmp, "c1",
593
+ {"A": "with-r1", "B": "without-r1"},
594
+ {"A": [1, 1, 1, 1], "B": [0, 0, 0, 0]})
595
+ os.remove(os.path.join(self.tmp, "map_c1.json"))
596
+ proc = self.tally()
597
+ self.assertEqual(proc.returncode, 2, proc.stdout)
598
+ self.assertIn("配对缺失", proc.stdout + proc.stderr)
599
+
600
+ def test_score_outside_0_or_1_exits_2(self):
601
+ write_pair(self.tmp, "c1",
602
+ {"A": "with-r1", "B": "without-r1"},
603
+ {"A": [1, 2, 1, 1], "B": [0, 0, 0, 0]})
604
+ proc = self.tally()
605
+ self.assertEqual(proc.returncode, 2, proc.stdout)
606
+ self.assertIn("分数非法", proc.stdout + proc.stderr)
607
+
608
+
609
+ class TestGradeDeprecation(unittest.TestCase):
610
+ def test_pass_still_works_and_prints_deprecated(self):
611
+ case = load_json()["evals"][0]
612
+ with tempfile.TemporaryDirectory(prefix="pd_grade_") as tmp:
613
+ answer = os.path.join(tmp, "answer.md")
614
+ with open(answer, "w", encoding="utf-8", newline="\n") as fh:
615
+ fh.write(gold_answer(case))
616
+ proc = run_runner("--mode", "grade", "--case", case["id"], "--answer", answer)
617
+ self.assertEqual(proc.returncode, 0, proc.stdout)
618
+ self.assertIn("DEPRECATED", proc.stdout)
619
+ self.assertIn("P-15-8", proc.stdout)
620
+ self.assertIn("CASE %s PASS" % case["id"], proc.stdout)
621
+
622
+ def test_fail_still_exits_1_and_prints_deprecated(self):
623
+ case = load_json()["evals"][0]
624
+ with tempfile.TemporaryDirectory(prefix="pd_grade_") as tmp:
625
+ answer = os.path.join(tmp, "answer.md")
626
+ with open(answer, "w", encoding="utf-8", newline="\n") as fh:
627
+ fh.write("完全无关的答案")
628
+ proc = run_runner("--mode", "grade", "--case", case["id"], "--answer", answer)
629
+ self.assertEqual(proc.returncode, 1, proc.stdout)
630
+ self.assertIn("DEPRECATED", proc.stdout)
631
+ self.assertIn("CASE %s FAIL" % case["id"], proc.stdout)
632
+
633
+
634
+ class TestHelpDocumentsFourModes(unittest.TestCase):
635
+ def test_help_lists_judge_tally_and_deprecation_reason(self):
636
+ proc = run_runner("--help")
637
+ self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
638
+ for token in ("static", "grade", "compare", "judge", "tally",
639
+ "DEPRECATED", "P-15-8", "Wilson"):
640
+ self.assertIn(token, proc.stdout)
641
+
642
+
643
+ if __name__ == "__main__":
644
+ unittest.main(verbosity=2)