feat: harden CAD showcase skill and delivery pipeline

This commit is contained in:
2026-07-10 09:21:13 +08:00
parent a6856f903d
commit 8b1b1d5e89
53 changed files with 5405 additions and 1327 deletions

View File

@@ -0,0 +1,84 @@
from __future__ import annotations
import json
import os
import socket
import subprocess
import sys
import time
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
@pytest.mark.skipif(
os.environ.get("RUN_BROWSER_SMOKE") != "1", reason="set RUN_BROWSER_SMOKE=1 with Playwright installed"
)
def test_served_viewer_in_desktop_and_mobile(tmp_path: Path) -> None:
from test_contracts import minimal_spec
spec = tmp_path / "spec.json"
glb = tmp_path / "model.glb"
metadata = tmp_path / "model_metadata.json"
web = tmp_path / "web"
spec.write_text(json.dumps(minimal_spec()), encoding="utf-8")
subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "spec_to_glb.py"),
"--spec",
str(spec),
"--out",
str(glb),
"--metadata-out",
str(metadata),
],
check=True,
)
subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "write_web_showcase.py"),
"--glb",
str(glb),
"--metadata",
str(metadata),
"--out-dir",
str(web),
],
check=True,
)
subprocess.run(["npm", "install", "--prefix", str(web), "--ignore-scripts"], check=True)
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
server = subprocess.Popen(
[sys.executable, "-m", "http.server", str(port), "--bind", "127.0.0.1"],
cwd=web,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
time.sleep(0.8)
report = tmp_path / "browser_report.json"
proc = subprocess.run(
[
"node",
str(ROOT / "scripts" / "web_smoke_test.mjs"),
"--url",
f"http://127.0.0.1:{port}",
"--out",
str(report),
"--screenshots-dir",
str(tmp_path / "screenshots"),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
assert json.loads(report.read_text(encoding="utf-8"))["status"] == "PASS"
finally:
server.terminate()
server.wait(timeout=10)

423
tests/test_contracts.py Normal file
View File

@@ -0,0 +1,423 @@
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
import pytest
import ezdxf
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import build_blender_showcase # noqa: E402
import cad_showcase # noqa: E402
import showcase_schema # noqa: E402
import spec_to_glb # noqa: E402
def minimal_spec() -> dict:
wall = {
"start": [0.0, 0.0],
"end": [10.0, 0.0],
"width": 0.2,
"layer": "WALL",
"source_type": "LINE",
}
return {
"schema_version": 1,
"project": {"name": "test", "description": "contract fixture"},
"source": {"config": {"config_version": 1, "use_footprint_slabs": True}},
"units": {"source": "meters", "scale_to_meters": 1.0, "origin_source": [0.0, 0.0]},
"categories": {
"walls": {"label": "墙", "color": "#cccccc"},
"slab": {"label": "楼板", "color": "#aaaaaa"},
},
"floors": {
"F1": {
"name": "一层",
"z": 0.0,
"height": 3.0,
"bounds": [0.0, 0.0, 10.0, 8.0],
"source_file": "fixture.dxf",
"segments": {"walls": [wall]},
"footprint": {"source": "fixture", "area": 80.0, "polygons": [[[0, 0], [10, 0], [10, 8], [0, 8]]]},
"caps": [{"z": 3.0, "polygons": [[[0, 0], [10, 0], [10, 8], [0, 8]]]}],
}
},
}
def test_config_rejects_unknown_keys() -> None:
with pytest.raises(showcase_schema.ValidationFailure, match="unexpected_typo"):
showcase_schema.validate_config({"config_version": 1, "unexpected_typo": True})
def test_config_requires_at_least_one_drawing() -> None:
with pytest.raises(showcase_schema.ValidationFailure, match="contains no drawings"):
showcase_schema.validate_config({"config_version": 1})
def test_config_rejects_duplicate_floor_keys(tmp_path: Path) -> None:
(tmp_path / "a.dxf").touch()
(tmp_path / "b.dxf").touch()
config = {
"config_version": 1,
"drawings": [
{"file": "a.dxf", "floors": [{"key": "F1"}]},
{"file": "b.dxf", "floors": [{"key": "F1"}]},
],
}
with pytest.raises(showcase_schema.ValidationFailure, match="duplicate floor key"):
showcase_schema.validate_config(config, tmp_path)
def test_config_rejects_missing_source(tmp_path: Path) -> None:
config = {"config_version": 1, "drawings": [{"file": "missing.dxf", "floors": [{"key": "F1"}]}]}
with pytest.raises(showcase_schema.ValidationFailure, match="does not exist"):
showcase_schema.validate_config(config, tmp_path)
def test_source_report_rejects_partial_gate() -> None:
report = {
"report_version": 1,
"gate": {"name": "all_sources_converted_and_readable", "status": "WARN"},
"files": [{"file": "partial.dxf", "status": "ok", "modelspace_entities": 1}],
}
with pytest.raises(showcase_schema.ValidationFailure, match="must be PASS"):
showcase_schema.validate_source_report(report)
def test_doctor_uses_platform_tool_resolvers(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys) -> None:
oda = tmp_path / "ODAFileConverter"
blender = tmp_path / "blender"
oda.touch()
blender.touch()
monkeypatch.setattr(cad_showcase, "oda_converter", lambda: str(oda))
monkeypatch.setattr(cad_showcase, "default_blender", lambda: str(blender))
assert cad_showcase.doctor() == 0
report = json.loads(capsys.readouterr().out)
checks = {item["name"]: item for item in report["checks"]}
assert checks["ODAFileConverter"] == {"name": "ODAFileConverter", "status": "PASS", "path": str(oda)}
assert checks["blender"] == {"name": "blender", "status": "PASS", "path": str(blender)}
def test_spec_schema_and_backend_group_contract() -> None:
spec = minimal_spec()
showcase_schema.validate_spec(spec)
config = {"cap_groups": [["TOWER_A_*", "A"], ["B*", "BASEMENT"]]}
assert showcase_schema.floor_group("TOWER_A_F3", config) == "A"
assert spec_to_glb.floor_group("TOWER_A_F3", config) == "A"
assert build_blender_showcase.floor_group("TOWER_A_F3", config) == "A"
def test_spec_rejects_segment_category_without_metadata() -> None:
spec = minimal_spec()
spec["floors"]["F1"]["segments"]["unregistered"] = [
{"start": [0, 0], "end": [1, 0], "width": 0.1, "layer": "X", "source_type": "LINE"}
]
with pytest.raises(showcase_schema.ValidationFailure, match="missing from spec.categories"):
showcase_schema.validate_spec(spec)
def test_report_empty_input_is_a_hard_failure(tmp_path: Path) -> None:
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_dxf_report.py"),
"--input",
str(tmp_path),
"--work",
str(tmp_path / "work"),
"--output",
str(tmp_path / "report"),
],
text=True,
capture_output=True,
)
assert proc.returncode == 3
assert "all_sources_converted_and_readable" in proc.stderr
def test_partial_report_requires_and_records_a_reason(tmp_path: Path) -> None:
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_dxf_report.py"),
"--input",
str(tmp_path),
"--work",
str(tmp_path / "work"),
"--output",
str(tmp_path / "report"),
"--allow-partial",
"--partial-reason",
"inventory-only test",
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
report = json.loads((tmp_path / "report" / "cad_read_report.json").read_text(encoding="utf-8"))
assert report["gate"]["status"] == "WARN"
assert report["gate"]["partial_reason"] == "inventory-only test"
def test_no_convert_cannot_hide_dwg_sources(tmp_path: Path) -> None:
ezdxf.new("R2010").saveas(tmp_path / "readable.dxf")
(tmp_path / "unconverted.dwg").write_bytes(b"not converted")
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_dxf_report.py"),
"--input",
str(tmp_path),
"--work",
str(tmp_path / "work"),
"--output",
str(tmp_path / "report"),
"--no-convert",
],
text=True,
capture_output=True,
)
assert proc.returncode == 3
report = json.loads((tmp_path / "report" / "cad_read_report.json").read_text(encoding="utf-8"))
assert "unconverted.dwg" in report["gate"]["detail"]
def test_variants_manifest_is_versioned(tmp_path: Path) -> None:
spec_path = tmp_path / "spec.json"
spec_path.write_text(json.dumps(minimal_spec()), encoding="utf-8")
out = tmp_path / "variants"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "build_showcase_variants.py"),
"--spec",
str(spec_path),
"--out-dir",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
manifest = json.loads((out / "variants_manifest.json").read_text(encoding="utf-8"))
assert manifest["manifest_version"] == 1
showcase_schema.validate_manifest(manifest)
def test_massing_output_conforms_to_schema(tmp_path: Path) -> None:
outline = tmp_path / "outline.json"
outline.write_text(json.dumps([[0, 0], [10, 0], [10, 8], [0, 8]]), encoding="utf-8")
out = tmp_path / "massing.json"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "massing_from_outline.py"),
"--outline",
str(outline),
"--storeys",
"3",
"--name",
"massing",
"--out",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
showcase_schema.validate_spec(json.loads(out.read_text(encoding="utf-8")))
def test_orchestrator_runs_resumable_trimesh_pipeline(tmp_path: Path) -> None:
input_dir = tmp_path / "dxf"
input_dir.mkdir()
doc = ezdxf.new("R2010")
doc.layers.add("WALL")
model = doc.modelspace()
for start, end in [
((0, 0), (10000, 0)),
((10000, 0), (10000, 8000)),
((10000, 8000), (0, 8000)),
((0, 8000), (0, 0)),
]:
model.add_line(start, end, dxfattribs={"layer": "WALL"})
doc.saveas(input_dir / "plan.dxf")
report_work = tmp_path / "report_work"
report_out = tmp_path / "source_report"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_dxf_report.py"),
"--input",
str(input_dir),
"--work",
str(report_work),
"--output",
str(report_out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
dxf_dir = report_work / "dxf_sanitized"
source_report = report_out / "cad_read_report.json"
config = {
"config_version": 1,
"project_name": "orchestrator-test",
"scale": 0.001,
"generate_footprints": True,
"use_footprint_slabs": True,
"layers": {"walls": ["WALL"]},
"roof_specs": [{"floor_key": "F1", "footprint_from": ["F1"], "z": 3.0, "thickness": 0.3}],
"drawings": [{"file": "plan.dxf", "floors": [{"key": "F1", "z": 0.0, "height": 3.0}]}],
}
config_path = tmp_path / "config.json"
config_path.write_text(json.dumps(config), encoding="utf-8")
out = tmp_path / "out"
command = [
sys.executable,
str(ROOT / "scripts" / "cad_showcase.py"),
"run",
"--dxf-dir",
str(dxf_dir),
"--config",
str(config_path),
"--source-report",
str(source_report),
"--out-dir",
str(out),
"--name",
"orchestrator-test",
"--budget-mb",
"5",
]
proc = subprocess.run(command, text=True, capture_output=True)
assert proc.returncode == 0, proc.stderr
evidence = json.loads((out / "evidence_manifest.json").read_text(encoding="utf-8"))
assert evidence["status"] == "PASS"
assert any(check["name"] == "cad_source_report" and check["status"] == "PASS" for check in evidence["checks"])
proc = subprocess.run([*command, "--resume"], text=True, capture_output=True)
assert proc.returncode == 0, proc.stderr
assert '"status": "SKIP"' in proc.stdout
proc = subprocess.run([*command[:-1], "6", "--resume"], text=True, capture_output=True)
assert proc.returncode == 0, proc.stderr
state = json.loads((out / "pipeline_state.json").read_text(encoding="utf-8"))
assert state["steps"]["preview"]["command"][-3:] == ["--budget-mb", "6.0", "--strict"]
def test_mesh_branch_exports_y_up_glb(tmp_path: Path) -> None:
doc = ezdxf.new("R2010")
mesh = doc.modelspace().add_mesh()
with mesh.edit_data() as data:
data.vertices = [(0, 0, 0), (2, 0, 0), (2, 1, 0), (0, 1, 0), (0, 0, 3), (2, 0, 3), (2, 1, 3), (0, 1, 3)]
data.faces = [(0, 1, 2, 3), (4, 7, 6, 5), (0, 4, 5, 1), (1, 5, 6, 2), (2, 6, 7, 3), (3, 7, 4, 0)]
source = tmp_path / "mesh.dxf"
doc.saveas(source)
glb = tmp_path / "mesh.glb"
report = tmp_path / "mesh_report.json"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "extract_3d_solids.py"),
"--dxf",
str(source),
"--out-glb",
str(glb),
"--report",
str(report),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
data = json.loads(report.read_text(encoding="utf-8"))
assert data["captured_meshes"] == 1
assert data["captured_triangles"] == 12
assert glb.read_bytes()[:4] == b"glTF"
def test_dwg_json_fallback_preserves_blocks_and_inserts(tmp_path: Path) -> None:
payload = {
"insunits": 4,
"layers": [{"name": "WALL", "color": 7}],
"blocks": {
"WINDOW": [
{"t": "LINE", "a": [0, 0], "b": [1000, 0], "layer": "WALL"},
]
},
"entities": [
{"t": "LINE", "a": [0, 0], "b": [5000, 0], "layer": "WALL"},
{"t": "INSERT", "name": "WINDOW", "p": [1000, 0], "layer": "WALL"},
],
}
source = tmp_path / "dump.json"
source.write_text(json.dumps(payload), encoding="utf-8")
out = tmp_path / "rebuilt.dxf"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "dwgjson_to_dxf.py"),
"--json",
str(source),
"--out",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
result = json.loads(proc.stdout)
assert result == {"out": str(out), "added": 2, "skipped": 0, "blocks": 1}
rebuilt = ezdxf.readfile(out)
assert "WINDOW" in rebuilt.blocks
assert [entity.dxftype() for entity in rebuilt.modelspace()] == ["LINE", "INSERT"]
def test_site_context_dump_builds_boundary_and_roads(tmp_path: Path) -> None:
payload = {
"entities": [
{
"t": "LWPOLYLINE",
"v": [[100, 200], [120, 200], [120, 215], [100, 215]],
"closed": True,
"layer": "Z2-用地红线",
},
{"t": "LINE", "a": [102, 202], "b": [118, 202], "layer": "Z5-车行道"},
]
}
source = tmp_path / "site_dump.json"
source.write_text(json.dumps(payload), encoding="utf-8")
out = tmp_path / "site_context.json"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "site_context_from_dump.py"),
"--dump",
str(source),
"--scale",
"1",
"--region",
"95",
"195",
"125",
"220",
"--origin",
"100",
"200",
"--out",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
fragment = json.loads(out.read_text(encoding="utf-8"))
assert set(fragment["floors"]) == {"SITE", "ROADS"}
assert fragment["floors"]["SITE"]["footprint"]["polygons"][0][0] == [0, 0]
assert len(fragment["floors"]["ROADS"]["segments"]["floor_lines"]) == 4
assert len(fragment["floors"]["ROADS"]["segments"]["detail_lines"]) == 1

213
tests/test_delivery.py Normal file
View File

@@ -0,0 +1,213 @@
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
from PIL import Image, ImageDraw
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import showcase_schema # noqa: E402
from test_contracts import minimal_spec # noqa: E402
def run(*args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(list(args), cwd=ROOT, text=True, capture_output=True)
def build_fixture(tmp_path: Path) -> tuple[Path, Path, Path]:
spec = tmp_path / "spec.json"
glb = tmp_path / "model.glb"
metadata = tmp_path / "model_metadata.json"
spec.write_text(json.dumps(minimal_spec()), encoding="utf-8")
proc = run(
sys.executable,
"scripts/spec_to_glb.py",
"--spec",
str(spec),
"--out",
str(glb),
"--metadata-out",
str(metadata),
)
assert proc.returncode == 0, proc.stderr
return spec, glb, metadata
def render_fixture(path: Path) -> None:
image = Image.new("RGB", (640, 480), "white")
draw = ImageDraw.Draw(image)
draw.rectangle((100, 120, 540, 400), fill="#4477aa", outline="black", width=4)
image.save(path)
def source_report_fixture(tmp_path: Path) -> Path:
path = tmp_path / "cad_read_report.json"
path.write_text(
json.dumps(
{
"report_version": 1,
"dxf_sanitized": str(tmp_path),
"gate": {"name": "all_sources_converted_and_readable", "status": "PASS"},
"files": [{"file": "fixture.dxf", "status": "ok", "modelspace_entities": 1}],
}
),
encoding="utf-8",
)
return path
def test_strict_delivery_passes_for_glb_render_and_offline_viewer(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
offline = tmp_path / "viewer.html"
proc = run(
sys.executable,
"scripts/write_offline_viewer.py",
"--spec",
str(spec),
"--glb",
str(glb),
"--out",
str(offline),
)
assert proc.returncode == 0, proc.stderr
evidence = tmp_path / "evidence.json"
source_report = source_report_fixture(tmp_path)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--offline-viewer",
str(offline),
"--evidence-out",
str(evidence),
)
assert proc.returncode == 0, proc.stderr
report = json.loads(evidence.read_text(encoding="utf-8"))
assert report["status"] == "PASS"
assert any(item["name"] == "offline:payload" and item["status"] == "PASS" for item in report["checks"])
def test_strict_delivery_requires_a_render(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
source_report = source_report_fixture(tmp_path)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--evidence-out",
str(tmp_path / "evidence.json"),
)
assert proc.returncode == 3
assert "At least one inspected render is required" in proc.stderr
def test_web_writer_and_static_delivery_checks(tmp_path: Path) -> None:
spec, glb, metadata = build_fixture(tmp_path)
web = tmp_path / "web"
proc = run(
sys.executable,
"scripts/write_web_showcase.py",
"--glb",
str(glb),
"--metadata",
str(metadata),
"--out-dir",
str(web),
)
assert proc.returncode == 0, proc.stderr
for relative in ("node_modules/three/build/three.module.js", "node_modules/lucide/dist/umd/lucide.js"):
target = web / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text("// test dependency", encoding="utf-8")
render = tmp_path / "render.png"
render_fixture(render)
source_report = source_report_fixture(tmp_path)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--web-dir",
str(web),
"--evidence-out",
str(tmp_path / "web_evidence.json"),
)
assert proc.returncode == 0, proc.stderr
def test_variants_manifest_requires_metadata_artifact(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
source_report = source_report_fixture(tmp_path)
manifest = tmp_path / "variants_manifest.json"
manifest.write_text(
json.dumps(
{
"manifest_version": 1,
"name": "missing-metadata",
"default_key": "standard",
"variants": [
{
"key": "standard",
"label": "standard",
"file": glb.name,
"source_glb": glb.name,
"metadata": "missing_metadata.json",
"spec": spec.name,
}
],
}
),
encoding="utf-8",
)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--source-report",
str(source_report),
"--spec",
str(spec),
"--variants-manifest",
str(manifest),
"--render",
str(render),
"--evidence-out",
str(tmp_path / "evidence.json"),
)
assert proc.returncode == 3
assert "missing_metadata.json" in proc.stderr
def test_schema_validator_rejects_legacy_spec_in_strict_mode() -> None:
legacy = minimal_spec()
legacy.pop("schema_version")
try:
showcase_schema.validate_spec(legacy)
except showcase_schema.ValidationFailure:
return
raise AssertionError("strict validator accepted a spec without schema_version")

File diff suppressed because it is too large Load Diff