diff --git a/AGENTS.md b/AGENTS.md index 6664708e..48829af0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -276,6 +276,20 @@ reader chooses, does or concludes. - A prerequisite Review already checks is not repeated. - `docs/standard.md` headings are never renamed: the import skills cite them. +### Test design + +- Test observable behavior, contracts and meaningful failure modes—not incidental + wording, internal structure or current catalogue contents. +- Before adding a test, inspect nearby coverage. Extend an existing case or use + subtests when the fixture and behavior are shared. +- Add a separate test when it protects a distinct regression or needs a different + setup. A past bug alone does not require a separate test. +- Assert exact text only when that text is a contract. +- Before removing a test as redundant, identify the surviving assertions that + protect its behavior. Shared line coverage alone is insufficient. +- Consolidation must preserve edge cases and fixture isolation. Fewer test methods + is not itself the goal. + ### Attribution **No machine attribution in commit messages or pull request descriptions** — no diff --git a/app/tests/harnesses/test_atif.py b/app/tests/harnesses/test_atif.py index f8214ae7..3ee3f1ba 100644 --- a/app/tests/harnesses/test_atif.py +++ b/app/tests/harnesses/test_atif.py @@ -62,12 +62,6 @@ def test_the_supported_versions_are_pinned(self): class Detection(unittest.TestCase): - - def test_it_does_not_claim_an_unrelated_directory(self): - self.assertFalse(atif.detect(tempfile.mkdtemp())) - self.assertFalse(atif.detect("/nonexistent/tree")) - - def test_well_formed_json_that_is_not_atif_is_passed_over(self): src = tempfile.mkdtemp() write_doc(src, "trace.json", {"harbor-trace-v1": True, "roots": []}) @@ -97,7 +91,6 @@ def convert(self, root, **kw): self.assertEqual(len(job_dirs), 1) return job_dirs[0], parse.parse_job(job_dirs[0]) - def test_trial_names_follow_the_tree_and_a_bare_trajectory_takes_its_directory(self): src = tempfile.mkdtemp() write_doc(src, "a.json", minimal()) @@ -177,7 +170,7 @@ def test_truncated_json_is_refused_by_name_and_redacted(self): # nothing was rewritten while refusing self.assertTrue(os.path.isfile(good) and os.path.isfile(bad)) - def test_a_document_without_steps_is_refused_as_partial(self): + def test_a_document_without_a_list_of_steps_is_refused(self): doc = minimal() doc.pop("steps") doc["extra"] = {"token": FAKE_KEY} @@ -186,8 +179,7 @@ def test_a_document_without_steps_is_refused_as_partial(self): self.assertIn("partial.json", message) self.assertIn("no steps", message) self.assertNotIn(FAKE_KEY, message) - - def test_steps_of_the_wrong_shape_are_refused(self): + os.remove(os.path.join(self.src, "partial.json")) write_doc(self.src, "odd.json", minimal(steps={"not": "a list"})) self.assertIn("steps is not a list", self.refused()) @@ -209,11 +201,9 @@ def test_a_directory_with_nothing_of_ours_is_refused(self): self.assertIn("no ATIF trajectories", message) self.assertIn("ATIF-v1.0", message) - def test_the_file_is_named_relative_to_the_tree_given(self): + def test_the_file_is_named_relative_to_the_tree_or_by_its_own_name(self): write_doc(self.src, "deep/er/bad.json", '{"schema_version": "ATIF-v1.7"') self.assertTrue(self.refused().startswith("deep/er/bad.json: ")) - - def test_a_single_bad_file_is_refused_by_its_own_name(self): path = write_doc(self.src, "lone.json", '{"schema_version": "ATIF-v1.7", "steps": ') self.assertTrue(self.refused(path).startswith("lone.json: not JSON")) @@ -223,15 +213,5 @@ def test_a_good_tree_passes_check_without_writing(self): self.assertEqual(os.listdir(self.out), []) -class Trees(unittest.TestCase): - """What one job is under a root the picker opened: the root, as the CLI - reads it — a nested directory of trajectories is one job of several - trials, not a job per child.""" - - - def test_a_directory_with_nothing_of_ours_is_no_tree(self): - self.assertEqual(atif.trees(tempfile.mkdtemp()), []) - - if __name__ == "__main__": unittest.main() diff --git a/app/tests/harnesses/test_otel_import.py b/app/tests/harnesses/test_otel_import.py index e4d7e337..9c082b53 100644 --- a/app/tests/harnesses/test_otel_import.py +++ b/app/tests/harnesses/test_otel_import.py @@ -19,13 +19,6 @@ class Detect(unittest.TestCase): - - def test_unrelated_directories_are_not_claimed(self): - self.assertFalse(importer.detect(tempfile.mkdtemp())) - self.assertFalse(importer.detect("/nonexistent/otel/export")) - # a Harbor job: result.json / trajectory / trace.json — no resourceSpans - self.assertFalse(importer.detect(str(APP / "tests" / "fixtures" / "harbor-jobs"))) - def test_a_directory_of_only_refused_files_is_not_claimed(self): root = tempfile.mkdtemp() with open(os.path.join(root, "broken.json"), "w") as fh: @@ -40,7 +33,6 @@ def setUp(self): self.out = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.out, True) - def test_nothing_readable_is_an_error_naming_the_refusals(self): src = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, src, True) @@ -71,16 +63,5 @@ def test_a_refused_file_deeper_down_is_named_by_its_path_under_the_root_once(sel self.assertEqual(reason.count("jaeger-trace.json"), 1) -class Trees(unittest.TestCase): - """What one job is under a root the picker opened: an export - directory is one job; a parent of several export directories is one job - per directory, each one producer's export, not one pooled job.""" - - - def test_a_directory_with_no_export_is_no_tree(self): - self.assertEqual(importer.trees(tempfile.mkdtemp()), []) - self.assertEqual(importer.trees("/nonexistent/export"), []) - - if __name__ == "__main__": unittest.main() diff --git a/app/tests/harnesses/test_registry.py b/app/tests/harnesses/test_registry.py index f43f89a2..ca5eff1c 100644 --- a/app/tests/harnesses/test_registry.py +++ b/app/tests/harnesses/test_registry.py @@ -38,38 +38,24 @@ def test_every_importer_satisfies_the_contract(self): self.assertTrue((module.__doc__ or "").strip(), "an importer documents what it reads") - def test_an_unknown_name_is_none_not_an_error(self): - # The CLI turns this into a usage message listing what exists; raising - # here would make a typo look like a crash. - self.assertIsNone(harnesses.get("no-such-harness")) - self.assertIsNone(harnesses.get("")) - def test_nothing_claims_an_unrelated_directory(self): # detect() runs against whatever a caller points at, including a plain # directory. A harness that answers yes to everything would capture # every future import. empty = tempfile.mkdtemp() self.assertIsNone(harnesses.detect(empty)) - - def test_detect_survives_a_path_that_does_not_exist(self): self.assertIsNone(harnesses.detect("/nonexistent/run/tree")) def test_the_registry_names_no_harness_itself(self): # The removal property: deleting a module must be the whole deletion, - # so this package cannot mention one by name. - source = (APP / "nullius" / "importers" / "__init__.py").read_text() - for name in harnesses.available(): - with self.subTest(harness=name): - self.assertNotIn(name, source.split('"""')[-1], - f"{name} is named in the registry's code") - - def test_the_cli_names_no_harness_either(self): - source = (APP / "nullius" / "importers" / "cli.py").read_text() - body = source.split('"""')[-1] - for name in harnesses.available(): - with self.subTest(harness=name): - self.assertNotIn(name, body, - f"{name} is named in the CLI's code") + # so neither this package nor its CLI can mention one by name. + for file, what in (("__init__.py", "the registry's code"), + ("cli.py", "the CLI's code")): + source = (APP / "nullius" / "importers" / file).read_text() + body = source.split('"""')[-1] + for name in harnesses.available(): + with self.subTest(file=file, harness=name): + self.assertNotIn(name, body, f"{name} is named in {what}") class FirstMatchIsStable(unittest.TestCase): @@ -80,7 +66,6 @@ class FirstMatchIsStable(unittest.TestCase): """ EXAMPLES = APP / "tests" / "fixtures" - def test_no_importer_claims_a_harbor_job(self): for job in ("liveboard-oracle-x4",): path = str(self.EXAMPLES / "harbor-jobs" / job) @@ -160,15 +145,6 @@ def convert(src, out, job_name="", command=""): self.assertEqual(len(outs), 1) self.assertFalse(os.path.exists(outs[0]), "the scratch directory is removed") - def test_a_good_tree_is_no_problem(self): - self.registry(stub("x", check=lambda path: None)) - self.assertIsNone(harnesses.problem("/t")) - - def test_labels_name_the_importers_for_a_person(self): - a, b = stub("a"), stub("b") - b.LABEL = "Bee" - self.registry(a, b) - self.assertEqual(harnesses.labels(), "a, Bee") class Disjoint(unittest.TestCase): """No two importers claim one directory. @@ -210,14 +186,6 @@ def test_at_most_one_importer_claims_each_shape(self): self.assertLessEqual(len(claimants), 1, f"{shape} is claimed by {claimants}") - def test_the_otel_importer_claims_none_of_the_other_shapes(self): - module = harnesses.get("otel") - self.assertIsNotNone(module) - for shape, path in self.candidates().items(): - with self.subTest(shape=shape): - self.assertFalse(module.detect(path)) - - class CLI(unittest.TestCase): """`--list` and refusal, against the registry there is and an empty one.""" @@ -241,16 +209,6 @@ def test_list_names_every_registered_importer(self): self.assertIn(name, out) self.assertNotIn("no importers registered", out) - def test_list_with_nothing_registered_says_so_and_exits_zero(self): - # With no importer registered, printing nothing would read exactly - # like a CLI that imported and did no work. - self.empty() - code, out, _ = self.run_cli("--list") - self.assertEqual(code, 0) - self.assertEqual(out.strip(), "no importers registered") - code, out, _ = self.run_cli("--list", "--json") - self.assertEqual((code, json.loads(out)), (0, {})) - def test_an_unrecognised_tree_is_refused_with_nothing_registered(self): self.empty() with tempfile.TemporaryDirectory() as run: @@ -275,10 +233,8 @@ class Trees(unittest.TestCase): The default: the root, as one job. """ - def test_a_claimed_root_is_one_tree_by_default(self): + def test_a_claimed_root_is_one_tree_by_default_and_an_unclaimed_one_none(self): self.assertEqual(harnesses.trees(stub("x"), "/exp"), ["/exp"]) - - def test_an_unclaimed_root_is_no_tree_by_default(self): self.assertEqual(harnesses.trees(stub("x", detect=False), "/exp"), []) def test_an_importer_with_its_own_answer_is_asked_and_the_default_is_not(self): @@ -286,11 +242,6 @@ def test_an_importer_with_its_own_answer_is_asked_and_the_default_is_not(self): module.trees = lambda root: [os.path.join(root, "a"), os.path.join(root, "b")] self.assertEqual(harnesses.trees(module, "/exp"), ["/exp/a", "/exp/b"]) - def test_trees_is_not_part_of_the_contract(self): - # A module without it still registers: the hook is optional, and - # the default is the CLI's reading rather than a missing name. - self.assertNotIn("trees", harnesses._CONTRACT) - def test_every_registered_importer_answers_and_an_empty_directory_is_nothing(self): # Each importer there is says what one job is under a root — the # answers differ, which is why diff --git a/app/tests/test_behavior.py b/app/tests/test_behavior.py index d745a6e3..370694de 100644 --- a/app/tests/test_behavior.py +++ b/app/tests/test_behavior.py @@ -125,14 +125,6 @@ def test_same_work_under_other_names_reads_the_same(self): self.assertEqual(short.exploration_per_edit, 3.0) self.assertEqual((short.n_search, short.n_read, short.n_edit), (1, 2, 1)) - def test_a_retry_is_the_same_name_and_target_within_one_agent(self): - # The one place a name is a key: repeating a call that already failed. - # That compares an agent with itself, so its own vocabulary is right. - failed = "success=False data={} error='boom'" - tr = _traj([_tool_step(1, "Run the tests", {"command": "pytest"}, observation=failed), - _tool_step(2, "Run the tests", {"command": "pytest"}, observation=failed)]) - self.assertEqual(behavior.analyze(tr).n_repeated_failed_calls, 1) - if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_benchmark_agents.py b/app/tests/test_benchmark_agents.py index 62a81f41..d78eaec4 100644 --- a/app/tests/test_benchmark_agents.py +++ b/app/tests/test_benchmark_agents.py @@ -135,7 +135,6 @@ def test_one_entry_list_whose_fits_are_the_builders(self): self.assertEqual(page["osworld1:openai-cua"]["protocol"], "Its own script") - RECIPE = {"harness": "standard", "name": "os", "benchmark": "osworld1", "datasets": ["test_small"], "provider": "openrouter", "model": "computer-use-preview", "model_choice": "paper", "where": "local", "backend": "local"} @@ -180,16 +179,11 @@ def test_like_the_paper_names_the_agent_a_model_is_not_published_with(self): self.assertEqual(said, [{"step": recipe.STEP["model"], "message": "OpenAI CUA is published with computer-use-preview: choose one of them, or Any of your choice for another."}]) - def test_two_of_its_agents_without_a_model_say_so_once(self): - said = [e["message"] for e in self.compiled(others=["osworld1:m3", "osworld1:claude"], model="")["errors"]] - self.assertEqual(said.count("Choose a model."), 1) - def test_another_benchmarks_agent_is_refused_with_its_reason(self): said = [e["message"] for e in self.compiled(others=["osworld2:m3"])["errors"]] self.assertEqual(said, ["MiniMax M3 cannot run OSWorld1: MiniMax M3 belongs to OSWorld2."]) - class Records(unittest.TestCase): def setUp(self): self.tmp = tempfile.mkdtemp(prefix="nullius-own-job-") diff --git a/app/tests/test_benchmarks.py b/app/tests/test_benchmarks.py index bc9e498f..b666a60c 100644 --- a/app/tests/test_benchmarks.py +++ b/app/tests/test_benchmarks.py @@ -105,8 +105,6 @@ def test_usable_is_unknown_when_nothing_was_produced(self): patch_successfully_applied=False)) self.assertIs(v.produced, False) self.assertIsNone(v.usable, "no patch means the question has no answer") - - def test_patch_is_none_counts_as_not_produced(self): self.assertIs(swe(report(patch_is_None=True)).produced, False) def test_tolerates_a_missing_or_malformed_report(self): @@ -140,17 +138,6 @@ def test_counts_fall_back_to_the_test_list_when_summary_is_absent(self): v = tb(ctrf(passed=("a",), failed=("b",), summary=False), 0.0) self.assertEqual((v.gained_pass, v.gained_fail), (1, 1)) - def test_the_reward_marker_scores_without_detail(self): - # Non-pytest tasks (qemu-alpine-ssh, mailman) leave only reward.txt; - # the loader hands read() a bare {} for them. - v = tb({}, 1.0) - self.assertIs(v.succeeded, True) - - def test_there_is_no_patch_vocabulary(self): - v = tb(ctrf(failed=("a",)), 0.0) - self.assertIsNone(v.produced) - self.assertIsNone(v.usable) - class Loading(unittest.TestCase): """Which file the report is: dataset-owned, so it dispatches like read().""" @@ -232,12 +219,6 @@ class VocabularyDispatch(unittest.TestCase): vocabulary names it, so a Terminal-Bench trial never says "Fail → Pass" and never answers "Patch applied: No" about patches it cannot have.""" - def test_swe_bench_speaks_its_own_names(self): - v = verifier.vocabulary_for("swebench-verified") - self.assertEqual((v.gained, v.held), ("Fail → Pass", "Pass → Pass")) - self.assertEqual((v.gained_abbr, v.held_abbr), ("F→P", "P→P")) - self.assertTrue(v.has_patch) - def test_terminal_bench_has_tests_and_nothing_else(self): v = verifier.vocabulary_for("terminal-bench") self.assertEqual(v.gained, "Tests") diff --git a/app/tests/test_catalog.py b/app/tests/test_catalog.py index 9bdc0055..31e5a3cd 100644 --- a/app/tests/test_catalog.py +++ b/app/tests/test_catalog.py @@ -29,15 +29,6 @@ def test_shipped_catalogue_is_consistent(self): for d in cat.datasets: self.assertIsNotNone(cat.benchmark(d.benchmark), d.key) - def test_an_entry_says_official_or_community_and_nothing_of_its_runs(self): - for b in catalog.load(catalog.ROOT).benchmarks: - self.assertIn(b.origin, catalog.ORIGINS, b.key) - self.assertEqual(catalog.ORIGINS, ("official", "community")) - for gone in ("status", "status_note", "branch", "experiment"): - self.assertNotIn(gone, catalog.Benchmark.__dataclass_fields__) - - def test_tabs_are_alphabetical_and_lanes_are_not_benchmarks(self): - cat = catalog.load(catalog.ROOT) titles = [b.title for b in cat.listed_benchmarks] self.assertEqual(titles, sorted(titles, key=catalog.sort_key)) # what has a usable route is listed, whoever made it and whether or not it has run @@ -49,6 +40,7 @@ def test_tabs_are_alphabetical_and_lanes_are_not_benchmarks(self): self.assertLess(titles.index("τ³-bench"), titles.index("Terminal-Bench 2.0")) self.assertTrue(all(d.source for d in cat.datasets)) + def test_units_that_may_not_be_redistributed_are_named_nowhere(self): """No UUID-shaped string, a task id's shape, in such a benchmark's folder or its generated page. A failure names the files, never what was found.""" @@ -144,10 +136,6 @@ class DeclaredTimeouts(unittest.TestCase): PHASES = ("env_setup", "agent_setup", "agent_run", "verify") - def test_tau3_carries_the_four_phases(self): - t = catalog.load(catalog.ROOT).benchmark("tau3-bench").timeouts - self.assertEqual({k: t[k] for k in self.PHASES}, {"env_setup": 600, "agent_setup": 1200, "agent_run": 3600, "verify": 300}) - def test_a_recording_is_complete_or_absent(self): for b in catalog.load(catalog.ROOT).benchmarks: with self.subTest(b.key): @@ -200,12 +188,6 @@ def test_every_folder_holds_an_entry_named_after_it(self): self.assertEqual([b.key for b in catalog.load(catalog.ROOT).benchmarks], folders) self.assertEqual(catalog.layout(catalog.ROOT), []) - def test_no_runner_definition_is_left(self): - # a benchmark's own scripts run as the standard's Original setup; no folder keeps a runner.json - self.assertEqual([f for f in sorted(os.listdir(self.ROOT / catalog.BENCHMARKS)) - if (self.ROOT / catalog.BENCHMARKS / f / "runner.json").exists()], []) - self.assertEqual(catalog.HARNESSES, (("standard", "Nullius"), ("harbor", "Harbor"))) - def test_an_entry_that_does_not_read_is_left_out_and_named(self): """A hand-edited user entry - a trailing comma, a list, no title - must not fail every page.""" @@ -220,10 +202,6 @@ def test_an_entry_that_does_not_read_is_left_out_and_named(self): for name in ("comma", "list", "bare"): self.assertTrue(any(p.startswith(f"{catalog.BENCHMARKS}/{name}/") for p in problems), (name, problems)) - def test_no_dataset_key_repeats(self): - keys = [d.key for d in catalog.load(catalog.ROOT).datasets] - self.assertEqual(len(keys), len(set(keys)), keys) - def test_validation_refuses_a_misnamed_folder_and_a_repeated_dataset(self): with tempfile.TemporaryDirectory() as root: def entry(folder, key, datasets): @@ -264,22 +242,6 @@ class Routes(unittest.TestCase): def _bench(self, **kw): return catalog.Benchmark(key="k", title="T", category="Coding", **kw) - def test_the_shipped_catalogue_carries_the_cases_its_harnesses_allow(self): - cat = catalog.load(catalog.ROOT) - cases = {b.key: b.route_case for b in cat.listed_benchmarks} - self.assertEqual(cases["terminal-bench"], "multi-route") # Harbor's dataset, and the standard (each task's own image) - self.assertEqual(cases["swe-bench-verified"], "multi-route") # Harbor's dataset, and the standard (each instance's own image) - self.assertEqual(cases["longmemeval"], "non-harbor") # the standard only - self.assertEqual(cases["tau3-bench"], "multi-route") # Harbor's adapter, and the standard - # every listed benchmark falls in one of the three; Harbor is every entry's route, and the - # standard only of the entries naming it - self.assertTrue(set(cases.values()) <= {"harbor-only", "multi-route", "non-harbor"}) - self.assertEqual(set(cases.values()), {"multi-route", "non-harbor"}) - for b in cat.listed_benchmarks: - self.assertEqual([r.harness for r in b.routes], [k for k, _ in catalog.HARNESSES if k == "harbor" or k in b.harness], b.key) - self.assertEqual([k for k, _ in catalog.HARNESSES], ["standard", "harbor"]) # Nullius first, everywhere - self.assertEqual(cat.benchmark("longmemeval").harness, ["standard"]) # its own scripts: the standard's Original setup - def test_every_listed_benchmark_says_how_to_cite_it_and_where_that_came_from(self): for b in catalog.load(catalog.ROOT).listed_benchmarks: self.assertTrue(b.citation.lstrip().startswith("@"), b.key) # BibTeX, as its repository gives it diff --git a/app/tests/test_catalogue_docs.py b/app/tests/test_catalogue_docs.py index f59e6192..83951c5e 100644 --- a/app/tests/test_catalogue_docs.py +++ b/app/tests/test_catalogue_docs.py @@ -8,7 +8,6 @@ """ from __future__ import annotations -import os import unittest from nullius.catalogue import catalog @@ -20,23 +19,6 @@ def test_the_generated_files_are_current(self): self.assertEqual(catalogue_docs.stale(), [], "run: python3 app/tests/catalogue_docs.py --write") - def test_project_with_helper_package_keeps_its_repository_source(self): - entry = {"upstream": {"repository": "https://example.org/agent", "tested": "a" * 40}, - "install": {"project": ".", "pip": ["websockets==15.0.1"]}} - self.assertEqual(catalogue_docs._from(entry), "repository") - installed = catalogue_docs._installed_from(entry) - self.assertIn("example.org/agent", installed) - self.assertIn("websockets==15.0.1", installed) - - def test_every_section_has_its_index_with_a_block(self): - for kind, folder in catalogue_docs.SECTIONS.items(): - path = os.path.join(folder, catalogue_docs.INDEX) - with open(path, encoding="utf-8") as fh: - text = fh.read() - self.assertIn(catalogue_docs.START, text, path) - self.assertIn(catalogue_docs.END, text, path) - self.assertLess(text.find(catalogue_docs.START), text.find(catalogue_docs.END), path) - def test_the_pages_name_every_definition(self): def named(key, text): # a key is a code chip: markdown's in a table, HTML's on a card diff --git a/app/tests/test_categorical_charts.py b/app/tests/test_categorical_charts.py index c7422b37..cb492bfd 100644 --- a/app/tests/test_categorical_charts.py +++ b/app/tests/test_categorical_charts.py @@ -19,9 +19,7 @@ def test_round_steps_enclose_the_range(self): self.assertEqual(c.nice_ticks(0, 1), (0, 0.25, 0.5, 0.75, 1)) self.assertEqual(c.nice_ticks(-3, 5), (-4, -2, 0, 2, 4, 6)) self.assertEqual(c.nice_ticks(0.0012, 0.0031)[0], 0.001) - - def test_whole_counts_never_step_below_one(self): - self.assertEqual(c.nice_ticks(0, 3, step_min=1), (0, 1, 2, 3)) + self.assertEqual(c.nice_ticks(0, 3, step_min=1), (0, 1, 2, 3)) # whole counts never step below one def test_long_tick_labels_that_would_touch_leave_one_out_never_the_last(self): p = c.bars(metric(0, 32, 85, 4, fmt=lambda v: f"${v:.2f}")) @@ -72,10 +70,8 @@ def test_the_baseline_is_a_reference_mark_at_its_value_in_each_row(self): self.assertEqual(len(refs), 2) # across each row's band, never its name self.assertEqual({r.x for r in refs}, {round(a.x + a.w, 2)}) self.assertEqual(p.table[1], (("a (baseline)", "2"), ("b", "4 +2"))) - - def test_a_single_run_has_no_reference_line(self): - p = c.bars(c.Metric("M", (c.Value("a", 2, "2", baseline=True),))) - self.assertEqual((len(shapes(p, "bar")), shapes(p, "ref")), (1, [])) + alone = c.bars(c.Metric("M", (c.Value("a", 2, "2", baseline=True),))) + self.assertEqual((len(shapes(alone, "bar")), shapes(alone, "ref")), (1, [])) # a single run has no reference line def test_a_long_name_wraps_never_clips(self): name = "agent " * 30 @@ -84,12 +80,6 @@ def test_a_long_name_wraps_never_clips(self): self.assertGreater(len(label.lines), 1) self.assertEqual(" ".join(label.lines), name.strip()) - def test_very_different_magnitudes_get_their_own_panels_and_axes(self): - panels = [c.bars(metric(0.002, 0.003)), c.bars(metric(4000, 9000))] - small, large = ([t.lines[0] for t in p.texts if t.cls == "tick"] for p in panels) - self.assertNotEqual(small[-1], large[-1]) - self.assertEqual(large[-1], "10000") - class Dots(unittest.TestCase): def test_the_axis_is_around_the_values_so_close_values_stay_apart(self): diff --git a/app/tests/test_charts.py b/app/tests/test_charts.py index 7713c1d4..9c4d3de6 100644 --- a/app/tests/test_charts.py +++ b/app/tests/test_charts.py @@ -16,7 +16,7 @@ from nullius.traces.waterfall import MAX_ROWS from nullius.traces import charts -from .tracedata import DEGRADED, RICH, doc, raw, span +from .tracedata import DEGRADED, RICH, doc, span MS = 1_000_000 @@ -43,9 +43,6 @@ def test_the_longest_span_lands_in_the_last_bin_rather_than_past_it(self): edges = charts.log_edges(1_000, 10 * MS) self.assertEqual(charts.bin_index(edges[-1], edges), len(edges) - 2) self.assertEqual(charts.bin_index(10 * MS, edges), len(edges) - 2) - - def test_the_shortest_span_lands_in_the_first_bin(self): - edges = charts.log_edges(1_000, 10 * MS) self.assertEqual(charts.bin_index(1_000, edges), 0) self.assertEqual(charts.bin_index(edges[0], edges), 0) @@ -61,10 +58,6 @@ def test_the_bin_count_stays_readable_across_one_decade_and_eight(self): self.assertGreaterEqual(len(edges) - 1, 4, f"{lo}..{hi} too coarse") self.assertLessEqual(len(edges) - 1, 24, f"{lo}..{hi} too fine") - def test_the_edges_increase(self): - edges = charts.log_edges(1_200, 3 * MS) - self.assertEqual(list(edges), sorted(set(edges))) - def test_a_bin_is_a_round_range(self): edges = charts.log_edges(MS, 10_000 * MS) self.assertEqual([e / MS for e in edges[:4]], [1, 2, 5, 10]) @@ -85,11 +78,6 @@ def test_a_span_with_no_end_is_counted_out_rather_than_binned_at_zero(self): for key in ("time-cdf", "kind-cdf"): self.assertTrue(all(s.n == 1 for s in chart(cs, key).series)) - def test_the_note_says_how_many_were_left_out(self): - cs = built(span("a", 0, MS), span("b", 0, None)) - self.assertIn("1 of 2 spans", cs.note) - self.assertNotIn("0 of", built(span("a", 0, MS)).note) - def test_an_unknown_clock_is_excluded_even_with_a_duration(self): # is_instant treats `unknown` as no measurement at all; a duration # alongside it is a number nobody stands behind. @@ -110,12 +98,6 @@ class Histograms(unittest.TestCase): def setUp(self): self.cs = charts.charts_for(trace.load(RICH).roots) - def test_every_plotted_span_is_in_a_bar(self): - self.assertEqual(sum(b.count for b in chart(self.cs, "time-hist").bars), - self.cs.plotted) - self.assertEqual(sum(b.count for b in chart(self.cs, "kind-hist").bars), - self.cs.plotted) - def test_the_bars_hold_all_of_the_summed_time(self): self.assertEqual(sum(b.ns for b in chart(self.cs, "time-hist").bars), self.cs.summed_ns) @@ -146,7 +128,7 @@ def test_the_bars_stay_inside_the_plot_box(self): self.assertGreaterEqual(round(b.y, 2), box.y0 - 0.01) self.assertLessEqual(round(b.y + b.h, 2), box.y1 + 0.01) - def test_the_stack_segments_sit_on_each_other_without_a_gap(self): + def test_a_stacked_column_holds_its_segments_from_the_baseline_up_without_a_gap(self): cs = built( span("a", 0, MS, kind="tool"), span("b", 0, MS, kind="llm_request"), @@ -159,6 +141,11 @@ def test_the_stack_segments_sit_on_each_other_without_a_gap(self): stack.sort(key=lambda b: -b.y) for lower, upper in zip(stack, stack[1:]): self.assertAlmostEqual(lower.y, upper.y + upper.h, places=1) + for column in chart(cs, "kind-hist").columns: + self.assertEqual(column.count, sum(b.count for b in column.segs)) + self.assertEqual(column.share, "") # it counts spans: no share of the time + tops = [b.y for b in column.segs] + self.assertEqual(tops, sorted(tops, reverse=True)) class Cdfs(unittest.TestCase): @@ -184,19 +171,6 @@ def test_every_cdf_starts_at_zero_and_reaches_one_hundred_percent(self): self.assertAlmostEqual(ys[0], box.y1, places=1) self.assertAlmostEqual(ys[-1], box.y0, places=1) - def test_each_kind_is_scaled_to_its_own_total_so_the_lines_are_comparable(self): - # Otherwise a kind with two spans is a flat line at the bottom and the - # chart says nothing about how long its calls ran. - cs = built( - span("a", 0, MS, kind="tool"), - span("b", 0, 2 * MS, kind="tool"), - span("c", 0, 900 * MS, kind="llm_request"), - ) - series = chart(cs, "kind-cdf").series - self.assertEqual({s.kind for s in series}, {"tool", "llm_request"}) - for s in series: - self.assertAlmostEqual(self.ys(s)[-1], cs.box.y0, places=1) - def test_the_series_share_the_histograms_x_axis(self): for key in ("time-cdf", "kind-cdf"): for s in chart(self.cs, key).series: @@ -221,9 +195,6 @@ def test_a_line_runs_from_its_shortest_span_to_its_longest_and_stops(self): self.assertEqual((tool.lo_ns, tool.hi_ns), (2 * MS, 5 * MS)) self.assertGreater(xs[0], cs.box.x0) self.assertLess(xs[-1], cs.box.x1) - - def test_a_readout_has_no_dot_where_a_line_is_not_drawn(self): - cs = built(span("a", 0, 2 * MS, kind="tool"), span("b", 0, 5 * MS, kind="tool"), span("c", 0, 8000 * MS, kind="llm_request")) c = chart(cs, "kind-cdf") i = [s.kind for s in c.series].index("tool") last = c.readouts[-1].rows[i] @@ -250,29 +221,12 @@ class SummedTimeIsNotWallClock(unittest.TestCase): them match would mean one of them had stopped measuring what it claims to. """ - def test_the_summed_span_time_is_not_the_wall_clock_on_the_real_capture(self): - tr = trace.load(RICH) - cs = charts.charts_for(tr.roots) - self.assertNotEqual(cs.summed_ns, tr.totals.wall_ns) - def test_calls_that_overlap_add_up_past_the_run(self): cs = built(span("a", 0, 10 * MS, kind="tool"), span("b", 0, 10 * MS, kind="tool")) self.assertEqual(cs.summed_ns, 20 * MS) - def test_nothing_here_reports_a_wall_clock(self): - cs = charts.charts_for(trace.load(RICH).roots) - self.assertFalse(hasattr(cs, "wall_ns")) - self.assertNotIn("wall", " ".join(c.subtitle for c in cs.items)) - class TheFilterReachesTheCharts(unittest.TestCase): - def test_hiding_a_label_shrinks_the_charts(self): - data = raw() - whole = charts.charts_for(trace.parse(data).roots) - cut = charts.charts_for(trace.parse(data, trace.Filter.of(names=("Write",))).roots) - self.assertLess(cut.total, whole.total) - self.assertLess(cut.plotted, whole.plotted) - def test_hiding_a_parent_takes_its_subtree_out_of_the_charts(self): parent = span("p", 0, 10 * MS, children=[span("c", 0, MS)]) whole = built(parent) @@ -281,12 +235,6 @@ def test_hiding_a_parent_takes_its_subtree_out_of_the_charts(self): self.assertEqual(cut.total, 0) self.assertFalse(cut.has_spans) - def test_a_view_with_every_span_hidden_plots_nothing_and_does_not_raise(self): - cs = built(span("a", 0, MS), filt=trace.Filter.of(span_ids=("a",))) - self.assertFalse(cs.has_spans) - self.assertEqual(len(cs.items), len(charts._SPECS)) - self.assertTrue(all(not (c.bars or c.series) for c in cs.items)) - class TheRenderCapDoesNotLeak(unittest.TestCase): def test_the_charts_see_spans_the_waterfall_stops_drawing(self): @@ -311,14 +259,6 @@ def test_an_empty_trace_still_returns_the_four_frames(self): self.assertFalse(cs.has_spans) self.assertEqual(cs.note, "") - def test_the_legend_lists_the_kinds_in_the_waterfalls_order(self): - cs = built( - span("a", 0, MS, kind="tool"), - span("b", 0, MS, kind="llm_request"), - ) - self.assertEqual([f.kind for f in chart(cs, "kind-hist").kinds], - ["llm_request", "tool"]) - def test_the_axis_labels_at_the_ends_are_anchored_inward(self): # Centred, they hang outside the viewBox and clip into a wrong number. ticks = chart(charts.charts_for(trace.load(RICH).roots), "time-hist").xticks @@ -336,11 +276,9 @@ def test_the_x_ticks_are_round_decades_inside_the_plot(self): class TheDurationAxisSaysItsStep(unittest.TestCase): - def test_each_mark_is_how_many_times_the_last(self): + def test_an_axis_says_its_own_step_thinned_or_not(self): cs = built(span("a", 0, MS, kind="tool"), span("b", 0, 9000 * MS, kind="llm_request")) self.assertEqual(chart(cs, "time-hist").x_step, 10) - - def test_a_thinned_axis_says_its_own_step(self): cs = built(span("a", 0, 1, kind="tool"), span("b", 0, 5000 * 1000 * MS, kind="llm_request")) c = chart(cs, "time-hist") self.assertEqual(c.x_step, round(c.xticks[1].ns / c.xticks[0].ns)) @@ -366,12 +304,12 @@ def test_a_time_bar_stands_at_its_real_share_of_the_axis(self): self.assertAlmostEqual(drawn, column.ns / self.cs.summed_ns * 100, places=0) self.assertIn(axis, charts._SHARE_TOPS) - def test_the_axis_rounds_up_to_the_fullest_bin(self): self.assertEqual(charts._share_top(84, 100), 100) self.assertEqual(charts._share_top(14, 100), 20) self.assertEqual(charts._share_top(3, 100), 5) self.assertEqual([t.text for t in charts._scaled_yticks(20)], ["0%", "10%", "20%"]) + def test_the_count_histogram_labels_a_count_of_spans(self): ticks = chart(self.cs, "kind-hist").yticks pooled = {} @@ -380,11 +318,6 @@ def test_the_count_histogram_labels_a_count_of_spans(self): self.assertEqual(ticks[0].text, "0") self.assertEqual(int(ticks[-1].text), max(pooled.values())) - def test_only_the_cumulative_charts_claim_a_hundred_percent(self): - for key in ("time-cdf", "kind-cdf"): - self.assertEqual([t.text for t in chart(self.cs, key).yticks], - ["0%", "50%", "100%"]) - def test_a_share_too_small_to_round_is_not_labelled_zero(self): # Same stance as the `share` filter: time that was really spent must not # render as "0%". @@ -412,13 +345,8 @@ def test_a_kind_switched_off_leaves_the_chart_it_was_switched_off_on(self): self.assertNotIn("tool", [s.kind for s in chart(cs, "kind-cdf").series]) self.assertIn("tool", [s.kind for s in charts.charts_for(trace.load(RICH).roots).items[3].series]) - - def test_switching_a_kind_off_in_one_chart_leaves_the_other_alone(self): - cs = charts.charts_for(trace.load(RICH).roots, self.cf("kind-cdf:tool")) - self.assertIn("tool", [b.kind for b in chart(cs, "kind-hist").bars]) + self.assertIn("tool", [b.kind for b in chart(cs, "kind-hist").bars]) # the other chart is left alone self.assertEqual(chart(cs, "kind-hist").hidden_kinds, ()) - - def test_the_stacked_histogram_drops_the_segments_of_a_kind_switched_off(self): cs = charts.charts_for(trace.load(RICH).roots, self.cf("kind-hist:tool")) self.assertNotIn("tool", [b.kind for b in chart(cs, "kind-hist").bars]) self.assertEqual(chart(cs, "kind-hist").hidden_kinds, ("tool",)) @@ -465,10 +393,6 @@ def test_switching_every_kind_off_leaves_an_empty_plot_and_a_way_back(self): self.assertTrue(c.kinds) # every chip still there to click back on self.assertIn("switched off", c.note) - def test_the_note_says_the_axis_moved(self): - cs = charts.charts_for(trace.load(RICH).roots, self.cf("kind-hist:tool")) - self.assertIn("rescaled", chart(cs, "kind-hist").note) - def test_the_trace_underneath_is_untouched(self): # The count of spans in the view is a property of `hide`, not of a legend. roots = trace.load(RICH).roots @@ -554,25 +478,16 @@ def test_the_time_histograms_columns_share_the_summed_time_coloured_by_kind(self self.assertEqual({k.kind for k in c.key_kinds}, {"tool", "llm_request"}) self.assertEqual(c.head.text, max(c.columns, key=lambda col: col.ns).share) - def test_a_stacked_column_holds_its_segments_from_the_baseline_up(self): - for column in chart(self.cs, "kind-hist").columns: - self.assertEqual(column.count, sum(b.count for b in column.segs)) - self.assertEqual(column.share, "") # it counts spans: no share of the time - tops = [b.y for b in column.segs] - self.assertEqual(tops, sorted(tops, reverse=True)) - - def test_how_many_calls_leads_with_how_many_and_draws_no_median_across_kinds(self): - c = chart(self.cs, "kind-hist") - self.assertEqual((c.head.text, c.head.unit), ("5", "calls")) - self.assertIsNone(c.marker) # tools in ms, calls in s: their middle is neither - - def test_the_headlines_are_a_real_spans_duration(self): + def test_the_headlines_are_a_real_spans_duration_or_how_many_calls(self): self.assertEqual(chart(self.cs, "time-cdf").head.ns, 8000 * MS) # 8s is past half of the 8.06s summed self.assertEqual(chart(self.cs, "kind-cdf").head.ns, 4000 * MS) # the llm calls' lower middle self.assertIn("llm_request", chart(self.cs, "kind-cdf").head.unit) fullest = chart(self.cs, "time-hist").head self.assertTrue(fullest.lo_ns <= 8000 * MS <= fullest.hi_ns) self.assertTrue(fullest.text.endswith("%")) + c = chart(self.cs, "kind-hist") + self.assertEqual((c.head.text, c.head.unit), ("5", "calls")) + self.assertIsNone(c.marker) # tools in ms, calls in s: their middle is neither def test_a_readout_gives_every_series_at_each_edge_and_the_plot_is_split_between_them(self): c = chart(self.cs, "kind-cdf") @@ -598,11 +513,6 @@ def test_a_kind_switched_off_leaves_the_chart_its_headline_from_what_is_left(sel self.assertIsNone(none.marker) self.assertEqual(none.columns, ()) - def test_the_box_places_a_coordinate_by_percentage(self): - box = self.cs.box - self.assertEqual((box.left(box.x0), box.left(box.x1), box.top(box.y0), box.top(box.y1)), (0, 100, 0, 100)) - self.assertEqual((box.width(box.w), box.height(box.h)), (100, 100)) - if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_classify.py b/app/tests/test_classify.py index 059a2ce2..6918c0b0 100644 --- a/app/tests/test_classify.py +++ b/app/tests/test_classify.py @@ -233,27 +233,15 @@ def test_a_cancelled_trial_is_labelled_and_excluded_from_the_adjusted_rate(self) class VerifierOutcomes(unittest.TestCase): """No exception: the outcome comes from the verifier report.""" - def test_resolved(self): - self.assertEqual(_outcome(None, {"resolved": True}), C.RESOLVED) - - def test_no_patch(self): - self.assertEqual(_outcome(None, {"resolved": False, "patch_exists": False}), - C.NO_PATCH) - - def test_patch_not_applied(self): - self.assertEqual( - _outcome(None, {"resolved": False, "patch_exists": True, - "patch_successfully_applied": False}), - C.PATCH_NOT_APPLIED) - - def test_patch_failed_tests(self): - self.assertEqual( - _outcome(None, {"resolved": False, "patch_exists": True, - "patch_successfully_applied": True}), - C.PATCH_FAILED_TESTS) - - def test_unknown_when_nothing_is_recorded(self): - self.assertEqual(_outcome(None, None), C.UNKNOWN) + def test_the_report_decides_the_outcome(self): + for report, outcome in ( + ({"resolved": True}, C.RESOLVED), + ({"resolved": False, "patch_exists": False}, C.NO_PATCH), + ({"resolved": False, "patch_exists": True, "patch_successfully_applied": False}, C.PATCH_NOT_APPLIED), + ({"resolved": False, "patch_exists": True, "patch_successfully_applied": True}, C.PATCH_FAILED_TESTS), + (None, C.UNKNOWN)): + with self.subTest(outcome): + self.assertEqual(_outcome(None, report), outcome) class Presentation(unittest.TestCase): diff --git a/app/tests/test_cli.py b/app/tests/test_cli.py index e7e241b5..c467d141 100644 --- a/app/tests/test_cli.py +++ b/app/tests/test_cli.py @@ -116,13 +116,6 @@ def test_each_cli_has_help_with_examples_and_the_exit_codes(self): self.assertIn("--matched", self.sh("compare.cli", "--help").stdout) self.assertCwdUntouched() - def test_the_subcommands_have_help_of_their_own(self): - for sub in ("list", "show"): - out = self.sh("runs.cli", sub, "--help") - self.assertEqual(out.returncode, 0) - self.assertIn("--json", out.stdout) - self.assertIn("exit codes:", out.stdout) - class ExitCodes(Scratch): """docs/cli.md's table, one line at a time. The modules must agree on the @@ -137,6 +130,15 @@ def test_usage_errors_are_2_and_say_so_on_stderr(self): ("runs.cli", ["list"]), # no root ("runs.cli", ["list", "--bogus", str(JOBS)]), ("runs.cli", ["show", str(JOBS)]), # no job id + ("runs.cli", ["show", str(JOBS), "1", TRIAL_1, "extra"]), + ("compare.cli", []), # no root + ("compare.cli", [str(JOBS)]), # no job + ("compare.cli", [str(JOBS), "1"]), # one job + ("compare.cli", [str(JOBS), "1", "1"]), # the same job twice + ("compare.cli", [str(JOBS), "1", "2", "--bogus"]), + ("workspace_cli", []), # no command + ("workspace_cli", ["list", "--bogus"]), + ("workspace_cli", ["delete", "x"]), # not a command here ] for module, args in cases: with self.subTest(module=module, args=args): @@ -146,70 +148,6 @@ def test_usage_errors_are_2_and_say_so_on_stderr(self): self.assertEqual(out.stdout, "") self.assertCwdUntouched() - def test_a_missing_path_is_3(self): - missing = os.path.join(self.tmp, "nowhere") - cases = [ - ("importers.cli", [missing, "-o", os.path.join(self.tmp, "out")]), - ("importers.cli", [missing, "--harness", "atif", "-o", os.path.join(self.tmp, "out")]), - ("runs.cli", ["list", missing]), - ("runs.cli", ["show", missing, "1"]), - ] - for module, args in cases: - with self.subTest(module=module, args=args): - out = self.sh(module, *args) - self.assertEqual(out.returncode, 3, out.stderr) - self.assertIn("no such directory", out.stderr) - self.assertEqual(out.stdout, "") - self.assertFalse(os.path.exists(os.path.join(self.tmp, "out"))) - self.assertCwdUntouched() - - def test_an_empty_directory_is_3_for_reads_and_says_what_was_looked_for(self): - empty = os.path.join(self.tmp, "empty") - os.makedirs(empty) - out = self.sh("runs.cli", "list", empty) - self.assertEqual(out.returncode, 3) - self.assertIn("no job directory found", out.stderr) - out = self.sh("runs.cli", "list", empty, "--json") - self.assertEqual((out.returncode, out.stdout), (3, "")) - out = self.sh("importers.cli", empty, "-o", os.path.join(self.tmp, "out")) - self.assertEqual(out.returncode, 3) - self.assertIn("no importer recognised", out.stderr) - self.assertEqual(os.listdir(empty), []) - self.assertCwdUntouched() - - def test_a_refused_operation_is_4(self): - empty = os.path.join(self.tmp, "empty") - os.makedirs(empty) - # the importer named outright finds nothing it can convert - out = self.sh("importers.cli", empty, "--harness", "atif", "-o", os.path.join(self.tmp, "out")) - self.assertEqual(out.returncode, 4, out.stderr) - self.assertIn("no ATIF trajectories", out.stderr) - self.assertEqual(out.stdout, "") - self.assertCwdUntouched() - - -class Runs(Scratch): - """`runs.cli`: what the runs list and the job page show, from the shell.""" - - - def test_an_errored_trial_shows_its_exception_and_never_the_credential(self): - errored_job(self.tmp) - with open(os.path.join(self.tmp, "errored-job", "task-a__x1", "result.json")) as fh: - self.assertIn(SECRET, fh.read()) # it is on disk - for args in (["show", self.tmp, "errored-job"], ["show", self.tmp, "errored-job", "--json"], - ["list", self.tmp, "--json"]): - with self.subTest(args=args): - out = self.sh("runs.cli", *args) - self.assertEqual(out.returncode, 0, out.stderr) - self.assertNotIn(SECRET, out.stdout + out.stderr) - out = self.sh("runs.cli", "show", self.tmp, "errored-job") - self.assertRegex(out.stdout, r"(?m)^ task-a__x1\s+api_error\s+ApiError$") - doc = json.loads(self.sh("runs.cli", "show", self.tmp, "errored-job", "--json").stdout) - self.assertEqual(doc["trials"][0]["exception_message"], "401 for api_key=[REDACTED]") - self.assertEqual(doc["counts"]["api_error"], 1) - self.assertEqual(doc["n_infra"], 1) - self.assertIsNone(doc["adjusted_solve_rate"]) - # ------------------------------------------------------- # The trial view, the comparison and the workspace list. Same table, same rules: @@ -228,28 +166,6 @@ def workspace_home(root: str, roots, label: str = "Failed jobs") -> tuple: return home, ws -class MoreExitCodes(Scratch): - def test_usage_errors_are_2(self): - cases = [ - ("compare.cli", []), # no root - ("compare.cli", [str(JOBS)]), # no job - ("compare.cli", [str(JOBS), "1"]), # one job - ("compare.cli", [str(JOBS), "1", "1"]), # the same job twice - ("compare.cli", [str(JOBS), "1", "2", "--bogus"]), - ("workspace_cli", []), # no command - ("workspace_cli", ["list", "--bogus"]), - ("workspace_cli", ["delete", "x"]), # not a command here - ("runs.cli", ["show", str(JOBS), "1", TRIAL_1, "extra"]), - ] - for module, args in cases: - with self.subTest(module=module, args=args): - out = self.sh(module, *args) - self.assertEqual(out.returncode, 2, out.stderr) - self.assertIn("usage:", out.stderr) - self.assertEqual(out.stdout, "") - self.assertCwdUntouched() - - class TrialShow(Scratch): """`runs.cli show `: the trial page from the shell.""" @@ -297,7 +213,6 @@ def test_a_credential_in_the_trajectory_is_redacted_on_the_way_out(self): class Workspaces(Scratch): """`workspace_cli list`: the workspaces table, from the shell.""" - def test_the_home_is_workspaces_dir_when_not_named(self): home, ws = workspace_home(self.tmp, [JOBS]) out = self.sh("workspace_cli", "list", env={"WORKSPACES_DIR": home}) diff --git a/app/tests/test_comparison.py b/app/tests/test_comparison.py index c50247c7..384952fc 100644 --- a/app/tests/test_comparison.py +++ b/app/tests/test_comparison.py @@ -277,11 +277,6 @@ def test_nothing_is_picked_until_both_sides_are_scored(self): self.assertIsNone(comparison.better_of(2.0, None)) self.assertIsNone(comparison.better_of(None, None)) - def test_swapping_the_sides_mirrors_the_verdict(self): - mirror = {"A": "B", "B": "A", "same": "same"} - for a, b in ((2.7, 1.2), (1.2, 2.7), (2.0, 2.4), (0.0, 0.0), (3.0, 2.4)): - self.assertEqual(comparison.better_of(b, a), mirror[comparison.better_of(a, b)], (a, b)) - class ScoredRuns(unittest.TestCase): """A benchmark that gives each task a score and no pass or fail - a diff --git a/app/tests/test_computer_kit.py b/app/tests/test_computer_kit.py index 3b70f99c..e7807fe2 100644 --- a/app/tests/test_computer_kit.py +++ b/app/tests/test_computer_kit.py @@ -87,15 +87,8 @@ def test_reading_accepts_repeats_and_other_vocabulary_before_or_after_the_run(se " ".join(words[::-1]) + "; actually, " + text, " ".join([words[0], "ZEBRA", *words[1:]]) + "; actually, " + text, words[0] + " " + text, - text + " " + words[-1]] - for answer in answers: - with self.subTest(check=check, answer=answer): - got = checks.verdict(check, {"words": words}, [ev("moved", 100.2, top=0.4)], ACTIONS, answer) - self.assertEqual(got, {"passed": True, "why": ""}) - - def test_reading_ignores_screen_and_action_prose_between_the_drawn_words(self): - for check, words in (("see", ["ACORN", "BASKET", "CANDLE"]), ("scroll", ["ACORN", "BASKET"])): - answers = ["The window shows " + " ".join(words) + ".", + text + " " + words[-1], + "The window shows " + text + ".", "The square holds " + words[0] + "; the paper holds " + " and ".join(words[1:]) + ".", "I mirror " + words[0] + " and then stream " + " and ".join(words[1:]) + "."] for answer in answers: @@ -103,6 +96,7 @@ def test_reading_ignores_screen_and_action_prose_between_the_drawn_words(self): got = checks.verdict(check, {"words": words}, [ev("moved", 100.2, top=0.4)], ACTIONS, answer) self.assertEqual(got, {"passed": True, "why": ""}) + def test_reading_fails_without_an_unbroken_run_of_the_drawn_words(self): for check, words in (("see", ["ACORN", "BASKET", "CANDLE"]), ("scroll", ["ACORN", "BASKET"])): answers = [" ".join(words[:-1]), " ".join(words[::-1]), @@ -116,7 +110,7 @@ def test_reading_fails_without_an_unbroken_run_of_the_drawn_words(self): self.assertEqual(got, {"passed": False, "why": "the words were not found together in order; expected " + ", ".join(words)}) - def test_reading_accepts_twelve_vocabulary_occurrences_including_repeats(self): + def test_reading_accepts_twelve_vocabulary_occurrences_and_rejects_more_even_with_a_correct_run(self): for check, words in (("see", ["ACORN", "BASKET", "CANDLE"]), ("scroll", ["ACORN", "BASKET"])): padding = ["ZEBRA"] * (12 - len(words)) for found in (words + padding, padding + words, words * (12 // len(words))): @@ -124,9 +118,6 @@ def test_reading_accepts_twelve_vocabulary_occurrences_including_repeats(self): got = checks.verdict(check, {"words": words}, [ev("moved", 100.2, top=0.4)], ACTIONS, " ".join(found)) self.assertEqual(got, {"passed": True, "why": ""}) - - def test_reading_rejects_more_than_twelve_vocabulary_occurrences_even_with_a_correct_run(self): - for check, words in (("see", ["ACORN", "BASKET", "CANDLE"]), ("scroll", ["ACORN", "BASKET"])): answers = [words + ["ZEBRA"] * (13 - len(words)), words * (12 // len(words)) + [words[0]], list(checks.WORDS), list(checks.WORDS) + words] @@ -382,19 +373,6 @@ def late(args, *, input=None, timeout): class EarnedPasses(unittest.TestCase): """A pass comes from input sent inside actions and seen by the fixture, nothing else.""" - def test_a_press_of_any_mouse_button_on_another_button_fails_click(self): - exp = {"target": "OCEAN", "labels": ["OCEAN", "APPLE"]} - for button in (1, 2, 3): - events = [ev("press", 100.1, button=button, hit="APPLE"), ev("press", 100.2, button=1, hit="OCEAN")] - self.assertIn("another button", checks.click(exp, events, [{"start": 100, "end": 101}], "")["why"]) - - def test_enter_is_input_whose_time_is_checked(self): - exp = {"word": "kotabiru"} - self.assertFalse(checks.type_word(exp, [ev("enter", 100, value="kotabiru")], [], "")["passed"]) - late = [ev("key", 100.1, char="k", hit="field"), ev("enter", 105, value="kotabiru")] - v = checks.type_word(exp, late, [{"start": 100, "end": 101}], "") - self.assertIn("outside every action", v["why"]) - def test_a_press_and_its_release_in_two_actions_pass(self): events = [ev("press", 100.2, hit="OCEAN", button=1), ev("release", 110.2, hit="OCEAN", button=1)] actions = [{"start": 100, "end": 101}, {"start": 110, "end": 111}] @@ -450,11 +428,6 @@ def the_click(**kw): self.assertTrue(checks.click({"target": "OCEAN", "labels": ["OCEAN"]}, events, [said], "")["passed"]) -class _FakeX: - AutoRepeatModeOff = 0 - AutoRepeatModeOn = 1 - - class Session(unittest.TestCase): def test_the_x_server_runs_with_access_control_on_and_as_its_own_account(self): argv = session.server_argv() @@ -465,13 +438,6 @@ def test_the_x_server_runs_with_access_control_on_and_as_its_own_account(self): with open(os.path.join(KIT, "desktop.Dockerfile")) as f: self.assertIn(f"useradd -u {session.SERVER_UID} ", f.read()) - def test_the_servers_key_repeat_is_turned_off(self): - d = mock.Mock() - d.get_keyboard_control.return_value = mock.Mock(global_auto_repeat=_FakeX.AutoRepeatModeOff) - with mock.patch.dict(sys.modules, {"Xlib": mock.Mock(X=_FakeX), "Xlib.X": _FakeX}): - self.assertTrue(session.repeat_off(d)) - d.change_keyboard_control.assert_called_once_with(auto_repeat_mode=_FakeX.AutoRepeatModeOff) - def test_the_cookie_file_names_this_host_and_any_host(self): data = session.xauthority(b"c" * 16, "desktop") self.assertTrue(data.startswith(struct.pack(">H", 256) + struct.pack(">H", 7) + b"desktop")) @@ -633,16 +599,6 @@ def why_no_desktop() -> str: return container.unusable() or "" -class TierGate(unittest.TestCase): - def test_the_desktop_tests_run_wherever_an_engine_answers_and_build_the_image(self): - with mock.patch.dict(os.environ, {docker_tier.VAR: "1"}), mock.patch.object(container, "unusable", return_value=None), \ - mock.patch.object(container, "present", return_value=False): - self.assertEqual(why_no_desktop(), "") - with mock.patch.object(desktop, "image", side_effect=container.Unavailable("no build")): - with self.assertRaises(container.Unavailable): - DockerDesktop.setUpClass() - - @unittest.skipIf(why_no_desktop(), why_no_desktop() or "") class DockerDesktop(unittest.TestCase): """Real desktops of the kit's image, one at a time; the image is built first when it is missing.""" diff --git a/app/tests/test_computer_kit_driver.py b/app/tests/test_computer_kit_driver.py index 0021759d..023a078b 100644 --- a/app/tests/test_computer_kit_driver.py +++ b/app/tests/test_computer_kit_driver.py @@ -6,7 +6,6 @@ import importlib.util import inspect -import io import json import math import os @@ -135,26 +134,21 @@ def test_every_check_fails_on_input_outside_every_action(self): stray = events + [ev("key", 105.0, keysym="a", char="a", hit="background")] self.assertFalse(checks.verdict(check, exp, stray, ACTIONS, message, calls)["passed"]) - def test_each_check_draws_its_own_screen(self): - for check in checks.CHECKS: - values, exp = checks.draw(check) - self.assertIn(values["screen"], ("see", "click", "type", "drag", "scroll", "batch"), check) - for label in values.get("labels") or []: - self.assertTrue(re.fullmatch(r"[A-Z]+", label), label) - self.assertEqual(sorted(checks.draw("limit")[0]["labels"]), sorted(checks.ORDER)) - self.assertEqual((checks.steps("limit"), checks.steps("batch"), checks.steps("see")), (2, 2, 8)) - # -- the kit's definition --------------------------------------------------------------------------------------------- class Definition(unittest.TestCase): def test_the_port_names_the_kit_and_the_kit_its_checks(self): kit = definitions.kit("agent.computer/v1") self.assertEqual(ports.PORTS["agent.computer/v1"]["kit"], "agent-computer-v1") - self.assertEqual(kit["key"], "agent-computer-v1") + self.assertEqual((kit["key"], kit["needs"], kit["datasets"]), ("agent-computer-v1", ["agent.computer/v1"], + [{"id": "kit", "units": 9}])) + self.assertTrue(kit["driver"]["task_given"] and kit["driver"]["unit_end"]) + self.assertEqual(driver.units("kit")["units"], list(checks.CHECKS) + ["late"]) self.assertEqual(definitions.problems({k: v for k, v in kit.items() if not k.startswith("_")}, "benchmark"), []) self.assertEqual(list(kit["check_details"]), list(driver.UNITS)) self.assertEqual(kit["basic"], list(checks.BASIC)) self.assertEqual(set(kit["skills"]), set(driver.UNITS) - set(checks.BASIC)) + self.assertEqual(set(kit["basic"]) | set(kit["skills"]), set(driver.UNITS)) self.assertTrue(kit["skills"]["late"].endswith("and presses it once")) self.assertEqual(kit["environments"]["desktop"], dict(desktop.KIT["environments"]["desktop"], summary=kit["environments"]["desktop"]["summary"])) @@ -175,15 +169,6 @@ def test_the_pipe_from_the_kits_folder_joins_stdio_to_the_socket(self): self.assertEqual(p.returncode, 0, p.stderr) self.assertEqual(json.loads(p.stdout)["result"]["tools"][0]["name"], "info") - def test_the_kit_has_nine_checks_and_is_told_the_task(self): - kit = definitions.kit("agent.computer/v1") - self.assertEqual((kit["key"], kit["needs"], kit["datasets"]), ("agent-computer-v1", ["agent.computer/v1"], - [{"id": "kit", "units": 9}])) - self.assertTrue(kit["driver"]["task_given"] and kit["driver"]["unit_end"]) - self.assertEqual(driver.units("kit")["units"], list(checks.CHECKS) + ["late"]) - self.assertEqual(set(kit["check_details"]), set(driver.UNITS)) - self.assertEqual(set(kit["basic"]) | set(kit["skills"]), set(driver.UNITS)) - # -- the driver over a fake desktop ------------------------------------------------------------------------------------- class FakeDesktop: @@ -422,14 +407,6 @@ def test_a_unit_is_served_scored_and_let_go(self): self.assertTrue(FakeDesktop.made[-1].removed) self.assertEqual([l.split()[0] for l in self.told], ["+container", "=container", "+folder", "-container", "-folder"]) self.assertNotIn("click", driver.OPEN) - - def test_the_units_record_keeps_the_fixtures_events_and_where_its_targets_were(self): - ws, s = self.unit("click") - u = driver.OPEN["click"] - c = driver.Client(s["mcp"][0]["args"][0]) - c.call("click", dict(zip("xy", driver.centre(u.boxes[u.expected["target"]])))) - c.close() - driver.score("click", ws, [], "done") verifier = os.path.join(os.path.dirname(ws), "verifier") with open(os.path.join(verifier, "computer-events.jsonl")) as f: events = [json.loads(line) for line in f] @@ -469,26 +446,21 @@ def test_a_step_with_an_end_is_one_step_and_ends_the_kits_loop(self): self.assertEqual(u.final, "typed") def test_a_client_that_acts_past_its_budget_fails(self): - ws, s = self.unit("limit") - u = driver.OPEN["limit"] - c = driver.Client(s["mcp"][0]["args"][0]) - answers = [c.call("click", {"x": x, "y": y})[0] for x, y in - (driver.centre(u.boxes[label]) for label in checks.ORDER[:3])] - c.close() - self.assertEqual(answers, [False, False, True]) # the third is refused - got = driver.score("limit", ws, [], "done") - self.assertFalse(got["passed"]) - self.assertEqual(got["detail"]["past_budget"], 1) - self.assertIn("once every step was taken", got["detail"]["why"]) - - def test_the_reference_passes_click_type_limit_and_recover(self): - for unit in ("click", "type", "limit", "recover"): - with self.subTest(unit=unit): - ws, s = self.unit(unit) - answer = driver.oracle(unit, ws)["answer"] - got = driver.score(unit, ws, [], answer) - self.assertTrue(got["passed"], got) - self.assertEqual(got["detail"]["errors"], 1) # recover: the first click answered with an error + for wrong in (None, {"x": "bad", "y": 100}): # a wrong call is counted too + with self.subTest(wrong=wrong): + ws, s = self.unit("limit") + u = driver.OPEN["limit"] + c = driver.Client(s["mcp"][0]["args"][0]) + calls = [dict(zip("xy", driver.centre(u.boxes[label]))) for label in checks.ORDER[:3]] + calls[2] = wrong or calls[2] + answers = [c.call("click", args)[0] for args in calls] + c.close() + self.assertEqual(answers, [False, False, True]) # the third is refused + self.assertEqual(u.bridge.past, 1) + got = driver.score("limit", ws, [], "done") + self.assertFalse(got["passed"]) + self.assertEqual(got["detail"]["past_budget"], 1) + self.assertIn("once every step was taken", got["detail"]["why"]) def test_a_unit_never_scored_is_let_go_by_the_next_setup_and_by_the_drivers_end(self): ws, s = self.unit("see") @@ -735,19 +707,7 @@ def test_recovery_refuses_done_and_fail_before_their_terminal_transition(self): class EarnedPasses(FakeUnits): """What a pass needs, over the fake desktop: every attempt past the budget counted, recover's call sent after - its error's answer, its error on the first acting call whatever it is, an action not ended in time an error, - and a reference that reads the screen.""" - - def test_a_wrong_call_past_the_budget_is_counted(self): - ws, s = self.unit("limit") - u = driver.OPEN["limit"] - c = driver.Client(s["mcp"][0]["args"][0]) - for label in checks.ORDER[:2]: - self.assertFalse(c.call("click", dict(zip("xy", driver.centre(u.boxes[label]))))[0]) - self.assertTrue(c.call("click", {"x": "bad", "y": 100})[0]) - c.close() - self.assertEqual(u.bridge.past, 1) - self.assertFalse(driver.score("limit", ws, [], "done")["passed"]) + its error's answer, its error on the first acting call whatever it is, and an action not ended in time an error.""" def test_two_calls_sent_together_for_the_last_step_are_one_taken_and_one_counted(self): ws, s = self.unit("limit") @@ -801,24 +761,6 @@ def test_recovers_error_goes_to_the_first_acting_call_whatever_it_is(self): self.assertTrue(driver.score("recover", ws, [], "done")["passed"]) driver.close_all() - def test_an_action_not_ended_in_time_is_answered_with_an_error_and_the_next_goes_on(self): - ws, s = self.unit("click") - u = driver.OPEN["click"] - fake = FakeDesktop.made[-1] - late = [True] - - def act(code, seconds=None): - if late.pop() if late else False: - return {"start": 1.0, "end": 2.0, "reply": None} - return FakeDesktop.act(fake, code, seconds) - fake.act = act - c = driver.Client(s["mcp"][0]["args"][0]) - self.assertTrue(c.call("step", {"actions": ["time.sleep(1000)"]})[0]) - self.assertFalse(c.call("click", dict(zip("xy", driver.centre(u.boxes[u.expected["target"]]))))[0]) - c.close() - self.assertEqual([c["isError"] for c in u.calls()], [True, False]) - self.assertTrue(driver.score("click", ws, [], "done")["passed"]) - def test_a_step_whose_action_did_not_end_in_time_takes_no_end_and_the_next_goes_on(self): ws, s = self.unit("click") u = driver.OPEN["click"] @@ -840,38 +782,12 @@ def act(code, seconds=None): self.assertTrue(got["passed"], got) self.assertEqual(got["detail"]["steps_used"], 2) - def test_the_reference_reads_the_words_from_the_screenshot_and_fails_without_one(self): - drawn = lambda fake: _png(" ".join(fake.values["words"]), driver.fixture.SEE_SCALE) - with mock.patch.object(FakeDesktop, "capture", drawn): # the start picture, taken as the unit starts - ws, s = self.unit("see") - text = " ".join(driver.OPEN["see"].expected["words"]) - self.assertEqual(driver.oracle("see", ws)["answer"], text) - self.assertTrue(driver.score("see", ws, [], text)["passed"]) - - def broken(fake): - raise desktop.DesktopError("the capture failed") - with mock.patch.object(FakeDesktop, "capture", broken): - ws, s = self.unit("see") - with self.assertRaises(driver.ReferenceFailed): - driver.oracle("see", ws) - with mock.patch.object(FakeDesktop, "capture", lambda fake: _png("ACORN", 9)): # a screen with only one word - ws, s = self.unit("see") - with self.assertRaises(driver.ReferenceFailed): - driver.oracle("see", ws) - class Shutdown(unittest.TestCase): def setUp(self): self.enterContext(mock.patch.object(desktop, "_CLIENTS_CLOSED", False, create=True)) self.enterContext(mock.patch.object(desktop, "_CLIENTS", set())) - def test_shutdown_ends_clients_after_every_unit_was_scored(self): - p = mock.Mock() - with mock.patch.dict(driver.OPEN, {}, clear=True), mock.patch.object(desktop, "_CLIENTS", {p}): - driver.close_all() - p.kill.assert_called_once_with() - p.wait.assert_called_once_with(timeout=10) - def test_shutdown_waits_for_launch_registration_and_refuses_later_launches(self): launched, release, draining, killed = (threading.Event() for _ in range(4)) p = mock.Mock(returncode=-9) @@ -1173,20 +1089,6 @@ def test_click_places_the_button_at_each_supplied_position(self): f._click() f.tk.Frame.return_value.place.assert_called_once_with(relx=at[0], rely=at[1], anchor="center") - def test_the_fake_starts_blank_and_draws_the_button_only_when_the_fixture_starts(self): - values = {"screen": "click", "labels": ["BUTTON"]} - d = Fake("desktop", values) - self.assertEqual(d.boxes, {}) - self.assertEqual(d.events(), []) - before = d.capture() - self.assertEqual(d.hit(200, 150), "background") - d.start_fixture(values) - self.assertEqual(d.hit(200, 150), "BUTTON") - self.assertNotEqual(d.capture(), before) - self.assertEqual(len(d.events()), 1) - self.assertEqual(d.events()[0]["kind"], "ready") - self.assertEqual(d.events()[0]["boxes"], d.boxes) - def blind_clicks(sock, u): """A control that must fail ``late``: a script that never looks. Once the task is given, one step clicks the @@ -1372,98 +1274,6 @@ def delayed(d, code, seconds=None): MARGIN = 30 # process starts, protocol messages and scheduling -class DockerTestBounds(unittest.TestCase): - """The docker tests' waits and assertions exercised without a container or a socket.""" - - def supported(self, setup=False): - limits = [] - - def engine(args, **kw): - limits.append(kw["timeout"]) - data = b"" - if desktop._CAPTURE in args: - data = b"\x89PNG\r\n\x1a\nfake" - elif desktop._RUN in args: - data = json.dumps({"start": 1, "end": 2, "timeout": False, "returncode": 0, - "output": "", "error": ""}).encode() - return subprocess.CompletedProcess(args, 0, data, b"") - - with mock.patch.object(desktop, "_engine", side_effect=engine), \ - mock.patch.object(container, "capped", return_value=[]): - if setup: - default = inspect.signature(container._docker).parameters["timeout"].default - - def image_engine(args, *, timeout=default, **kw): - limits.append(timeout) - return subprocess.CompletedProcess(args, 0, "", "") - - with mock.patch.object(container, "_built", {}), \ - mock.patch.object(container, "_docker", side_effect=image_engine): - desktop.image() # a fresh driver inspects both already-built images - d = desktop.Desktop.start("image", "fake") - d.start_fixture({}) - d.events() - else: - d = desktop.Desktop("fake") - d.capture() - d.act("pass", driver.PYTHON_SECONDS) - d.capture() - return sum(limits) + (0 if setup else driver.PAUSE + computer_pipe.END_SECONDS) - - def test_the_setup_deadline_covers_start_readiness_fixture_and_events(self): - supported = self.supported(setup=True) - case = DockerKit("test_a_driver_killed_during_a_unit_leaves_no_container_socket_or_process") - with tempfile.TemporaryDirectory(dir=os.environ.get("TMPDIR")) as tmp: - case.tmp = tmp - p = mock.Mock(pid=123, stdin=io.StringIO(), stdout=io.StringIO(json.dumps( - {"mcp": [{"args": [os.path.join(tmp, "socket", "s")]}]}) + "\n")) - - def select_reply(read, write, error, seconds): - self.assertGreater(seconds, supported) - return read, [], [] - - def run(args, **kw): - return subprocess.CompletedProcess(args, 0, "456 python reaper.py\n" if args[0] == "ps" else "", "") - - with mock.patch.object(subprocess, "Popen", return_value=p), \ - mock.patch.object(subprocess, "run", side_effect=run), \ - mock.patch.object(select, "select", side_effect=select_reply), \ - mock.patch.object(os, "killpg"), mock.patch(__name__ + "._alive", return_value=False): - case.test_a_driver_killed_during_a_unit_leaves_no_container_socket_or_process() - - def scripted(self, *, click_error=False, prompt=None, check_timeout=None): - case = DockerKit("test_a_session_of_the_scripted_acp_agent_reaches_the_server_through_the_pipe") - setup = {"mcp": [{"args": ["/unused/s"]}], "prompt": "click"} - case.unit = mock.Mock(return_value=("/unused/workspace", setup)) - u = mock.Mock() - u.calls.return_value = [{"tool": "screenshot", "isError": False}, {"tool": "click", "isError": click_error}] - messages = [{"id": 1, "result": {}}, {"id": 2, "result": {"sessionId": "s1"}}, - {"method": "session/update", "params": {"update": {"content": {"text": "screenshot taken"}}}}, - {"id": 3, **(prompt if prompt is not None else {"result": {"stopReason": "end_turn"}})}] - p = mock.Mock(stdin=io.StringIO(), stdout=io.StringIO("".join(json.dumps(m) + "\n" for m in messages))) - original = queue.Queue.get - - def get(q, *, timeout): - if check_timeout is not None: - check_timeout(timeout) - return original(q, timeout=timeout) - - with mock.patch.dict(driver.OPEN, {"click": u}, clear=True), \ - mock.patch.object(subprocess, "Popen", return_value=p), \ - mock.patch.object(queue.Queue, "get", get): - case.test_a_session_of_the_scripted_acp_agent_reaches_the_server_through_the_pipe() - - def test_the_prompt_deadline_covers_both_captures_the_action_and_pipe_exit(self): - supported = self.supported() - self.scripted(check_timeout=lambda seconds: self.assertGreater(seconds, supported)) - - def test_the_scripted_session_rejects_a_failed_click_or_prompt(self): - for bad in ({"click_error": True}, {"prompt": {"error": {"code": -32603, "message": "failed"}}}, - {"prompt": {"result": {}}}): - with self.subTest(bad=bad), self.assertRaises(AssertionError): - self.scripted(**bad) - - def why_no_desktop() -> str: if not os.environ.get(docker_tier.VAR): return "the docker tier runs with parallel.py --docker" diff --git a/app/tests/test_computer_merge.py b/app/tests/test_computer_merge.py index 710b4ee0..c5200036 100644 --- a/app/tests/test_computer_merge.py +++ b/app/tests/test_computer_merge.py @@ -9,7 +9,6 @@ import subprocess import sys import tempfile -import time import unittest from unittest import mock @@ -28,29 +27,20 @@ class MeetingPoints(unittest.TestCase): def test_one_step_option_applies_to_scripts_and_the_port(self): bench = definitions.get("benchmark", "osworld1") self.assertEqual(definitions.problems(bench, "benchmark"), []) - for scope, kind in (("original", "upstream"), ("model", "upstream"), ("yours", "agent")): - values, bad = definitions.bench_options_of(bench, "test_small", setup=scope, kind=kind) - self.assertEqual((values["max_steps"], bad), ("default", [])) - for value in ("default", "1", "15", "100", "1500", "9999"): - values, bad = definitions.bench_options_of(bench, "test_small", {"max_steps": value}, scope, kind=kind) - self.assertEqual((values["max_steps"], bad), (value, [])) - for value in ("0", "10000", "1.5"): - self.assertTrue(definitions.bench_options_of(bench, "test_small", {"max_steps": value}, scope, kind=kind)[1]) + for scope, kind in (("original", "upstream"), ("model", "upstream"), ("yours", "agent"), + ("yours", "control"), ("yours", "capability")): + with self.subTest(scope=scope, kind=kind): + values, bad = definitions.bench_options_of(bench, "test_small", setup=scope, kind=kind) + self.assertEqual((values["max_steps"], bad), ("default", [])) + for value in ("default", "1", "15", "100", "1500", "9999"): + values, bad = definitions.bench_options_of(bench, "test_small", {"max_steps": value}, scope, kind=kind) + self.assertEqual((values["max_steps"], bad), (value, [])) + for value in ("0", "10000", "1.5"): + self.assertTrue(definitions.bench_options_of(bench, "test_small", {"max_steps": value}, scope, kind=kind)[1]) option = recipe._bench_page(bench)["options"]["max_steps"] self.assertEqual((option["limit"], option["by"]["agent"]["m3"]), (True, "100")) self.assertEqual(option["setups"], ["original", "model", "yours"]) - def test_step_option_also_applies_to_controls_and_capabilities_that_do_not_read_it(self): - """The shared yours scope includes the null control and capability runs.""" - bench = definitions.get("benchmark", "osworld1") - for kind in ("control", "capability"): - with self.subTest(kind=kind): - values, bad = definitions.bench_options_of(bench, "test_small", setup="yours", kind=kind) - self.assertEqual((values["max_steps"], bad), ("default", [])) - values, bad = definitions.bench_options_of(bench, "test_small", {"max_steps": "1500"}, - "yours", kind=kind) - self.assertEqual((values["max_steps"], bad), ("1500", [])) - @unittest.skipUnless(shutil.which("node"), "Node is required for builder options") def test_the_builder_shows_one_steps_field_for_scripts_agents_and_both(self): source = (Path(__file__).resolve().parents[1] / "static/builder/command-builder.js").read_text() @@ -97,9 +87,6 @@ def test_boat_refuses_the_computer_port_before_probes_or_units(self): probe.assert_not_called() driver.assert_not_called() - def test_retry_closes_processes_before_archive_and_keeps_hooks_records_and_clocks_apart(self): - self.retry_run(inert=True) - def test_retry_with_a_real_computer_server_and_acp_session(self): try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe: @@ -108,14 +95,14 @@ def test_retry_with_a_real_computer_server_and_acp_session(self): probe.bind(os.path.join(tmp, "s")) except OSError as e: self.skipTest(f"local sockets unavailable: {e}") - self.retry_run(inert=False) + self.retry_run() - def retry_run(self, inert): + def retry_run(self): with tempfile.TemporaryDirectory() as tmp, mock.patch.object(install, "HOME", os.path.join(tmp, "install")): bench = {"key": "fixture", "label": "Fixture", "_here": str(FIX), "family": "agent", "needs": ["agent.computer/v1"], "datasets": [{"id": "all"}], "units": {"noun": "unit", "nouns": "units"}, "score": {"kind": "pass", "says": "The fixture answered."}, - "driver": {"command": [sys.executable, "{here}/computer_merge_driver.py", *(["inert"] if inert else [])], + "driver": {"command": [sys.executable, "{here}/computer_merge_driver.py"], "participant": True, "unit_end": True}, "limits": {"setup_seconds": 50, "attempts": "A seed per attempt."}, "mcp_servers": {"computer": {"command": [sys.executable, computer_pipe.__file__]}}} @@ -131,20 +118,12 @@ def drive(r, *args, **kwargs): with self.assertRaises(ProcessLookupError): os.kill(before["pid"], 0) seen.append(json.loads((trial / "setup.json").read_text())) - if inert: - kwargs["clock"]["ready"] = time.time() - r.phase(trial.name, args[0], "agent_run", r.agent_limit(args[4])) - self.assertEqual(r.max_calls, 1) - self.assertEqual(r.driver().request("act")["steps"], 2) - answer = "done", None, {} - else: - answer = real(r, *args, **kwargs) + answer = real(r, *args, **kwargs) if len(seen) == 1: raise run._Ended("NonZeroAgentExitCodeError", "fixture failure", answer[1]) return answer - with mock.patch.object(run.Run, "drive_agent", drive), \ - mock.patch.object(run.Run, "unit_relay", return_value=None) if inert else mock.patch.dict(os.environ, {}): + with mock.patch.object(run.Run, "drive_agent", drive): path = Path(run.run(bench, other, model="m", provider="custom", jobs_root=tmp, concurrency=1, proving=True, unsandboxed=True, retries=1, timeouts={"setup": 30, "agent": 10}, max_calls=1, env={"MODEL_API_URL": "http://127.0.0.1:9/v1"}, say=lambda _: None)) diff --git a/app/tests/test_constraints.py b/app/tests/test_constraints.py index 8531f157..a99e5e93 100644 --- a/app/tests/test_constraints.py +++ b/app/tests/test_constraints.py @@ -29,13 +29,6 @@ class Table(unittest.TestCase): - def test_each_entry_is_whole(self): - for c in constraints.TABLE: - self.assertTrue(c.label and c.kind in ("cap", "pin"), c.key) - if "docker" in c.apply: - self.assertTrue(c.files and c.enforced, c.key) # a container flag is read back - self.assertEqual(list(constraints.container(ALL)), ["cpus", "memory_mb", "processes", "cpu_set"]) - def test_values_are_refused_by_key_type_and_minimum(self): self.assertEqual(constraints.problems(ALL), []) self.assertEqual(constraints.problems({"gpu_ids": []}), []) diff --git a/app/tests/test_dependency_surface.py b/app/tests/test_dependency_surface.py index 0c29a6fe..117897e3 100644 --- a/app/tests/test_dependency_surface.py +++ b/app/tests/test_dependency_surface.py @@ -103,28 +103,10 @@ def test_every_requirement_is_on_the_allowlist(self): f"this application is a deliberate act: name it and say why.", ) - def test_the_allowlist_is_not_stale(self): - """An entry nothing installs is a claim about a dependency that is gone.""" - named = {name_of(r) for r in requirements()} - self.assertEqual( - set(ALLOWED) - named, set(), - "ALLOWED names something requirements.txt no longer installs.", - ) - class TheRuntimeStaysOut(unittest.TestCase): """Viewing must not acquire a dependency on executing.""" - def test_no_runtime_or_execution_dependency(self): - text = REQUIREMENTS.read_text(encoding="utf-8").lower() - for name in FORBIDDEN: - with self.subTest(name): - self.assertNotIn( - name, text, - f"{name!r} appears in app/requirements.txt. Reading a job " - f"directory never needs the runtime that produced it.", - ) - def test_the_backend_suite_runs_where_the_runtime_is_absent(self): """Assert that the runtime is absent so imports cannot hide an undeclared dependency.""" for name in RUNTIME_MODULES: diff --git a/app/tests/test_digitalmate_run.py b/app/tests/test_digitalmate_run.py index 3d69a66c..d952a02f 100644 --- a/app/tests/test_digitalmate_run.py +++ b/app/tests/test_digitalmate_run.py @@ -44,7 +44,7 @@ def prepare(self): file.parent.mkdir(parents=True, exist_ok=True) file.touch() - def test_runtime_must_be_installed_before_a_process_starts(self): + def test_runtime_and_product_launcher_must_be_installed_before_a_process_starts(self): with patch.object(adapter.subprocess, "Popen") as launch: with self.assertRaisesRegex(RuntimeError, "missing its runtime"): adapter.run(self.install, "question") @@ -52,12 +52,8 @@ def test_runtime_must_be_installed_before_a_process_starts(self): (self.install / "runtime/bin/python").unlink() with self.assertRaisesRegex(RuntimeError, "missing its runtime"): adapter.run(self.install, "question") - launch.assert_not_called() - - def test_product_entry_points_must_exist(self): - self.prepare() - (self.install / "src/harness/personal-agent/services/agent_bridge/src/server_engine/workswarm_launcher.py").unlink() - with patch.object(adapter.subprocess, "Popen") as launch: + self.prepare() + (self.install / "src/harness/personal-agent/services/agent_bridge/src/server_engine/workswarm_launcher.py").unlink() with self.assertRaisesRegex(RuntimeError, "product launcher"): adapter.run(self.install, "question") launch.assert_not_called() diff --git a/app/tests/test_driver_path.py b/app/tests/test_driver_path.py index b40242bc..bd764e62 100644 --- a/app/tests/test_driver_path.py +++ b/app/tests/test_driver_path.py @@ -45,9 +45,6 @@ def test_from_a_wheel_the_driver_does_not_see_the_tools_site_packages(self): self.assertEqual(imports(path, "nullius.standard.protocols.jsonl", "nullius_tool_only_dep"), {"nullius.standard.protocols.jsonl": True, "nullius_tool_only_dep": False}) - def test_it_is_made_once_and_kept(self): - self.assertEqual(run.driver_path(), run.driver_path()) - def test_while_it_is_made_the_folder_holds_only_the_link(self): """A driver starting while another's link is being made sees only ``nullius``.""" with tempfile.TemporaryDirectory() as site: diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index 2bb9307a..c2c324a5 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -274,10 +274,6 @@ def test_trials_are_said_as_the_feed_says_them(self): self.assertEqual(said, [" ✕ r-nop · tau3-bench__tau3-airline-0 · unresolved · reward 0.0 · 1:31", " ✓ r-nop · tau3-bench__tau3-retail-0 · resolved · reward 1.0 · 0:03"]) ex._trial_lines(); self.assertEqual(len([l for l in ex.lines if "tau3-bench__" in l]), 2) # said once - def test_ssh_noise_stays_out_of_the_log(self): - ex = self.wait(execution.Execution(execution.Plan(name="r", script="echo '** WARNING: connection is not using a post-quantum key exchange algorithm.'; echo real"), root=str(self.tmp)).start()) - self.assertNotIn("post-quantum", "\n".join(ex.lines)); self.assertIn("real", ex.lines) - class Transport(unittest.TestCase): def test_bytes_that_are_not_utf_8_never_end_a_run(self): @@ -627,6 +623,10 @@ def test_the_recipe_is_part_of_the_record_and_survives_a_restart(self): # a record from when a plan could name an installed Harbor release still loads old = execution.Plan.from_dict({"name": "old", "script": "true", "harbor_version": "0.22.0", "wheels": ["/w.whl"], "requires_python": ">=3.12"}) self.assertEqual((old.name, old.runner), ("old", "harbor")) + pin = {"kind": "release", "version": "0.24.0", "extras": []} + back = execution.Plan.from_dict(execution.Plan(name="p", script="true", harbor_pin=pin).to_dict()) + self.assertEqual(back.harbor_pin, pin) + self.assertEqual(execution.Plan.from_dict({"name": "old", "script": "true", "host": None}).harbor_pin, {}) # from before the pin: harbor on PATH class Refused(Base): @@ -754,23 +754,6 @@ def test_a_run_of_a_runner_no_longer_offered_is_refused_on_a_host_and_nothing_se self.assertIn("is no longer offered", ex.error) self.assertFalse(any("setsid nohup" in c for c in self.ssh_commands())) - def test_stop_kills_the_detached_process_on_the_host(self): - polls = {"n": 0} - def answer(argv, timeout=0, stdin=None): - self.calls.append((argv, stdin)); cmd = argv[-1] - if argv[0] == "rsync": return 0, "" - if "printf 'ok" in cmd: return 0, "ok\nuv=yes\ndocker=yes\nharbor=yes\ndocker_ok=yes\nhostname=x\n" - if "setsid nohup" in cmd: return 0, "777\n" - if "__nullius__" in cmd: polls["n"] += 1; return 0, "\n__nullius__ alive" - return 0, "" - ex = execution.Execution(self.plan, root=str(self.tmp / "runs"), run=answer, key="k" * 20).start() - self.until(ex, "running") - for _ in range(50): - if polls["n"]: break - time.sleep(0.02) - ex.stop(); self.wait(ex) - self.assertEqual(ex.state, "stopped"); self.assertTrue(self.killed(777)) - class StandardOnHost(HostBase): """A standard recipe's part on a host: python3 and git there, docker when @@ -1029,12 +1012,6 @@ def test_a_pin_that_cannot_be_built_stops_the_run_before_the_host(self): self.assertTrue(any('detail="harbor from owner/harbor, commit cccccccccccc: building it here, once for this commit"' in l for l in ex.lines)) self.assertEqual(self.calls, []) # nothing asked of the host - def test_the_pin_is_kept_in_the_record_and_an_old_record_has_none(self): - pin = {"kind": "release", "version": "0.24.0", "extras": []} - back = execution.Plan.from_dict(execution.Plan(name="p", script="true", harbor_pin=pin).to_dict()) - self.assertEqual(back.harbor_pin, pin) - self.assertEqual(execution.Plan.from_dict({"name": "old", "script": "true", "host": None}).harbor_pin, {}) # from before the pin: harbor on PATH - if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_execution_job_state.py b/app/tests/test_execution_job_state.py index f75e9442..93135525 100644 --- a/app/tests/test_execution_job_state.py +++ b/app/tests/test_execution_job_state.py @@ -32,12 +32,10 @@ def test_a_finished_kit_keeps_its_own_end_while_its_sibling_runs_or_fails(self): self.assertEqual(self.ex.job_state("kit-next"), None if state == "running" else ("failed", datetime.fromtimestamp(3, timezone.utc))) self.assertEqual(self.ex.state, state) # the launch's state is untouched - - def test_a_restored_run_reads_each_job_end_from_disk(self): - ex = execution.Execution(self.plan, root=self.temp.name, - record={"state": "failed", "finished": 3, "ends": {"run": {"rc": 1, "at": 3}}}) - self.assertEqual(ex.job_state("kit-ok")[0], "done") - self.assertEqual(ex.job_state("kit-next")[0], "failed") + restored = execution.Execution(self.plan, root=self.temp.name, + record={"state": "failed", "finished": 3, "ends": {"run": {"rc": 1, "at": 3}}}) + self.assertEqual(restored.job_state("kit-ok")[0], "done") + self.assertEqual(restored.job_state("kit-next")[0], "failed") def test_incomplete_errored_or_unreadable_results_keep_the_runner_state(self): path = self.folder / "result.json" diff --git a/app/tests/test_execution_recovery.py b/app/tests/test_execution_recovery.py index febab6f6..e9a0f7d2 100644 --- a/app/tests/test_execution_recovery.py +++ b/app/tests/test_execution_recovery.py @@ -115,17 +115,6 @@ def test_a_pause_waits_again_after_a_restart(self): again.continue_(); self.wait(again) self.assertEqual(again.state, "done"); self.assertIn("b", (self.tmp / "r" / "run-b.log").read_text()) - def test_a_finished_run_is_listed_and_a_gone_process_is_a_failure(self): - ex = self.wait(execution.Execution(execution.Plan(name="fin", script="true"), root=str(self.tmp)).start()) - execution.EXECUTIONS.clear() - # a record that says running with a pid nothing answers to, and no exit file - gone = self.tmp / "gone"; gone.mkdir(); (gone / "run-run.sh").write_text("true\n"); (gone / "run-run.log").write_text("") - (gone / "run.json").write_text(json.dumps({"id": "gone-1", "plan": execution.Plan(name="gone", script="true").to_dict(), "state": "running", "part": 0, "pid": 999999, "log_offset": 0})) - back = execution.restore(str(self.tmp)) - self.assertEqual([e.plan.name for e in back], ["gone"]); self.wait(back[0]) - self.assertEqual(back[0].state, "failed"); self.assertIn("gone without an exit code", "\n".join(back[0].lines)) - self.assertEqual(execution.EXECUTIONS["fin-" + str(int(ex.started))].state if f"fin-{int(ex.started)}" in execution.EXECUTIONS else "done", "done") - def test_an_ended_runs_log_is_read_when_its_page_asks_not_at_start(self): from unittest import mock ex = self.wait(execution.Execution(execution.Plan(name="fin", script="echo said-once"), root=str(self.tmp)).start()) @@ -560,15 +549,6 @@ def test_a_record_from_before_a_part_s_end_was_one_save_asks_then_launches_the_n self.assertEqual([c[-1].count("run-b.sh") for c, _ in self.calls if "setsid nohup" in c[-1]], [1]) # b launched, once self.assertEqual({p: v["rc"] for p, v in again.ends.items()}, {"a": 2, "b": 0}) - def test_a_part_that_left_nothing_is_launched(self): - self.recorded(self.plan, state="running", step="run", part=0, pid=None, harbor="harbor") - back = execution.restore(str(self.tmp / "runs"), run=self.holding({}), key="k" * 20) - self.wait(back[0]) - self.assertEqual(back[0].state, "done", back[0].lines) - launch = [c[-1] for c, _ in self.calls if "setsid nohup" in c[-1]] - self.assertEqual(len(launch), 1); self.assertIn("rm -f run-run.exit run-run.pid; ", launch[0]) - self.assertIn("bash -c 'echo $$ >run-run.pid; [ -e run-run.stop ] && exit 130; bash run-run.sh run-run.log 2>&1;", launch[0]) # its pid, a look for a Stop, then the log - class PartPidsWithoutProc(unittest.TestCase): """A target with no /proc (not Linux) cannot prove a pid is still the diff --git a/app/tests/test_execution_stop.py b/app/tests/test_execution_stop.py index 8115c052..9541b6aa 100644 --- a/app/tests/test_execution_stop.py +++ b/app/tests/test_execution_stop.py @@ -301,19 +301,7 @@ def test_a_stop_a_restart_finishes_copies_the_job_back(self): class Stop(HostBase): - """The Stop button: said at once, finished by the run's own - thread; a command in flight gives way instead of holding the stop for - its timeout; a restart in the middle of a stop finishes it.""" - - def test_a_command_in_flight_gives_way_to_a_stop(self): - stop = threading.Event() - threading.Timer(0.3, stop.set).start() - t0 = time.monotonic() - rc, out = execution.subprocess_run(["sleep", "30"], timeout=30, stop=stop) - self.assertEqual((rc, out), (130, "stopped")); self.assertLess(time.monotonic() - t0, 5) - rc, out = execution.subprocess_run(["sleep", "30"], timeout=0.4, stop=threading.Event()) - self.assertEqual(rc, 124); self.assertIn("no answer within 0 s", out) - self.assertEqual(execution.subprocess_run(["cat"], timeout=5, stdin="fed\n", stop=threading.Event()), (0, "fed\n")) + """The Stop button: said at once, finished by the run's own thread.""" def test_stop_is_said_at_once_while_the_host_does_not_answer(self): self.have_uv = self.have_harbor = True @@ -337,20 +325,6 @@ def answer(argv, timeout=0, stdin=None): ex.stop() # a second stop is nothing self.assertEqual(ex.state, "stopped") - def test_a_stop_cut_short_by_a_restart_is_finished_not_resumed(self): - self.have_uv = self.have_harbor = True - ex = execution.Execution(self.plan, root=str(self.tmp / "runs"), run=self.answer, key="k" * 20) - ex._save() - rec = json.loads((self.tmp / "runs" / "tau3-x3" / "run.json").read_text()) - rec.update(state="stopping", step="run", part=0, pid=4242) - (self.tmp / "runs" / "tau3-x3" / "run.json").write_text(json.dumps(rec)) - execution.EXECUTIONS.clear(); self.calls.clear() - back = execution.restore(str(self.tmp / "runs"), run=self.answer, key="k" * 20) - self.assertEqual(len(back), 1); self.wait(back[0]) - self.assertEqual(back[0].state, "stopped") - self.assertTrue(self.killed(4242)) - self.assertFalse(any("setsid nohup" in c[-1] for c, _ in self.calls)) # nothing launched - if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_feasibility.py b/app/tests/test_feasibility.py index 2ceafdaa..93528703 100644 --- a/app/tests/test_feasibility.py +++ b/app/tests/test_feasibility.py @@ -151,10 +151,6 @@ def test_a_control_over_another_dataset_is_not_this_jobs(self): self.assertEqual(rep.not_run, ["nop"]) self.assertTrue(rep.caveat.startswith("Only oracle ran")) - def test_the_full_scope_is_said_when_no_limit_was_recorded(self): - jobs = self.sweep({"a": 0}, {"a": 1}) - self.assertEqual(feasibility.report(jobs[0], jobs).scope, "every task of tb-small (no task limit recorded)") - class TaskBroken(unittest.TestCase): """A task whose nop control fails previously-passing tests was @@ -208,12 +204,6 @@ def test_task_broken_is_decided_by_nop_alone_after_unexpected_reward(self): jobs = self.sweep({"t": leaky}, {"t": swe_report(resolved=True)}, prefix="leaky") self.assertEqual(feasibility.report(jobs[0], jobs).rows[0].verdict, feasibility.UNEXPECTED_REWARD) - def test_a_benchmark_without_held_checks_never_produces_the_class(self): - # Terminal-Bench reports no held checks: a rejected nop there is a rejection, nothing more - jobs = [write_job(self.root, "tb-nop", "nop", {"t": 0}), write_job(self.root, "tb-oracle", "oracle", {"t": 1})] - row = feasibility.report(jobs[0], jobs).rows[0] - self.assertEqual((row.verdict, row.nop.broke_tests, row.nop.p2p_fail, row.nop.p2p_failures), (feasibility.FEASIBLE, False, 0, [])) - def test_the_agents_regression_is_not_the_tasks(self): # the agent's patch broke a held test; the controls are clean — that is ⚠ Broke tests on the trial, not task_broken here nop = {"t": swe_report(p2p=(["t1"], []), f2p=([], ["f1"]), patch=False)} diff --git a/app/tests/test_gaia_driver.py b/app/tests/test_gaia_driver.py index c5b4077e..3ec74fdf 100644 --- a/app/tests/test_gaia_driver.py +++ b/app/tests/test_gaia_driver.py @@ -231,14 +231,6 @@ def test_load_rejects_invalid_rows_before_caching_them(self): patch.object(self.driver, "cached_file", return_value=self.attachment), self.assertRaisesRegex(ValueError, message): self.driver.load() - def test_load_rejects_checksum_mismatch_before_parsing(self): - dataset = self.metadata([self.row]) - self.attachment.write_text("changed bytes") - with patch.dict("sys.modules", {"datasets": dataset}), \ - patch.object(self.driver, "cached_file", return_value=self.attachment), self.assertRaisesRegex(ValueError, "checksum differs"): - self.driver.load() - dataset.load_dataset.assert_not_called() - if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_hf_endpoint.py b/app/tests/test_hf_endpoint.py index 9d7c76a4..95bba1bf 100644 --- a/app/tests/test_hf_endpoint.py +++ b/app/tests/test_hf_endpoint.py @@ -53,13 +53,6 @@ def test_a_driver_is_started_with_the_endpoint(self): os.environ.pop("HF_ENDPOINT", None) self.assertEqual(run.data_env(), {}) - def test_every_driver_environment_carries_it(self): - """The local driver, the Original setup's driver in a container and a - benchmark's MCP server on the machine: each environment takes data_env.""" - import inspect - source = inspect.getsource(run.Run) - self.assertEqual(source.count("**data_env()"), 3) - class DatasetDownload(unittest.TestCase): URL = "https://huggingface.co/datasets/o/n/resolve/abc/data.json" diff --git a/app/tests/test_hosts.py b/app/tests/test_hosts.py index 64801dbf..f9283a49 100644 --- a/app/tests/test_hosts.py +++ b/app/tests/test_hosts.py @@ -74,8 +74,6 @@ def test_aliases_with_what_the_config_says_and_no_key(self): self.assertEqual(scanned[1]["user"], "me"); self.assertIsNone(scanned[1]["hostname"]) # a Match block does not leak into lab self.assertEqual([h["hostname"] for h in scanned[2:]], ["shared", "shared"]) self.assertNotIn("id_bench", repr(scanned)) - - def test_no_config_is_no_hosts(self): self.assertEqual(hosts.scan_ssh_config(str(self.tmp / "absent")), []) @@ -92,7 +90,7 @@ def run(argv, timeout): self.assertEqual(seen[0][-1], hosts.PROBE); self.assertIn("BatchMode=yes", seen[0]) # one command, no prompt possible self.assertFalse(r["docker_userns"]) - def test_the_probe_says_when_the_host_s_docker_has_userns_remap(self): + def test_the_probe_asks_each_engine_that_is_there(self): tmp = tempfile.mkdtemp(); self.addCleanup(shutil.rmtree, tmp, True) for tool in ("sh", "sed", "grep", "hostname"): # the probe's tools: no docker, podman, uv or harbor of the machine's os.symlink(shutil.which(tool), os.path.join(tmp, tool)) @@ -106,6 +104,14 @@ def test_the_probe_says_when_the_host_s_docker_has_userns_remap(self): with self.subTest(options=options): r = hosts.test(hosts.parse("bench"), run=run) self.assertEqual((r["docker_userns"], r["podman"], r["uv"], r["harbor"]), (said, False, False, False)) + os.remove(os.path.join(tmp, "docker")) # podman alone + for name in ("podman", "uv"): + with open(os.path.join(tmp, name), "w") as f: + f.write("#!/bin/sh\nexit 0\n") + os.chmod(os.path.join(tmp, name), 0o755) + out = subprocess.run(["/bin/sh", "-c", hosts.PROBE], env=env, capture_output=True, text=True).stdout + self.assertEqual([l for l in out.splitlines() if l.split("=")[0] in ("docker", "podman", "docker_ok", "podman_ok")], + ["docker=no", "podman=yes", "podman_ok=yes"]) def test_missing_tools_are_said_not_failed(self): r = hosts.test(hosts.parse("bench"), run=lambda a, t: (0, "ok\nuv=no\ndocker=no\npodman=no\nharbor=no\nhostname=x\n", "")) @@ -120,16 +126,6 @@ def test_the_engine_is_the_one_that_answers(self): r = hosts.test(hosts.parse("bench"), run=lambda a, t: (0, f"ok\ndocker=yes\npodman=yes\n{said}\n", "")) self.assertEqual(r["engine"], want, said) - def test_the_probe_asks_each_engine_that_is_there(self): - with tempfile.TemporaryDirectory() as d: - for name, code in (("podman", 0), ("uv", 0)): - with open(os.path.join(d, name), "w") as f: - f.write(f"#!/bin/sh\nexit {code}\n") - os.chmod(os.path.join(d, name), 0o755) - out = subprocess.run(["/bin/sh", "-c", hosts.PROBE], env={"PATH": d}, capture_output=True, text=True).stdout - self.assertEqual([l for l in out.splitlines() if l.split("=")[0] in ("docker", "podman", "docker_ok", "podman_ok")], - ["docker=no", "podman=yes", "podman_ok=yes"]) - def test_a_refusal_names_its_reason(self): denied = hosts.test(hosts.parse("bench"), run=lambda a, t: (255, "", "ubuntu@10.0.0.4: Permission denied (publickey).\n")) self.assertFalse(denied["ok"]); self.assertEqual(denied["error"], "refused: no usable key") diff --git a/app/tests/test_icons.py b/app/tests/test_icons.py index db47765e..a4330c08 100644 --- a/app/tests/test_icons.py +++ b/app/tests/test_icons.py @@ -76,7 +76,10 @@ def test_every_name_passed_as_data_is_a_symbol(self): for name in re.findall(r"""['"](?:filter_)?icon['"]\s*:\s*['"]([a-z0-9-]+)['"]|\b(?:filter_)?icon=['"]([a-z0-9-]+)['"]""", text(path)): self.assertKnown(next(n for n in name if n), str(path.relative_to(APP))) - def test_symbols_take_their_style_from_the_page(self): + def test_symbols_are_unique_and_take_their_style_from_the_page(self): + ids = [s.get("id") for s in symbols()] + self.assertEqual(sorted(i for i in set(ids) if ids.count(i) > 1), []) + self.assertTrue(all(i and i.startswith("i-") for i in ids), ids) for symbol in symbols(): name = symbol.get("id") if name in STYLE_EXCEPTIONS: @@ -85,11 +88,6 @@ def test_symbols_take_their_style_from_the_page(self): for part in symbol.iter(): self.assertFalse({"stroke", "stroke-width", "fill"} & set(part.attrib), f"{name}: {part.attrib}") - def test_symbol_ids_are_unique(self): - ids = [s.get("id") for s in symbols()] - self.assertEqual(sorted(i for i in set(ids) if ids.count(i) > 1), []) - self.assertTrue(all(i and i.startswith("i-") for i in ids), ids) - if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_jiuwenswarm_wrapper.py b/app/tests/test_jiuwenswarm_wrapper.py index 9d8452ea..fe7893ce 100644 --- a/app/tests/test_jiuwenswarm_wrapper.py +++ b/app/tests/test_jiuwenswarm_wrapper.py @@ -55,17 +55,6 @@ def run(path): for path in paths: self.assertFalse(os.path.exists(os.path.dirname(path))) - def test_runtime_directory_is_cleaned_when_startup_fails(self): - paths = [] - - def fail(path): - paths.append(path) - raise RuntimeError("startup failed") - - with patch.object(agent, "run", side_effect=fail), self.assertRaisesRegex(RuntimeError, "startup failed"): - agent.main() - self.assertFalse(os.path.exists(os.path.dirname(paths[0]))) - def test_older_versions_without_a_worker_need_no_shutdown_call(self): with tempfile.TemporaryDirectory() as directory, patch.object(agent.subprocess, "run") as run: agent.stop_worker({"JIUWENSWARM_RUNTIME_SOCKET": os.path.join(directory, "missing.sock")}) diff --git a/app/tests/test_judge.py b/app/tests/test_judge.py index 2936ac79..f02f22e4 100644 --- a/app/tests/test_judge.py +++ b/app/tests/test_judge.py @@ -95,18 +95,6 @@ def test_groups_are_the_surfaces_and_an_id_is_declared_once(self): questions.register("bad", {"typed": {"type": "essay", "state": "trial", "instructions": "x", "criteria": {}}}) self.assertNotIn("bad", questions.GROUPS) - def test_every_group_is_asked_by_the_application(self): - """A group no surface asks is dead vocabulary: the application (`app/nullius`, `app/web`) asks it by - `group_ids(name)`, or names one of its ids outside the module that declares them.""" - app = HERE.parent - own = app / "nullius" / "judge" / "questions.py" - sources = {p: p.read_text(encoding="utf-8") for d in ("nullius", "web") for p in (app / d).rglob("*.py")} - for g, ids in questions.GROUPS.items(): - by_group = re.compile(r"group_ids\(\s*['\"]" + re.escape(g) + r"['\"]\s*\)") - by_id = re.compile(r"['\"](" + "|".join(map(re.escape, ids)) + r")['\"]") - asked = any(by_group.search(text) or (p != own and by_id.search(text)) for p, text in sources.items()) - self.assertTrue(asked, f"question group {g!r} is asked by nothing in the application") - class Client(unittest.TestCase): def answer(self, status=200, payload=None): @@ -177,11 +165,6 @@ def told(url, body, key): self.assertEqual(naps, [7.0]) # the provider's own wait self.assertEqual(client.backoff(0, {client.RETRY_AFTER: "9999"}), client.MAX_WAIT) - def test_the_estimate(self): - est = client.estimate(18342) - self.assertEqual({k: est[k] for k in ("calls", "input_tokens", "usd")}, {"calls": 1, "input_tokens": 6115, "usd": 0.000257}) # the point; the band is test_judge_cost's - self.assertEqual(client.estimate(400_000, calls=20)["input_tokens"], 133_353) - class Store(unittest.TestCase): def setUp(self): @@ -207,7 +190,6 @@ def test_save_load_merge_and_survive_a_reparse(self): workspace.clear_cache(self.ws) # a re-parse of the job self.assertEqual(store.load(self.ws.dir, "job-1", "task__abc/def")["answers"]["task_completed"], {"noul": 0.9}) - def test_count_is_one_per_trial_and_lane_every_version_inside(self): self.assertEqual(store.count(self.ws.dir), 0) for version in ("judgement.questions.v1", questions.VERSION): @@ -298,7 +280,6 @@ def post(url, body, key): self.assertIsNone(batch.ask_and_store(str(self.tmp), "job", "empty", {"trial": ([], "", False)}, KEY, post=post)) self.assertIsNone(store.load(str(self.tmp), "job", "empty")) - def test_the_llm_judge_keeps_its_records_apart_from_decision_judge(self): import json as _json def chat(url, body, key): @@ -355,19 +336,6 @@ class Hygiene(unittest.TestCase): def setUp(self): self.tmp = Path(tempfile.mkdtemp(prefix="nullius-judge-hygiene-")); self.addCleanup(shutil.rmtree, self.tmp, True) - def test_the_vocabulary_declares_two_nouls_over_every_state_and_sends_them_as_questions(self): - self.assertEqual(questions.hygiene_ids(), ["addresses_the_judge", "credential_visible"]) - for q in questions.hygiene_ids(): - spec = questions.QUESTIONS[q] - self.assertEqual((spec["type"], spec["state"], spec["group"], spec.get("hygiene")), ("noul", "*", "hygiene", True)) - self.assertEqual(sorted(spec["criteria"]), ["false", "true"]) - self.assertEqual(sorted(questions.request_questions([q])[q]), ["criteria", "instructions", "type"]) # `hygiene` and `state` stay here - self.assertNotIn("addresses_the_judge", questions.for_trial(False)) # not a trial-page row of its own - self.assertIn("An agent telling the user it finished", questions.QUESTIONS["addresses_the_judge"]["criteria"]["false"]) # the boundary case, in the criteria - self.assertIn("[REDACTED]", questions.QUESTIONS["credential_visible"]["criteria"]["false"]) - self.assertEqual(batch.with_hygiene(["task_completed"]), ["task_completed", "addresses_the_judge", "credential_visible"]) - self.assertEqual(batch.with_hygiene(["credential_visible"]), ["credential_visible", "addresses_the_judge"]) - def test_every_call_carries_them_and_the_readings_land_per_kind_apart_from_the_answers(self): traj = trajectory.load(str(ADVERSARIAL)); self.assertFalse(traj.error) calls = [] @@ -446,14 +414,10 @@ def section(self, text): def failure(self, trial): return self.section(state.build("failure", self.traj, trial=trial, trial_dir=str(self.tmp))[0]) - def test_no_verifier_file_and_no_trial_is_nothing_recorded(self): + def test_without_a_verifier_file_the_section_follows_the_trial(self): self.assertEqual(self.failure(None), "[verifier]\nnothing recorded") self.assertEqual(self.section(state.build("failure", self.traj)[0]), "[verifier]\nnothing recorded") - - def test_a_trial_with_no_reward_and_no_verifier_phase_says_the_verifier_did_not_run(self): self.assertEqual(self.failure(self.trial(None, None)), self.DID_NOT_RUN) - - def test_a_trial_with_a_reward_or_a_verifier_phase_is_nothing_recorded(self): for reward, dur_verifier in ((0.0, None), (None, 4.5), (1.0, 4.5)): with self.subTest(reward=reward, dur_verifier=dur_verifier): self.assertEqual(self.failure(self.trial(reward, dur_verifier)), "[verifier]\nnothing recorded") @@ -475,11 +439,9 @@ def steps(self, *pairs): from types import SimpleNamespace return SimpleNamespace(steps=[SimpleNamespace(source=src, message=msg) for src, msg in pairs]) - def test_the_task_is_the_first_user_step_not_the_system_prompt(self): + def test_the_task_is_the_first_user_step_and_falls_back_without_one(self): t = self.steps(("system", "You are a helpful assistant."), ("user", "Fix the bug in calc.py"), ("agent", "ok")) self.assertEqual(state.instruction_of(t), "Fix the bug in calc.py") - - def test_a_trajectory_with_no_user_step_falls_back(self): self.assertEqual(state.instruction_of(self.steps(("system", "only this"), ("agent", "ok"))), "only this") self.assertEqual(state.instruction_of(self.steps(("agent", "ok"))), "") @@ -537,20 +499,17 @@ def made_up(self, steps): def transcript_lines(self, text): return text.split("\n\n[transcript]\n", 1)[1].split("\n\n[final message]\n", 1)[0].splitlines() - def test_each_kind_holds_the_final_message_once_per_trajectory(self): - for fixture in (CLEAN, ADVERSARIAL): - traj = trajectory.load(str(fixture)); final = traj.last_agent_message; self.assertTrue(final) - with self.subTest(fixture=fixture.name): - for kind in ("trial", "failure", "final"): - self.assertEqual(state.build(kind, traj)[0].count(final), 1, kind) - self.assertEqual(state.build("pair", traj, other=traj)[0].count(final), 2) def test_the_marker_stands_where_the_final_message_stood(self): for fixture in (CLEAN, ADVERSARIAL): traj = trajectory.load(str(fixture)); final = traj.last_agent_message + self.assertTrue(final) line = "[agent] " + final head = "[instruction]\n" + state.instruction_of(traj) + "\n\n[transcript]\n" + state.transcript_of(traj) with self.subTest(fixture=fixture.name): + for kind in ("trial", "failure", "final"): + self.assertEqual(state.build(kind, traj)[0].count(final), 1, kind) + self.assertEqual(state.build("pair", traj, other=traj)[0].count(final), 2) trial = state.build("trial", traj)[0] self.assertEqual(trial.count(self.MARKER), 1) self.assertEqual(trial.replace(self.MARKER, line), redact.redact(head + "\n\n[final message]\n" + final)) @@ -634,24 +593,6 @@ def test_permissions_are_read_contents_write_pull_requests_and_issues_and_nothin perms = {l.split(":")[0]: l.split(":", 1)[1].split("#")[0].strip() for l in self.block("permissions")} self.assertEqual(perms, {"contents": "read", "pull-requests": "write", "issues": "write"}) - def test_it_triggers_on_pull_requests_and_on_a_created_comment(self): - on = self.block("on") - self.assertIn("pull_request:", on) - self.assertIn("types: [opened, synchronize, reopened, ready_for_review]", on) - self.assertIn("issue_comment:", on) - self.assertIn("types: [created]", on) - - def test_a_comment_is_admitted_only_as_a_slash_judge_from_the_repositorys_own_people(self): - jobs = self.block("jobs") - guard = next(l for l in jobs if l.startswith("if:")) - self.assertIn("github.event_name == 'issue_comment'", guard) - self.assertIn("github.event.issue.pull_request", guard) - self.assertIn("startsWith(github.event.comment.body, '/judge')", guard) - self.assertIn("""contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.comment.author_association)""", guard) - # The body is read by that expression only: nowhere else in the file, no shell line. - self.assertEqual(sum("comment.body" in l for l in self.lines()), 1) - self.assertFalse([l for l in self.lines() if l.strip().startswith("run:") and "comment" in l.lower() and "body" in l.lower()]) - def expression(self, source, event): """Exercise the workflow's boolean operators with event fixtures. @@ -682,6 +623,13 @@ def test_only_ready_pull_requests_or_authorized_manual_requests_enter_the_judge( with self.subTest(role=role, is_pr=is_pr, body=body): self.assertEqual(bool(self.expression(expression, event)), expected) self.assertFalse(self.expression(expression, {"github.event_name": "workflow_dispatch"})) + self.assertIn("github.event_name == 'issue_comment'", guard) + self.assertIn("github.event.issue.pull_request", guard) + self.assertIn("startsWith(github.event.comment.body, '/judge')", guard) + self.assertIn("""contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.comment.author_association)""", guard) + # The body is read by that expression only: nowhere else in the file, no shell line. + self.assertEqual(sum("comment.body" in l for l in self.lines()), 1) + self.assertFalse([l for l in self.lines() if l.strip().startswith("run:") and "comment" in l.lower() and "body" in l.lower()]) def test_cancellation_is_scoped_to_an_admitted_job_and_the_same_pull_request(self): lines = self.lines() @@ -797,6 +745,11 @@ def test_the_floors_the_checks_and_the_before_and_after_count(self): self.assertTrue(all(c["ok"] for c in clean["checks"])) self.assertEqual(clean["visible"], []) + body = "Closes #1\n\n## What\nthe change\n\n## Verified\nnot verified\n\n## Risk\nnone" + self.assertEqual(J.section(body, "verified"), "not verified") + self.assertEqual(J.section(body, "Risk"), "none") + self.assertIsNone(J.section(body, "Before and after")) + def test_the_judges_risk_is_raised_to_the_floor_never_lowered(self): J = self._mod() dc = {"pick": "minor", "undecided": False} @@ -804,10 +757,3 @@ def test_the_judges_risk_is_raised_to_the_floor_never_lowered(self): self.assertEqual(J.risk_of({"pick": "severe", "undecided": False}, {"risk_floor": "major", "risk_floor_why": "parse.py"})[0], "severe") self.assertEqual(J.risk_of(dc, {"risk_floor": None, "risk_floor_why": ""})[0], "minor") self.assertEqual(J.risk_of({"pick": "unanswered", "undecided": True}, {"risk_floor": None, "risk_floor_why": ""})[0], "not asked") - - def test_a_sections_text_is_read_by_its_heading(self): - J = self._mod() - body = "Closes #1\n\n## What\nthe change\n\n## Verified\nnot verified\n\n## Risk\nnone" - self.assertEqual(J.section(body, "verified"), "not verified") - self.assertEqual(J.section(body, "Risk"), "none") - self.assertIsNone(J.section(body, "Before and after")) diff --git a/app/tests/test_judge_cost.py b/app/tests/test_judge_cost.py index f38acb1b..8582b14f 100644 --- a/app/tests/test_judge_cost.py +++ b/app/tests/test_judge_cost.py @@ -27,7 +27,7 @@ def record(states: dict, truncated: bool = False, version: str = questions.VERSI class Estimate(unittest.TestCase): - def test_a_point_and_a_band_on_the_rule_of_thumb(self): + def test_a_point_and_a_band_on_a_dated_price_that_says_when_it_is_old(self): est = client.estimate(18342, today="2026-09-18") self.assertEqual((est["calls"], est["input_tokens"], est["usd"]), (1, 6115, 0.000257)) # the point: 3.0 characters per token, measured self.assertEqual((est["tokens_low"], est["tokens_high"]), (int(18342 // 3.5) + 1, int(18342 // 2.5) + 1)) # the band: 2.5 to 3.5 characters per token @@ -36,14 +36,12 @@ def test_a_point_and_a_band_on_the_rule_of_thumb(self): self.assertEqual((est["price_per_mtok"], est["price_as_of"], est["price_stale"]), (0.042, "2026-09-17", False)) self.assertEqual(client.estimate(400_000, calls=20)["input_tokens"], 133_353) self.assertEqual(client.estimate(0, calls=0)["tokens_high"], 0) - - def test_the_price_is_dated_never_fetched_and_says_when_it_is_old(self): self.assertFalse(client.price_stale("2026-09-17")); self.assertFalse(client.price_stale("2026-12-16")) self.assertTrue(client.price_stale("2026-12-17")); self.assertTrue(client.price_stale("2027-09-17")) self.assertTrue(client.estimate(100, today="2027-01-01")["price_stale"]) self.assertIsInstance(client.price_stale(), bool) src = Path(client.__file__).read_text(encoding="utf-8") - self.assertNotIn("urlopen(\"https://docs", src); self.assertIn('PRICE_AS_OF = "2026-09-17"', src) # a constant with a date, not a fetch + self.assertNotIn("urlopen(\"https://docs", src) # a constant with a date, not a fetch def test_calibration_from_stored_calls_tightens_the_band(self): recs = [record({"trial": {"chars": 10000, "truncated": False, "input_tokens": 2500}, "final": {"chars": 300, "truncated": False, "input_tokens": 100}}), diff --git a/app/tests/test_judge_decisions.py b/app/tests/test_judge_decisions.py index ad7d1e2d..d12e082c 100644 --- a/app/tests/test_judge_decisions.py +++ b/app/tests/test_judge_decisions.py @@ -32,7 +32,7 @@ def judge(env): class Protocols(unittest.TestCase): - def test_each_provider_and_model_gets_its_decision_protocol(self): + def test_each_provider_and_model_gets_its_decision_protocol_and_is_asked_there(self): got = lambda env: (judge(env).protocol, judge(env).url) self.assertEqual(got({"TYPESAFE_API_KEY": "k"}), ("systemone", "https://api.typesafe.ai/v1/systemone")) self.assertEqual(got({"OPENROUTER_API_KEY": "k"}), ("systemone", "https://openrouter.ai/api/v1/systemone")) @@ -44,6 +44,18 @@ def test_each_provider_and_model_gets_its_decision_protocol(self): "DECISION_PROVIDER": "custom:GW", "DECISION_MODEL": "m"} self.assertEqual(got(custom), ("decisions", "https://gw/v1/alpha/decisions")) self.assertNotIn("custom:LAB", client.decision_judge_providers({"MODEL_LAB": '{"base": "http://lab/v1"}'})) # lists none: not offered + self.assertEqual(judge({"OPENROUTER_API_KEY": "sk-or-1"}).provider, "openrouter") # the only key: OpenRouter + self.assertEqual(judge({"OPENROUTER_API_KEY": "sk-or-1", "TYPESAFE_API_KEY": "ts-1"}).provider, "typesafe") + self.assertEqual(judge({"OPENROUTER_API_KEY": "k", "DECISION_PROVIDER": "openrouter"}).model, "~typesafe/jev-latest") + j = judge({"OPENROUTER_API_KEY": "sk-or-1", "DECISION_PROVIDER": "openrouter", "DECISION_MODEL": "jaredpalmer/kev-4b"}) + self.assertEqual((j.lane, j.url, j.model), ("decision", "https://openrouter.ai/api/v1/systemone", "jaredpalmer/kev-4b")) + post, sent = fake(200, {"model": "jaredpalmer/kev-4b", "answers": {"task_completed": {"type": "noul", "noul": 0.81}}, "usage": {"input_tokens": 50}}) + rec = client.ask("the state", ["task_completed"], j, post=post) + url, body, key = sent[0]["url"], sent[0]["body"], sent[0]["key"] + self.assertEqual((url, key, body["model"]), ("https://openrouter.ai/api/v1/systemone", "sk-or-1", "jaredpalmer/kev-4b")) + self.assertIn("questions", body); self.assertEqual(body["state"], "the state") # the Decision contract, not a chat + self.assertEqual(rec["judge"], {"provider": "openrouter", "model": "jaredpalmer/kev-4b"}) + self.assertEqual(rec["answers"], {"task_completed": {"noul": 0.81}}) def test_a_setting_saved_before_the_rename_is_still_read_and_the_new_name_wins(self): old = {"OPENROUTER_API_KEY": "k", "SYSTEM_ONE_PROVIDER": "openrouter", "SYSTEM_ONE_MODEL": "typesafe/jev-1.14", @@ -92,6 +104,9 @@ def test_systemone_keeps_the_providers_cost_and_records_a_refusal(self): self.assertEqual(rec["usage"]["cost_usd"], 0.00004) merged = client.merge([rec, dict(rec, refusals={"transcript_quality": "refused"})]) self.assertEqual(set(merged["refusals"]), {"failure_cause", "transcript_quality"}) + post, _ = fake(200, {"answers": {"task_completed": {"noul": 0.7, "refusal": None}}}) # a null refusal: the answer + rec = client.ask("state", IDS, judge({"OPENROUTER_API_KEY": "sk-or-1"}), post=post) + self.assertEqual(rec["answers"], {"task_completed": {"noul": 0.7}}); self.assertNotIn("refusals", rec) def test_a_402_says_what_it_means(self): post, _ = fake(402, {"error": {"code": 402, "message": "Insufficient credits"}}) @@ -114,12 +129,6 @@ def test_decisions_reads_confidence_and_its_error_shape(self): client.ask("state", IDS, judge(env), post=post) self.assertIn("Box questions are Jev-only", str(e.exception)) - - def test_a_null_refusal_beside_an_answer_is_the_answer(self): - post, _ = fake(200, {"answers": {"task_completed": {"noul": 0.7, "refusal": None}}}) - rec = client.ask("state", IDS, judge({"OPENROUTER_API_KEY": "sk-or-1"}), post=post) - self.assertEqual(rec["answers"], {"task_completed": {"noul": 0.7}}); self.assertNotIn("refusals", rec) - def test_a_reply_of_another_shape_is_a_judge_error(self): for env, data in (({"OPENROUTER_API_KEY": "k"}, {"answers": [1, 2]}), ({"OPENROUTER_API_KEY": "k"}, {"answers": {"failure_cause": {"choice": "a", "probabilities": {"a": "x"}}}}), @@ -212,25 +221,6 @@ def test_no_network_and_no_cache_is_no_list(self): self.assertEqual(self.models(body), []) self.assertEqual(self.models(fetch=False), []) - def test_a_redirect_is_refused(self): - seen = [] - - class Handler(BaseHTTPRequestHandler): - def log_message(self, *a): - pass - - def do_GET(self): - seen.append(self.path) - self.send_response(302); self.send_header("Location", f"http://127.0.0.1:{srv.server_address[1]}/elsewhere") - self.send_header("Content-Length", "0"); self.end_headers() - - srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler) - threading.Thread(target=srv.serve_forever, daemon=True).start() - self.addCleanup(srv.server_close); self.addCleanup(srv.shutdown) - with mock.patch.dict(providers.PRESETS["openrouter"], base=f"http://127.0.0.1:{srv.server_address[1]}/api/v1"): - self.assertEqual(providers.decision_models(self.env), []) - self.assertEqual(seen, ["/api/v1/models?output_modalities=decisions"]) # never followed - def test_the_suggestions_are_the_list_with_the_alias_first_or_the_short_list(self): with mock.patch.object(providers, "decision_models", return_value=["z/one", "typesafe/jev-1.14", "a/two:free", "~typesafe/jev-latest"]) as live: self.assertEqual(client.decision_judge_models("openrouter"), ["~typesafe/jev-latest", "typesafe/jev-1.14", "a/two:free", "z/one"]) @@ -282,8 +272,6 @@ def test_the_reply_is_read_into_the_record_and_a_refusal_is_said(self): self.assertEqual(rec["answers"]["failure_cause"]["probabilities"], {option: 0.6}) self.assertEqual(rec["refusals"], {"transcript_quality": "cannot judge"}) self.assertNotIn("not_asked", rec["answers"]); self.assertEqual(rec["usage"]["input_tokens"], 50) - - def test_a_score_out_of_its_levels_is_left_out(self): post, _ = fake(200, {"answers": [{"name": "transcript_quality", "type": "score", "level": "7"}]}) self.assertEqual(client.ask("s", IDS, judge(self.ENV), post=post)["answers"], {}) post, _ = fake(200, {"answers": [{"name": "transcript_quality", "type": "score", "level": "2"}]}) diff --git a/app/tests/test_judge_openrouter.py b/app/tests/test_judge_openrouter.py index 96de8b88..50a47882 100644 --- a/app/tests/test_judge_openrouter.py +++ b/app/tests/test_judge_openrouter.py @@ -55,25 +55,6 @@ def test_the_llm_judge_on_a_named_endpoint_uses_its_url_and_its_key(self): self.assertEqual((gone.provider, gone.key), ("custom", "default-key")) -class DecisionOnOpenRouter(unittest.TestCase): - def test_decision_judge_is_asked_where_settings_say_with_the_model_named(self): - self.assertEqual(client.decision_judge({"OPENROUTER_API_KEY": "sk-or-1"}).provider, "openrouter") # the only key: OpenRouter - self.assertEqual(client.decision_judge({"OPENROUTER_API_KEY": "sk-or-1", "TYPESAFE_API_KEY": "ts-1"}).provider, "typesafe") - j = client.decision_judge({"OPENROUTER_API_KEY": "sk-or-1", "DECISION_PROVIDER": "openrouter", "DECISION_MODEL": "jaredpalmer/kev-4b"}) - self.assertEqual((j.lane, j.url, j.model), ("decision", "https://openrouter.ai/api/v1/systemone", "jaredpalmer/kev-4b")) - sent = [] - def post(url, body, key): - sent.append((url, body, key)) - return 200, {"model": body["model"], "answers": {"task_completed": {"type": "noul", "noul": 0.81}}, "usage": {"input_tokens": 50}} - rec = client.ask("the state", ["task_completed"], j, post=post) - url, body, key = sent[0] - self.assertEqual((url, key, body["model"]), ("https://openrouter.ai/api/v1/systemone", "sk-or-1", "jaredpalmer/kev-4b")) - self.assertIn("questions", body); self.assertEqual(body["state"], "the state") # the Decision contract, not a chat - self.assertEqual(rec["judge"], {"provider": "openrouter", "model": "jaredpalmer/kev-4b"}) - self.assertEqual(rec["answers"], {"task_completed": {"noul": 0.81}}) - self.assertEqual(client.decision_judge({"OPENROUTER_API_KEY": "k", "DECISION_PROVIDER": "openrouter"}).model, "~typesafe/jev-latest") - - class OpenRouterJudge(unittest.TestCase): judge = client.Judge("openrouter", "sk-or-1", "vendor/judge-1", "https://openrouter.ai/api/v1/chat/completions") diff --git a/app/tests/test_judge_store_keys.py b/app/tests/test_judge_store_keys.py index fb19b79e..cff38481 100644 --- a/app/tests/test_judge_store_keys.py +++ b/app/tests/test_judge_store_keys.py @@ -21,20 +21,14 @@ def setUp(self): self.ws = tempfile.mkdtemp(prefix="nullius-judge-keys-") self.addCleanup(shutil.rmtree, self.ws, True) - def test_two_task_names_keep_two_records(self): - store.save(self.ws, "task:ds", "task:abc", rec("first")) - store.save(self.ws, "task:ds", "task_abc", rec("second")) - self.assertEqual(store.load(self.ws, "task:ds", "task:abc")["answers"]["q"]["choice"], "first") - self.assertEqual(store.load(self.ws, "task:ds", "task_abc")["answers"]["q"]["choice"], "second") - - def test_a_split_agent_view_and_a_job_of_the_lookalike_name_keep_two_records(self): - store.save(self.ws, "job~a-b", "t1", rec("view")) # parse.py names an agent's view ~