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