Skip to content

Official Codebase of 3DCodeVerse

Python

tests: core, install, gallery — 86 tests go that cover no line another test does not (−744 lines)

gaoypeng6444dd163d25
diff --git a/harness/tests/core/test_addons_boundary.py b/harness/tests/core/test_addons_boundary.py
index 93b8dfe8..ee5c387c 100644
--- a/harness/tests/core/test_addons_boundary.py
+++ b/harness/tests/core/test_addons_boundary.py
@@ -6,7 +6,6 @@ import re
from pathlib import Path
import codeverse3d
-import codeverse3d.addons
PKG = Path(codeverse3d.__file__).parent
# an import statement, or a module named in a string (the lazy `_import("codeverse3d.…")` call sites);
@@ -21,9 +20,3 @@ def test_nothing_outside_the_cli_imports_an_addon() -> None:
if p.relative_to(PKG).parts[0] not in {"addons", "cli"} and IMPORTS_ADDON.search(p.read_text())
]
assert offenders == [], f"the core imports an addon: {offenders}"
-
-
-def test_the_addons_are_the_ones_the_docstring_lists() -> None:
- names = sorted(p.stem for p in (PKG / "addons").iterdir() if p.name not in {"__init__.py", "__pycache__"})
- assert names == ["calibration", "costreport", "dataset", "gallery", "select", "skill_targets"]
- assert all(f"``{n}``" in (codeverse3d.addons.__doc__ or "") for n in names)
diff --git a/harness/tests/core/test_config_backends.py b/harness/tests/core/test_config_backends.py
index 69908784..73c52304 100644
--- a/harness/tests/core/test_config_backends.py
+++ b/harness/tests/core/test_config_backends.py
@@ -1,4 +1,4 @@
-"""Settings.backends() — one source of backend-role defaults (Batch-1)."""
+"""Settings.backends() — one source of backend-role defaults."""
from __future__ import annotations
@@ -8,36 +8,9 @@ from codeverse3d.config import Settings
from codeverse3d.contracts.common import Backends
-def test_settings_defaults_mirror_backends():
- s = Settings()
- assert s.backends() == Backends()
- assert s.default_planner == Backends().planner
- assert s.default_generator == Backends().generator
- assert s.default_judge == Backends().judge
- assert s.default_captioner == Backends().captioner
-
-
-def test_settings_overrides_flow_through():
- s = Settings(default_generator="single-shot:gemini:gemini-3.7-flash", default_captioner="gemini:x")
- b = s.backends()
- assert b.generator == "single-shot:gemini:gemini-3.7-flash"
- assert b.captioner == "gemini:x"
- assert b.planner == Backends().planner
-
-
-def test_backends_keyword_overrides_win_when_truthy():
- s = Settings()
- b = s.backends(judge="gemini:custom", planner=None, generator="")
+def test_backends_keyword_overrides_win_only_when_truthy_and_name_a_role():
+ b = Settings().backends(judge="gemini:custom", planner=None, generator="")
assert b.judge == "gemini:custom"
- assert b.planner == Backends().planner # None falls through
- assert b.generator == Backends().generator # "" falls through
-
-
-def test_backends_rejects_unknown_role():
+ assert (b.planner, b.generator) == (Backends().planner, Backends().generator)
with pytest.raises(TypeError, match="unknown backend role"):
Settings().backends(judger="x")
-
-
-def test_env_override_still_wins(monkeypatch):
- monkeypatch.setenv("C3D_DEFAULT_CAPTIONER", "gemini:from-env")
- assert Settings().backends().captioner == "gemini:from-env"
diff --git a/harness/tests/core/test_config_env_aliases.py b/harness/tests/core/test_config_env_aliases.py
index 556c8e9d..8d662dd5 100644
--- a/harness/tests/core/test_config_env_aliases.py
+++ b/harness/tests/core/test_config_env_aliases.py
@@ -5,31 +5,16 @@ from __future__ import annotations
import logging
import pytest
-from pydantic import WrapValidator
from codeverse3d.config import Settings
-#: every on/off switch, by the name an operator types (nested ones by their flat spelling)
-_FLAGS = sorted([(f"C3D_{name.upper()}", field.default) for name, field in Settings.model_fields.items()
- if field.annotation is bool and any(isinstance(m, WrapValidator) for m in field.metadata)]
- + [("C3D_SEED_RECIPES", True)])
-
-
-def test_the_switches_are_the_ones_the_harness_reads():
- """A guard on the list the next test walks: every switch with its shipped default."""
- assert dict(_FLAGS) == {
- "C3D_AUTO_EXPOSURE": False, "C3D_AXIS_REPAIR": True, "C3D_CAMERA_REPAIR": True, "C3D_IPV4": True,
- "C3D_PLAN_BRIEF": True, "C3D_PLAN_RESTART": True, "C3D_POST": True, "C3D_REFERENCE_DIFF": True,
- "C3D_SCENE_TEXTURES": False, "C3D_SCOPED_PARTS": True, "C3D_SEED_RECIPES": True, "C3D_SETTLE": True,
- "C3D_SKILLS": True, "C3D_SKILLS_UNVERIFIED": True, "C3D_STREAM": True, "C3D_ZONE_LAYOUTS": True}
+#: every switch shares one validator: one top-level and one nested (flat-spelled) case
+_FLAGS = [("C3D_SKILLS", True), ("C3D_SEED_RECIPES", True)]
@pytest.mark.parametrize(("env", "default"), _FLAGS)
def test_every_switch_speaks_one_grammar(monkeypatch, caplog, env, default):
- """``C3D_STREAM=off``, ``C3D_IPV4=off`` and ``C3D_AXIS_REPAIR=off`` were silently ignored
- until 2026-09-22 (only "0" was read), fourteen switches were parsed by hand, and a typo
- in ``C3D_FEWER_TURNS`` crashed. Now: on/off, 1/0, true/false, yes/no in any case and
- padding; empty is unset; anything else warns and keeps the default (D44 c)."""
+ """on/off, 1/0, true/false, yes/no in any case and padding; empty is unset; else warn (D44 c)."""
def read(raw: str | None) -> bool:
if raw is None:
monkeypatch.delenv(env, raising=False)
@@ -57,6 +42,12 @@ def test_flat_and_nested_max_in_flight_aliases(monkeypatch):
assert Settings().rate.max_in_flight == 24
monkeypatch.setenv("C3D_MAX_IN_FLIGHT", "8")
assert Settings().rate.max_in_flight == 8
+ for name in ("C3D_MAX_IN_FLIGHT", "C3D_RATE__MAX_IN_FLIGHT"): # both spellings reject a negative cap
+ monkeypatch.delenv("C3D_MAX_IN_FLIGHT", raising=False)
+ monkeypatch.delenv("C3D_RATE__MAX_IN_FLIGHT", raising=False)
+ monkeypatch.setenv(name, "-5")
+ with pytest.raises(ValueError, match="max_in_flight"):
+ Settings()
def test_empty_is_unset_and_garbage_in_a_sizing_knob_is_loud(monkeypatch):
@@ -70,9 +61,7 @@ def test_empty_is_unset_and_garbage_in_a_sizing_knob_is_loud(monkeypatch):
def test_render_gpu_is_read_by_both_spellings_and_garbage_is_loud(monkeypatch):
- """C3D_RENDER_GPU is the spelling every doc and the node side use — it used to be
- read by NOTHING in Settings (only C3D_RENDER__GPU was), so the documented knob
- was dead on 2 of 3 tracks."""
+ """C3D_RENDER_GPU is the documented spelling; C3D_RENDER__GPU is the nested one."""
monkeypatch.delenv("C3D_RENDER__GPU", raising=False)
monkeypatch.setenv("C3D_RENDER_GPU", "off")
assert Settings().render.gpu == "off"
@@ -86,20 +75,7 @@ def test_render_gpu_is_read_by_both_spellings_and_garbage_is_loud(monkeypatch):
Settings()
-def test_a_negative_cap_is_rejected_by_both_spellings(monkeypatch):
- """Both spellings reject negative caps; zero remains the unlimited sentinel."""
- monkeypatch.delenv("C3D_RATE__MAX_IN_FLIGHT", raising=False)
- monkeypatch.setenv("C3D_MAX_IN_FLIGHT", "-5")
- with pytest.raises(ValueError, match="max_in_flight"):
- Settings()
- monkeypatch.delenv("C3D_MAX_IN_FLIGHT")
- monkeypatch.setenv("C3D_RATE__MAX_IN_FLIGHT", "-5")
- with pytest.raises(ValueError, match="max_in_flight"):
- Settings()
-
-
def test_the_rate_and_limits_dials_carry_their_bounds(monkeypatch):
- """Reject rate/worker values that cannot make progress."""
from codeverse3d.config import Limits, Rate
for kwargs in ({"max_in_flight": -1}, {"hedge": 0}):
@@ -148,10 +124,7 @@ def test_a_project_file_overrides_only_the_keys_it_names(tmp_path, monkeypatch):
def test_the_environment_beats_the_config_files_per_setting(monkeypatch):
- """docs/INSTALL.md §8.3 promises "... < project config < C3D_* env", but get_settings hands
- the yaml to Settings as init kwargs, which pydantic-settings ranked ABOVE the environment:
- a `skills: true` in a config file silently overrode an A/B arm's C3D_SKILLS=0 (the
- switches became Settings fields 2026-09-22, so this now decides A/B arms)."""
+ """INSTALL §8.3: config files < C3D_* env, per setting — it decides A/B arms."""
for name, raw in (("C3D_SKILLS", "0"), ("C3D_RUNS_DIR", "/from_env"), ("C3D_JUDGE__SAMPLES", "3")):
monkeypatch.setenv(name, raw)
s = Settings(skills=True, runs_dir="/from_yaml", judge={"samples": 2, "max_px": 512})
@@ -159,18 +132,6 @@ def test_the_environment_beats_the_config_files_per_setting(monkeypatch):
assert s.judge.max_px == 512, "a yaml sibling the environment does not name survives"
-def test_deep_merge_overlays_per_key_at_every_depth():
- from codeverse3d.config import _deep_merge
-
- base = {"rate": {"tpm": 1, "rpm": 2}, "judge": {"samples": 4}, "scalar": 1}
- over = {"rate": {"tpm": 9}, "scalar": 2, "new": {"a": 1}}
- assert _deep_merge(base, over) == {
- "rate": {"tpm": 9, "rpm": 2}, "judge": {"samples": 4}, "scalar": 2, "new": {"a": 1}}
- assert base == {"rate": {"tpm": 1, "rpm": 2}, "judge": {"samples": 4}, "scalar": 1}, "no mutation"
- # a non-dict overlay replaces a dict outright rather than trying to merge into it
- assert _deep_merge({"a": {"b": 1}}, {"a": 5}) == {"a": 5}
-
-
def test_runtime_js_dir_override_and_loud_failure(tmp_path, monkeypatch):
"""C3D_RUNTIME_JS supports relocation and rejects a missing directory."""
@@ -186,8 +147,7 @@ def test_runtime_js_dir_override_and_loud_failure(tmp_path, monkeypatch):
def test_the_config_names_before_d78_are_still_read_under_the_new_ones(tmp_path, monkeypatch):
- """`~/.config/codeverse/config.yaml` and `./codeverse.yaml` were the names until 2026-09-22:
- a machine that still has them keeps its settings, and a new file wins per setting."""
+ """The pre-D78 config file names are still read; a new file wins per setting."""
from codeverse3d import config as C
home = tmp_path / "fakehome"
diff --git a/harness/tests/core/test_contract_additions.py b/harness/tests/core/test_contract_additions.py
index 903eded4..0a3b7135 100644
--- a/harness/tests/core/test_contract_additions.py
+++ b/harness/tests/core/test_contract_additions.py
@@ -1,46 +1,15 @@
-"""Registry, finding, agent-job, and run-option contracts."""
+"""Finding lines, run options, and old-record compatibility."""
from __future__ import annotations
import pytest
from pydantic import ValidationError
-from codeverse3d.contracts.artifacts import GateFinding, GateReport, RenderSet, RenderView, Severity
-from codeverse3d.contracts.common import (
- ENTRY_FILE,
- LANGUAGE_LABEL,
- TRACK_INFO,
- TRACK_LANGUAGES,
- Language,
- Track,
- code_file,
-)
+from codeverse3d.contracts.artifacts import GateFinding, RenderSet, Severity
+from codeverse3d.contracts.common import Language, Track
from codeverse3d.contracts.spec import RunOptions, Spec
-# ------------------------------------------------------------------ registries
-def test_registries_cover_their_enums_and_are_frozen():
- from codeverse3d.conventions import LANGUAGE_FRAME, Frame
-
- assert set(TRACK_INFO) == set(Track)
- assert TRACK_INFO[Track.STATIC_OBJECT].rubric == "static_object_v1"
- assert TRACK_INFO[Track.ARTICULATED_OBJECT].rubric == "articulated_v1"
- assert TRACK_INFO[Track.SCENE].rubric == "scene_v1"
- assert TRACK_INFO[Track.GRAPHICS].rubric == "shader_v2"
- with pytest.raises(ValidationError):
- TRACK_INFO[Track.SCENE].rubric = "other" # frozen
- assert set(ENTRY_FILE) == set(Language)
- assert set(LANGUAGE_LABEL) == set(Language)
- assert set(TRACK_LANGUAGES) == set(Track)
- assert all(e.startswith("src/") for e in ENTRY_FILE.values())
- assert code_file(Language.BLENDER) == "code.py"
- assert code_file(Language.THREEJS) == "code.js"
- assert code_file(Language.GLSL_SHADER) == "code.frag"
- assert set(LANGUAGE_FRAME) == {lang.value for lang in Language}
- assert LANGUAGE_FRAME["glsl_shader"] is Frame.Y_UP_POS_Z_FRONT
- assert LANGUAGE_FRAME["opengl_python"] is Frame.Y_UP_POS_Z_FRONT
-
-
# ------------------------------------------------------------------ as_line
def _finding(**kw) -> GateFinding:
base = dict(gate="contract", severity=Severity.ERROR, target="leg_1", message="leg floats", fix_hint="drop z by 0.02")
@@ -61,25 +30,9 @@ def test_as_line_formats_defaults_flags_and_empty_fields():
assert _finding(target=None).as_line(with_target=True, with_hint=False) == "leg floats"
-def test_a_gate_report_of_its_findings_passes_iff_none_is_an_error():
- warn, err = _finding(severity=Severity.WARN), _finding()
- assert GateReport.of("contract").passed and GateReport.of("contract", [warn]).passed
- rep = GateReport.of("contract", (warn, err), duration_ms=7)
- assert not rep.passed and rep.findings == [warn, err] and rep.errors == [err] and rep.duration_ms == 7
-
-
-# ------------------------------------------------------------------ render flags
-def test_render_view_judge_flag_defaults_none():
- v = RenderView(name="front", path="front.png")
- assert v.judge is None
- assert RenderView(name="front", path="front.png", judge=True).judge is True
- assert RenderSet().out_dir == ""
-
-
# ------------------------------------------------------------------ RunOptions
-def test_spec_options_default_legacy_roundtrip_and_validation():
+def test_spec_options_legacy_roundtrip_and_validation():
s = Spec(id="x", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a chair")
- assert s.options == RunOptions()
d = s.model_dump(mode="json")
d.pop("options")
s2 = Spec(**d) # old spec.json without options still parses
@@ -102,10 +55,7 @@ def test_spec_options_do_not_change_the_plan_stage_hash():
def test_records_written_before_the_2026_08_30_field_retirements_still_load():
- """RenderSet.turntable (360 records carry the key, none non-null), SkillRead.
- first_seen_turn (an api-agent leftover) and AgentJob.images (dead once image staging
- moved to .3dcode/images/) were deleted. Every model here ignores unknown keys, so the
- stored runs on disk must keep re-reading — that is the whole licence for the delete."""
+ """Stored runs carry keys since retired; every model here must keep ignoring them."""
from codeverse3d.contracts.agent import AgentJob
from codeverse3d.contracts.run import RoundRecord, SkillRead
@@ -117,7 +67,6 @@ def test_records_written_before_the_2026_08_30_field_retirements_still_load():
job = AgentJob.model_validate({"workspace": "/w", "prompt": "p",
"images": [{"path": "renders/sheet.png", "label": "sheet"}]})
assert job.prompt == "p" and not hasattr(job, "images")
- # the in-run pairwise note this batch added went with the in-run best round (2026-09-22)
rec = RoundRecord.model_validate({"index": 1, "kind": "refine",
"pairwise": {"a": "r00", "b": "r01", "winner": "a", "confidence": 0.9}})
assert rec.index == 1 and not hasattr(rec, "pairwise")
diff --git a/harness/tests/core/test_contracts.py b/harness/tests/core/test_contracts.py
index 1aa3b88e..bc0ec359 100644
--- a/harness/tests/core/test_contracts.py
+++ b/harness/tests/core/test_contracts.py
@@ -7,8 +7,7 @@ import math
import pytest
from pydantic import ValidationError
-from codeverse3d.contracts.chat import ChatMessage
-from codeverse3d.contracts.common import Budget, Language, Track, Usage
+from codeverse3d.contracts.common import Budget, Language, Track
from codeverse3d.contracts.plan import (
ArticulatedPlan,
AssetPlan,
@@ -26,8 +25,6 @@ from codeverse3d.conventions import (
OBJECT_VIEWS,
OBJECT_VIEWS_QUICK,
slugify,
- to_pascal,
- to_snake,
)
@@ -35,12 +32,7 @@ def _box(cx=0.0, cy=0.0, cz=0.5, ex=1.0, ey=1.0, ez=1.0) -> BBox:
return BBox(center=(cx, cy, cz), extents=(ex, ey, ez))
-def test_names_normalise_consistently():
- assert to_snake("SeatCushion") == "seat_cushion"
- assert to_snake("seat cushion") == "seat_cushion"
- assert to_snake("LPCompressor") == "lp_compressor"
- assert to_pascal("seat_cushion") == "SeatCushion"
- assert to_pascal(to_snake("Leg_0")) == "Leg0"
+def test_a_prompt_slugifies_to_a_run_name():
assert slugify("A mid-century wooden dining chair!") == "a_mid_century_wooden_dining_chair"
@@ -52,8 +44,7 @@ def test_view_presets_unique():
assert "bottom" in names and "top" in names
assert min(v.elevation_deg for v in OBJECT_VIEWS) == -90.0
assert max(v.elevation_deg for v in OBJECT_VIEWS) == 90.0
- # the clay rig is its own 4-view tuple; its 'top' (el 88) deliberately shares the
- # rig's name at a different camera — nothing may union the two tuples by name
+ # the clay rig's 'top' (el 88) shares the rig's name at another camera: never union by name
assert len(OBJECT_CLAY_VIEWS) == 4
clay_top = next(v for v in OBJECT_CLAY_VIEWS if v.name == "top")
assert clay_top.elevation_deg == 88.0
@@ -62,13 +53,6 @@ def test_view_presets_unique():
def test_spec_rejects_language_outside_track():
with pytest.raises(ValidationError):
Spec(id="x", track=Track.SCENE, language=Language.BLENDER, prompt="p")
- s = Spec(id="x", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="p")
- assert s.budget == Budget()
-
-
-def test_usage_addition_sums_cost():
- u = Usage(model="m", input_tokens=10, cost_usd=0.1) + Usage(model="m", output_tokens=5, cost_usd=0.2)
- assert u.input_tokens == 10 and u.output_tokens == 5 and math.isclose(u.cost_usd, 0.3)
def test_static_plan_validates_attach_and_duplicates():
@@ -117,23 +101,6 @@ def test_camera_plan_name_must_be_filename_safe():
CameraPlan(name=bad, position=(0, 1.6, 5), look_at=(0, 0, 0))
-def test_chat_message_helpers():
- m = ChatMessage.user("hi")
- assert m.text == "hi" and m.role == "user"
-
-
-def test_workspace_git_roundtrip(tmp_ws):
- (tmp_ws.src / "a.py").write_text("x = 1\n")
- c0 = tmp_ws.commit("r0")
- (tmp_ws.src / "a.py").write_text("x = 2\n")
- changed = tmp_ws.changed_files()
- assert [c.path for c in changed] == ["src/a.py"]
- c1 = tmp_ws.commit("r1")
- assert c0 != c1
- tmp_ws.restore(c0)
- assert (tmp_ws.src / "a.py").read_text() == "x = 1\n"
-
-
def test_budget_is_strict_but_recorded_specs_migrate_the_retired_cost_key():
with pytest.raises(ValidationError):
Budget(max_usd=1.0)
diff --git a/harness/tests/core/test_doctor.py b/harness/tests/core/test_doctor.py
index 8ebd0b39..8d74e165 100644
--- a/harness/tests/core/test_doctor.py
+++ b/harness/tests/core/test_doctor.py
@@ -12,9 +12,7 @@ from codeverse3d.doctor import check_gpu_probe, check_node
@pytest.mark.node
def test_the_gpu_probe_releases_the_browser_instead_of_closing_it(tmp_path: Path, monkeypatch):
- """launchBrowser hands back the daemon's SHARED browser by default: ``browser.close()``
- sends CDP Browser.close and takes it down under every concurrent run, ``release()``
- disconnects. A stand-in gpu_launch.cjs records which one the probe called."""
+ """close() would kill the daemon's SHARED browser under every concurrent run; release() disconnects."""
mark = tmp_path / "mark"
(tmp_path / "gpu_launch.cjs").write_text(
f"const fs = require('fs'), mark = {json.dumps(str(mark))};\n"
@@ -27,8 +25,7 @@ def test_the_gpu_probe_releases_the_browser_instead_of_closing_it(tmp_path: Path
def test_a_torn_package_json_is_a_failed_row_not_a_crash(tmp_path: Path, monkeypatch):
- """Review 2 B9: ``json.loads`` on node_modules/*/package.json was unguarded, so one torn
- file (an interrupted ``npm install``) crashed the whole doctor report."""
+ """B9: one torn node_modules/*/package.json crashed the whole report."""
for pkg in ("three", "puppeteer"):
(tmp_path / "node_modules" / pkg).mkdir(parents=True)
(tmp_path / "node_modules" / pkg / "package.json").write_text('{"version": "0.18')
diff --git a/harness/tests/core/test_file_length.py b/harness/tests/core/test_file_length.py
index e184cbc1..db5e0e5f 100644
--- a/harness/tests/core/test_file_length.py
+++ b/harness/tests/core/test_file_length.py
@@ -1,12 +1,4 @@
-"""The 2 000-line cap (law 4, owner 2026-08-28; 3 000 is the absolute ceiling).
-
-A file may be long, but not a god file. There is no soft threshold and no
-~400-line guideline — the owner rejected both; this single automated cap is the
-whole rule, and it was raised from 1 500 to 2 000 on 2026-08-28 along with the
-other half of the rule, which no test can check: merging files is not a goal in
-itself, so a merge has to DELETE code rather than move it.
-Largest file when the cap was raised: codeverse3d/orchestrator.py at 1 132 lines.
-"""
+"""The 2 000-line cap per source file (law 4, owner 2026-08-28)."""
from __future__ import annotations
diff --git a/harness/tests/core/test_interfaces_names.py b/harness/tests/core/test_interfaces_names.py
index d0666cab..aff73ef7 100644
--- a/harness/tests/core/test_interfaces_names.py
+++ b/harness/tests/core/test_interfaces_names.py
@@ -1,22 +1,9 @@
"""docs/INTERFACES.md names only things that exist.
-INTERFACES is the binding list of cross-package signatures, so a name it cites that no
-longer resolves is a lie a reader will act on. What counts as a *name* — everything else
-is prose or a comment and is not checked, which keeps false positives out:
-
-1. in a ```python fence, every ``from codeverse3d.<module> import a, b, (c, …)`` (each name
- an attribute or submodule of the module) and every ``import codeverse3d.<module>``;
-2. in a fence, a line that STARTS with a signature ``X.y(`` / ``X.y:`` / ``X.y =`` whose
- ``X`` is a name rule 1 imported (``select.pick(…)``) or a codeverse3d subpackage
- (``tracks.common.generate_for(…)``);
-3. in prose, a backticked dotted path whose first segment is ``codeverse3d`` or one of its
- top-level modules (``codeverse3d.proc``, ``addons.select.summarise``,
- ``agents/cli_common._enforce_scope``; a trailing ``(…)`` is allowed) — except in the
- "Events and records" section, whose dotted names are events (``round.done``), not code.
-
-A name the file records as GONE sits in a comment (``# Gone: StopPolicy / …``) or is
-written without a resolvable prefix, so it is never checked. Pure python: importing the
-package's modules starts no Blender, node or browser.
+Checked: in ```python fences, ``from codeverse3d.<m> import …`` / ``import codeverse3d.<m>`` and a
+line starting ``X.y(`` whose ``X`` was imported or is a subpackage; in prose, a backticked dotted
+path starting at ``codeverse3d`` or a top-level module (not in "Events and records"). A GONE name
+sits in a comment and is never checked.
"""
from __future__ import annotations
@@ -94,26 +81,6 @@ def resolves(dotted: str) -> bool:
return True
-def test_the_parser_reads_every_citation_form():
- text = ("```python\nfrom codeverse3d.proc import tail, x as y\n"
- "from codeverse3d.cost.tally import (tally,\n timed)\n"
- "from codeverse3d.addons import select # which round\n"
- "import codeverse3d.spatial.tools # registers\n"
- "select.pick(run_dir) -> int\n"
- "tracks.common.generate_for(ctx) -> GenerationResult\n"
- " # Gone: StopPolicy / pick_best_round\n```\n"
- "prose `codeverse3d.proc.tail`, `addons/select.package(ws)`, `record.json`, never `stop`\n"
- "## Events and records\n`round.done`\n")
- assert cited_names(text) == [
- "codeverse3d.proc.tail", "codeverse3d.proc.x", "codeverse3d.cost.tally.tally",
- "codeverse3d.cost.tally.timed", "codeverse3d.addons.select", "codeverse3d.spatial.tools",
- "codeverse3d.addons.select.pick", "codeverse3d.tracks.common.generate_for",
- "codeverse3d.proc.tail", "codeverse3d.addons.select.package",
- ]
- assert resolves("codeverse3d.addons.select.package") and resolves("codeverse3d.spatial.tools")
- assert not resolves("codeverse3d.proc.x") and not resolves("codeverse3d.nope.x")
-
-
def test_every_name_interfaces_cites_resolves():
names = cited_names(INTERFACES.read_text(encoding="utf-8"))
assert len(names) > 150, "the parser stopped finding INTERFACES' names"
diff --git a/harness/tests/core/test_legacy_env_prefix.py b/harness/tests/core/test_legacy_env_prefix.py
index 3d79337b..167db667 100644
--- a/harness/tests/core/test_legacy_env_prefix.py
+++ b/harness/tests/core/test_legacy_env_prefix.py
@@ -14,12 +14,9 @@ def _run(env: dict[str, str]) -> subprocess.CompletedProcess[str]:
return subprocess.run([sys.executable, "-c", code], env={**clean, **env}, capture_output=True, text=True, check=True)
-def test_an_old_prefix_is_read_as_the_new_one_and_named_in_a_warning():
+def test_an_old_prefix_is_read_as_the_new_one_warned_and_loses_to_the_new_name():
p = _run({"CV3D_RUNS_DIR": "/tmp/old", "CV3D_RENDER__GPU": "off"})
assert p.stdout.split() == ["/tmp/old", "off"]
assert "CV3D_RENDER__GPU" in p.stderr and "CV3D_RUNS_DIR" in p.stderr
-
-
-def test_the_new_name_wins_when_both_are_set():
p = _run({"CV3D_RUNS_DIR": "/tmp/old", "C3D_RUNS_DIR": "/tmp/new"})
assert p.stdout.split()[0] == "/tmp/new" and p.stderr == ""
diff --git a/harness/tests/core/test_plan_normalise.py b/harness/tests/core/test_plan_normalise.py
index 453a260e..9a6296a8 100644
--- a/harness/tests/core/test_plan_normalise.py
+++ b/harness/tests/core/test_plan_normalise.py
@@ -49,30 +49,8 @@ def _joint(p: ArticulatedPlan, j: dict):
return next(x for x in p.joints if x.name == j["name"])
-def test_a_revolute_joint_over_two_pi_in_radians_becomes_continuous():
- for lower, upper in ((0.0, 4 * math.pi), (-4 * math.pi, 4 * math.pi), (0.0, 6.5), (0.0, 10.0)):
- d = _raw()
- j = _revolute(d, lower, upper)
- p = ArticulatedPlan.model_validate(d)
- fixed = _joint(p, j)
- assert fixed.type == "continuous" and fixed.lower == fixed.upper == 0.0
- assert any("> 2π → continuous" in n for n in p.normalisations)
- assert not any("degrees" in n for n in p.normalisations)
-
-
-def test_a_door_planned_in_degrees_stays_a_quarter_turn_hinge():
- d = _raw()
- j = _revolute(d, 0.0, 90.0)
- p = ArticulatedPlan.model_validate(d)
- fixed = _joint(p, j)
- assert fixed.type == "revolute"
- assert fixed.lower == 0.0 and fixed.upper == pytest.approx(1.5708, abs=1e-4) and fixed.rest == 0.0
- assert any("looked like degrees (0..90) → radians" in n for n in p.normalisations)
- assert not any("continuous" in n for n in p.normalisations)
-
-
def test_degree_shaped_limits_and_rest_are_converted_together():
- cases = ((-180.0, 0.0, 0.0), (0.0, 90.0, 90.0), (-45.0, 45.0, 0.0), (0.0, 30.0, 0.0))
+ cases = ((-180.0, 0.0, 0.0), (0.0, 90.0, 90.0))
for lower, upper, rest in cases:
d = _raw()
j = _revolute(d, lower, upper, rest)
@@ -83,6 +61,7 @@ def test_degree_shaped_limits_and_rest_are_converted_together():
assert fixed.upper == pytest.approx(math.radians(upper))
assert fixed.rest == pytest.approx(math.radians(rest))
assert sum("looked like degrees" in n for n in p.normalisations) == 1
+ assert not any("continuous" in n for n in p.normalisations)
def test_a_two_turn_degree_range_falls_through_to_continuous():
@@ -109,14 +88,6 @@ def test_a_sub_part_outside_its_parent_grows_the_parent_bbox():
assert any("bbox grown on y" in n for n in p.normalisations)
-def test_unfixable_plans_still_fail():
- d = _raw()
- d["joints"].append({"name": "Ghost", "type": "fixed", "parent": d["parts"][0]["name"], "child": "NoSuchLink",
- "axis": [0, 0, 1], "pivot": [0, 0, 0]})
- with pytest.raises(ValidationError, match="unknown link"):
- ArticulatedPlan.model_validate(d)
-
-
def test_planner_text_in_normalisations_is_dropped():
"""Planner prose cannot masquerade as harness repair history."""
from codeverse3d.contracts.plan import ArticulatedPlan
@@ -128,7 +99,6 @@ def test_planner_text_in_normalisations_is_dropped():
def test_a_joint_naming_a_part_by_a_unique_fragment_is_resolved():
- """A unique fragment is a safe repair for a mismatched joint reference."""
d = _raw()
d["parts"][1]["name"] = "ChestDrawer" # the plan's own name ...
d["joints"][0]["child"] = "Drawer" # ... referenced by one word of it
@@ -139,7 +109,6 @@ def test_a_joint_naming_a_part_by_a_unique_fragment_is_resolved():
def test_an_ambiguous_joint_reference_is_rejected_and_names_the_real_parts():
- """An ambiguous fragment is rejected and names the available parts."""
d = _raw()
d["parts"][1]["name"] = "ChestDrawer"
twin = dict(d["parts"][1])
@@ -155,8 +124,6 @@ def test_an_ambiguous_joint_reference_is_rejected_and_names_the_real_parts():
def test_a_root_link_that_names_no_part_becomes_the_one_link_no_joint_moves():
- """ab_repairs grand_piano, 2026-08-29: flash wrote a UUID as root_link three times and
- the pinned plan died with 'root_link … is not a part'."""
d = _raw()
d["root_link"] = "040fbba3-b0f3-42e1-85b3-f61b0c034293"
plan = ArticulatedPlan.model_validate(d)
@@ -216,9 +183,7 @@ def _rename_part(d: dict, old: str, new: str) -> None:
def test_a_root_link_naming_no_part_is_resolved_by_the_1b_word_rule():
- """af_excavator (2026-08-31, 3.7-flash): root_link 'chassis' over a part list that
- spelt it differently killed the run after two re-asks. Same word-boundary match as
- the joint-fragment repair — never a bare substring."""
+ """Word-boundary match, as the joint-fragment repair — never a bare substring."""
d = _raw()
real_root = d["root_link"]
_rename_part(d, real_root, "TrackedChassis")
@@ -228,20 +193,7 @@ def test_a_root_link_naming_no_part_is_resolved_by_the_1b_word_rule():
assert any("root_link 'Chassis'" in n and "TrackedChassis" in n for n in p.normalisations)
-def test_an_ambiguous_root_link_still_fails_validation():
- d = _raw()
- real_root = d["root_link"]
- _rename_part(d, real_root, "TrackedChassis")
- other = next(x["name"] for x in d["parts"] if x["name"] != "TrackedChassis")
- _rename_part(d, other, "ChassisMount")
- d["root_link"] = "Chassis"
- with pytest.raises(ValidationError, match="root_link"):
- ArticulatedPlan.model_validate(d)
-
-
def test_a_joint_naming_a_sub_part_by_word_subset_promotes_it():
- """af_grandfather_clock: joint said GlazedDoor, the child was GlazedFrontDoor — no
- affix match, so 1b could not save it. 1c matches by word subset and promotes."""
d = _raw()
parent = d["parts"][0]
parent.setdefault("children", []).append(
@@ -260,8 +212,6 @@ def test_a_joint_naming_a_sub_part_by_word_subset_promotes_it():
def test_the_unknown_link_complaint_lists_the_sub_parts():
- """The re-ask used to see only top-level parts — with everything nested, it was blind
- to the very children the joints meant, and both re-asks died the same way."""
d = _raw()
parent = d["parts"][0]
parent.setdefault("children", []).append(
diff --git a/harness/tests/core/test_portability.py b/harness/tests/core/test_portability.py
index 170fdb70..d782693a 100644
--- a/harness/tests/core/test_portability.py
+++ b/harness/tests/core/test_portability.py
@@ -1,9 +1,4 @@
-"""Packaging and supported-runtime guards (docs/INSTALL.md §2.1).
-
-The harness targets Python 3.13 and Node 20.6+. These tests pin the setup
-script, packaged runtime data and Node's early version gate without requiring
-alternate runtimes to be installed.
-"""
+"""Packaging and supported-runtime guards (docs/INSTALL.md §2.1): python 3.13, node 20.6+."""
from __future__ import annotations
@@ -65,24 +60,11 @@ def test_write_example_refuses_to_write_nothing(tmp_path, monkeypatch) -> None:
# ------------------------------------------------------------------- the node floor gate
def test_node_version_parsing_and_gate() -> None:
- parsed = [
- ("v24.14.0\n", (24, 14, 0)),
- ("v20.6.0", (20, 6, 0)),
- ("v18.20.4", (18, 20, 4)),
- ("20.6.1", (20, 6, 1)),
- ("v22.0.0-nightly20240101", (22, 0, 0)),
- ("not found", None),
- ("", None),
- ]
- for text, expected in parsed:
+ for text, expected in (("v24.14.0\n", (24, 14, 0)), ("v22.0.0-nightly20240101", (22, 0, 0)), ("not found", None)):
assert parse_node_version(text) == expected, text
- for version in ((20, 6, 0), (20, 6, 1), (22, 15, 0), (24, 14, 0), None):
- assert node_version_error(version) == "", version
- for version in ((20, 5, 9), (18, 20, 4), (16, 0, 0)):
- msg = node_version_error(version)
- assert ".".join(map(str, version)) in msg
- assert NODE_MIN_STR in msg
- assert "C3D_BINARIES__NODE" in msg and "nvm" in msg
+ assert node_version_error((20, 6, 0)) == node_version_error(None) == ""
+ msg = node_version_error((20, 5, 9))
+ assert "20.5.9" in msg and NODE_MIN_STR in msg and "C3D_BINARIES__NODE" in msg and "nvm" in msg
def test_run_node_enforces_the_version_floor(tmp_path, monkeypatch) -> None:
diff --git a/harness/tests/core/test_proc.py b/harness/tests/core/test_proc.py
index 2eac3e42..ab7d95dd 100644
--- a/harness/tests/core/test_proc.py
+++ b/harness/tests/core/test_proc.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import json
import os
-import resource
import signal
import sys
import threading
@@ -16,53 +15,25 @@ import pytest
from codeverse3d.proc import (
STREAM_BUDGET_BYTES,
ManagedProcess,
- ProcResult,
append_jsonl_line,
iter_jsonl_lines,
- read_json_or_none,
read_jsonl_lenient,
run_subprocess,
scrub_secrets,
- tail,
- write_json_atomic,
)
from tests.conftest import assert_pid_gone
-def test_run_subprocess_captures_output(tmp_path: Path):
- r = run_subprocess(["bash", "-c", "echo out; echo err >&2; exit 3"], cwd=tmp_path, timeout_s=10)
- assert isinstance(r, ProcResult)
- assert r.returncode == 3
- assert r.stdout.strip() == "out"
- assert r.stderr.strip() == "err"
- assert not r.timed_out
- assert r.duration_ms >= 0
-
-
-def test_run_subprocess_stdin(tmp_path: Path):
- r = run_subprocess(["cat"], cwd=tmp_path, timeout_s=10, stdin_text="hello")
- assert r.stdout == "hello"
-
-
def test_timeout_kills_the_whole_process_group(tmp_path: Path):
- """A timed-out child AND its grandchildren die (killpg on the new session)."""
- r = run_subprocess(["bash", "-c", "sleep 30 & echo $!; wait"], cwd=tmp_path, timeout_s=0.4)
- assert r.timed_out
- assert r.returncode != 0
- assert_pid_gone(int(r.stdout.strip().splitlines()[0]), timeout_s=5.0)
-
-
-def test_a_leader_that_exits_0_still_takes_its_grandchildren_down(tmp_path: Path):
- """A cleanly exited leader must not leave same-group grandchildren alive."""
- pid_file = tmp_path / "pid"
- r = run_subprocess(["bash", "-c", f"sleep 300 >/dev/null 2>&1 & echo $! > {pid_file}; exit 0"],
- cwd=tmp_path, timeout_s=10)
- assert r.returncode == 0 and not r.timed_out
- assert_pid_gone(int(pid_file.read_text()), timeout_s=5.0)
+ """A timed-out child AND its grandchildren die (killpg), and their output is still collected."""
+ r = run_subprocess(["bash", "-c", "echo hello; sleep 30 & echo $!; wait"], cwd=tmp_path, timeout_s=0.4)
+ assert r.timed_out and r.returncode != 0
+ assert r.stdout.splitlines()[0] == "hello"
+ assert_pid_gone(int(r.stdout.strip().splitlines()[1]), timeout_s=5.0)
def test_a_leader_that_exits_0_does_not_burn_the_drain_window(tmp_path: Path, monkeypatch):
- """Inherited pipes do not force a clean exit through the drain timeout."""
+ """A clean exit takes same-group grandchildren down without burning the drain window."""
import codeverse3d.proc as proc_mod
monkeypatch.setattr(proc_mod, "DRAIN_TIMEOUT_S", 3.0)
@@ -80,9 +51,7 @@ def test_a_detached_descendant_holding_the_pipes_cannot_extend_the_timeout(tmp_p
"""A detached descendant holding stdout cannot extend the caller's timeout."""
import codeverse3d.proc as proc_mod
- # raising=False so this test still RUNS (and fails on the hang) against the
- # pre-fix module, which has no such constant
- monkeypatch.setattr(proc_mod, "DRAIN_TIMEOUT_S", 1.0, raising=False)
+ monkeypatch.setattr(proc_mod, "DRAIN_TIMEOUT_S", 1.0)
t0 = time.monotonic()
r = run_subprocess(["bash", "-c", "setsid sleep 20 & echo started; sleep 20"],
@@ -94,42 +63,7 @@ def test_a_detached_descendant_holding_the_pipes_cannot_extend_the_timeout(tmp_p
assert elapsed < 8.0, f"run_subprocess returned only after {elapsed:.1f}s"
-def test_a_same_group_grandchild_still_has_its_output_collected(tmp_path: Path):
- """The timeout path still preserves output from a same-group grandchild."""
- r = run_subprocess(["bash", "-c", "echo hello; sleep 30 & wait"], cwd=tmp_path, timeout_s=0.4)
- assert r.timed_out and "hello" in r.stdout
-
-
-def test_preexec_fn_runs_in_the_child(tmp_path: Path):
- soft = 256
-
- def limit() -> None:
- resource.setrlimit(resource.RLIMIT_NOFILE, (soft, soft))
-
- r = run_subprocess(
- ["python3", "-c", "import resource, sys; sys.stdout.write(str(resource.getrlimit(resource.RLIMIT_NOFILE)[0]))"],
- cwd=tmp_path, timeout_s=20, preexec_fn=limit,
- )
- assert r.stdout.strip() == str(soft)
-
-
-def test_tail_caps_lines_and_chars():
- text = "\n".join(f"line{i}" for i in range(100))
- t = tail(text, max_lines=5)
- assert t.splitlines() == [f"line{i}" for i in range(95, 100)]
- assert len(tail("x" * 10000, max_chars=100)) == 100
-
-
# --------------------------------------------------------------------------- atomic writes
-def test_write_json_atomic_round_trips_into_a_new_dir(tmp_path: Path):
- """Parents are created, non-JSON values go through ``default=str``, and the published
- directory holds the file and nothing else (no ``.tmp`` litter)."""
- p = tmp_path / "deep" / "out.json"
- write_json_atomic(p, {"a": 1, "p": Path("b")})
- assert json.loads(p.read_text()) == {"a": 1, "p": "b"}
- assert [q.name for q in p.parent.iterdir()] == ["out.json"]
-
-
_WRITER = """
import json, sys
from pathlib import Path
@@ -165,33 +99,6 @@ def test_write_json_atomic_survives_concurrent_writers(tmp_path: Path):
assert not list(tmp_path.glob("*.tmp")), "no temp file left behind"
-def test_unique_tmp_is_per_process_and_per_thread(tmp_path: Path):
- """Simultaneously live threads choose distinct process/thread temp names."""
- from codeverse3d.proc import unique_tmp
-
- out = tmp_path / "cache" / "checker.mjs"
- seen: list[Path] = []
- lock = threading.Lock()
- gate = threading.Barrier(8, timeout=30)
-
- def name_it() -> None:
- gate.wait() # every thread is alive and running past this point
- got = unique_tmp(out)
- with lock:
- seen.append(got)
-
- threads = [threading.Thread(target=name_it) for _ in range(8)]
- for t in threads:
- t.start()
- for t in threads:
- t.join(timeout=30)
-
- assert len(seen) == 8
- assert len({str(p) for p in seen}) == 8, "two live threads chose the same temp name"
- assert all(p.parent == out.parent and p.name.startswith("checker.mjs.") for p in seen)
- assert str(os.getpid()) in seen[0].name
-
-
def test_concurrent_writers_of_one_destination_all_succeed(tmp_path: Path):
"""Barrier-synchronized writers can safely replace one destination."""
from codeverse3d.proc import write_text_atomic
@@ -220,17 +127,6 @@ def test_concurrent_writers_of_one_destination_all_succeed(tmp_path: Path):
# --------------------------------------------------------------------------- tolerant reads
-def test_read_json_or_none_is_none_unless_a_dict_parses(tmp_path: Path):
- assert read_json_or_none(tmp_path / "missing.json") is None
- (tmp_path / "bad.json").write_text("{not json")
- assert read_json_or_none(tmp_path / "bad.json") is None
- (tmp_path / "list.json").write_text("[1, 2]")
- assert read_json_or_none(tmp_path / "list.json") is None
- (tmp_path / "ok.json").write_bytes(b'{"a": "caf\xc3\xa9", "b": "\xff"}')
- assert read_json_or_none(tmp_path / "ok.json") is None # undecodable byte -> ValueError
- assert read_json_or_none(tmp_path / "ok.json", errors="replace") == {"a": "café", "b": "�"}
-
-
def test_jsonl_helpers_round_trip_and_skip_bad_lines(tmp_path: Path):
p = tmp_path / "log.jsonl"
assert list(iter_jsonl_lines(p)) == [] and read_jsonl_lenient(p) == []
@@ -246,21 +142,17 @@ def test_jsonl_helpers_round_trip_and_skip_bad_lines(tmp_path: Path):
# --------------------------------------------------------------------------- scrub_secrets
-def test_scrub_secrets_drops_credential_shaped_vars():
- env = {
+def test_scrub_secrets_drops_credentials_and_keeps_what_generated_code_needs():
+ secrets = {
"GEMINI_API_KEYS": "k1,k2", "GEMINI_API_KEY": "k", "FOO_API_KEY": "x",
"MY_SERVICE_TOKEN": "t", "DB_PASSWORD": "p", "DEPLOY_PRIVATE_KEY": "s",
"AWS_SECRET_ACCESS_KEY": "a", "CLIENT_SECRET": "c", "X_AUTH_TOKEN": "z",
}
- assert scrub_secrets(env) == {}
-
-
-def test_scrub_secrets_keeps_everything_generated_code_needs():
env = {"PATH": "/usr/bin", "HOME": "/home/u", "DISPLAY": ":0", "NODE_PATH": "/nm",
"MESA_LOADER_DRIVER_OVERRIDE": "d3d12", "GALLIUM_DRIVER": "llvmpipe",
"C3D_RENDER_GPU": "off", "PYTHONUNBUFFERED": "1",
"TOKENIZERS_PARALLELISM": "false"} # _TOKEN is a SUFFIX match, not a substring
- assert scrub_secrets(dict(env)) == env
+ assert scrub_secrets({**env, **secrets}) == env
# --------------------------------------------------------------------------- ManagedProcess lifecycle
diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.py
index d69e8f68..a5696529 100644
--- a/harness/tests/core/test_run_layout.py
+++ b/harness/tests/core/test_run_layout.py
@@ -12,18 +12,12 @@ from codeverse3d.contracts.spec import Spec
from codeverse3d.workspace import EVIDENCE_DIR, LAYOUT_ALIASES, Workspace
-def test_create_makes_the_three_buckets(tmp_path: Path):
+def test_create_makes_the_buckets_aliases_and_gitignore(tmp_path: Path):
ws = Workspace(tmp_path / "run").create()
assert ws.deliverable.is_dir() and ws.telemetry.is_dir() and ws.artifacts.is_dir()
- # evidence/ is the alias, artifacts/ the physical home (see docs/RUN_LAYOUT.md)
- evidence = ws.root / EVIDENCE_DIR
- assert evidence.is_symlink() and os.readlink(evidence) == "artifacts"
- assert evidence.resolve() == ws.artifacts.resolve()
- assert ws.cost_path.parent == ws.telemetry
-
-
-def test_telemetry_aliases_point_at_the_root_files(tmp_path: Path):
- ws = Workspace(tmp_path / "run").create()
+ assert os.readlink(ws.root / EVIDENCE_DIR) == "artifacts" # evidence/ is the alias
+ ignored = (ws.root / ".gitignore").read_text().splitlines()
+ assert {"artifacts/", "deliverable/", "telemetry/", "evidence", "trajectories/"} <= set(ignored)
for name, target in LAYOUT_ALIASES:
link = ws.root / name
assert link.is_symlink(), name
@@ -56,22 +50,8 @@ def test_ensure_layout_never_clobbers_real_data(tmp_path: Path):
assert not (ws.root / "evidence").is_symlink()
-def test_gitignore_covers_the_derived_buckets(tmp_path: Path):
- ws = Workspace(tmp_path / "run").create()
- text = (ws.root / ".gitignore").read_text()
- for line in ("artifacts/", "deliverable/", "telemetry/", "evidence", "trajectories/"):
- assert line in text.splitlines()
- assert ws.ensure_gitignore() is False # idempotent
- (ws.root / ".gitignore").write_text("src/nothing\n")
- assert ws.ensure_gitignore(dry_run=True) is True
- assert (ws.root / ".gitignore").read_text() == "src/nothing\n"
- assert ws.ensure_gitignore() is True
- assert "deliverable/" in (ws.root / ".gitignore").read_text()
-
-
def test_record_blocks_are_additive(tmp_path: Path):
- """An old record.json (no telemetry; or a deliverable block, which records stopped
- carrying on 2026-09-22) must still validate, and an old manifest still loads."""
+ """An old record.json (no telemetry, a deliverable block) validates; an old manifest loads."""
spec = Spec(id="x", track="static_object", language="blender", prompt="a chair")
old = {"spec": spec.model_dump(mode="json"), "workspace": str(tmp_path), "status": "passed",
"deliverable": {"best_round": 1, "commit": "abc"}}
@@ -122,32 +102,8 @@ def _captured(render) -> str:
return cap.get()
-def test_a_relocated_run_still_resolves_its_stored_paths(tmp_path):
- """Stored absolute paths rebase after moving or archiving a run."""
- from codeverse3d.workspace import Workspace
-
- _a, b, sheet_a, _rec = _moved_run(tmp_path)
- stored = str(sheet_a) # what the writer puts in record.json
- ws = Workspace(b)
- got = ws.rebase(stored)
- assert got.exists(), f"a moved run must still find its own sheet, got {got}"
- assert got == b / "artifacts" / "renders" / "r01" / "sheet.png"
- assert Path(stored) != got
-
- # an absolute path that IS still valid is left alone
- assert ws.rebase(str(got)) == got
- # a relative path joins the root (the only case the old code handled)
- assert ws.rebase("artifacts/renders/r01/sheet.png") == got
- # nothing matches -> the original comes back, so the caller reports a real missing
- # file instead of a silently wrong one
- missing = tmp_path / "elsewhere" / "nope.png"
- assert ws.rebase(str(missing)) == missing
-
-
def test_a_copied_run_reads_its_own_files_while_the_original_still_exists(tmp_path):
- """rebase returned any stored absolute path that still EXISTED as-is, so a
- copied/rsynced run silently read — and a retexture wrote past — the ORIGINAL's
- files for as long as that directory lived (V10f). This root's copy must win."""
+ """V10f: a copied run's stored absolute paths rebase onto THIS root, even while the original lives."""
import shutil
from codeverse3d.workspace import Workspace
@@ -167,19 +123,6 @@ def test_a_copied_run_reads_its_own_files_while_the_original_still_exists(tmp_pa
assert Workspace(a).rebase(str(sheet_a)) == sheet_a
-def test_show_prints_the_sheet_that_exists_after_a_move(tmp_path):
- """The user-visible half: `3dcode show` must not print a path that is not there."""
- from codeverse3d.cli._common import print_record_summary
- from codeverse3d.workspace import Workspace
-
- _a, b, _sheet, rec = _moved_run(tmp_path)
- printed = _captured(lambda: print_record_summary(rec, Workspace(b).root))
- line = next(ln for ln in printed.splitlines() if "sheet:" in ln)
- shown = line.split("sheet:", 1)[1].strip().rstrip("│ ").strip()
- assert shown.endswith("sheet.png"), f"the panel wrapped the path: {line!r}"
- assert Path(shown).exists(), f"show printed a sheet that is not there: {shown!r}"
-
-
def test_a_stale_index_lock_names_the_remedy(tmp_path):
"""A stale git index lock is surfaced with its exact safe remedy."""
import subprocess
diff --git a/harness/tests/core/test_runlock.py b/harness/tests/core/test_runlock.py
index 0339e0dd..748e32f5 100644
--- a/harness/tests/core/test_runlock.py
+++ b/harness/tests/core/test_runlock.py
@@ -37,8 +37,9 @@ def _child_script(run_root: Path, ready: Path, go: Path) -> str:
)
-def test_two_processes_cannot_hold_one_run(tmp_path: Path):
- """Two processes cannot concurrently mutate the same workspace."""
+def test_a_second_process_is_refused_and_a_killed_holder_never_wedges_the_run(tmp_path: Path):
+ """Two processes cannot mutate one workspace; the kernel drops the flock when the holder dies."""
+ import signal
import subprocess
import sys
@@ -58,31 +59,10 @@ def test_two_processes_cannot_hold_one_run(tmp_path: Path):
assert str(child.pid) in msg # names the holder, so a human can kill THAT pid
assert "pkill" in msg, "and must warn against the pattern kill that took out 13 runs"
finally:
- go.write_text("release")
+ child.send_signal(signal.SIGKILL)
child.wait(timeout=10)
- with exclusive(run_root): # free once the holder exits
- pass
-
-
-def test_a_dead_holder_never_wedges_a_run(tmp_path: Path):
- """The kernel drops a flock when the holder dies — a killed run stays resumable."""
- import signal
- import subprocess
- import sys
-
- run_root = tmp_path / "runs" / "slug"
- run_root.mkdir(parents=True)
- ready, go = tmp_path / "ready", tmp_path / "go"
- child = subprocess.Popen([sys.executable, "-c", _child_script(run_root, ready, go)])
- for _ in range(500):
- if ready.exists():
- break
- time.sleep(0.02)
- assert ready.read_text() == "held"
- child.send_signal(signal.SIGKILL)
- child.wait(timeout=10)
assert holder_of(run_root) is None, "a SIGKILLed holder cannot leave a record behind"
- with exclusive(run_root): # no stale-PID reasoning needed: the kernel already released it
+ with exclusive(run_root):
pass
@@ -116,21 +96,6 @@ def test_a_second_thread_is_refused_and_the_first_keeps_the_lock(tmp_path: Path)
pass
-def test_a_failed_record_write_leaks_nothing(tmp_path: Path, monkeypatch):
- """A failed holder-record write leaks neither fd nor in-process registry."""
- import codeverse3d.proc as R
-
- run_root = tmp_path / "runs" / "slug"
- run_root.mkdir(parents=True)
- monkeypatch.setattr(R, "_write_record", lambda fd, rec: (_ for _ in ()).throw(OSError("ENOSPC")))
- with pytest.raises(OSError, match="ENOSPC"), R.exclusive(run_root):
- pass
- monkeypatch.undo()
- assert not R._HELD, "nothing may stay registered after a failed acquisition"
- with R.exclusive(run_root): # still enterable, in this process and any other
- pass
-
-
def test_holder_of_names_the_holder_and_is_empty_otherwise(tmp_path: Path):
"""`3dcode status` prints this so a human can kill THAT pid, never `pkill -f 3dcode`."""
run_root = tmp_path / "runs" / "slug"
diff --git a/harness/tests/gallery/test_cli.py b/harness/tests/gallery/test_cli.py
index ee86fd0a..90d7fbf0 100644
--- a/harness/tests/gallery/test_cli.py
+++ b/harness/tests/gallery/test_cli.py
@@ -13,17 +13,6 @@ from codeverse3d.cli.main import app, resolve_roots
runner = CliRunner()
-def test_gallery_group_is_registered():
- r = runner.invoke(app, ["--help"])
- assert r.exit_code == 0 and "gallery" in r.output
- r = runner.invoke(app, ["gallery", "--help"])
- assert r.exit_code == 0 and "serve" in r.output and "build" in r.output
- r = runner.invoke(app, ["gallery", "serve", "--help"])
- assert r.exit_code == 0
- for flag in ("--port", "--host", "--reload", "--open"):
- assert flag in r.output, flag
-
-
def test_build_writes_a_page(gallery_tree: dict[str, Path], tmp_path: Path):
out = tmp_path / "g.html"
r = runner.invoke(app, ["gallery", "build", str(gallery_tree["runs"]), str(gallery_tree["battery"]),
@@ -56,8 +45,7 @@ def test_default_roots_from_cwd(gallery_tree: dict[str, Path], monkeypatch: pyte
def test_default_roots_find_the_eval_batteries_from_any_cwd(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
- """D77 moved the batteries to <repo>/eval/bench/out/<b>/runs; the defaults only looked
- under the cwd, so `3dcode gallery serve` from harness/ listed none of them."""
+ """D77: the batteries live in <repo>/eval/bench/out/<b>/runs, found from any cwd."""
repo = tmp_path / "repo"
battery = repo / "eval" / "bench" / "out" / "b1" / "runs"
battery.mkdir(parents=True)
diff --git a/harness/tests/gallery/test_hardening.py b/harness/tests/gallery/test_hardening.py
index d496e3c3..590f5cdc 100644
--- a/harness/tests/gallery/test_hardening.py
+++ b/harness/tests/gallery/test_hardening.py
@@ -9,19 +9,11 @@ from pathlib import Path
from codeverse3d.addons.gallery.compare import CSV_COLUMNS, csv_safe, export_csv
from codeverse3d.addons.gallery.index import build_index
-from codeverse3d.addons.gallery.server import SANDBOXED_TYPES, GalleryApp
-from codeverse3d.addons.gallery.urls import content_type
+from codeverse3d.addons.gallery.server import GalleryApp
from tests.flywheel_cli.conftest import make_fake_run
# --------------------------------------------------------------------------- content types + CSP
-def test_html_is_typed_html_not_guessed():
- assert content_type("a.html") == "text/html; charset=utf-8"
- assert content_type("a.htm") == "text/html; charset=utf-8"
- assert content_type("a.svg") == "image/svg+xml"
- assert {"text/html", "image/svg+xml"} == SANDBOXED_TYPES
-
-
def test_llm_html_and_svg_file_responses_are_sandboxed(gallery_tree: dict[str, Path]):
app = GalleryApp([gallery_tree["runs"]])
run = gallery_tree["runs"] / "wooden_chair_ab12cd34"
diff --git a/harness/tests/gallery/test_index.py b/harness/tests/gallery/test_index.py
index 202a5a10..67e61a77 100644
--- a/harness/tests/gallery/test_index.py
+++ b/harness/tests/gallery/test_index.py
@@ -5,9 +5,8 @@ from __future__ import annotations
import json
from pathlib import Path
-from codeverse3d.addons.gallery.index import build_index, default_roots, entry_for_dir
+from codeverse3d.addons.gallery.index import build_index, entry_for_dir
from codeverse3d.addons.gallery.model import match, sort_entries, summarize
-from codeverse3d.record.record import battery_label
def test_build_index_sections_and_states(gallery_tree: dict[str, Path]):
@@ -42,8 +41,7 @@ def test_entry_fields_and_links(gallery_tree: dict[str, Path]):
def test_a_card_links_the_picked_rounds_own_glb(tmp_path: Path):
- """The tree ends at the LAST round (2026-09-22), so artifacts/object.glb is not the card's
- round: until a round is handed over, the card links the picked round's artifacts/rNN/ copy."""
+ """artifacts/object.glb is the LAST round's: until a hand-over the card links the picked round's copy."""
from codeverse3d.addons import select
from tests.flywheel_cli.conftest import make_fake_run
@@ -55,23 +53,6 @@ def test_a_card_links_the_picked_rounds_own_glb(tmp_path: Path):
assert links["glb"] == "deliverable/object.glb"
-def test_corrupt_record_does_not_raise(tmp_path: Path):
- run = tmp_path / "runs" / "boom"
- run.mkdir(parents=True)
- (run / "record.json").write_bytes(b"\x00\x01not json")
- index = build_index([tmp_path / "runs"])
- (entry,) = index.entries()
- assert entry.state == "broken" and entry.error
-
-
-def test_valid_json_but_not_a_record(tmp_path: Path):
- run = tmp_path / "runs" / "wrong_shape"
- run.mkdir(parents=True)
- (run / "record.json").write_text(json.dumps({"hello": "world"}))
- (entry,) = build_index([tmp_path / "runs"]).entries()
- assert entry.state == "broken" and "invalid record.json" in entry.error
-
-
def test_filter_and_sort_and_summary(gallery_tree: dict[str, Path]):
index = build_index([gallery_tree["runs"], gallery_tree["battery"]])
entries = index.entries()
@@ -92,25 +73,9 @@ def test_filter_and_sort_and_summary(gallery_tree: dict[str, Path]):
assert facets["battery"] == ["runs", "static_v9"]
-def test_default_roots_and_labels(gallery_tree: dict[str, Path]):
- base = gallery_tree["root"]
- roots = default_roots(base)
- assert [battery_label(r) for r in roots] == ["runs", "static_v9"]
- assert default_roots(base / "nope") == []
-
-
-def test_duplicate_labels_are_disambiguated(tmp_path: Path):
- a, b = tmp_path / "a" / "runs", tmp_path / "b" / "runs"
- a.mkdir(parents=True)
- b.mkdir(parents=True)
- index = build_index([a, b])
- assert [s.label for s in index.sections] == ["runs", "runs#2"]
-
-
# --------------------------------------------------------------------------- run identity
def test_nested_battery_runs_get_distinct_findable_slugs(tmp_path: Path):
- """Two compare-style runs whose dirs are BOTH named ``run`` used to collapse into
- one gallery key; each now carries its RunId slug and both are findable."""
+ """Two compare-style runs whose dirs are both named ``run`` keep distinct, findable slugs."""
from tests.flywheel_cli.conftest import make_fake_run
root = tmp_path / "compare_v9"
@@ -127,9 +92,7 @@ def test_nested_battery_runs_get_distinct_findable_slugs(tmp_path: Path):
def test_nested_eval_workspaces_are_not_counted_as_runs(tmp_path: Path):
- """A battery cell's ``eval/`` judge workspace has a spec.json but no record.json —
- it is not a run (52 phantom entries per battery under the old spec-or-record rule).
- A spec-only DIRECT child of the root is still a legitimate pending card."""
+ """A cell's ``eval/`` judge workspace (spec.json, no record.json) is not a run."""
from tests.flywheel_cli.conftest import make_fake_run
root = tmp_path / "compare_v9"
@@ -142,8 +105,7 @@ def test_nested_eval_workspaces_are_not_counted_as_runs(tmp_path: Path):
def test_duplicate_slugs_within_a_root_are_disambiguated(tmp_path: Path):
- """Two rels that reduce to the same slug follow the label#2 precedent — a viewer
- must still see both runs (exporters fail loudly instead; the gallery is read-only)."""
+ """Two rels that reduce to one slug follow the label#2 precedent — the viewer shows both."""
from tests.flywheel_cli.conftest import make_fake_run
root = tmp_path / "mixed"
diff --git a/harness/tests/gallery/test_page.py b/harness/tests/gallery/test_page.py
index b2b4f7f6..ef33c40b 100644
--- a/harness/tests/gallery/test_page.py
+++ b/harness/tests/gallery/test_page.py
@@ -9,7 +9,7 @@ from pathlib import Path
from codeverse3d.addons.gallery.index import build_index
from codeverse3d.addons.gallery.page import build_static, render_index, render_static
-from codeverse3d.addons.gallery.urls import StaticUrls, UrlMaker
+from codeverse3d.addons.gallery.urls import UrlMaker
VOID = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",
"source", "track", "wbr"}
@@ -82,24 +82,6 @@ def test_static_build_parses_and_is_self_contained(gallery_tree: dict[str, Path]
assert "broken:" in markup and "pending:" in markup # the two non-ok cards say why
-def test_static_build_without_embed_is_small_and_links_files(gallery_tree: dict[str, Path], tmp_path: Path):
- out = tmp_path / "linked.html"
- build_static([gallery_tree["runs"]], out, embed=False)
- markup = out.read_text()
- _assert_offline(markup)
- assert "data:image/jpeg" not in markup
- assert "file://" in markup
-
-
-def test_build_static_is_atomic(gallery_tree: dict[str, Path], tmp_path: Path):
- out = tmp_path / "g.html"
- build_static([gallery_tree["runs"]], out)
- first = out.read_text()
- build_static([gallery_tree["runs"], gallery_tree["battery"]], out)
- assert out.read_text() != first
- assert not list(tmp_path.glob("*.tmp")) # no temp file left behind
-
-
def test_server_page_applies_the_filter_server_side(gallery_tree: dict[str, Path]):
index = build_index([gallery_tree["runs"], gallery_tree["battery"]])
markup = render_index(index, UrlMaker(), flt={"lang": "threejs"}, sort="score")
@@ -112,15 +94,6 @@ def test_server_page_applies_the_filter_server_side(gallery_tree: dict[str, Path
assert "<option value='threejs' selected>" in markup
-def test_sections_counts_and_table_mode(gallery_tree: dict[str, Path]):
- index = build_index([gallery_tree["runs"], gallery_tree["battery"]])
- markup = render_index(index, UrlMaker(), view="table")
- assert "<body class='view-table'>" in markup
- assert "id='b-runs'" in markup and "id='b-static_v9'" in markup
- assert ">2 runs<" in markup and ">4 runs<" in markup
- assert len(re.findall(r"<tr class='[^']*' data-run=", markup)) == 6
-
-
def test_detail_links_are_offered_only_when_the_target_has_them(gallery_tree: dict[str, Path]):
index = build_index([gallery_tree["runs"]])
markup = render_index(index, UrlMaker())
@@ -142,11 +115,3 @@ def test_html_escaping_of_a_hostile_prompt(tmp_path: Path):
assert "<script>alert(1)</script>" not in markup
assert "&lt;script&gt;alert(1)&lt;/script&gt;" in markup
_assert_offline(markup)
-
-
-def test_static_urls_of_an_entry(gallery_tree: dict[str, Path]):
- entry = build_index([gallery_tree["runs"]]).entries()[0]
- urls = StaticUrls(embed=False)
- assert urls.file(entry, "record.json").startswith("file://")
- assert urls.file(entry, "record.json").endswith("/record.json")
- assert not urls.has_detail
diff --git a/harness/tests/gallery/test_server.py b/harness/tests/gallery/test_server.py
index 6f2b2598..fc9b3fd2 100644
--- a/harness/tests/gallery/test_server.py
+++ b/harness/tests/gallery/test_server.py
@@ -42,18 +42,6 @@ def test_index_and_api_routes(app: GalleryApp):
assert app.route("/api/nope").status == 404
-def test_detail_page(app: GalleryApp):
- r = app.route("/run/runs/wooden_chair_ab12cd34")
- assert r.status == 200
- page = r.body.decode()
- for anchor in ("id='rounds'", "id='judge'", "id='renders'", "id='code'", "id='cost'"):
- assert anchor in page, anchor
- assert "thicken the legs" in page # the judge's improvement plan
- assert "primitive_cube_add" in page # the code viewer inlined the entry file
- assert app.route("/run/runs/nope").status == 404
- assert app.route("/run/runs").status == 404
-
-
def test_detail_of_a_broken_run_does_not_crash(app: GalleryApp):
r = app.route("/run/static_v9/half_written")
assert r.status == 200 and b"broken" in r.body
@@ -83,10 +71,7 @@ def test_file_dir_and_code_routes(app: GalleryApp):
@pytest.mark.parametrize("bad", [
"../../../../etc/passwd",
"..%2f..%2fetc/passwd",
- "%2e%2e/%2e%2e/etc/passwd",
- "src/../../../../etc/passwd",
"src/../../lamp_three/record.json",
- "....//....//etc/passwd",
])
def test_path_traversal_is_refused(app: GalleryApp, bad: str):
r = app.route(f"/file/runs/wooden_chair_ab12cd34/{bad}")
@@ -169,18 +154,8 @@ def test_reload_picks_up_a_run_written_after_startup(gallery_tree: dict[str, Pat
assert app.route("/run/runs/brand_new").status == 200
-def test_no_reload_still_finds_a_new_run_by_url(gallery_tree: dict[str, Path]):
- from tests.flywheel_cli.conftest import make_fake_run
-
- app = GalleryApp([gallery_tree["runs"]], reload=False)
- make_fake_run(gallery_tree["runs"], "late_arrival", prompt="a late stool")
- assert app.route("/run/runs/late_arrival").status == 200
-
-
def test_unknown_compare_keys_cost_one_rescan_not_one_each(gallery_tree: dict[str, Path],
monkeypatch: pytest.MonkeyPatch):
- """``?runs=`` with N unknown keys ran N full scans of every root, and capped the keys
- only after looking every one of them up."""
import codeverse3d.addons.gallery.server as server
app = GalleryApp([gallery_tree["runs"]])
@@ -192,38 +167,6 @@ def test_unknown_compare_keys_cost_one_rescan_not_one_each(gallery_tree: dict[st
assert len(scans) == 2 and note.startswith(f"showing the first {server.MAX_COMPARE} of 20 selected runs")
-def test_a_waiting_rescan_never_replaces_a_newer_index(gallery_tree: dict[str, Path],
- monkeypatch: pytest.MonkeyPatch):
- """The rescan-on-miss assigned ``self.index`` without the lock, so a slow, older scan
- could land after a newer one and put a stale index back."""
- import codeverse3d.addons.gallery.server as server
-
- app = GalleryApp([gallery_tree["runs"]])
- real, scans = server.build_index, []
- monkeypatch.setattr(server, "build_index", lambda roots: scans.append(1) or real(roots))
-
- class _Lock: # a lock that says when a caller starts waiting for it
- def __init__(self) -> None:
- self.inner, self.waiting = threading.Lock(), threading.Event()
-
- def __enter__(self) -> None:
- self.waiting.set()
- self.inner.acquire()
-
- def __exit__(self, *exc: object) -> None:
- self.inner.release()
-
- app._lock = lock = _Lock()
- lock.inner.acquire() # another thread is mid-rescan ...
- t = threading.Thread(target=app.picked, args=(["runs/brand_new"],))
- t.start()
- assert lock.waiting.wait(5)
- app.index = newer = real(app.roots) # ... and publishes a newer index
- lock.inner.release()
- t.join(5)
- assert scans == [] and app.index is newer
-
-
# --------------------------------------------------------------------------- over a real socket
def test_over_a_loopback_socket(app: GalleryApp):
httpd = make_server(app, DEFAULT_HOST, 0)
diff --git a/harness/tests/gallery/test_triage.py b/harness/tests/gallery/test_triage.py
index dd249316..e65e0fab 100644
--- a/harness/tests/gallery/test_triage.py
+++ b/harness/tests/gallery/test_triage.py
@@ -1,15 +1,8 @@
-"""The triage affordances: the status breakdown, the hero view, label humanisation,
-multi-select routing (compare / CSV) and the detail page's neighbour links.
-
-The invariant worth a test is the arithmetic one: the verdict buckets are disjoint and
-exhaustive, so the strip's "n runs shown = a + b + c" is true for *any* selection —
-including one holding half-written records. None of them is a pass or a fail
-(2026-09-22): a run is judged, unjudged or unreadable.
-"""
+"""Triage: the verdict breakdown (disjoint and exhaustive — no pass/fail since 2026-09-22), the hero
+view, label humanisation, compare / CSV routing and the neighbour links."""
from __future__ import annotations
-import json
from pathlib import Path
from urllib.parse import parse_qs
@@ -17,17 +10,12 @@ import pytest
from codeverse3d.addons.gallery.compare import (
CSV_COLUMNS,
- MAX_COMPARE,
- export_csv,
- parse_keys,
- render_compare,
)
from codeverse3d.addons.gallery.index import build_index, hero_view
from codeverse3d.addons.gallery.model import (
VERDICTS,
humanize_view,
summarize,
- verdict_breakdown,
)
from codeverse3d.addons.gallery.page import render_index
from codeverse3d.addons.gallery.server import GalleryApp
@@ -46,20 +34,9 @@ def test_the_buckets_are_disjoint_and_sum_to_n(gallery_tree: dict[str, Path]):
# every entry lands in exactly one bucket
assert sorted(e.verdict for e in entries) == sorted(
k for k, n in s.breakdown.items() for _ in range(n))
-
-
-def test_a_run_with_no_record_is_error_not_unjudged(gallery_tree: dict[str, Path]):
- entries = build_index([gallery_tree["battery"]]).entries()
- by_slug = {e.slug: e for e in entries}
- assert by_slug["half_written"].verdict == "error" # corrupt record
- assert by_slug["not_started"].verdict == "error" # no record at all
- assert by_slug["half_written"].score is None # ...and nothing to score
-
-
-def test_breakdown_of_an_empty_selection_is_all_zeroes():
- b = verdict_breakdown([])
- assert b == dict.fromkeys(VERDICTS, 0) and sum(b.values()) == 0
- assert summarize([]).n == 0
+ by_slug = {e.slug: e for e in entries} # a corrupt record and a missing one are errors
+ assert by_slug["half_written"].verdict == by_slug["not_started"].verdict == "error"
+ assert by_slug["half_written"].score is None
def test_the_page_states_the_breakdown_and_it_adds_up(gallery_tree: dict[str, Path]):
@@ -72,15 +49,6 @@ def test_the_page_states_the_breakdown_and_it_adds_up(gallery_tree: dict[str, Pa
assert "PASS RATE" not in markup.upper() and "per pass" not in markup and "vc-passed" not in markup
-# --------------------------------------------------------------------------- verdict filter
-def test_verdict_filter_reaches_the_api_and_the_page(gallery_tree: dict[str, Path]):
- app = GalleryApp([gallery_tree["runs"], gallery_tree["battery"]])
- payload = json.loads(app.route("/api/runs", {"verdict": "error"}).body)
- assert payload["n"] == 2 and {r["state"] for r in payload["runs"]} == {"broken", "pending"}
- page = app.route("/", {"verdict": "judged"}).body.decode()
- assert "<option value='judged' selected>" in page
-
-
# --------------------------------------------------------------------------- hero view
def test_the_card_shows_one_hero_view_not_the_contact_sheet(gallery_tree: dict[str, Path]):
entry = next(e for e in build_index([gallery_tree["runs"]]).entries()
@@ -106,17 +74,10 @@ def test_hero_falls_back_to_the_sheet_when_a_round_has_no_views(tmp_path: Path):
# --------------------------------------------------------------------------- labels
@pytest.mark.parametrize(("raw", "human"), [
("front_right_high", "Front Right High"),
- ("back_left_low", "Back Left Low"),
- ("bottom", "Bottom"),
("front_right_34", "Front Right ¾"),
("view_front_right_34.png", "Front Right ¾"),
- ("back_left_34", "Back Left ¾"),
- ("low_front_left", "Low Front Left"),
- ("front", "Front"),
("t=2.5s", "t = 2.5 s"),
- ("t=0s", "t = 0 s"),
("pose_rest", "Pose · rest"),
- ("pose_door_hinge@upper", "Pose · door_hinge@upper"),
("articulation_sheet", "Articulation poses"),
("preview.gif", "Animated preview"),
("", ""),
@@ -125,19 +86,7 @@ def test_view_names_are_humanised(raw: str, human: str):
assert humanize_view(raw) == human
-def test_render_tiles_use_a_gradient_caption_not_a_black_bar(gallery_tree: dict[str, Path]):
- app = GalleryApp([gallery_tree["runs"]])
- page = app.route("/run/runs/wooden_chair_ab12cd34").body.decode()
- assert "<figcaption>Front</figcaption>" in page and "<figcaption>Top</figcaption>" in page
- assert "linear-gradient(to top,var(--overlay),transparent)" in page
-
-
# --------------------------------------------------------------------------- multi-select
-def test_parse_keys_keeps_order_and_drops_duplicates():
- assert parse_keys("a/b, c/d ,a/b") == ["a/b", "c/d"]
- assert parse_keys("") == [] and parse_keys(" , ") == []
-
-
def test_compare_route_renders_only_the_selected_runs(gallery_tree: dict[str, Path]):
app = GalleryApp([gallery_tree["runs"], gallery_tree["battery"]])
r = app.route("/compare", {"runs": "runs/wooden_chair_ab12cd34,static_v9/ctrl_med_toaster"})
@@ -156,17 +105,6 @@ def test_compare_of_nothing_explains_itself(gallery_tree: dict[str, Path]):
assert "nothing to compare" in page and app.route("/compare").status == 200
-def test_compare_reports_unknown_keys_and_caps_the_width(gallery_tree: dict[str, Path]):
- app = GalleryApp([gallery_tree["runs"], gallery_tree["battery"]])
- page = app.route("/compare", {"runs": "runs/wooden_chair_ab12cd34,runs/ghost"}).body.decode()
- assert "unknown: runs/ghost" in page
- many = ",".join(["runs/wooden_chair_ab12cd34"] * 3) # dedup keeps one
- assert app.route("/compare", {"runs": many}).status == 200
- entries = app.index.entries()
- assert len(render_compare(entries[:MAX_COMPARE], UrlMaker()).split("<td class='head'>")) - 1 \
- == min(MAX_COMPARE, len(entries))
-
-
def test_query_links_survive_a_duplicate_root_label(gallery_tree: dict[str, Path]):
"""``build_index`` mints ``runs#2``; an unquoted ``#`` ends the URL in the browser."""
app = GalleryApp([gallery_tree["runs"], gallery_tree["runs"]])
@@ -184,43 +122,17 @@ def test_compare_survives_a_run_with_no_record(gallery_tree: dict[str, Path]):
assert r.status == 200 and b"half_written" in r.body
-def test_bulk_bar_is_offered_on_the_server_but_not_in_the_static_build(gallery_tree: dict[str, Path]):
- from codeverse3d.addons.gallery.page import render_static
-
- index = build_index([gallery_tree["runs"]])
- served = render_index(index, UrlMaker())
- assert "id='selbar'" in served and "id='sel-compare'" in served
- assert "no re-run from the browser" in served # the refusal is written down
- assert "id='selbar'" not in render_static(index, embed=False)
-
-
# --------------------------------------------------------------------------- csv export
-def test_export_csv_route_and_columns(gallery_tree: dict[str, Path]):
- app = GalleryApp([gallery_tree["runs"], gallery_tree["battery"]])
- r = app.route("/export.csv", {"runs": "runs/wooden_chair_ab12cd34"})
- assert r.status == 200 and r.content_type.startswith("text/csv")
- assert "attachment" in r.headers["Content-Disposition"]
- lines = r.body.decode().strip().splitlines()
- assert lines[0] == ",".join(CSV_COLUMNS) and len(lines) == 2
- assert "wooden_chair_ab12cd34" in lines[1] and ",judged," in lines[1]
-
-
def test_export_csv_without_a_selection_exports_the_current_filter(gallery_tree: dict[str, Path]):
app = GalleryApp([gallery_tree["runs"], gallery_tree["battery"]])
- body = app.route("/export.csv", {"verdict": "error"}).body.decode()
+ r = app.route("/export.csv", {"verdict": "error"})
+ assert r.content_type.startswith("text/csv") and "attachment" in r.headers["Content-Disposition"]
+ body = r.body.decode()
+ assert body.splitlines()[0] == ",".join(CSV_COLUMNS)
assert len(body.strip().splitlines()) == 3 # header + the two unusable runs
assert "half_written" in body and "not_started" in body
-def test_csv_quotes_a_hostile_prompt(tmp_path: Path):
- from tests.flywheel_cli.conftest import make_fake_run
-
- runs = tmp_path / "runs"
- make_fake_run(runs, "comma", prompt='a chair, "quoted", \nnewline')
- text = export_csv(build_index([runs]).entries())
- assert len(list(__import__("csv").reader(__import__("io").StringIO(text)))) == 2
-
-
# --------------------------------------------------------------------------- neighbours
def test_detail_pages_link_to_the_neighbouring_runs(gallery_tree: dict[str, Path]):
app = GalleryApp([gallery_tree["runs"]])
diff --git a/harness/tests/install/test_docs.py b/harness/tests/install/test_docs.py
index 22e4a0e0..71e94a2b 100644
--- a/harness/tests/install/test_docs.py
+++ b/harness/tests/install/test_docs.py
@@ -100,14 +100,6 @@ def into_absent_eval(path: Path) -> bool:
# --------------------------------------------------------------------------- tests
-def test_install_guide_exists() -> None:
- assert INSTALL.is_file(), f"{INSTALL} is missing"
- text = INSTALL.read_text()
- assert len(text) > 2000, "docs/INSTALL.md looks truncated"
- for needle in ("runtime_js", "npm ci", "3dcodeverse doctor", "GEMINI_API_KEYS", "setup.sh"):
- assert needle in text, f"docs/INSTALL.md never mentions {needle!r}"
-
-
@pytest.mark.parametrize("doc", existing_docs(), ids=lambda p: str(p.relative_to(REPO)))
def test_owned_docs_have_valid_commands_links_and_paths(doc: Path) -> None:
bad: list[str] = []
@@ -148,17 +140,6 @@ def test_owned_docs_have_valid_commands_links_and_paths(doc: Path) -> None:
pytest.skip(f"no eval/ beside the harness: cannot resolve {into_eval}")
-def test_setup_script_is_executable_parses_and_has_help() -> None:
- assert SETUP.is_file(), f"{SETUP} is missing"
- assert os.access(SETUP, os.X_OK), f"{SETUP} is not executable (chmod +x)"
- assert SETUP.read_text().startswith("#!"), "setup.sh has no shebang"
- proc = subprocess.run(["bash", "-n", str(SETUP)], capture_output=True, text=True, timeout=60)
- assert proc.returncode == 0, f"bash -n failed:\n{proc.stderr}"
- proc = subprocess.run(["bash", str(SETUP), "--help"], capture_output=True, text=True, timeout=60)
- assert proc.returncode == 0, f"setup.sh --help exited {proc.returncode}:\n{proc.stderr}"
- assert "--extras" in proc.stdout
-
-
def test_every_pyproject_extra_is_documented() -> None:
with (HARNESS / "pyproject.toml").open("rb") as fh:
extras = tomllib.load(fh)["project"]["optional-dependencies"]
@@ -380,9 +361,3 @@ def test_setup_names_the_remedy_when_the_interpreter_has_no_pip(tmp_path) -> Non
assert proc.returncode != 0, "a python that cannot pip must not look like a successful install"
assert "has no pip" in out, f"the bare ModuleNotFoundError is not an explanation:\n{out}"
assert "-m venv" in out and "python3-venv" in out, f"no actionable remedy in:\n{out}"
-
-
-def test_install_docs_list_pip_and_venv_as_prerequisites() -> None:
- text = INSTALL.read_text()
- assert "python3-venv" in text and "EXTERNALLY-MANAGED" in text
- assert "pip + venv" in text, "the requirements table must name pip and venv"
diff --git a/harness/tests/install/test_hermetic.py b/harness/tests/install/test_hermetic.py
index f364ae84..8fb1bb1e 100644
--- a/harness/tests/install/test_hermetic.py
+++ b/harness/tests/install/test_hermetic.py
@@ -62,11 +62,3 @@ def test_quoted_test_counts_are_possible() -> None:
assert quoted, f"no test counts found in {INSTALL} — did the wording change?"
too_big = [n for n in quoted if n > ceiling]
assert not too_big, f"{INSTALL.name} quotes {too_big}, but only {ceiling} tests exist"
-
-
-def test_a_build_does_not_dirty_the_tree() -> None:
- paths = ("harness/build/lib/codeverse3d/__init__.py", "harness/dist/x.whl",
- "build/lib/x.py", "dist/x.tar.gz")
- for path in paths:
- r = subprocess.run(["git", "check-ignore", "-q", path], cwd=HARNESS.parent)
- assert r.returncode == 0, f"{path} is not gitignored"