Skip to content

Official Codebase of 3DCodeVerse

Python

tests: one FakeChatModel (queue, by_label, responder) replaces nine chat fakes; FakeAgent takes a scripted AgentResult — five scripted agents go

gaoypeng3ced6ad7cd36
diff --git a/harness/tests/flywheel_cli/test_captions.py b/harness/tests/flywheel_cli/test_captions.py
index 6dd95ee9..2cc73e18 100644
--- a/harness/tests/flywheel_cli/test_captions.py
+++ b/harness/tests/flywheel_cli/test_captions.py
@@ -12,10 +12,10 @@ from codeverse3d.addons.dataset.captions import (
caption_sample,
validate_captions,
)
-from codeverse3d.contracts.chat import ChatRequest, ChatResponse, ImagePart
-from codeverse3d.contracts.common import Usage
+from codeverse3d.contracts.chat import ImagePart
from codeverse3d.record.deliverable import load_deliverable
from codeverse3d.record.record import load_record
+from tests.orchestrator_tracks.fakes import FakeChatModel
GOOD = {
"detailed": "A four-legged wooden dining chair with a flat square seat and a tall slatted backrest.",
@@ -24,30 +24,13 @@ GOOD = {
}
-class FakeModel:
- provider, model = "fake", "fake"
-
- def __init__(self, replies):
- self.replies = list(replies)
- self.requests: list[ChatRequest] = []
-
- @property
- def id(self):
- return "fake:fake"
-
- def generate(self, request: ChatRequest) -> ChatResponse:
- self.requests.append(request)
- data = self.replies.pop(0)
- return ChatResponse(text=json.dumps(data), parsed=data, usage=Usage(cost_usd=0.001))
-
-
def test_caption_sample_stores_and_writes(fake_run):
from codeverse3d.addons import select
from codeverse3d.record.deliverable import load_deliverable
ws, rec = fake_run
select.package(ws.root, 1) # a round was handed over: its deliverable/ must follow the caption
- m = FakeModel([GOOD])
+ m = FakeChatModel([GOOD])
caps = caption_sample(ws, rec, "fake:fake", model=m)
assert caps.detailed.startswith("A four-legged")
req = m.requests[0]
@@ -59,7 +42,7 @@ def test_caption_sample_stores_and_writes(fake_run):
again = load_record(ws)
assert again.extra["captions"]["factory"] == GOOD["factory"]
assert again.extra["captions"]["provenance"]["captioner"] == "fake:fake"
- assert again.extra["captions"]["provenance"]["cost_usd"] == pytest.approx(0.001)
+ assert again.extra["captions"]["provenance"]["cost_usd"] == pytest.approx(0.002)
# a caption changes the hand-over folder too — it used to leave deliverable/,
# the manifest and telemetry/ describing an uncaptioned run
assert json.loads((ws.deliverable / "captions.json").read_text())["factory"] == GOOD["factory"]
@@ -82,7 +65,7 @@ def test_caption_cmd_writes_the_captioner_row_into_the_run_ledger(fake_run, monk
select.package(ws.root, 1)
ledger = open_run_ledger(ws.root) # the run already keeps one (create=False appends)
ledger.path.touch()
- monkeypatch.setattr(R, "build_chat_model", lambda _mid: FakeModel([GOOD]))
+ monkeypatch.setattr(R, "build_chat_model", lambda _mid: FakeChatModel([GOOD]))
r = CliRunner().invoke(app, ["flywheel", "caption", ws.root.name, "--runs-dir", str(ws.root.parent),
"--model", "fake:fake"])
assert r.exit_code == 0, r.output
@@ -94,11 +77,11 @@ def test_caption_cmd_writes_the_captioner_row_into_the_run_ledger(fake_run, monk
def test_caption_retry_then_fail(fake_run):
ws, rec = fake_run
bad = dict(GOOD, detailed="Made with bpy.ops primitives: a chair with four legs and a backrest.")
- m = FakeModel([bad, GOOD])
+ m = FakeChatModel([bad, GOOD])
caps = caption_sample(ws, rec, "fake:fake", model=m)
assert caps.detailed == GOOD["detailed"] and len(m.requests) == 2
assert "bpy" in m.requests[1].messages[-1].text
- m2 = FakeModel([bad, bad])
+ m2 = FakeChatModel([bad, bad])
with pytest.raises(CaptionError):
caption_sample(ws, rec, "fake:fake", model=m2)
@@ -154,7 +137,7 @@ def test_caption_sample_threejs_run(tmp_path):
from tests.flywheel_cli.conftest import make_fake_run
ws, rec = make_fake_run(tmp_path / "runs", "lamp_js", prompt="a desk lamp", language=Language.THREEJS)
- m = FakeModel([GOOD_JS])
+ m = FakeChatModel([GOOD_JS])
caps = caption_sample(ws, rec, "fake:fake", model=m)
assert "Three.js" in caps.instruction and len(m.requests) == 1 # no retry needed
@@ -190,7 +173,7 @@ def test_caption_graphics_run_from_frames(tmp_path):
"instruction": "Write a GLSL fragment shader with neon rain streaking down a dark window.",
"factory": "Hash-place bokeh discs in three depth layers, add per-cell rain trails, then tonemap and vignette.",
}
- m = FakeModel([reply])
+ m = FakeChatModel([reply])
caps = caption_sample(ws, rec, "fake:fake", model=m)
assert caps.instruction.lower().count("glsl")
req = m.requests[0]
@@ -229,7 +212,7 @@ def test_an_old_runs_caption_then_export_still_ships_its_glb_gif_and_meshes(tmp_
ws, rec = _old_urdf_run(tmp_path)
urdf = dict(GOOD, instruction="Write a URDF model of a simple robot arm with a base and one hinged link.")
- caption_sample(ws, rec, "fake:fake", model=FakeModel([urdf]))
+ caption_sample(ws, rec, "fake:fake", model=FakeChatModel([urdf]))
assert json.loads(ws.record_path.read_text())["best_round"] == 1 # the rewrite keeps the legacy key
handed = {f.path for f in load_deliverable(ws).files}
assert {"deliverable/object.glb", "deliverable/preview.gif", "deliverable/meshes/base.glb"} <= handed
diff --git a/harness/tests/flywheel_cli/test_quality_gallery.py b/harness/tests/flywheel_cli/test_quality_gallery.py
index c1bc866b..bd4e1e1b 100644
--- a/harness/tests/flywheel_cli/test_quality_gallery.py
+++ b/harness/tests/flywheel_cli/test_quality_gallery.py
@@ -16,7 +16,8 @@ from codeverse3d.addons.dataset.quality import (
from codeverse3d.contracts.common import Language
from codeverse3d.record.record import load_record
from tests.flywheel_cli.conftest import make_fake_run
-from tests.flywheel_cli.test_captions import GOOD, FakeModel
+from tests.flywheel_cli.test_captions import GOOD
+from tests.orchestrator_tracks.fakes import FakeChatModel
# --------------------------------------------------------------------------- tiers + dedupe
@@ -138,7 +139,7 @@ def test_caption_out_dir_leaves_run_untouched(fake_run, tmp_path: Path):
ws, rec = fake_run
before = ws.record_path.read_text()
side = tmp_path / "caps"
- caps = caption_sample(ws, rec, "fake:fake", model=FakeModel([GOOD]), out_dir=side)
+ caps = caption_sample(ws, rec, "fake:fake", model=FakeChatModel([GOOD]), out_dir=side)
assert caps.factory == GOOD["factory"]
assert ws.record_path.read_text() == before and not (ws.root / "captions.json").exists()
data = json.loads((side / f"{ws.root.name}.json").read_text())
diff --git a/harness/tests/flywheel_cli/test_run_identity.py b/harness/tests/flywheel_cli/test_run_identity.py
index e6a41974..6c3df4a4 100644
--- a/harness/tests/flywheel_cli/test_run_identity.py
+++ b/harness/tests/flywheel_cli/test_run_identity.py
@@ -131,13 +131,14 @@ def test_nested_run_identity_survives_every_flywheel_consumer(tmp_path: Path):
# Caption sidecars are equally isolated.
from codeverse3d.addons.dataset.captions import caption_sample
- from tests.flywheel_cli.test_captions import GOOD, FakeModel
+ from tests.flywheel_cli.test_captions import GOOD
+ from tests.orchestrator_tracks.fakes import FakeChatModel
side = tmp_path / "caps"
by_slug = {f.run_id.slug: f for f in found}
a = by_slug["cmp_a_stool__armx"]
b = by_slug["cmp_b_lamp__armx"]
- caption_sample(a.ws, a.record, "fake:fake", model=FakeModel([GOOD]),
+ caption_sample(a.ws, a.record, "fake:fake", model=FakeChatModel([GOOD]),
out_dir=side, slug=a.run_id.slug)
assert (side / "cmp_a_stool__armx.json").is_file()
assert not (side / "run.json").exists(), "the degenerate basename side-car is the bleed"
diff --git a/harness/tests/judges/conftest.py b/harness/tests/judges/conftest.py
index 75cac748..e382930c 100644
--- a/harness/tests/judges/conftest.py
+++ b/harness/tests/judges/conftest.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-import threading
+from functools import partial
from pathlib import Path
from typing import Any
@@ -10,13 +10,13 @@ import pytest
from PIL import Image, ImageDraw
from codeverse3d.contracts.artifacts import Measurement, PartMeasure, RenderSet, RenderView
-from codeverse3d.contracts.chat import ChatRequest, ChatResponse, ImagePart
-from codeverse3d.contracts.common import Language, Track, Usage
+from codeverse3d.contracts.chat import ChatRequest, ImagePart
+from codeverse3d.contracts.common import Language, Track
from codeverse3d.contracts.plan import AcceptanceItem
from codeverse3d.contracts.spec import Spec
from codeverse3d.judges.base import JudgeInput
from codeverse3d.judges.rubrics import Rubric
-from codeverse3d.models.base import ModelError
+from tests.orchestrator_tracks.fakes import FakeChatModel as _FakeChatModel
VIEW_NAMES = ("front_right_high", "back_left_high", "front", "top")
@@ -110,51 +110,8 @@ def good_reply(rubric: Rubric, acceptance_ids: list[str], score: float = 0.8, *,
}
-class FakeChatModel:
- """ChatModel stand-in: pops replies from a queue (dict → parsed; str → text;
- Exception → raised). Thread-safe: judges fan samples/orderings across threads.
-
- ``by_label`` routes deterministically under concurrency: each key is a substring
- of ``request.label`` with its own reply queue (longest matching key wins);
- unmatched requests fall back to the shared queue / ``default``."""
-
- provider = "fake"
- model = "fake-1"
-
- def __init__(self, replies: list[Any] | None = None, *, default: Any = None, cost: float = 0.001,
- by_label: dict[str, list[Any]] | None = None):
- self.replies = list(replies or [])
- self.default = default
- self.cost = cost
- self.by_label = {k: list(v) for k, v in (by_label or {}).items()}
- self.requests: list[ChatRequest] = []
- self._lock = threading.Lock()
-
- @property
- def id(self) -> str:
- return "fake:fake-1"
-
- def _next_reply(self, request: ChatRequest) -> Any:
- for key in sorted(self.by_label, key=len, reverse=True):
- if key in (request.label or "") and self.by_label[key]:
- return self.by_label[key].pop(0)
- return self.replies.pop(0) if self.replies else self.default
-
- def generate(self, request: ChatRequest) -> ChatResponse:
- with self._lock:
- self.requests.append(request)
- reply = self._next_reply(request)
- if callable(reply) and not isinstance(reply, type):
- reply = reply(request)
- if isinstance(reply, Exception):
- raise reply
- if reply is None:
- raise ModelError("no reply configured", retryable=False)
- usage = Usage(backend="fake", model="fake-1", input_tokens=1000, output_tokens=300, cost_usd=self.cost)
- if isinstance(reply, str):
- return ChatResponse(text=reply, parsed=None, usage=usage)
- import json
- return ChatResponse(text=json.dumps(reply), parsed=reply, usage=usage)
+# the shared fake, with the judge tests' id, price and token counts
+FakeChatModel = partial(_FakeChatModel, model="fake-1", cost=0.001, tokens=(1000, 300))
def image_parts(req: ChatRequest) -> list[ImagePart]:
diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.py
index 049038c4..c3f20a57 100644
--- a/harness/tests/orchestrator_tracks/fakes.py
+++ b/harness/tests/orchestrator_tracks/fakes.py
@@ -32,6 +32,7 @@ from codeverse3d.contracts.plan import Plan
from codeverse3d.contracts.run import RunRecord
from codeverse3d.conventions import to_snake
from codeverse3d.languages import get_runtime
+from codeverse3d.models.base import ModelError
from codeverse3d.tracks.common import Services
from codeverse3d.workspace import Workspace
@@ -136,12 +137,13 @@ class FakeRuntime:
# ----------------------------------------------------------------------------- agent / model
class FakeAgent:
- """``writer(job, ws) -> dict[path, content]``; None → no files (silent bail)."""
+ """``writer(job, ws) -> dict[path, content]``; None → no files (silent bail); an
+ ``AgentResult`` → that session outcome, returned as is."""
kind = "fake"
model = "fake-model"
- def __init__(self, writer: Callable[[AgentJob, Workspace], dict[str, str] | None], cost: float = 0.01,
+ def __init__(self, writer: Callable[[AgentJob, Workspace], dict[str, str] | AgentResult | None], cost: float = 0.01,
minutes: float = 0.0):
self.writer = writer
self.cost = cost
@@ -161,6 +163,8 @@ class FakeAgent:
with ws._lock: # noqa: SLF001 — the fake mimics a real agent's serialised writes
before = ws.head()
files = self.writer(job, ws)
+ if isinstance(files, AgentResult): # a scripted session outcome: a crash, a quota wall, an idle session
+ return files
for rel, content in (files or {}).items():
p = ws.root / rel
p.parent.mkdir(parents=True, exist_ok=True)
@@ -175,31 +179,56 @@ class FakeAgent:
class FakeChatModel:
- """``responder(request) -> str | dict``; dict is returned as ``parsed`` (structured output)."""
+ """The one ChatModel fake. Each request is answered by the next reply: the longest
+ ``by_label`` key found in ``request.label`` that still has replies, else the ``replies``
+ queue, else ``default``. ``replies`` may itself be a callable (the responder every
+ request goes to). A callable reply is called with the request; an Exception is raised;
+ None raises ModelError; a ChatResponse is returned as is; a dict/list is returned as
+ ``parsed`` (structured output); anything else as text. Thread-safe: judges fan samples
+ across threads."""
provider = "fake"
- model = "fake-model"
- def __init__(self, responder: Callable[[ChatRequest], Any], cost: float = 0.002, minutes: float = 0.0):
- self.responder = responder
- self.cost = cost
+ def __init__(self, replies: Callable[[ChatRequest], Any] | Sequence[Any] | None = None, *, default: Any = None,
+ by_label: dict[str, list[Any]] | None = None, model: str = "fake-model", cost: float = 0.002,
+ tokens: tuple[int, int] = (500, 200), minutes: float = 0.0):
+ self.replies, self.default = ([], replies) if callable(replies) else (list(replies or []), default)
+ self.by_label = {k: list(v) for k, v in (by_label or {}).items()}
+ self.model, self.cost, self.tokens = model, cost, tokens
self.minutes = minutes # wall clock each call burns (see conftest.fake_clock)
self.requests: list[ChatRequest] = []
+ self._lock = threading.Lock()
@property
def id(self) -> str:
- return "fake:fake-model"
+ return f"fake:{self.model}"
- def generate(self, request: ChatRequest) -> ChatResponse:
- from tests.orchestrator_tracks.conftest import FAKE_CLOCK
+ def _next_reply(self, request: ChatRequest) -> Any:
+ for key in sorted(self.by_label, key=len, reverse=True):
+ if key in (request.label or "") and self.by_label[key]:
+ return self.by_label[key].pop(0)
+ return self.replies.pop(0) if self.replies else self.default
- self.requests.append(request)
- FAKE_CLOCK["minutes"] += self.minutes
- out = self.responder(request)
- usage = Usage(backend="fake", model="fake-model", cost_usd=self.cost, input_tokens=500, output_tokens=200)
- if isinstance(out, (dict, list)):
- return ChatResponse(text=json.dumps(out), parsed=out, usage=usage)
- return ChatResponse(text=str(out), usage=usage)
+ def generate(self, request: ChatRequest) -> ChatResponse:
+ with self._lock:
+ self.requests.append(request)
+ reply = self._next_reply(request)
+ if self.minutes:
+ from tests.orchestrator_tracks.conftest import FAKE_CLOCK
+
+ FAKE_CLOCK["minutes"] += self.minutes
+ if callable(reply) and not isinstance(reply, type):
+ reply = reply(request)
+ if isinstance(reply, ChatResponse):
+ return reply
+ if isinstance(reply, Exception):
+ raise reply
+ if reply is None:
+ raise ModelError("no reply configured for " + (request.label or "?"), retryable=False)
+ usage = Usage(backend="fake", model=self.model, cost_usd=self.cost, input_tokens=self.tokens[0], output_tokens=self.tokens[1])
+ if isinstance(reply, (dict, list)):
+ return ChatResponse(text=json.dumps(reply), parsed=reply, usage=usage)
+ return ChatResponse(text=str(reply), usage=usage)
def _planner(payload: Any) -> FakeChatModel:
diff --git a/harness/tests/orchestrator_tracks/test_cost_latency.py b/harness/tests/orchestrator_tracks/test_cost_latency.py
index d957985c..f8c84130 100644
--- a/harness/tests/orchestrator_tracks/test_cost_latency.py
+++ b/harness/tests/orchestrator_tracks/test_cost_latency.py
@@ -253,13 +253,9 @@ def test_single_shot_ctx_is_none_for_cli_backends(tmp_path, settings):
assert single_shot_ctx(ctx2) is None # FakeServices has no chat model → agent path stays
-class _StormAgent(FakeAgent):
- """A CLI session that died at the wall after a 503 streak: nothing written, transient."""
-
- def run(self, job):
- self.jobs.append(job)
- return AgentResult(ok=False, exit_reason="timeout", transient=True,
- errors=["killed by watchdog (hard_timeout) after 720s", "11 x 503 inside the CLI's own retry loop before the wall; nothing produced"])
+# a CLI session that died at the wall after a 503 streak: nothing written, transient
+STORM_DEATH = AgentResult(ok=False, exit_reason="timeout", transient=True,
+ errors=["killed by watchdog (hard_timeout) after 720s", "11 x 503 inside the CLI's own retry loop before the wall; nothing produced"])
def test_a_storm_dead_session_falls_back_to_single_shot(tmp_path, settings):
@@ -270,7 +266,7 @@ def test_a_storm_dead_session_falls_back_to_single_shot(tmp_path, settings):
return _envelope("src/env.js", "export function buildEnv() { return {}; }\n")
services = _ChatServices(FakeChatModel(respond))
- agent = _StormAgent(lambda j, w: None)
+ agent = FakeAgent(lambda j, w: STORM_DEATH)
ctx = _scene_ctx(tmp_path, settings, services=services, agent=agent, agent_id="fake-agent:gemini:x")
task = GenerationTask(label="env", prompt="write `src/env.js`", files_hint=["src/env.js"], round=0, kind="env")
res = generate_for(ctx, task)
diff --git a/harness/tests/orchestrator_tracks/test_fix_generation.py b/harness/tests/orchestrator_tracks/test_fix_generation.py
index 62913851..304e3252 100644
--- a/harness/tests/orchestrator_tracks/test_fix_generation.py
+++ b/harness/tests/orchestrator_tracks/test_fix_generation.py
@@ -13,22 +13,15 @@ from codeverse3d.tracks.generation import (
run_agent_task,
)
from codeverse3d.workspace import Workspace
+from tests.orchestrator_tracks.fakes import FakeChatModel
FULL = "=== FILE: src/model.py ===\nimport bpy\nprint('ok')\n=== END FILE ==="
TRUNCATED = "=== FILE: src/model.py ===\nimport bpy\nbpy.ops.mesh.primitive_cube_add(size=0.4, location=(0, 0,"
-class ScriptedModel:
- """Yields ``(text, finish_reason)`` pairs in order."""
-
- def __init__(self, answers):
- self.answers = list(answers)
- self.requests = []
-
- def generate(self, req):
- self.requests.append(req)
- text, fr = self.answers.pop(0)
- return ChatResponse(text=text, usage=Usage(backend="fake", cost_usd=0.001), finish_reason=fr)
+def scripted(answers) -> FakeChatModel:
+ """A chat model answering ``(text, finish_reason)`` pairs in order."""
+ return FakeChatModel([ChatResponse(text=t, usage=Usage(backend="fake", cost_usd=0.001), finish_reason=fr) for t, fr in answers])
# --------------------------------------------------------------------- finding: truncated single-shot answer written verbatim
@@ -41,7 +34,7 @@ def test_parse_multifile_strips_header_from_unterminated_block():
def test_generate_files_truncation_policy(tmp_path):
ws = Workspace(tmp_path / "success").create()
- model = ScriptedModel([(TRUNCATED, "MAX_TOKENS"), (FULL, "STOP")])
+ model = scripted([(TRUNCATED, "MAX_TOKENS"), (FULL, "STOP")])
events = EventLog(tmp_path / "success.jsonl")
task = GenerationTask(label="baseline", prompt="p", files_hint=["src/model.py"], max_output_tokens=32000)
res = generate_files(ws, model=model, task=task, events=events)
@@ -50,14 +43,14 @@ def test_generate_files_truncation_policy(tmp_path):
assert "generate.truncated" in [e["event"] for e in events.read()]
ws = Workspace(tmp_path / "failure").create()
- model = ScriptedModel([(TRUNCATED, "MAX_TOKENS"), (TRUNCATED, "length")])
+ model = scripted([(TRUNCATED, "MAX_TOKENS"), (TRUNCATED, "length")])
task = GenerationTask(label="baseline", prompt="p", files_hint=["src/model.py"], max_output_tokens=32000)
res = generate_files(ws, model=model, task=task, events=EventLog(tmp_path / "failure.jsonl"))
assert not res.ok and res.notes.startswith("truncated")
assert not (ws.root / "src" / "model.py").exists()
ws = Workspace(tmp_path / "ceiling").create()
- model = ScriptedModel([(TRUNCATED, "MAX_TOKENS")])
+ model = scripted([(TRUNCATED, "MAX_TOKENS")])
task = GenerationTask(label="baseline", prompt="p", files_hint=["src/model.py"])
events = EventLog(tmp_path / "ceiling.jsonl")
res = generate_files(ws, model=model, task=task, events=events)
@@ -77,7 +70,7 @@ def test_out_of_root_paths_are_skipped_not_fatal(tmp_path):
)
events = EventLog(tmp_path / "e.jsonl")
task = GenerationTask(label="baseline", prompt="p", files_hint=["src/model.py"])
- res = generate_files(ws, model=ScriptedModel([(answer, "STOP")]), task=task, events=events)
+ res = generate_files(ws, model=scripted([(answer, "STOP")]), task=task, events=events)
assert res.ok, res.notes # the good file was paid for — never abort the round on a README
assert (ws.root / "src" / "model.py").is_file()
assert not (ws.root / "README.md").exists() and not (tmp_path / "evil.py").exists()
diff --git a/harness/tests/orchestrator_tracks/test_round_economics.py b/harness/tests/orchestrator_tracks/test_round_economics.py
index ccf4f286..d44f8dd5 100644
--- a/harness/tests/orchestrator_tracks/test_round_economics.py
+++ b/harness/tests/orchestrator_tracks/test_round_economics.py
@@ -181,13 +181,8 @@ def test_skip_judge_reasons_are_only_states_where_the_verdict_is_never_bought(tm
def test_a_round_that_changed_no_file_never_reaches_the_judge_question(tmp_path, spec, settings):
from codeverse3d.tracks.steps import RoundFailed, run_generation_tasks
- class _Idle:
- kind, model = "fake", "m"
-
- def run(self, job: AgentJob) -> AgentResult:
- return AgentResult(ok=True, exit_reason="completed", files_changed=[], usage=Usage(cost_usd=0.01))
-
- ctx = _ctx(tmp_path, spec, settings, agent=_Idle(), name="nochange")
+ idle = FakeAgent(lambda job, ws: AgentResult(ok=True, exit_reason="completed", files_changed=[], usage=Usage(cost_usd=0.01)))
+ ctx = _ctx(tmp_path, spec, settings, agent=idle, name="nochange")
with pytest.raises(RoundFailed):
run_generation_tasks(ctx, [GenerationTask(label="refine", prompt="p", round=1, kind="refine")])
diff --git a/harness/tests/orchestrator_tracks/test_transport_retry.py b/harness/tests/orchestrator_tracks/test_transport_retry.py
index e78216c7..bf42f239 100644
--- a/harness/tests/orchestrator_tracks/test_transport_retry.py
+++ b/harness/tests/orchestrator_tracks/test_transport_retry.py
@@ -94,30 +94,16 @@ class CrashUntilRetried(FakeAgent):
return super().run(job)
-class QuotaAfterBaseline(FakeAgent):
- """Baseline works; every refine session dies on the vendor's usage limit."""
+def after_baseline(failure: AgentResult) -> FakeAgent:
+ """Baseline works; every refine session ends in ``failure``."""
+ return FakeAgent(lambda job, ws: _writer(job, ws) if job.round == 0 else failure)
- def __init__(self):
- super().__init__(_writer)
-
- def run(self, job: AgentJob) -> AgentResult:
- if job.round == 0:
- return super().run(job)
- self.jobs.append(job)
- return AgentResult(ok=False, exit_reason="error", errors=[QUOTA], usage=Usage(cost_usd=0.0), quota=True)
-
-
-class IdleAfterBaseline(FakeAgent):
- """Baseline works; every refine session completes fine and changes nothing."""
-
- def __init__(self):
- super().__init__(_writer)
- def run(self, job: AgentJob) -> AgentResult:
- if job.round == 0:
- return super().run(job)
- self.jobs.append(job)
- return AgentResult(ok=True, exit_reason="no_changes", usage=Usage(cost_usd=0.01))
+QUOTA_WALL = AgentResult(ok=False, exit_reason="error", errors=[QUOTA], usage=Usage(cost_usd=0.0), quota=True)
+IDLE = AgentResult(ok=True, exit_reason="no_changes", usage=Usage(cost_usd=0.01))
+# a transport-looking message its backend did NOT classify transient (a CLI crash, no provider error)
+UNTYPED_CRASH = AgentResult(ok=False, exit_reason="error", usage=Usage(cost_usd=0.01),
+ errors=["rc=1; response=<empty>; stderr tail: at process.processTicksAndRejections"])
def _track(agent, scores, chair_plan, settings) -> StaticObjectTrack:
@@ -164,33 +150,18 @@ def test_baseline_transport_crash_is_retried_once_then_fails(tmp_path, chair_pla
assert evs.count("round.transport_retry") == 1 and "run.failed" in evs
-class CrashAfterBaseline(FakeAgent):
- """Baseline works; every refine session dies with a transport-looking message that its
- backend did NOT classify transient (a CLI crash with no provider error)."""
-
- def __init__(self):
- super().__init__(_writer)
-
- def run(self, job: AgentJob) -> AgentResult:
- if job.round == 0:
- return super().run(job)
- self.jobs.append(job)
- return AgentResult(ok=False, exit_reason="error", usage=Usage(cost_usd=0.01),
- errors=["rc=1; response=<empty>; stderr tail: at process.processTicksAndRejections"])
-
-
def test_an_untyped_crash_is_no_longer_a_transport_retry(tmp_path, chair_plan, settings):
"""The words "response=<empty>" used to buy a retry of the whole round; only the backend's
own verdict does now (0 of 34 recorded gemini-cli error exits lacked a provider signature)."""
ws = Workspace(tmp_path / "runs" / "crash")
- rec = _track(CrashAfterBaseline(), (0.55,), chair_plan, settings).run(make_spec(max_rounds=3), ws)
+ rec = _track(after_baseline(UNTYPED_CRASH), (0.55,), chair_plan, settings).run(make_spec(max_rounds=3), ws)
assert rec.status is RunStatus.NO_CHANGE
evs = _events(ws)
assert "round.transport_retry" not in evs and "round.no_change" in evs
def test_an_idle_agent_is_a_no_change_stop_not_a_retry(tmp_path, chair_plan, settings):
- agent = IdleAfterBaseline()
+ agent = after_baseline(IDLE)
ws = Workspace(tmp_path / "runs" / "idle")
rec = _track(agent, (0.55,), chair_plan, settings).run(make_spec(max_rounds=3), ws)
assert rec.status is RunStatus.NO_CHANGE
@@ -199,7 +170,7 @@ def test_an_idle_agent_is_a_no_change_stop_not_a_retry(tmp_path, chair_plan, set
def test_a_vendor_usage_limit_stops_the_run_as_agent_quota_not_no_change(tmp_path, chair_plan, settings):
- agent = QuotaAfterBaseline()
+ agent = after_baseline(QUOTA_WALL)
ws = Workspace(tmp_path / "runs" / "quota")
rec = _track(agent, (0.55,), chair_plan, settings).run(make_spec(max_rounds=3), ws)
assert rec.status is RunStatus.AGENT_QUOTA and rec.extra["stop_reason"] == "agent_quota"
diff --git a/harness/tests/orchestrator_tracks/test_write_scope.py b/harness/tests/orchestrator_tracks/test_write_scope.py
index 261811a0..2d005d1a 100644
--- a/harness/tests/orchestrator_tracks/test_write_scope.py
+++ b/harness/tests/orchestrator_tracks/test_write_scope.py
@@ -11,8 +11,7 @@
from __future__ import annotations
from codeverse3d.contracts.artifacts import BuildResult, Judgment
-from codeverse3d.contracts.chat import ChatResponse
-from codeverse3d.contracts.common import Language, Track, Usage
+from codeverse3d.contracts.common import Language, Track
from codeverse3d.contracts.plan import BBox, PartPlan, ScenePlan, StaticPlan
from codeverse3d.contracts.run import RoundRecord
from codeverse3d.languages.scene_threejs import zone_file
@@ -30,6 +29,7 @@ from codeverse3d.tracks.planner import plan_example
from codeverse3d.tracks.scene import SceneTrack
from codeverse3d.tracks.static_object import StaticObjectTrack
from codeverse3d.workspace import Workspace
+from tests.orchestrator_tracks.test_fix_generation import scripted
from .conftest import make_spec
from .fakes import FakeAgent, FakeRuntime, FakeServices
@@ -72,17 +72,6 @@ def test_write_files_normalises_a_path_before_the_owned_and_scope_checks(tmp_ws:
assert (tmp_ws.src / "zones" / "q.js").read_text() == "// old q\n"
-class ScriptedModel:
- """Yields ``(text, finish_reason)`` pairs in order (same as test_fix_generation)."""
-
- def __init__(self, answers):
- self.answers = list(answers)
-
- def generate(self, req):
- text, fr = self.answers.pop(0)
- return ChatResponse(text=text, usage=Usage(backend="fake", cost_usd=0.001), finish_reason=fr)
-
-
ANSWER = (
"=== FILE: src/parts/a.js ===\n// new a\n=== END FILE ===\n"
"=== FILE: src/object.js ===\n// new entry\n=== END FILE ===\n"
@@ -105,7 +94,7 @@ def test_generate_files_enforces_the_task_scope(tmp_path):
ws = _envelope_ws(tmp_path)
events = EventLog(tmp_path / "e.jsonl")
task = GenerationTask(label="refine_a", prompt="p", files_hint=["src/parts/a.js"], edit_only=True)
- res = generate_files(ws, model=ScriptedModel([(ANSWER, "STOP")]), task=task, events=events)
+ res = generate_files(ws, model=scripted([(ANSWER, "STOP")]), task=task, events=events)
assert res.ok and [c.path for c in res.files_changed] == ["src/parts/a.js", "src/parts/new.js"]
assert (ws.src / "parts" / "a.js").read_text() == "// new a\n"
assert (ws.src / "object.js").read_text() == "// entry\n", "the entry is not owned"
@@ -120,7 +109,7 @@ def test_generate_files_lets_an_owner_write_the_entry(tmp_path):
ws = _envelope_ws(tmp_path)
task = GenerationTask(label="refine_a", prompt="p", files_hint=["src/parts/a.js"],
edit_only=True, owns_entry=True)
- res = generate_files(ws, model=ScriptedModel([(ANSWER, "STOP")]), task=task,
+ res = generate_files(ws, model=scripted([(ANSWER, "STOP")]), task=task,
events=EventLog(tmp_path / "e.jsonl"))
assert res.ok and (ws.src / "object.js").read_text() == "// new entry\n"
assert (ws.src / "parts" / "b.js").read_text() == "// b\n", "b stays out of scope"
@@ -129,7 +118,7 @@ def test_generate_files_lets_an_owner_write_the_entry(tmp_path):
def test_generate_files_without_edit_only_is_unchanged(tmp_path):
ws = _envelope_ws(tmp_path)
task = GenerationTask(label="baseline", prompt="p", files_hint=["src/parts/a.js"])
- generate_files(ws, model=ScriptedModel([(ANSWER, "STOP")]), task=task,
+ generate_files(ws, model=scripted([(ANSWER, "STOP")]), task=task,
events=EventLog(tmp_path / "e.jsonl"))
assert (ws.src / "object.js").read_text() == "// new entry\n"
assert (ws.src / "parts" / "b.js").read_text() == "// new b\n"
@@ -144,7 +133,7 @@ def test_generate_files_never_rewrites_a_harness_owned_file(tmp_path):
events = EventLog(tmp_path / "e.jsonl")
answer = ("=== FILE: src/shader.frag ===\nvoid main(){}\n=== END FILE ===\n"
"=== FILE: src/recipes.glsl ===\n// clobbered\n=== END FILE ===")
- res = generate_files(ws, model=ScriptedModel([(answer, "STOP")]),
+ res = generate_files(ws, model=scripted([(answer, "STOP")]),
task=GenerationTask(label="baseline", prompt="p"), events=events)
assert res.ok and [c.path for c in res.files_changed] == ["src/shader.frag"]
assert (ws.src / "recipes.glsl").read_text().startswith("float aurora")
@@ -164,7 +153,7 @@ def test_generate_files_never_writes_under_a_harness_owned_directory(tmp_path):
events = EventLog(tmp_path / "e.jsonl")
answer = ("=== FILE: src/scene.js ===\n// scene\n=== END FILE ===\n"
"=== FILE: src/lib/post.js ===\n// clobbered\n=== END FILE ===")
- res = generate_files(ws, model=ScriptedModel([(answer, "STOP")]),
+ res = generate_files(ws, model=scripted([(answer, "STOP")]),
task=GenerationTask(label="baseline", prompt="p"), events=events)
assert res.ok and [c.path for c in res.files_changed] == ["src/scene.js"]
assert (ws.src / "lib" / "post.js").read_text() == "// harness effect library\n"
diff --git a/harness/tests/orchestrator_tracks/test_zone_layout.py b/harness/tests/orchestrator_tracks/test_zone_layout.py
index f770bb9b..2c87f28a 100644
--- a/harness/tests/orchestrator_tracks/test_zone_layout.py
+++ b/harness/tests/orchestrator_tracks/test_zone_layout.py
@@ -2,10 +2,9 @@
from __future__ import annotations
-from types import SimpleNamespace
-
from codeverse3d.contracts.plan import AssetPlan, BBox, CameraPlan, ScenePlan, ZoneLayout, ZonePlan
from codeverse3d.tracks.zone_layout import layout_block, layout_zones, validate_layout
+from tests.orchestrator_tracks.fakes import FakeChatModel
def _plan() -> ScenePlan:
@@ -105,27 +104,15 @@ def test_layout_block_renders_numbers_the_builder_can_follow():
assert layout_block(None) == ""
-class _Model:
- """Scripted planner: first answer per zone from the queue, then valid ones."""
-
- def __init__(self, answers):
- self.answers = list(answers)
- self.calls = 0
-
- def generate(self, req):
- self.calls += 1
- return SimpleNamespace(parsed=self.answers.pop(0), text="", usage=None)
-
-
def test_layout_zones_runs_per_zone_and_reasks_once_with_the_complaint():
plan = _plan()
good_quay = _layout().model_dump(mode="json")
bad_quay = _layout(placements=[{"asset": "Kraken", "count": 1, "cluster": (0.0, 0.0), "spread_m": 1.0}]).model_dump(mode="json")
good_market = {"zone": "Market", "placements": [{"asset": "Stall", "count": 4, "cluster": (10.0, 0.0), "spread_m": 5.0}]}
# zones fan out with max_workers=1 so the scripted queue stays ordered
- model = _Model([bad_quay, good_quay, good_market])
+ model = FakeChatModel([bad_quay, good_quay, good_market])
out = layout_zones(plan, model, max_workers=1)
- assert set(out) == {"Quay", "Market"} and model.calls == 3
+ assert set(out) == {"Quay", "Market"} and len(model.requests) == 3
assert out["Quay"].placements[0].asset == "Bollard"
@@ -133,7 +120,7 @@ def test_layout_zones_drops_a_twice_rejected_zone_instead_of_dying():
plan = _plan()
bad = {"zone": "Quay", "placements": [{"asset": "Kraken", "count": 1, "cluster": (0.0, 0.0), "spread_m": 1.0}]}
good_market = {"zone": "Market", "placements": [{"asset": "Stall", "count": 4, "cluster": (10.0, 0.0), "spread_m": 5.0}]}
- out = layout_zones(plan, _Model([bad, bad, good_market]), max_workers=1)
+ out = layout_zones(plan, FakeChatModel([bad, bad, good_market]), max_workers=1)
assert set(out) == {"Market"}
@@ -146,10 +133,10 @@ def test_a_run_past_its_ceiling_buys_no_layout_calls():
from codeverse3d.contracts.common import Budget
from codeverse3d.orchestrator import BudgetGuard
- model = _Model([]) # any call would pop an empty queue and explode the test
+ model = FakeChatModel() # any call finds no reply and raises
guard = BudgetGuard(Budget(max_minutes=30), start_time=time.time() - 45 * 60)
out = layout_zones(_plan(), model, budget=guard, max_workers=1)
- assert out == {} and model.calls == 0
+ assert out == {} and len(model.requests) == 0
def test_layout_waits_are_clipped_to_the_remaining_run_clock():
@@ -159,19 +146,11 @@ def test_layout_waits_are_clipped_to_the_remaining_run_clock():
from codeverse3d.contracts.common import Budget
from codeverse3d.orchestrator import BudgetGuard
- class _Recorder(_Model):
- def __init__(self, answers):
- super().__init__(answers)
- self.waits = []
-
- def generate(self, req):
- self.waits.append(req.max_wait_s)
- return super().generate(req)
-
good_quay = _layout().model_dump(mode="json")
good_market = {"zone": "Market", "placements": [{"asset": "Stall", "count": 4, "cluster": (10.0, 0.0), "spread_m": 5.0}]}
- model = _Recorder([good_quay, good_market])
+ model = FakeChatModel([good_quay, good_market])
guard = BudgetGuard(Budget(max_minutes=30), start_time=time.time() - 28 * 60) # ~2 min left
out = layout_zones(_plan(), model, budget=guard, max_workers=1)
assert set(out) == {"Quay", "Market"}
- assert model.waits and all(20 <= w <= 125 for w in model.waits), model.waits
+ waits = [r.max_wait_s for r in model.requests]
+ assert waits and all(20 <= w <= 125 for w in waits), waits
diff --git a/harness/tests/reference/conftest.py b/harness/tests/reference/conftest.py
index f2a32531..66167b04 100644
--- a/harness/tests/reference/conftest.py
+++ b/harness/tests/reference/conftest.py
@@ -1,51 +1,18 @@
-"""Fakes for the reference package: a scripted chat model and an image model."""
+"""Fakes for the reference package: an image model (chat: the shared FakeChatModel)."""
from __future__ import annotations
-import threading
from pathlib import Path
from typing import Any
import pytest
from PIL import Image, ImageDraw
-from codeverse3d.contracts.chat import ChatRequest, ChatResponse
from codeverse3d.contracts.common import Language, Track, Usage
from codeverse3d.contracts.spec import Constraints, Spec
from codeverse3d.models.base import ModelError
-class FakeChat:
- """ChatModel stand-in routed by ``request.label`` (``by_label``), else a queue."""
-
- provider = "fake"
- model = "fake-1"
-
- def __init__(self, by_label: dict[str, list[Any]] | None = None, *, default: Any = None):
- self.by_label = {k: list(v) for k, v in (by_label or {}).items()}
- self.default = default
- self.requests: list[ChatRequest] = []
- self._lock = threading.Lock()
-
- @property
- def id(self) -> str:
- return "fake:fake-1"
-
- def generate(self, request: ChatRequest) -> ChatResponse:
- with self._lock:
- self.requests.append(request)
- reply = self.default
- for key in sorted(self.by_label, key=len, reverse=True):
- if key in (request.label or "") and self.by_label[key]:
- reply = self.by_label[key].pop(0)
- break
- if isinstance(reply, Exception):
- raise reply
- if reply is None:
- raise ModelError("no reply configured for " + (request.label or "?"))
- return ChatResponse(parsed=reply, text="", usage=Usage(backend="fake", model="fake-1", cost_usd=0.001))
-
-
class FakeImageModel:
"""ImageModel stand-in: paints a solid rectangle so the silhouette code has work."""
diff --git a/harness/tests/reference/test_mismatch.py b/harness/tests/reference/test_mismatch.py
index 3048e755..be67f0cf 100644
--- a/harness/tests/reference/test_mismatch.py
+++ b/harness/tests/reference/test_mismatch.py
@@ -8,7 +8,8 @@ from PIL import Image
from codeverse3d.models.base import ModelError
from codeverse3d.reference import compare
-from tests.reference.conftest import FakeChat, make_spec
+from tests.orchestrator_tracks.fakes import FakeChatModel
+from tests.reference.conftest import make_spec
ANSWER = {
"mismatches": [
@@ -30,7 +31,7 @@ def _png(p: Path) -> Path:
def test_compare_names_mismatches_and_builds_text(tmp_path: Path):
ref, ren = _png(tmp_path / "ref.png"), _png(tmp_path / "ren.png")
- chat = FakeChat({"reference_diff": [ANSWER]})
+ chat = FakeChatModel(by_label={"reference_diff": [ANSWER]})
d = compare(make_spec(), [ref], [ren], model=chat, part_names=["Hopper", "Body"],
measured={"iou": 0.42, "aspect_ratio_err": 0.13, "reliable": True, "view": "front"},
synthesized=True)
@@ -47,16 +48,16 @@ def test_compare_names_mismatches_and_builds_text(tmp_path: Path):
def test_top_orders_by_severity(tmp_path: Path):
ref, ren = _png(tmp_path / "ref.png"), _png(tmp_path / "ren.png")
- d = compare(make_spec(), [ref], [ren], model=FakeChat({"reference_diff": [ANSWER]}))
+ d = compare(make_spec(), [ref], [ren], model=FakeChatModel(by_label={"reference_diff": [ANSWER]}))
assert [m.severity for m in d.top(3)] == ["critical", "major", "minor"]
def test_model_failure_is_soft(tmp_path: Path):
ref, ren = _png(tmp_path / "ref.png"), _png(tmp_path / "ren.png")
- d = compare(make_spec(), [ref], [ren], model=FakeChat({"reference_diff": [ModelError("nope")]}))
+ d = compare(make_spec(), [ref], [ren], model=FakeChatModel(by_label={"reference_diff": [ModelError("nope")]}))
assert d.mismatches == [] and "diff call failed" in d.error and d.as_text() == ""
def test_missing_images_short_circuit(tmp_path: Path):
- d = compare(make_spec(), [tmp_path / "gone.png"], [_png(tmp_path / "r.png")], model=FakeChat())
+ d = compare(make_spec(), [tmp_path / "gone.png"], [_png(tmp_path / "r.png")], model=FakeChatModel())
assert "nothing to compare" in d.error
diff --git a/harness/tests/reference/test_run_and_cli.py b/harness/tests/reference/test_run_and_cli.py
index 46a5424f..c420346d 100644
--- a/harness/tests/reference/test_run_and_cli.py
+++ b/harness/tests/reference/test_run_and_cli.py
@@ -11,11 +11,12 @@ from codeverse3d.contracts.spec import ReferenceImage
from codeverse3d.proc import EventLog
from codeverse3d.reference import SYNTH_TAG, ground_spec
from codeverse3d.workspace import Workspace
-from tests.reference.conftest import GOOD_GATE, PROMPT_PLAN, FakeChat, FakeImageModel, make_spec
+from tests.orchestrator_tracks.fakes import FakeChatModel
+from tests.reference.conftest import GOOD_GATE, PROMPT_PLAN, FakeImageModel, make_spec
def _chat(gates=None):
- return FakeChat({"reference_prompt": [PROMPT_PLAN], "reference_gate": list(gates or [GOOD_GATE, GOOD_GATE])})
+ return FakeChatModel(by_label={"reference_prompt": [PROMPT_PLAN], "reference_gate": list(gates or [GOOD_GATE, GOOD_GATE])})
def test_ground_spec_rewrites_the_spec_and_records_everything(tmp_ws: Workspace, cache_dir: Path):
diff --git a/harness/tests/reference/test_synth.py b/harness/tests/reference/test_synth.py
index 6ca605f3..732915e0 100644
--- a/harness/tests/reference/test_synth.py
+++ b/harness/tests/reference/test_synth.py
@@ -13,11 +13,12 @@ from codeverse3d.reference import (
template_hash,
views_for,
)
-from tests.reference.conftest import GOOD_GATE, PROMPT_PLAN, FakeChat, FakeImageModel, make_spec
+from tests.orchestrator_tracks.fakes import FakeChatModel
+from tests.reference.conftest import GOOD_GATE, PROMPT_PLAN, FakeImageModel, make_spec
def _chat(gates=None, plan=PROMPT_PLAN):
- return FakeChat({"reference_prompt": [plan], "reference_gate": list(gates or [GOOD_GATE, GOOD_GATE])})
+ return FakeChatModel(by_label={"reference_prompt": [plan], "reference_gate": list(gates or [GOOD_GATE, GOOD_GATE])})
def test_views_and_prompt_composition():
@@ -89,7 +90,7 @@ def test_no_image_model_is_not_fatal(cache_dir: Path):
def test_prompt_writer_failure_falls_back_to_the_brief(cache_dir: Path):
- chat = FakeChat({"reference_prompt": [ModelError("boom")], "reference_gate": [GOOD_GATE]})
+ chat = FakeChatModel(by_label={"reference_prompt": [ModelError("boom")], "reference_gate": [GOOD_GATE]})
rs = synth_reference(make_spec(), model=chat, image_model=FakeImageModel(), n_views=1, cache_dir=cache_dir)
assert rs.ok and "coffee grinder" in rs.subject
diff --git a/harness/tests/texturing/conftest.py b/harness/tests/texturing/conftest.py
index 4fd5f19d..6bccc127 100644
--- a/harness/tests/texturing/conftest.py
+++ b/harness/tests/texturing/conftest.py
@@ -4,7 +4,6 @@ its plan + spec, a fake image model, a fake render function and a fake judge."""
from __future__ import annotations
import hashlib
-import json
import threading
import time
from collections.abc import Sequence
@@ -17,7 +16,6 @@ import trimesh
from PIL import Image
from codeverse3d.contracts.artifacts import Judgment, RenderSet, RenderView
-from codeverse3d.contracts.chat import ChatResponse
from codeverse3d.contracts.common import Language, Track, Usage
from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan
from codeverse3d.contracts.spec import Spec
@@ -113,31 +111,17 @@ class FakeJudge:
usage=Usage(cost_usd=0.01))
-class FakePlanModel:
- """A ChatModel that answers the material-plan call — no credentials, no network.
-
- ``texture_pass(plan_model=)`` is one of its five injection points, and a test that
- leaves it None makes ``material_plan`` build a REAL model from the spec's planner id:
- the test then only passes on a box that happens to have keys (PORT-2).
- """
-
- id = "fake:plan"
-
- def __init__(self, payload: dict[str, Any] | None = None):
- self.payload = payload or {"parts": [
- {"part": "Seat", "texture_id": "oak_wood", "material_family": "wood",
- "subject": "light oak", "projection": "planar_y", "tile_size_m": 0.4},
- {"part": "Back", "texture_id": "oak_wood", "material_family": "wood",
- "subject": "light oak", "projection": "box"},
- {"part": "Leg", "texture_id": "steel", "material_family": "metal",
- "subject": "brushed steel", "projection": "cylinder", "metallic": 1, "roughness": 0.3},
- ], "notes": "fake plan"}
- self.calls: list[Any] = []
-
- def generate(self, req: Any) -> ChatResponse:
- self.calls.append(req)
- return ChatResponse(text=json.dumps(self.payload), parsed=self.payload,
- usage=Usage(cost_usd=0.002, input_tokens=100))
+# the material-plan answer for ``texture_pass(plan_model=FakeChatModel(default=PLAN_REPLY))``: a test
+# that leaves plan_model None makes ``material_plan`` build a REAL model from the spec's planner id
+# and then only passes on a box that happens to have keys (PORT-2)
+PLAN_REPLY = {"parts": [
+ {"part": "Seat", "texture_id": "oak_wood", "material_family": "wood",
+ "subject": "light oak", "projection": "planar_y", "tile_size_m": 0.4},
+ {"part": "Back", "texture_id": "oak_wood", "material_family": "wood",
+ "subject": "light oak", "projection": "box"},
+ {"part": "Leg", "texture_id": "steel", "material_family": "metal",
+ "subject": "brushed steel", "projection": "cylinder", "metallic": 1, "roughness": 0.3},
+], "notes": "fake plan"}
# --------------------------------------------------------------------------- fake image model
diff --git a/harness/tests/texturing/test_plan.py b/harness/tests/texturing/test_plan.py
index d4f97cb4..36756b1a 100644
--- a/harness/tests/texturing/test_plan.py
+++ b/harness/tests/texturing/test_plan.py
@@ -2,14 +2,11 @@
from __future__ import annotations
-import json
from pathlib import Path
import pytest
from PIL import Image
-from codeverse3d.contracts.chat import ChatRequest, ChatResponse
-from codeverse3d.contracts.common import Usage
from codeverse3d.texturing.plan import (
STYLE_SUFFIX,
PlannerOutput,
@@ -22,6 +19,7 @@ from codeverse3d.texturing.plan import (
material_plan,
plan_table,
)
+from tests.orchestrator_tracks.fakes import FakeChatModel
def test_family_keywords_are_whole_words():
@@ -66,23 +64,6 @@ def test_compose_prompt():
assert p.startswith("red brick wall, stone surface") and p.endswith("1:1 square")
-class _FakeChat:
- provider = "fake"
- model = "fake"
-
- def __init__(self, payload: dict):
- self.payload = payload
- self.calls: list[ChatRequest] = []
-
- @property
- def id(self):
- return "fake:fake"
-
- def generate(self, req: ChatRequest) -> ChatResponse:
- self.calls.append(req)
- return ChatResponse(text=json.dumps(self.payload), parsed=self.payload, usage=Usage(cost_usd=0.002, input_tokens=100))
-
-
def test_material_plan_one_call_with_sheet_and_cache(tmp_path: Path, chair_plan, chair_spec):
sheet = tmp_path / "sheet.png"
Image.new("RGB", (32, 32), (1, 2, 3)).save(sheet)
@@ -92,26 +73,26 @@ def test_material_plan_one_call_with_sheet_and_cache(tmp_path: Path, chair_plan,
{"part": "Leg", "texture_id": "steel", "material_family": "metal", "subject": "brushed steel", "projection": "cylinder", "metallic": 1, "roughness": 0.3},
{"part": "Knob", "texture_id": "glass", "material_family": "glass", "skip": True, "reason": "glass"},
], "notes": "two materials"}
- chat = _FakeChat(payload)
+ chat = FakeChatModel(default=payload)
tp = material_plan(chair_spec, chair_plan, sheet, "fake:fake", model=chat, cache_dir=tmp_path / "cache")
assert isinstance(tp, TexturePlan) and tp.source == "vlm" and tp.usage.cost_usd == pytest.approx(0.002)
- assert len(chat.calls) == 1
- req = chat.calls[0]
+ assert len(chat.requests) == 1
+ req = chat.requests[0]
assert req.response_schema is not None and any(p.type == "image" for p in req.messages[0].parts)
assert "Seat" in req.messages[0].text and chair_spec.prompt in req.messages[0].text
assert tp.by_part()["seat"].projection == "planar_y" and tp.by_part()["seat"].tile_size_m == 0.4
assert tp.texture_ids() == ["oak_wood", "steel"]
# cache hit: no second call
tp2 = material_plan(chair_spec, chair_plan, sheet, "fake:fake", model=chat, cache_dir=tmp_path / "cache")
- assert tp2.source == "cache" and len(chat.calls) == 1 and tp2.texture_ids() == tp.texture_ids()
+ assert tp2.source == "cache" and len(chat.requests) == 1 and tp2.texture_ids() == tp.texture_ids()
# different sheet → new key → new call
Image.new("RGB", (32, 32), (9, 9, 9)).save(sheet)
material_plan(chair_spec, chair_plan, sheet, "fake:fake", model=chat, cache_dir=tmp_path / "cache")
- assert len(chat.calls) == 2
+ assert len(chat.requests) == 2
def test_material_plan_invalid_payload_fails_loud(tmp_path, chair_plan, chair_spec):
- chat = _FakeChat({"nope": 1})
+ chat = FakeChatModel(default={"nope": 1})
with pytest.raises(ValueError):
material_plan(chair_spec, chair_plan, None, "fake:fake", model=chat, cache_dir=tmp_path, use_cache=False)
diff --git a/harness/tests/texturing/test_scene_pack.py b/harness/tests/texturing/test_scene_pack.py
index 34503dd3..638527d6 100644
--- a/harness/tests/texturing/test_scene_pack.py
+++ b/harness/tests/texturing/test_scene_pack.py
@@ -14,8 +14,8 @@ from codeverse3d.texturing.plan import (
scene_texture_pack,
texture_pack_prompt,
)
+from tests.orchestrator_tracks.fakes import FakeChatModel
from tests.texturing.conftest import FakeImageModel
-from tests.texturing.test_plan import _FakeChat
@pytest.fixture
@@ -45,13 +45,13 @@ def test_scene_pack_plan_with_model_and_cap(garden_plan):
{"name": "moss_ground", "material_family": "other", "subject": "dup", "tile_size_m": 1.0, "role": "ground"},
{"name": "granite_gravel", "material_family": "stone", "subject": "fine grey gravel", "tile_size_m": 0.8, "role": "ground"},
], "notes": "n"}
- chat = _FakeChat(payload)
+ chat = FakeChatModel(default=payload)
entries, notes, usage = scene_pack_plan(garden_plan, "fake:fake", model=chat, n_max=2)
assert [e.name for e in entries] == ["moss_ground", "granite_gravel"] and notes == "n" and usage.cost_usd > 0
assert entries[0].tile_size_m == 1.2 and "green moss carpet, matte natural surface" in entries[0].prompt
- assert "Zen Garden" in chat.calls[0].messages[0].text and "GravelCourt" in chat.calls[0].messages[0].text
+ assert "Zen Garden" in chat.requests[0].messages[0].text and "GravelCourt" in chat.requests[0].messages[0].text
with pytest.raises(ValueError):
- scene_pack_plan(garden_plan, "fake:fake", model=_FakeChat({"textures": []}))
+ scene_pack_plan(garden_plan, "fake:fake", model=FakeChatModel(default={"textures": []}))
def test_scene_texture_pack_writes_manifest_and_prompt(tmp_path: Path, garden_plan):
diff --git a/harness/tests/texturing/test_tools_cli.py b/harness/tests/texturing/test_tools_cli.py
index 58fd472a..5e0c0579 100644
--- a/harness/tests/texturing/test_tools_cli.py
+++ b/harness/tests/texturing/test_tools_cli.py
@@ -9,7 +9,8 @@ from typer.testing import CliRunner
from codeverse3d.texturing.run import texture_pass
from codeverse3d.workspace import Workspace
-from tests.texturing.conftest import FakeImageModel, FakeJudge, FakePlanModel, fake_render
+from tests.orchestrator_tracks.fakes import FakeChatModel
+from tests.texturing.conftest import PLAN_REPLY, FakeImageModel, FakeJudge, fake_render
def _ws(tmp_path: Path, chair_glb, chair_spec, chair_plan) -> Workspace:
@@ -26,7 +27,7 @@ def test_texture_pass_runs_with_injected_fakes(tmp_path, chair_glb, chair_spec,
ws = _ws(tmp_path, chair_glb, chair_spec, chair_plan)
judge = FakeJudge([(0.7, {"materials": 0.5}), (0.72, {"materials": 0.7})])
rep = texture_pass(ws, chair_spec, chair_plan, model_id=chair_spec.backends.planner, image_model=FakeImageModel(),
- plan_model=FakePlanModel(), judge_obj=judge, render=fake_render, cache_dir=tmp_path / "c")
+ plan_model=FakeChatModel(default=PLAN_REPLY), judge_obj=judge, render=fake_render, cache_dir=tmp_path / "c")
assert rep.shipped and rep.plan.source != "default"
assert (ws.artifacts / "object_textured.glb").is_file()