Official Codebase of 3DCodeVerse
Python
tests: core, install, gallery, second pass — ten more exceptions did not hold (−210 lines)
gaoypeng42ae6120908b
diff --git a/harness/tests/core/test_config_env_aliases.py b/harness/tests/core/test_config_env_aliases.pyindex 8d662dd5..ac615768 100644--- a/harness/tests/core/test_config_env_aliases.py+++ b/harness/tests/core/test_config_env_aliases.py@@ -8,20 +8,17 @@ import pytestfrom codeverse3d.config import Settings-#: every switch shares one validator: one top-level and one nested (flat-spelled) case-_FLAGS = [("C3D_SKILLS", True), ("C3D_SEED_RECIPES", True)]-[email protected](("env", "default"), _FLAGS)-def test_every_switch_speaks_one_grammar(monkeypatch, caplog, env, default):+def test_every_switch_speaks_one_grammar(monkeypatch, caplog):"""on/off, 1/0, true/false, yes/no in any case and padding; empty is unset; else warn (D44 c)."""+ env, default = "C3D_SEED_RECIPES", True # a nested field under its flat spellingdef read(raw: str | None) -> bool:if raw is None:monkeypatch.delenv(env, raising=False)else:monkeypatch.setenv(env, raw)s = Settings()- return s.limits.seed_recipes if env == "C3D_SEED_RECIPES" else getattr(s, env[4:].lower())+ return s.limits.seed_recipesassert read(None) is default and read("") is defaultfor word in ("off", "0", "false", "no", "OFF", " Off "):@@ -42,12 +39,9 @@ def test_flat_and_nested_max_in_flight_aliases(monkeypatch):assert Settings().rate.max_in_flight == 24monkeypatch.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()+ monkeypatch.delenv("C3D_RENDER__GPU", raising=False)+ monkeypatch.setenv("C3D_RENDER_GPU", " ON ") # the documented flat spelling, case- and space-tolerant+ assert Settings().render.gpu == "on"def test_empty_is_unset_and_garbage_in_a_sizing_knob_is_loud(monkeypatch):@@ -60,68 +54,15 @@ def test_empty_is_unset_and_garbage_in_a_sizing_knob_is_loud(monkeypatch):Settings()-def test_render_gpu_is_read_by_both_spellings_and_garbage_is_loud(monkeypatch):- """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"- monkeypatch.setenv("C3D_RENDER_GPU", "ON") # case-tolerant- assert Settings().render.gpu == "on"- monkeypatch.delenv("C3D_RENDER_GPU", raising=False)- monkeypatch.setenv("C3D_RENDER__GPU", "off")- assert Settings().render.gpu == "off"- monkeypatch.setenv("C3D_RENDER_GPU", "maybe")- with pytest.raises(ValueError, match="gpu"):- Settings()--def test_the_rate_and_limits_dials_carry_their_bounds(monkeypatch):+def test_zero_in_flight_is_unlimited_and_a_bad_turn_cap_asks_for_none():from codeverse3d.config import Limits, Rate- for kwargs in ({"max_in_flight": -1}, {"hedge": 0}):- with pytest.raises(ValueError):- Rate(**kwargs)- for kwargs in ({"max_parallel_agents": 0}, {"max_parallel_builds": -2}):- with pytest.raises(ValueError):- Limits(**kwargs)assert Rate(max_in_flight=0).max_in_flight == 0, "0 stays legal: it means unlimited"assert Limits(agent_max_turns=-1).agent_max_turns == 0, "a switch: a bad cap warns and asks for none"# --------------------------------------------------------------------------- yaml layering-def test_a_project_file_overrides_only_the_keys_it_names(tmp_path, monkeypatch):- """Project YAML overlays named keys without discarding user-config siblings."""- import os-- from codeverse3d import config as C-- home = tmp_path / "fakehome"- (home / ".config" / "3dcodeverse").mkdir(parents=True)- (home / ".config" / "3dcodeverse" / "config.yaml").write_text(- "limits:\n agent_timeout_s: 900\n max_parallel_builds: 3\njudge:\n samples: 4\n")- proj = tmp_path / "proj"- proj.mkdir()- (proj / "3dcodeverse.yaml").write_text("limits:\n max_parallel_agents: 4\n")-- monkeypatch.setattr(C, "_USER_CONFIG", home / ".config" / "3dcodeverse" / "config.yaml")- monkeypatch.setattr(C, "_LEGACY_USER_CONFIG", home / ".config" / "codeverse" / "config.yaml")- monkeypatch.chdir(proj)- for var in ("C3D_LIMITS__MAX_PARALLEL_AGENTS", "C3D_LIMITS__AGENT_TIMEOUT_S", "C3D_LIMITS__MAX_PARALLEL_BUILDS"):- monkeypatch.delenv(var, raising=False)- C.get_settings.cache_clear()- try:- s = C.get_settings()- # the project file's own key applies ...- assert s.limits.max_parallel_agents == 4- # ... and the user's siblings in the SAME section survive it- assert s.limits.agent_timeout_s == 900, "a sibling the project file never named must not reset"- assert s.limits.max_parallel_builds == 3- # a section the project file does not name is untouched (this always worked)- assert s.judge.samples == 4- finally:- C.get_settings.cache_clear()- os.environ.pop("C3D_PROFILE", None)-def test_the_environment_beats_the_config_files_per_setting(monkeypatch):"""INSTALL §8.3: config files < C3D_* env, per setting — it decides A/B arms."""diff --git a/harness/tests/core/test_contract_additions.py b/harness/tests/core/test_contract_additions.pyindex 0a3b7135..7bfd6c4d 100644--- a/harness/tests/core/test_contract_additions.py+++ b/harness/tests/core/test_contract_additions.py@@ -1,37 +1,14 @@-"""Finding lines, run options, and old-record compatibility."""+"""Run options and old-record compatibility."""from __future__ import annotations-import pytest-from pydantic import ValidationError--from codeverse3d.contracts.artifacts import GateFinding, RenderSet, Severity+from codeverse3d.contracts.artifacts import RenderSetfrom codeverse3d.contracts.common import Language, Trackfrom codeverse3d.contracts.spec import RunOptions, Spec-# ------------------------------------------------------------------ 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")- base.update(kw)- return GateFinding(**base)---def test_as_line_formats_defaults_flags_and_empty_fields():- assert _finding().as_line() == "leg floats FIX: drop z by 0.02"- assert _finding(fix_hint="").as_line() == "leg floats"- f = _finding()- assert f.as_line(with_gate=True, with_hint=False) == "GATE contract: leg floats"- assert f.as_line(with_severity=True, with_hint=False) == "[error] leg floats"- assert f.as_line(with_target=True, with_hint=False) == "leg floats [leg_1]"- assert (f.as_line(with_gate=True, with_severity=True, with_target=True)- == "GATE contract: [error] leg floats [leg_1] FIX: drop z by 0.02")- assert not f.as_line().startswith("- ")- assert _finding(target=None).as_line(with_target=True, with_hint=False) == "leg floats"--# ------------------------------------------------------------------ RunOptions-def test_spec_options_legacy_roundtrip_and_validation():+def test_spec_options_legacy_roundtrip():s = Spec(id="x", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a chair")d = s.model_dump(mode="json")d.pop("options")@@ -41,8 +18,6 @@ def test_spec_options_legacy_roundtrip_and_validation():options=RunOptions(candidates=3, texture=True))s2 = Spec(**s.model_dump(mode="json"))assert s2.options == RunOptions(candidates=3, texture=True)- with pytest.raises(ValidationError):- RunOptions(candidates=0) # ge=1def test_spec_options_do_not_change_the_plan_stage_hash():diff --git a/harness/tests/core/test_events.py b/harness/tests/core/test_events.pydeleted file mode 100644index d1b84585..00000000--- a/harness/tests/core/test_events.py+++ /dev/null@@ -1,35 +0,0 @@-"""EventLog durability: a run killed mid-write leaves a partial trailing line,-and `3dcode status` is the first thing anyone types on a run that died (CP-3 / RS-6)."""--from __future__ import annotations--from pathlib import Path--from typer.testing import CliRunner--from codeverse3d.cli.main import app-from codeverse3d.contracts.common import Backends, Language, Track-from codeverse3d.contracts.spec import Spec-from codeverse3d.proc import EventLog-from codeverse3d.workspace import Workspace--runner = CliRunner()---def test_status_still_prints_the_run_when_events_are_truncated(tmp_path: Path) -> None:- """The whole status view used to be lost to the last line of the log."""- runs = tmp_path / "runs"- ws = Workspace(runs / "stool").create()- spec = Spec(id="stool", track=Track.STATIC_OBJECT, language=Language.BLENDER,- prompt="a small wooden stool", backends=Backends(generator="gemini-cli:gemini-3.6-flash"))- ws.write_json(ws.spec_path, spec)- log = EventLog(ws.events_path)- log.emit("run.start")- with log.path.open("a") as fh:- fh.write('{"t": 1756000001.0, "event": "round.start", "rou')-- res = runner.invoke(app, ["status", "stool", "--runs-dir", str(runs)])-- assert res.exit_code == 0, res.output- assert "a small wooden stool" in res.output- assert "run.start" in res.outputdiff --git a/harness/tests/core/test_plan_normalise.py b/harness/tests/core/test_plan_normalise.pyindex 9a6296a8..ea136f54 100644--- a/harness/tests/core/test_plan_normalise.py+++ b/harness/tests/core/test_plan_normalise.py@@ -50,18 +50,14 @@ def _joint(p: ArticulatedPlan, j: dict):def test_degree_shaped_limits_and_rest_are_converted_together():- 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)- p = ArticulatedPlan.model_validate(d)- fixed = _joint(p, j)- assert fixed.type == "revolute"- assert fixed.lower == pytest.approx(math.radians(lower))- 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)+ d = _raw()+ j = _revolute(d, 0.0, 90.0, 90.0)+ p = ArticulatedPlan.model_validate(d)+ fixed = _joint(p, j)+ assert fixed.type == "revolute"+ assert (fixed.lower, fixed.upper, fixed.rest) == pytest.approx((0.0, math.radians(90), math.radians(90)))+ 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():diff --git a/harness/tests/core/test_proc.py b/harness/tests/core/test_proc.pyindex ab7d95dd..bdc73cc5 100644--- a/harness/tests/core/test_proc.py+++ b/harness/tests/core/test_proc.py@@ -2,7 +2,6 @@from __future__ import annotations-import jsonimport osimport signalimport sys@@ -64,43 +63,8 @@ def test_a_detached_descendant_holding_the_pipes_cannot_extend_the_timeout(tmp_p# --------------------------------------------------------------------------- atomic writes-_WRITER = """-import json, sys-from pathlib import Path-from codeverse3d.proc import write_json_atomic--path, tag, n = Path(sys.argv[1]), sys.argv[2], int(sys.argv[3])-payload = {"writer": tag, "blob": [tag * 40] * 900}-bad = 0-for _ in range(n):- write_json_atomic(path, payload) # a second writer must not break this one- try:- json.loads(path.read_text()) # ... and readers must never see a partial file- except ValueError:- bad += 1-print(bad)-"""---def test_write_json_atomic_survives_concurrent_writers(tmp_path: Path):- """Concurrent processes publish only complete JSON and leave no temp files."""- import subprocess-- harness = Path(__file__).resolve().parents[2]- target = tmp_path / "shared.json"- procs = [subprocess.Popen([sys.executable, "-c", _WRITER, str(target), tag, "40"],- cwd=harness, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)- for tag in ("A", "B", "C")]- outs = [(p.wait(), *p.communicate()) for p in procs]- for rc, out, errtext in outs:- assert rc == 0, f"a writer crashed: {errtext[-500:]}"- assert out.strip() == "0", f"a reader saw a partial file {out.strip()} time(s)"- assert json.loads(target.read_text())["writer"] in ("A", "B", "C") # last writer wins, whole- assert not list(tmp_path.glob("*.tmp")), "no temp file left behind"--def test_concurrent_writers_of_one_destination_all_succeed(tmp_path: Path):- """Barrier-synchronized writers can safely replace one destination."""+ """Barrier-synchronised writers (one pid, many threads) all publish one destination, no temp litter."""from codeverse3d.proc import write_text_atomicout = tmp_path / "shared.txt"diff --git a/harness/tests/core/test_runlock.py b/harness/tests/core/test_runlock.pyindex 748e32f5..6449e2c6 100644--- a/harness/tests/core/test_runlock.py+++ b/harness/tests/core/test_runlock.py@@ -2,7 +2,6 @@from __future__ import annotations-import osimport threadingimport timefrom pathlib import Path@@ -96,17 +95,6 @@ def test_a_second_thread_is_refused_and_the_first_keeps_the_lock(tmp_path: Path)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"- run_root.mkdir(parents=True)- assert holder_of(run_root) is None- with exclusive(run_root, what="3dcode make slug"):- held = holder_of(run_root)- assert held is not None and held["pid"] == os.getpid()- assert held["what"] == "3dcode make slug"- assert holder_of(run_root) is None, "the record is truncated on release, never left to lie"-def test_the_lock_file_lives_outside_the_run_directory(tmp_path: Path):"""A --force wipe rmtree's the run root; a lock inside it would be deleted mid-hold."""diff --git a/harness/tests/gallery/test_index.py b/harness/tests/gallery/test_index.pyindex 67e61a77..c29c1942 100644--- a/harness/tests/gallery/test_index.py+++ b/harness/tests/gallery/test_index.py@@ -9,37 +9,6 @@ from codeverse3d.addons.gallery.index import build_index, entry_for_dirfrom codeverse3d.addons.gallery.model import match, sort_entries, summarize-def test_build_index_sections_and_states(gallery_tree: dict[str, Path]):- index = build_index([gallery_tree["runs"], gallery_tree["battery"]])- assert [s.label for s in index.sections] == ["runs", "static_v9"]- assert index.build_ms >= 0- states = {e.slug: e.state for e in index.entries()}- assert states == {"lamp_three": "ok", "wooden_chair_ab12cd34": "ok", "art_easy_hinge": "ok",- "ctrl_med_toaster": "ok", "half_written": "broken", "not_started": "pending"}- broken = index.find("static_v9", "half_written")- assert broken is not None and "record.json" in broken.error- assert broken.prompt == "a stool" and broken.track == "static_object" # spec still read- pending = index.find("static_v9", "not_started")- assert pending is not None and pending.prompt == "a bookshelf"- # a broken/pending run still offers its workspace, and nothing raised- assert "workspace" in {link.label for link in broken.links}---def test_entry_fields_and_links(gallery_tree: dict[str, Path]):- entry = entry_for_dir("runs", gallery_tree["runs"] / "wooden_chair_ab12cd34")- assert entry.state == "ok" and entry.verdict == "judged" and entry.tier == "A"- assert entry.score == 0.80 and entry.baseline_score == 0.55 and entry.rounds == 2- assert entry.picked_round == 1 and entry.minutes is not None- assert entry.sheet == "artifacts/renders/r01/sheet.png"- labels = [link.label for link in entry.links]- assert labels[:2] == ["workspace", "record.json"]- assert "src/" in labels and "sheet" in labels and "glb" in labels- assert all(not Path(link.rel).is_absolute() for link in entry.links) # every link is run-relative- assert [r.index for r in entry.round_rows] == [0, 1]- assert entry.round_rows[1].sheet == "artifacts/renders/r01/sheet.png"- assert entry.key == "runs/wooden_chair_ab12cd34"--def test_a_card_links_the_picked_rounds_own_glb(tmp_path: Path):"""artifacts/object.glb is the LAST round's: until a hand-over the card links the picked round's copy."""from codeverse3d.addons import selectdiff --git a/harness/tests/gallery/test_page.py b/harness/tests/gallery/test_page.pyindex ef33c40b..433049e6 100644--- a/harness/tests/gallery/test_page.py+++ b/harness/tests/gallery/test_page.py@@ -92,6 +92,7 @@ def test_server_page_applies_the_filter_server_side(gallery_tree: dict[str, Pathassert len(re.findall(r"<article class='card [^']*is-hidden' data-run=", markup)) == 5assert ">1 <span class='faint'>of 6</span><" in markupassert "<option value='threejs' selected>" in markup+ assert "vc-passed" not in markup and "PASS RATE" not in markup.upper() # no pass/fail since 2026-09-22def test_detail_links_are_offered_only_when_the_target_has_them(gallery_tree: dict[str, Path]):diff --git a/harness/tests/gallery/test_triage.py b/harness/tests/gallery/test_triage.pyindex e65e0fab..80699d7b 100644--- a/harness/tests/gallery/test_triage.py+++ b/harness/tests/gallery/test_triage.py@@ -39,15 +39,6 @@ def test_the_buckets_are_disjoint_and_sum_to_n(gallery_tree: dict[str, Path]):assert by_slug["half_written"].score is None-def test_the_page_states_the_breakdown_and_it_adds_up(gallery_tree: dict[str, Path]):- index = build_index([gallery_tree["runs"], gallery_tree["battery"]])- markup = render_index(index, UrlMaker())- for bucket in VERDICTS:- assert f"id='vc-{bucket}'" in markup- assert "runs shown" in markup- # no pass rate and no pass/fail bucket: a run is not passed or failed- assert "PASS RATE" not in markup.upper() and "per pass" not in markup and "vc-passed" not in markup-# --------------------------------------------------------------------------- hero viewdef test_the_card_shows_one_hero_view_not_the_contact_sheet(gallery_tree: dict[str, Path]):