Files
cad-building-showcase/tests/test_contracts.py

731 lines
26 KiB
Python

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 audit_showcase_extraction # noqa: E402
import build_blender_showcase # noqa: E402
import cad_showcase # noqa: E402
import delivery_waivers # noqa: E402
import derive_showcase_spec # 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_vertical_storey_continuity_rejects_representative_floor_islands() -> None:
spec = minimal_spec()
spec["floors"]["F2"] = {**spec["floors"]["F1"], "name": "二层", "z": 5.0}
spec["floors"]["F16"] = {**spec["floors"]["F1"], "name": "十六层", "z": 59.6}
gate = audit_showcase_extraction.vertical_storey_continuity_gate(spec)
assert gate["status"] == "WARN"
assert "F2->F16" in gate["detail"]
def test_vertical_storey_continuity_accepts_instantiated_typical_floors() -> None:
spec = minimal_spec()
base = spec["floors"]["F1"]
spec["floors"] = {f"F{number}": {**base, "name": f"{number}层", "z": (number - 1) * 3.9} for number in range(1, 17)}
gate = audit_showcase_extraction.vertical_storey_continuity_gate(spec)
assert gate["status"] == "PASS"
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_requires_reason_for_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="partial reason"):
showcase_schema.validate_source_report(report)
def test_source_report_accepts_reasoned_partial_gate() -> None:
report = {
"report_version": 1,
"gate": {
"name": "all_sources_converted_and_readable",
"status": "WARN",
"partial_reason": "One optional elevation DWG is unavailable",
},
"files": [{"file": "partial.dxf", "status": "ok", "modelspace_entities": 1}],
}
assert showcase_schema.validate_source_report(report) == report
def test_unarmed_cross_evidence_gates_are_not_applicable() -> None:
spec = minimal_spec()
assert audit_showcase_extraction.frame_ledger_gate({}, None)["status"] == "NOT_APPLICABLE"
assert audit_showcase_extraction.declared_area_gate(spec, {})["status"] == "NOT_APPLICABLE"
assert audit_showcase_extraction.storey_count_gate(spec, {})["status"] == "NOT_APPLICABLE"
def test_annotation_is_waivable_warn_and_absent_glazing_is_not_applicable() -> None:
report = {
"spec_counts": {"F1": {"glazing": 0}},
"block_locked_layers": [],
"top_insert_names": [],
"classified_layers": [{"layer": "A-ANNO-DIMS"}],
"coverage": {
"block_locked_classifiable_length_meters": 0,
"block_captured_classified_length_meters": 0,
},
}
gates = {
gate["name"]: gate["status"]
for gate in audit_showcase_extraction.evaluate_gates(report, minimal_spec(), {}, None)
}
assert gates["no_annotation_layers_classified"] == "WARN"
assert gates["glazing_captured"] == "NOT_APPLICABLE"
def test_config_rejects_malformed_category_overrides() -> None:
config = {
"config_version": 1,
"drawings": [{"file": "fixture.dxf", "floors": [{"key": "F1"}]}],
"categories": {"walls": "not-an-object"},
}
with pytest.raises(showcase_schema.ValidationFailure, match="categories.walls"):
showcase_schema.validate_config(config)
def test_all_derive_geometry_loss_warnings_are_forbidden() -> None:
assert set(cad_showcase.DERIVE_FORBIDDEN_WARNINGS) == {
"WARNING isolated_cluster",
"WARNING unsupported_roof",
"WARNING floor_order",
"WARNING topless_group",
}
def test_waivers_share_one_implementation_and_reject_not_applicable_targets(tmp_path: Path) -> None:
import verify_delivery
assert cad_showcase.parse_waivers is delivery_waivers.parse_waivers
assert verify_delivery.parse_waivers is delivery_waivers.parse_waivers
audit = tmp_path / "audit.json"
audit.write_text(
json.dumps(
{
"gates": [
{
"name": "frame_ledger",
"status": "NOT_APPLICABLE",
"detail": "No frame report supplied",
}
]
}
),
encoding="utf-8",
)
pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False)
assert not cad_showcase.enforce_audit_gates(
pipeline,
audit,
{"audit:frame_ledger": "pre-approved in case this gate becomes armed"},
)
state = json.loads((tmp_path / "state.json").read_text(encoding="utf-8"))
blocked = state["blocked_gates"]
assert blocked[0]["name"] == "waiver:audit:frame_ledger"
assert "NOT_APPLICABLE" in blocked[0]["detail"]
def test_audit_waiver_typo_fails_before_downstream_work(tmp_path: Path) -> None:
audit = tmp_path / "audit.json"
audit.write_text(
json.dumps({"gates": [{"name": "floors_aligned", "status": "PASS", "detail": "aligned"}]}),
encoding="utf-8",
)
pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False)
assert not cad_showcase.enforce_audit_gates(
pipeline,
audit,
{"audit:floors_aligend": "typo must not survive to final verification"},
)
state = json.loads((tmp_path / "state.json").read_text(encoding="utf-8"))
assert state["blocked_gates"][0]["name"] == "waiver:audit:floors_aligend"
def test_waiver_preflight_rejects_misspelled_namespace_and_extra_future_waiver(tmp_path: Path) -> None:
scope = tmp_path / "scope.json"
scope.write_text(
json.dumps(
{
"scope_version": 1,
"mode": "single",
"requested": ["main"],
"buildings": [{"id": "main", "status": "PASS", "artifacts": ["future.glb"]}],
}
),
encoding="utf-8",
)
args = cad_showcase.parser().parse_args(
[
"run",
"--dxf-dir",
str(tmp_path),
"--config",
str(tmp_path / "config.json"),
"--source-report",
str(tmp_path / "source.json"),
"--out-dir",
str(tmp_path / "out"),
"--scope-manifest",
str(scope),
"--web",
]
)
invalid = cad_showcase.preflight_waiver_targets(
args,
{"gate": {"status": "PASS"}},
{"gates": [{"name": "floors_aligned", "status": "WARN", "detail": "needs evidence"}]},
scope,
{
"audti:floors_aligned": "misspelled namespace",
"browser:smoke": "cannot pre-waive a generated PASS check",
},
)
assert {check["name"] for check in invalid} == {
"waiver:audti:floors_aligned",
"waiver:browser:smoke",
}
def test_default_cap_buffer_is_small_and_large_overhang_is_explicit() -> None:
pytest.importorskip("shapely")
base_floor = {
"name": "一层",
"z": 0.0,
"height": 3.0,
"bounds": [0.0, 0.0, 10.0, 10.0],
"source_file": "fixture.dxf",
"segments": {},
"footprint": {"polygons": [[[0, 0], [10, 0], [10, 10], [0, 10]]]},
}
upper_floor = {**base_floor, "name": "二层", "z": 3.0}
floors = {"F1": json.loads(json.dumps(base_floor)), "F2": json.loads(json.dumps(upper_floor))}
derive_showcase_spec.compute_caps(floors, {})
default_max_x = max(point[0] for polygon in floors["F1"]["caps"][0]["polygons"] for point in polygon)
assert default_max_x == pytest.approx(10.1)
floors = {"F1": json.loads(json.dumps(base_floor)), "F2": json.loads(json.dumps(upper_floor))}
derive_showcase_spec.compute_caps(floors, {"cap_buffer": 1.3})
colonnade_max_x = max(point[0] for polygon in floors["F1"]["caps"][0]["polygons"] for point in polygon)
assert colonnade_max_x == pytest.approx(11.3)
def test_pipeline_fails_on_derive_geometry_loss_warning(tmp_path: Path) -> None:
pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False)
command = [
sys.executable,
"-c",
"import sys; print('WARNING isolated_cluster F1: dropped geometry', file=sys.stderr)",
]
with pytest.raises(SystemExit):
pipeline.run("derive", command, [], forbidden_stderr=cad_showcase.DERIVE_FORBIDDEN_WARNINGS)
state = json.loads((tmp_path / "state.json").read_text(encoding="utf-8"))
assert state["steps"]["derive"]["status"] == "FAIL"
assert state["steps"]["derive"]["forbidden_stderr_hits"] == ["WARNING isolated_cluster"]
def test_windows_command_resolution_uses_cmd_shims(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(cad_showcase.sys, "platform", "win32")
monkeypatch.setattr(
cad_showcase.shutil,
"which",
lambda candidate: f"C:/tools/{candidate}" if candidate in {"npm.cmd", "node.exe"} else None,
)
assert cad_showcase.npm_command("install")[0] == "C:/tools/npm.cmd"
assert cad_showcase.node_script(Path("smoke.mjs"))[0] == "C:/tools/node.exe"
def test_resume_fingerprint_tracks_tools_offline_libs_and_extra_inputs(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
root = tmp_path / "skill"
scripts = root / "scripts"
dxf_dir = tmp_path / "dxf"
for directory in (
scripts,
root / "schemas",
root / "tools",
root / "assets" / "web-showcase-template",
root / "assets" / "offline-viewer-libs",
dxf_dir,
):
directory.mkdir(parents=True, exist_ok=True)
config = tmp_path / "config.json"
source = tmp_path / "source.json"
frames = tmp_path / "frames.json"
config.write_text("{}", encoding="utf-8")
source.write_text("{}", encoding="utf-8")
frames.write_text("{}", encoding="utf-8")
(dxf_dir / "plan.dxf").write_text("DXF", encoding="utf-8")
(scripts / "step.py").write_text("pass", encoding="utf-8")
compressor = root / "tools" / "compress.mjs"
compressor.write_text("v1", encoding="utf-8")
offline_lib = root / "assets" / "offline-viewer-libs" / "three.min.js"
offline_lib.write_text("v1", encoding="utf-8")
monkeypatch.setattr(cad_showcase, "ROOT", root)
monkeypatch.setattr(cad_showcase, "SCRIPTS", scripts)
first = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
compressor.write_text("v2", encoding="utf-8")
second = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
offline_lib.write_text("v2", encoding="utf-8")
third = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
frames.write_text('{"changed": true}', encoding="utf-8")
fourth = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
assert len({first, second, third, fourth}) == 4
def test_pipeline_state_is_atomic_and_corruption_is_loud(tmp_path: Path) -> None:
state = tmp_path / "pipeline_state.json"
pipeline = cad_showcase.Pipeline(state, "fingerprint", resume=False)
pipeline.state["proof"] = "saved"
pipeline.save()
assert json.loads(state.read_text(encoding="utf-8"))["proof"] == "saved"
assert not list(tmp_path.glob(".pipeline_state.json.*.tmp"))
state.write_text("{truncated", encoding="utf-8")
with pytest.raises(SystemExit, match="corrupt and was not overwritten"):
cad_showcase.Pipeline(state, "fingerprint", resume=True)
assert state.read_text(encoding="utf-8") == "{truncated"
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_normalize_spec_backfills_categories_used_by_legacy_segments() -> None:
legacy = minimal_spec()
legacy.pop("schema_version")
legacy.pop("categories")
legacy["floors"]["F1"]["segments"]["legacy_custom"] = [
{"start": [0, 0], "end": [0, 1], "width": 0.1, "layer": "OLD", "source_type": "LINE"}
]
normalized = showcase_schema.normalize_spec(legacy)
assert normalized["categories"]["walls"] == {"label": "墙体", "color": "#d4cbb8"}
assert normalized["categories"]["slab"] == {"label": "楼板", "color": "#c8ccc2"}
assert normalized["categories"]["legacy_custom"] == {"label": "legacy_custom", "color": "#8c9088"}
showcase_schema.validate_spec(normalized)
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_showcase.py"),
"inspect",
"--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_showcase.py"),
"inspect",
"--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"
scope_manifest = tmp_path / "scope_manifest.json"
scope_manifest.write_text(
json.dumps(
{
"scope_version": 1,
"mode": "single",
"requested": ["orchestrator-test"],
"buildings": [
{
"id": "orchestrator-test",
"status": "PASS",
"artifacts": [str(out / "building_spec.json")],
}
],
}
),
encoding="utf-8",
)
command = [
sys.executable,
str(ROOT / "scripts" / "cad_showcase.py"),
"run",
"--dxf-dir",
str(dxf_dir),
"--config",
str(config_path),
"--source-report",
str(source_report),
"--scope-manifest",
str(scope_manifest),
"--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