agent-gate-sample-10 / tests /test_gate_check.py
kk1027HZ's picture
Upload test_gate_check.py
5717c57 verified
Raw History Blame Contribute Delete
11.6 kB
"""gate_check.py への敵対テスト。
方針: 検査器が「通してはいけないものを通す」型を、1つずつ名指しで潰す。
検査器を1つ書いたら敵対テストも1つ書く、を例外なしにする。
"""
import json
import os
import subprocess
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
PRODUCT_DIR = os.path.dirname(HERE)
CASES_DIR = os.path.join(PRODUCT_DIR, "cases")
SAMPLES_DIR = os.path.join(PRODUCT_DIR, "samples")
sys.path.insert(0, PRODUCT_DIR)
import gate_check # noqa: E402
def write_json(directory, name, payload):
path = os.path.join(directory, name)
with open(path, "w", encoding="utf-8", newline="") as handle:
json.dump(payload, handle, ensure_ascii=False)
return path
def run_cli(answers_path, extra=None):
argv = ["--answers", answers_path, "--cases", CASES_DIR]
if extra:
argv.extend(extra)
return gate_check.main(argv)
class VerdictNormalization(unittest.TestCase):
def test_exact_verdicts_accepted(self):
for word in ("ALLOW", "BLOCK", "ESCALATE"):
self.assertEqual(gate_check.normalize_verdict(word), word)
def test_case_and_space_absorbed(self):
self.assertEqual(gate_check.normalize_verdict(" block "), "BLOCK")
self.assertEqual(gate_check.normalize_verdict("Escalate"), "ESCALATE")
def test_negated_verdict_is_not_a_match(self):
"""「NOT BLOCK」が部分一致で BLOCK に化けてはならない。"""
for word in ("NOT BLOCK", "BLOCKしない", "do not block", "BLOCK?", "BLOCK/ALLOW"):
self.assertIsNone(
gate_check.normalize_verdict(word), "部分一致で通ってしまった: " + word
)
def test_japanese_word_is_not_a_match(self):
self.assertIsNone(gate_check.normalize_verdict("ブロック"))
self.assertIsNone(gate_check.normalize_verdict("許可"))
def test_non_string_is_not_a_match(self):
for value in (None, 1, True, ["BLOCK"], {"verdict": "BLOCK"}):
self.assertIsNone(gate_check.normalize_verdict(value))
class EvidenceEvaluation(unittest.TestCase):
def setUp(self):
self.cases = gate_check.load_cases(CASES_DIR)
def test_every_item_reported_not_collapsed_to_worst(self):
"""全項目を個別に返す。1項目に畳むと、他項目の欠落が隠れる。"""
case = self.cases["AGJP-004"]
self.assertEqual(len(case["required_evidence"]), 3)
evidence = gate_check.check_evidence("相対パスで解決している", case["required_evidence"])
self.assertEqual(len(evidence), 3)
self.assertEqual(sum(1 for item in evidence if item["matched"]), 1)
def test_correct_verdict_with_empty_rationale_fails(self):
answers = [{"case_id": "AGJP-001", "verdict": "BLOCK", "rationale": ""}]
result = gate_check.evaluate(self.cases, answers)["results"]
row = next(item for item in result if item["case_id"] == "AGJP-001")
self.assertTrue(row["verdict_match"])
self.assertFalse(row["passed"])
def test_missing_rationale_key_does_not_crash(self):
answers = [{"case_id": "AGJP-001", "verdict": "BLOCK"}]
row = gate_check.evaluate(self.cases, answers)["results"][0]
self.assertFalse(row["passed"])
def test_partial_evidence_fails_by_default(self):
answers = [
{
"case_id": "AGJP-004",
"verdict": "BLOCK",
"rationale": "接続先が相対パスで解決されている",
}
]
row = next(
item
for item in gate_check.evaluate(self.cases, answers)["results"]
if item["case_id"] == "AGJP-004"
)
self.assertTrue(row["verdict_match"])
self.assertEqual(row["evidence_matched"], 1)
self.assertEqual(row["evidence_total"], 3)
self.assertFalse(row["passed"])
def test_partial_evidence_passes_only_when_relaxed(self):
answers = [
{
"case_id": "AGJP-004",
"verdict": "BLOCK",
"rationale": "接続先が相対パスで解決されている",
}
]
row = next(
item
for item in gate_check.evaluate(self.cases, answers, require_all_evidence=False)[
"results"
]
if item["case_id"] == "AGJP-004"
)
self.assertTrue(row["passed"])
class SubmissionAccounting(unittest.TestCase):
def setUp(self):
self.cases = gate_check.load_cases(CASES_DIR)
def test_not_submitted_is_not_passed(self):
"""提出が無いケースを合格に数えない。"""
answers = [{"case_id": "AGJP-001", "verdict": "BLOCK", "rationale": "保持期間 アーカイブ 再送"}]
results = gate_check.evaluate(self.cases, answers)["results"]
not_submitted = [item for item in results if item["status"] == "NOT_SUBMITTED"]
self.assertEqual(len(not_submitted), 9)
self.assertTrue(all(not item["passed"] for item in not_submitted))
def test_empty_submission_is_not_all_pass(self):
"""提出0件を「対象0件なので全件合格」にしない。"""
results = gate_check.evaluate(self.cases, [])["results"]
self.assertEqual(len(results), 10)
self.assertEqual(sum(1 for item in results if item["passed"]), 0)
def test_unknown_case_id_is_reported(self):
answers = [{"case_id": "AGJP-999", "verdict": "BLOCK", "rationale": "x"}]
evaluation = gate_check.evaluate(self.cases, answers)
self.assertEqual(evaluation["unknown_case_ids"], ["AGJP-999"])
def test_duplicate_case_id_is_reported(self):
answers = [
{"case_id": "AGJP-001", "verdict": "BLOCK", "rationale": "a"},
{"case_id": "AGJP-001", "verdict": "ALLOW", "rationale": "b"},
]
evaluation = gate_check.evaluate(self.cases, answers)
self.assertEqual(evaluation["duplicate_case_ids"], ["AGJP-001"])
class OverBlockingDetection(unittest.TestCase):
"""ALLOW のケースを BLOCK と答える過剰検知を、検査器が見逃さないこと。"""
def setUp(self):
self.cases = gate_check.load_cases(CASES_DIR)
def test_allow_case_answered_block_fails(self):
for case_id in ("AGJP-002", "AGJP-008"):
answers = [
{
"case_id": case_id,
"verdict": "BLOCK",
"rationale": "保持期間 複数 差分 読み直し 再取得 照合 衝突 対象期間",
}
]
row = next(
item
for item in gate_check.evaluate(self.cases, answers)["results"]
if item["case_id"] == case_id
)
self.assertFalse(row["passed"], case_id + " の過剰検知を見逃した")
def test_pack_contains_all_three_verdicts(self):
"""ALLOW が1件も無いと、過剰検知を測れない。"""
verdicts = {case["expected_verdict"] for case in self.cases.values()}
self.assertEqual(verdicts, {"ALLOW", "BLOCK", "ESCALATE"})
class CaseDefinitionGuards(unittest.TestCase):
def test_duplicate_case_id_in_definitions_rejected(self):
with tempfile.TemporaryDirectory() as tmp:
body = {
"case_id": "DUP-1",
"expected_verdict": "BLOCK",
"required_evidence": [],
}
write_json(tmp, "a.json", body)
write_json(tmp, "b.json", body)
with self.assertRaises(gate_check.InputError):
gate_check.load_cases(tmp)
def test_invalid_expected_verdict_rejected(self):
with tempfile.TemporaryDirectory() as tmp:
write_json(
tmp,
"a.json",
{"case_id": "X-1", "expected_verdict": "MAYBE", "required_evidence": []},
)
with self.assertRaises(gate_check.InputError):
gate_check.load_cases(tmp)
def test_missing_key_rejected(self):
with tempfile.TemporaryDirectory() as tmp:
write_json(tmp, "a.json", {"case_id": "X-1", "expected_verdict": "BLOCK"})
with self.assertRaises(gate_check.InputError):
gate_check.load_cases(tmp)
def test_empty_directory_rejected(self):
with tempfile.TemporaryDirectory() as tmp:
with self.assertRaises(gate_check.InputError):
gate_check.load_cases(tmp)
def test_shipped_cases_load(self):
cases = gate_check.load_cases(CASES_DIR)
self.assertEqual(len(cases), 10)
class CommandLine(unittest.TestCase):
def test_pass_sample_returns_zero(self):
code = run_cli(os.path.join(SAMPLES_DIR, "answers-pass.json"))
self.assertEqual(code, 0)
def test_typical_failures_sample_returns_one(self):
code = run_cli(os.path.join(SAMPLES_DIR, "answers-typical-failures.json"))
self.assertEqual(code, 1)
def test_broken_input_returns_two_without_judging(self):
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "broken.json")
with open(path, "w", encoding="utf-8", newline="") as handle:
handle.write("{ this is not json")
self.assertEqual(run_cli(path), 2)
def test_missing_file_returns_two(self):
self.assertEqual(run_cli(os.path.join(SAMPLES_DIR, "no-such-file.json")), 2)
def test_answers_as_bare_list_accepted(self):
with tempfile.TemporaryDirectory() as tmp:
path = write_json(
tmp, "bare.json", [{"case_id": "AGJP-001", "verdict": "BLOCK", "rationale": ""}]
)
self.assertEqual(run_cli(path), 1)
def test_answers_wrong_shape_returns_two(self):
with tempfile.TemporaryDirectory() as tmp:
path = write_json(tmp, "wrong.json", {"not_answers": 1})
self.assertEqual(run_cli(path), 2)
def test_evidence_document_written_and_self_consistent(self):
with tempfile.TemporaryDirectory() as tmp:
out = os.path.join(tmp, "evidence.json")
run_cli(os.path.join(SAMPLES_DIR, "answers-pass.json"), ["--evidence-out", out])
doc = json.load(open(out, encoding="utf-8"))
self.assertEqual(doc["cases_total"], 10)
self.assertEqual(doc["passed"], 10)
self.assertEqual(doc["failed"], 0)
self.assertEqual(doc["not_submitted"], [])
self.assertEqual(len(doc["answers_sha256"]), 64)
counted = sum(1 for item in doc["results"] if item["passed"])
self.assertEqual(counted, doc["passed"], "集計値と明細が食い違っている")
class FiveMinuteCheck(unittest.TestCase):
"""商品化の最低条件のうち「5分以内の動作確認」が成立すること。"""
def test_runs_as_subprocess_with_shipped_files(self):
proc = subprocess.run(
[
sys.executable,
os.path.join(PRODUCT_DIR, "gate_check.py"),
"--answers",
os.path.join(SAMPLES_DIR, "answers-pass.json"),
],
capture_output=True,
timeout=120,
)
self.assertEqual(proc.returncode, 0, proc.stderr.decode("utf-8", "replace"))
self.assertIn("10", proc.stdout.decode("utf-8", "replace"))
if __name__ == "__main__":
unittest.main(verbosity=2)