import json import os import pathlib import subprocess import sys import tempfile import textwrap import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from question_bench.questions import agreement, askable, calls, Code, misses, prompt, questions, referred, sampled from failure import Failure from test_loop_claude_black_box import host_env TOOL = pathlib.Path(__file__).resolve().parent / "question-bench" SOURCE = textwrap.dedent(""" def hard(a): def inner(): return easy() return inner() + helpers.shared(a) def easy(): return len([]) class Box: def __init__(self): self.shared() def shared(self): return hard(1) def shared(): pass """) class Questions(unittest.TestCase): def code(self) -> Code: found = calls("a.py", SOURCE) assert not isinstance(found, Failure) tests = referred("test_a.py", "from a import hard\n# easy\n\ndef test():\n\tassert a.Box\n\t'easy'\n") assert not isinstance(tests, Failure) return Code(found, {"test_a.py": tests}) def test_counts_a_nested_functions_calls_and_attribute_calls_toward_their_unit(self): self.assertEqual(dict(self.code().calls)[("a.py", "hard")], {"inner", "easy", "shared"}) def test_a_test_file_refers_to_names_in_code_not_strings_or_comments(self): self.assertEqual(self.code().tests["test_a.py"], {"hard", "a", "Box"}) def test_asks_only_about_units_whose_name_no_other_unit_shares_and_no_dunder(self): self.assertEqual(askable(self.code()), [("a.py", "easy"), ("a.py", "hard")]) def test_answers_each_question_from_the_syntax_tree(self): truths = {question.text: set(question.truth) for question in questions(self.code(), [("a.py", "hard")], "abc")} self.assertEqual(truths, { "Which units call `hard`, defined in `a.py`?": {"a.py:shared"}, "Which unit names does `a.py:hard` call? Answer each as the bare name.": {"easy", "shared"}, "Which test files refer to `hard` in their code, not only in a string or comment?": {"test_a.py"}, }) def test_samples_every_named_unit_and_as_many_others_the_same_way_each_run(self): units = [("a.py", name) for name in "abcdef"] picked = sampled(units, {("a.py", "c")}, "abc") self.assertEqual((picked[0], len(picked)), (("a.py", "c"), 2)) self.assertEqual(picked, sampled(units, {("a.py", "c")}, "abc")) def test_numbers_the_questions_in_the_prompt(self): asked = questions(self.code(), [("a.py", "easy")], "abc") self.assertIn(f"3. {asked[2].text}", prompt(asked)) def test_scores_an_answer_by_its_jaccard_index_with_paths_read_from_the_root(self): self.assertEqual(agreement(frozenset({"a.py:x", "a.py:y"}), [" `/tmp/r/a.py:x` ", "./a.py:z"], "/tmp/r"), 1 / 3) self.assertEqual(agreement(frozenset(), [], "/tmp/r"), 1.0) def test_a_unit_misses_by_one_less_its_answers_mean_score(self): asked = questions(self.code(), [("a.py", "easy")], "abc") self.assertEqual(misses(asked, [sorted(question.truth) for question in asked[:2]] + [["wrong"]], "/r"), {("a.py", "easy"): 1 - 2 / 3}) # Plays claude: answers each question from FAKE_ANSWERS by its text, or fails with FAKE_FAIL. FAKE_CLAUDE = """#!{python} import json, os, re, sys if os.environ.get("FAKE_FAIL"): sys.exit("out of credit") answers = json.loads(os.environ["FAKE_ANSWERS"]) texts = re.findall(r"^\\d+\\. (.*)$", sys.stdin.read(), re.M) print(json.dumps({{"structured_output": {{"answers": [answers.get(text, []) for text in texts]}}, "usage": {{"input_tokens": 5, "cache_creation_input_tokens": 95}}, "total_cost_usd": 0.25}})) """ class BlackBox(unittest.TestCase): def project(self, history: str) -> str: directory = tempfile.TemporaryDirectory() self.addCleanup(directory.cleanup) top = str(pathlib.Path(directory.name, "project")) os.makedirs(pathlib.Path(top, "docs")) env = host_env() for args in (["init", "-q"], ["config", "user.email", "t@t"], ["config", "user.name", "t"]): subprocess.run(["git", *args], cwd=top, check=True, env=env) pathlib.Path(top, "a.py").write_text("def hard(a):\n\tif a:\n\t\treturn easy()\n\n\ndef easy():\n\treturn 1\n") pathlib.Path(top, "test_a.py").write_text("from a import hard\n") subprocess.run(["git", "add", "."], cwd=top, check=True, env=env) subprocess.run(["git", "commit", "-qm", "a"], cwd=top, check=True, env=env) commit = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=top, check=True, capture_output=True, text=True, env=env).stdout.strip() pathlib.Path(top, "docs", "comprehension-history.md").write_text(history.replace("COMMIT", commit)) fakes = pathlib.Path(directory.name, "fakes") fakes.mkdir() fake = fakes / "claude" fake.write_text(FAKE_CLAUDE.format(python=sys.executable)) fake.chmod(0o755) self.path = f"{fakes}{os.pathsep}{env['PATH']}" return top def run_tool(self, top: str, answers: dict[str, list[str]], *args: str, fail: bool = False) -> subprocess.CompletedProcess: env = {**host_env(), "FAKE_ANSWERS": json.dumps(answers), "PATH": self.path, **({"FAKE_FAIL": "1"} if fail else {})} return subprocess.run([sys.executable, str(TOOL), *args], cwd=top, capture_output=True, text=True, env=env) HISTORY = "# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mean | 7.00 | 7.00 | 7.00 | 7.00 | 6.75 |\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n" def test_prints_the_answer_score_tokens_cost_and_each_ranking_on_each_run(self): top = self.project(self.HISTORY) ran = self.run_tool(top, {"Which test files refer to `easy` in their code, not only in a string or comment?": [], "Which unit names does `a.py:easy` call? Answer each as the bare name.": [], "Which units call `easy`, defined in `a.py`?": ["a.py:hard"]}) self.assertEqual(ran.returncode, 0, ran.stderr) self.assertIn("| 2026-10-08T12:50:49Z, PR #1 at ", ran.stdout) self.assertIn("| 2 | 1 | 6.75 | 0.67 | 100 | 0.25 | AUC 1.00, top k 1.00 |", ran.stdout) self.assertIn("| Median |", ran.stdout) self.assertEqual(subprocess.run(["git", "worktree", "list"], cwd=top, capture_output=True, text=True, env=host_env()).stdout.count("\n"), 1) def test_names_a_run_claude_did_not_answer_and_exits_1_when_none_was(self): top = self.project(self.HISTORY) ran = self.run_tool(top, {}, fail=True) self.assertEqual(ran.returncode, 1) self.assertIn("Not answered: 2026-10-08T12:50:49Z, PR #1", ran.stderr) self.assertIn("out of credit", ran.stderr) def test_names_a_run_with_nothing_to_ask(self): top = self.project(self.HISTORY.replace("`a.py:1` `hard`", "`README.md:1` \"Install\"")) ran = self.run_tool(top, {}) self.assertEqual(ran.returncode, 1) self.assertIn("Not asked, no unit it names can be asked about", ran.stderr) def test_takes_a_model_and_rejects_unknown_arguments(self): top = self.project(self.HISTORY) self.assertEqual(self.run_tool(top, {}, "--model", "haiku").returncode, 0) self.assertEqual(self.run_tool(top, {}, "--x").returncode, 1) self.assertEqual(self.run_tool(top, {}, "--model").returncode, 1)