mirror of
https://github.com/IfcOpenShell/IfcOpenShell.git
synced 2026-08-12 02:23:34 +00:00
Add ifcquery CLI tool for IFC model interrogation (#7845)
ifcquery is a new command-line tool for querying and inspecting IFC models. All output is JSON.
Subcommands:
summary — schema version, entity counts, project metadata
tree — full spatial hierarchy (Project → Site → Building → Storeys → Spaces → Elements)
info <id> — deep inspection of any entity by step ID (attributes, psets, placement matrix, type, material)
select <query> — filter elements using ifcopenshell selector syntax
relations <id> — relationships for an element; --traverse up walks to IfcProject
clash <id> — geometric intersection and clearance detection
validate — schema/constraint validation; --rules adds EXPRESS checks
schedule — work schedules with nested task trees
cost — cost schedules with nested cost item trees
schema <class> — IFC class documentation from the model's schema version
plot — SVG plan drawing
render — 3D geometry rendering
contexts — geometric representation contexts
materials — material assignments
Usage:
python3 -m ifcquery <file.ifc> <subcommand> [args]
Generated with the assistance of an AI coding tool.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
@@ -0,0 +1,36 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.aggregate
|
||||
import ifcopenshell.api.owner.settings
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.spatial
|
||||
import ifcopenshell.api.unit
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def model():
|
||||
"""Create an IFC4 model with a spatial hierarchy and a wall."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
site = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSite", name="TestSite")
|
||||
building = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuilding", name="TestBuilding")
|
||||
storey = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="Ground Floor")
|
||||
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[site], relating_object=project)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[building], relating_object=site)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[storey], relating_object=building)
|
||||
|
||||
wall = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall001")
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall], relating_structure=storey)
|
||||
|
||||
slab = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSlab", name="Slab001")
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[slab], relating_structure=storey)
|
||||
|
||||
return f
|
||||
@@ -0,0 +1,330 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.aggregate
|
||||
import ifcopenshell.api.context
|
||||
import ifcopenshell.api.geometry
|
||||
import ifcopenshell.api.owner.settings
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.spatial
|
||||
import ifcopenshell.api.unit
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from ifcquery.clash import clash
|
||||
|
||||
try:
|
||||
import ifcopenshell.geom
|
||||
|
||||
HAS_GEOM = True
|
||||
except ImportError:
|
||||
HAS_GEOM = False
|
||||
|
||||
pytestmark = pytest.mark.skipif(not HAS_GEOM, reason="ifcopenshell geometry engine not available")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def model_with_geometry():
|
||||
"""Create an IFC4 model with walls that have geometric representations."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
site = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSite", name="TestSite")
|
||||
building = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuilding", name="TestBuilding")
|
||||
storey = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="Ground Floor")
|
||||
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[site], relating_object=project)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[building], relating_object=site)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[storey], relating_object=building)
|
||||
|
||||
# Create geometry context
|
||||
model_ctx = ifcopenshell.api.context.add_context(f, context_type="Model")
|
||||
body = ifcopenshell.api.context.add_context(
|
||||
f, context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model_ctx
|
||||
)
|
||||
|
||||
# Wall 1 at origin
|
||||
wall1 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall001")
|
||||
rep1 = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall1, representation=rep1)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall1], relating_structure=storey)
|
||||
|
||||
# Wall 2 perpendicular, crossing through wall 1
|
||||
wall2 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall002")
|
||||
rep2 = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall2, representation=rep2)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall2], relating_structure=storey)
|
||||
matrix2 = np.array([[0, -1, 0, 2.5], [1, 0, 0, -2.0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=float)
|
||||
ifcopenshell.api.geometry.edit_object_placement(f, product=wall2, matrix=matrix2)
|
||||
|
||||
# Wall 3 far away (10m offset in Y)
|
||||
wall3 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall003")
|
||||
rep3 = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall3, representation=rep3)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall3], relating_structure=storey)
|
||||
matrix3 = np.eye(4)
|
||||
matrix3[1, 3] = 10.0 # 10m in Y direction
|
||||
ifcopenshell.api.geometry.edit_object_placement(f, product=wall3, matrix=matrix3)
|
||||
|
||||
# Wall 4 close but not overlapping (0.3m offset in Y, wall thickness is 0.2m)
|
||||
wall4 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall004")
|
||||
rep4 = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall4, representation=rep4)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall4], relating_structure=storey)
|
||||
matrix4 = np.eye(4)
|
||||
matrix4[1, 3] = 0.3 # 0.3m in Y (gap of 0.1m from wall1)
|
||||
ifcopenshell.api.geometry.edit_object_placement(f, product=wall4, matrix=matrix4)
|
||||
|
||||
return f
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def model_two_storeys():
|
||||
"""Create a model with walls in different storeys."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
site = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSite", name="TestSite")
|
||||
building = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuilding", name="TestBuilding")
|
||||
storey1 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="Ground Floor")
|
||||
storey2 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="First Floor")
|
||||
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[site], relating_object=project)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[building], relating_object=site)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[storey1, storey2], relating_object=building)
|
||||
|
||||
model_ctx = ifcopenshell.api.context.add_context(f, context_type="Model")
|
||||
body = ifcopenshell.api.context.add_context(
|
||||
f, context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model_ctx
|
||||
)
|
||||
|
||||
# Wall in storey 1
|
||||
wall1 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="GroundWall")
|
||||
rep1 = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall1, representation=rep1)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall1], relating_structure=storey1)
|
||||
|
||||
# Wall in storey 2, perpendicular and crossing wall1
|
||||
wall2 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="FirstFloorWall")
|
||||
rep2 = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall2, representation=rep2)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall2], relating_structure=storey2)
|
||||
matrix2 = np.array([[0, -1, 0, 2.5], [1, 0, 0, -2.0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=float)
|
||||
ifcopenshell.api.geometry.edit_object_placement(f, product=wall2, matrix=matrix2)
|
||||
|
||||
return f
|
||||
|
||||
|
||||
class TestNoClashes:
|
||||
def test_no_clashes_far_apart(self, model_with_geometry):
|
||||
wall3 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall003")
|
||||
result = clash(model_with_geometry, wall3)
|
||||
assert result["pass"] is True
|
||||
assert result["checks"]["intersection"]["pass"] is True
|
||||
assert result["checks"]["intersection"]["clashes"] == []
|
||||
|
||||
def test_no_clashes_empty_scope(self, model_with_geometry):
|
||||
"""A model where the element is the only one in scope should pass."""
|
||||
# Create a model with a single wall
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="P")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
site = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSite", name="S")
|
||||
building = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuilding", name="B")
|
||||
storey = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="GF")
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[site], relating_object=project)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[building], relating_object=site)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[storey], relating_object=building)
|
||||
model_ctx = ifcopenshell.api.context.add_context(f, context_type="Model")
|
||||
body = ifcopenshell.api.context.add_context(
|
||||
f, context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model_ctx
|
||||
)
|
||||
wall = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="OnlyWall")
|
||||
rep = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall, representation=rep)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall], relating_structure=storey)
|
||||
|
||||
result = clash(f, wall)
|
||||
assert result["pass"] is True
|
||||
|
||||
|
||||
class TestIntersectionDetected:
|
||||
def test_overlapping_walls(self, model_with_geometry):
|
||||
wall1 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall001")
|
||||
result = clash(model_with_geometry, wall1)
|
||||
assert result["pass"] is False
|
||||
assert result["checks"]["intersection"]["pass"] is False
|
||||
clashes = result["checks"]["intersection"]["clashes"]
|
||||
assert len(clashes) > 0
|
||||
# Wall002 should be in the clashes (it overlaps wall1)
|
||||
clash_ids = {c["element"]["id"] for c in clashes}
|
||||
wall2 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall002")
|
||||
assert wall2.id() in clash_ids
|
||||
|
||||
def test_clash_has_points(self, model_with_geometry):
|
||||
wall1 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall001")
|
||||
result = clash(model_with_geometry, wall1)
|
||||
clashes = result["checks"]["intersection"]["clashes"]
|
||||
for c in clashes:
|
||||
assert "p1" in c
|
||||
assert "p2" in c
|
||||
assert len(c["p1"]) == 3
|
||||
assert len(c["p2"]) == 3
|
||||
assert "type" in c
|
||||
assert "distance" in c
|
||||
|
||||
|
||||
class TestClearance:
|
||||
def test_clearance_violation(self, model_with_geometry):
|
||||
"""Wall004 is 0.1m from wall1; clearance of 0.5m should fail."""
|
||||
wall1 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall001")
|
||||
result = clash(model_with_geometry, wall1, clearance=0.5)
|
||||
assert "clearance" in result["checks"]
|
||||
# Wall004 should violate clearance
|
||||
clearance_clashes = result["checks"]["clearance"]["clashes"]
|
||||
clash_ids = {c["element"]["id"] for c in clearance_clashes}
|
||||
wall4 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall004")
|
||||
assert wall4.id() in clash_ids
|
||||
assert result["checks"]["clearance"]["pass"] is False
|
||||
|
||||
def test_clearance_pass(self, model_with_geometry):
|
||||
"""Wall003 is 10m away; clearance of 0.5m should pass for wall003."""
|
||||
wall3 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall003")
|
||||
result = clash(model_with_geometry, wall3, clearance=0.5)
|
||||
assert result["checks"]["clearance"]["pass"] is True
|
||||
assert result["checks"]["clearance"]["clashes"] == []
|
||||
|
||||
def test_clearance_not_included_by_default(self, model_with_geometry):
|
||||
wall1 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall001")
|
||||
result = clash(model_with_geometry, wall1)
|
||||
assert "clearance" not in result["checks"]
|
||||
|
||||
|
||||
class TestScope:
|
||||
def test_scope_storey_excludes_other_storeys(self, model_two_storeys):
|
||||
wall1 = next(w for w in model_two_storeys.by_type("IfcWall") if w.Name == "GroundWall")
|
||||
result = clash(model_two_storeys, wall1, scope="storey")
|
||||
assert result["scope"] == "storey"
|
||||
# No clashes because the overlapping wall is in a different storey
|
||||
assert result["pass"] is True
|
||||
|
||||
def test_scope_all_includes_other_storeys(self, model_two_storeys):
|
||||
wall1 = next(w for w in model_two_storeys.by_type("IfcWall") if w.Name == "GroundWall")
|
||||
result = clash(model_two_storeys, wall1, scope="all")
|
||||
assert result["scope"] == "all"
|
||||
# Should detect clash with the other-storey wall
|
||||
assert result["pass"] is False
|
||||
clash_ids = {c["element"]["id"] for c in result["checks"]["intersection"]["clashes"]}
|
||||
wall2 = next(w for w in model_two_storeys.by_type("IfcWall") if w.Name == "FirstFloorWall")
|
||||
assert wall2.id() in clash_ids
|
||||
|
||||
|
||||
class TestNoGeometry:
|
||||
def test_no_geometry_error(self, model):
|
||||
"""Element without geometry reports error."""
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = clash(model, wall)
|
||||
assert result["pass"] is None
|
||||
assert "error" in result
|
||||
assert "No geometry" in result["error"]
|
||||
|
||||
|
||||
class TestJsonSerializable:
|
||||
def test_result_serializable(self, model_with_geometry):
|
||||
wall1 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall001")
|
||||
result = clash(model_with_geometry, wall1)
|
||||
serialized = json.dumps(result)
|
||||
parsed = json.loads(serialized)
|
||||
assert parsed["element"]["type"] == "IfcWall"
|
||||
|
||||
def test_clearance_result_serializable(self, model_with_geometry):
|
||||
wall1 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall001")
|
||||
result = clash(model_with_geometry, wall1, clearance=0.5)
|
||||
serialized = json.dumps(result)
|
||||
parsed = json.loads(serialized)
|
||||
assert "clearance" in parsed["checks"]
|
||||
|
||||
|
||||
class TestCLI:
|
||||
@staticmethod
|
||||
def _ifc_path(model):
|
||||
f = tempfile.NamedTemporaryFile(suffix=".ifc", delete=False)
|
||||
model.write(f.name)
|
||||
f.close()
|
||||
return f.name
|
||||
|
||||
def test_clash_json(self, model_with_geometry):
|
||||
path = self._ifc_path(model_with_geometry)
|
||||
try:
|
||||
wall1 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall001")
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", path, "clash", str(wall1.id())],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0
|
||||
data = json.loads(result.stdout)
|
||||
assert data["element"]["type"] == "IfcWall"
|
||||
assert "checks" in data
|
||||
assert "intersection" in data["checks"]
|
||||
finally:
|
||||
os.unlink(path)
|
||||
|
||||
def test_clash_with_clearance(self, model_with_geometry):
|
||||
path = self._ifc_path(model_with_geometry)
|
||||
try:
|
||||
wall1 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall001")
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", path, "clash", str(wall1.id()), "--clearance", "0.5"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0
|
||||
data = json.loads(result.stdout)
|
||||
assert "clearance" in data["checks"]
|
||||
finally:
|
||||
os.unlink(path)
|
||||
|
||||
def test_clash_scope_all(self, model_with_geometry):
|
||||
path = self._ifc_path(model_with_geometry)
|
||||
try:
|
||||
wall1 = next(w for w in model_with_geometry.by_type("IfcWall") if w.Name == "Wall001")
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", path, "clash", str(wall1.id()), "--scope", "all"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0
|
||||
data = json.loads(result.stdout)
|
||||
assert data["scope"] == "all"
|
||||
finally:
|
||||
os.unlink(path)
|
||||
|
||||
def test_clash_bad_id(self, model_with_geometry):
|
||||
path = self._ifc_path(model_with_geometry)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", path, "clash", "999999"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode != 0
|
||||
assert "Error" in result.stderr
|
||||
finally:
|
||||
os.unlink(path)
|
||||
@@ -0,0 +1,52 @@
|
||||
import ifcopenshell.api.context
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.unit
|
||||
|
||||
from ifcquery.contexts import contexts
|
||||
|
||||
|
||||
class TestContexts:
|
||||
def test_empty_model(self):
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
result = contexts(f)
|
||||
assert isinstance(result, list)
|
||||
assert len(result) == 0
|
||||
|
||||
def test_model_context(self, model):
|
||||
import ifcopenshell.api.context
|
||||
|
||||
ifcopenshell.api.context.add_context(model, context_type="Model")
|
||||
result = contexts(model)
|
||||
assert len(result) == 1
|
||||
entry = result[0]
|
||||
assert entry["type"] == "IfcGeometricRepresentationContext"
|
||||
assert entry["context_type"] == "Model"
|
||||
assert "id" in entry
|
||||
assert "context_identifier" in entry
|
||||
|
||||
def test_subcontext(self, model):
|
||||
import ifcopenshell.api.context
|
||||
|
||||
model_ctx = ifcopenshell.api.context.add_context(model, context_type="Model")
|
||||
ifcopenshell.api.context.add_context(
|
||||
model,
|
||||
context_type="Model",
|
||||
context_identifier="Body",
|
||||
target_view="MODEL_VIEW",
|
||||
parent=model_ctx,
|
||||
)
|
||||
result = contexts(model)
|
||||
assert len(result) == 2
|
||||
subctx = next(e for e in result if e["type"] == "IfcGeometricRepresentationSubContext")
|
||||
assert subctx["context_identifier"] == "Body"
|
||||
assert subctx["target_view"] == "MODEL_VIEW"
|
||||
assert subctx["parent_context_id"] == model_ctx.id()
|
||||
|
||||
def test_ids_are_integers(self, model):
|
||||
import ifcopenshell.api.context
|
||||
|
||||
ifcopenshell.api.context.add_context(model, context_type="Model")
|
||||
result = contexts(model)
|
||||
for entry in result:
|
||||
assert isinstance(entry["id"], int)
|
||||
@@ -0,0 +1,108 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.cost
|
||||
import ifcopenshell.api.owner.settings
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.unit
|
||||
import pytest
|
||||
|
||||
from ifcquery.cost import cost
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cost_model():
|
||||
"""Create an IFC4 model with a cost schedule, a top-level item, and one nested subitem."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
cs = ifcopenshell.api.cost.add_cost_schedule(f, name="Bill of Quantities")
|
||||
item = ifcopenshell.api.cost.add_cost_item(f, cost_schedule=cs)
|
||||
ifcopenshell.api.cost.edit_cost_item(f, cost_item=item, attributes={"Name": "Concrete Works"})
|
||||
cv = ifcopenshell.api.cost.add_cost_value(f, parent=item)
|
||||
ifcopenshell.api.cost.edit_cost_value(f, cost_value=cv, attributes={"AppliedValue": 1200.0, "Category": "material"})
|
||||
|
||||
# Add a nested subitem
|
||||
subitem = ifcopenshell.api.cost.add_cost_item(f, cost_item=item)
|
||||
ifcopenshell.api.cost.edit_cost_item(f, cost_item=subitem, attributes={"Name": "Formwork"})
|
||||
|
||||
return f
|
||||
|
||||
|
||||
class TestCost:
|
||||
def test_returns_list(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert isinstance(result, list)
|
||||
|
||||
def test_finds_cost_schedule(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_schedule_has_name(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert result[0]["name"] == "Bill of Quantities"
|
||||
|
||||
def test_schedule_has_id(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert isinstance(result[0]["id"], int)
|
||||
assert result[0]["id"] > 0
|
||||
|
||||
def test_schedule_has_items(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert len(result[0]["items"]) == 1
|
||||
|
||||
def test_item_has_required_fields(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
item = result[0]["items"][0]
|
||||
assert "id" in item
|
||||
assert "name" in item
|
||||
assert "values" in item
|
||||
assert "subitems" in item
|
||||
|
||||
def test_item_name(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert result[0]["items"][0]["name"] == "Concrete Works"
|
||||
|
||||
def test_item_has_values(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
values = result[0]["items"][0]["values"]
|
||||
assert len(values) == 1
|
||||
assert "formula" in values[0]
|
||||
assert "category" in values[0]
|
||||
|
||||
def test_item_value_category(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
values = result[0]["items"][0]["values"]
|
||||
assert values[0]["category"] == "material"
|
||||
|
||||
def test_empty_model_returns_empty_list(self, model):
|
||||
result = cost(model)
|
||||
assert result == []
|
||||
|
||||
def test_max_depth_none_returns_full_tree(self, cost_model):
|
||||
result = cost(cost_model, max_depth=None)
|
||||
item = result[0]["items"][0]
|
||||
assert isinstance(item["subitems"], list)
|
||||
assert len(item["subitems"]) == 1
|
||||
assert item["subitems"][0]["name"] == "Formwork"
|
||||
|
||||
def test_max_depth_1_truncates_subitems(self, cost_model):
|
||||
result = cost(cost_model, max_depth=1)
|
||||
item = result[0]["items"][0]
|
||||
assert isinstance(item["subitems"], dict)
|
||||
assert item["subitems"]["truncated"] is True
|
||||
assert item["subitems"]["count"] == 1
|
||||
|
||||
def test_max_depth_2_expands_to_depth_2(self, cost_model):
|
||||
result = cost(cost_model, max_depth=2)
|
||||
item = result[0]["items"][0]
|
||||
assert isinstance(item["subitems"], list)
|
||||
assert item["subitems"][0]["name"] == "Formwork"
|
||||
# subitem has no children, so subitems should be empty list
|
||||
assert item["subitems"][0]["subitems"] == []
|
||||
@@ -0,0 +1,112 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.context
|
||||
import ifcopenshell.api.geometry
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.unit
|
||||
import ifcopenshell.util.representation
|
||||
import ifcopenshell.util.shape_builder
|
||||
|
||||
from ifcquery.info import info
|
||||
|
||||
|
||||
class TestInfo:
|
||||
def test_basic_attributes(self, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = info(model, wall)
|
||||
assert result["id"] == wall.id()
|
||||
assert result["type"] == "IfcWall"
|
||||
assert result["attributes"]["Name"] == "Wall001"
|
||||
|
||||
def test_container(self, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = info(model, wall)
|
||||
assert result["container"]["type"] == "IfcBuildingStorey"
|
||||
assert result["container"]["name"] == "Ground Floor"
|
||||
|
||||
def test_project_info(self, model):
|
||||
project = model.by_type("IfcProject")[0]
|
||||
result = info(model, project)
|
||||
assert result["type"] == "IfcProject"
|
||||
assert result["attributes"]["Name"] == "TestProject"
|
||||
|
||||
def test_all_attributes_serializable(self, model):
|
||||
"""All attribute values should be JSON-serializable (no entity instances)."""
|
||||
import json
|
||||
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = info(model, wall)
|
||||
# Should not raise
|
||||
json.dumps(result)
|
||||
|
||||
def test_no_geometry_summary_without_representation(self, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = info(model, wall)
|
||||
assert "geometry_summary" not in result
|
||||
|
||||
|
||||
class TestGeometrySummary:
|
||||
def _make_model_with_wall(self):
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
model_ctx = ifcopenshell.api.context.add_context(f, context_type="Model")
|
||||
ifcopenshell.api.context.add_context(
|
||||
f,
|
||||
context_type="Model",
|
||||
context_identifier="Body",
|
||||
target_view="MODEL_VIEW",
|
||||
parent=model_ctx,
|
||||
)
|
||||
wall = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="W1")
|
||||
ifcopenshell.api.geometry.edit_object_placement(f, product=wall)
|
||||
return f, wall
|
||||
|
||||
def _body_context(self, f):
|
||||
return ifcopenshell.util.representation.get_context(f, "Model", "Body", "MODEL_VIEW")
|
||||
|
||||
def test_swept_solid_summary(self):
|
||||
f, wall = self._make_model_with_wall()
|
||||
body = self._body_context(f)
|
||||
rep = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5.0, height=3.0, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall, representation=rep)
|
||||
result = info(f, wall)
|
||||
gs = result["geometry_summary"]
|
||||
assert gs["representation_type"] == "SweptSolid"
|
||||
assert len(gs["solids"]) == 1
|
||||
solid = gs["solids"][0]
|
||||
assert solid["depth"] == 3000.0 # stored in project units (mm)
|
||||
assert solid["profile"]["type"] == "IfcArbitraryClosedProfileDef"
|
||||
assert len(solid["profile"]["points"]) == 5 # closed polyline
|
||||
|
||||
def test_clipping_summary(self):
|
||||
f, wall = self._make_model_with_wall()
|
||||
body = self._body_context(f)
|
||||
rep = ifcopenshell.api.geometry.add_wall_representation(
|
||||
f,
|
||||
context=body,
|
||||
length=5.0,
|
||||
height=4.0,
|
||||
thickness=0.2,
|
||||
clippings=[{"location": (0.0, 0.0, 3.0), "normal": (0.0, 0.0, 1.0)}],
|
||||
)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall, representation=rep)
|
||||
result = info(f, wall)
|
||||
gs = result["geometry_summary"]
|
||||
assert gs["representation_type"] == "Clipping"
|
||||
solid = gs["solids"][0]
|
||||
assert len(solid["clipping_planes"]) == 1
|
||||
plane = solid["clipping_planes"][0]
|
||||
assert plane["location"][2] == 3000.0 # stored in project units (mm)
|
||||
assert plane["normal"] == [0.0, 0.0, 1.0]
|
||||
|
||||
def test_geometry_summary_json_serializable(self):
|
||||
import json
|
||||
|
||||
f, wall = self._make_model_with_wall()
|
||||
body = self._body_context(f)
|
||||
rep = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5.0, height=3.0, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall, representation=rep)
|
||||
result = info(f, wall)
|
||||
json.dumps(result)
|
||||
@@ -0,0 +1,84 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.project
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ifc_path(model):
|
||||
"""Write the model fixture to a temp file and return its path."""
|
||||
with tempfile.NamedTemporaryFile(suffix=".ifc", delete=False) as f:
|
||||
model.write(f.name)
|
||||
yield f.name
|
||||
os.unlink(f.name)
|
||||
|
||||
|
||||
def run_ifcquery(*args):
|
||||
"""Run ifcquery as a subprocess and return (returncode, stdout, stderr)."""
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
return result.returncode, result.stdout, result.stderr
|
||||
|
||||
|
||||
class TestCLI:
|
||||
def test_summary_json(self, ifc_path):
|
||||
rc, stdout, stderr = run_ifcquery(ifc_path, "summary")
|
||||
assert rc == 0
|
||||
data = json.loads(stdout)
|
||||
assert data["schema"] == "IFC4"
|
||||
assert "types" in data
|
||||
|
||||
def test_tree_json(self, ifc_path):
|
||||
rc, stdout, stderr = run_ifcquery(ifc_path, "tree")
|
||||
assert rc == 0
|
||||
data = json.loads(stdout)
|
||||
assert data["type"] == "IfcProject"
|
||||
|
||||
def test_info_json(self, ifc_path, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
rc, stdout, stderr = run_ifcquery(ifc_path, "info", str(wall.id()))
|
||||
assert rc == 0
|
||||
data = json.loads(stdout)
|
||||
assert data["type"] == "IfcWall"
|
||||
|
||||
def test_info_hash_id(self, ifc_path, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
rc, stdout, stderr = run_ifcquery(ifc_path, "info", f"#{wall.id()}")
|
||||
assert rc == 0
|
||||
data = json.loads(stdout)
|
||||
assert data["type"] == "IfcWall"
|
||||
|
||||
def test_select_json(self, ifc_path):
|
||||
rc, stdout, stderr = run_ifcquery(ifc_path, "select", "IfcWall")
|
||||
assert rc == 0
|
||||
data = json.loads(stdout)
|
||||
assert len(data) == 1
|
||||
assert data[0]["type"] == "IfcWall"
|
||||
|
||||
def test_text_format(self, ifc_path):
|
||||
rc, stdout, stderr = run_ifcquery(ifc_path, "--format", "text", "summary")
|
||||
assert rc == 0
|
||||
assert "schema:" in stdout
|
||||
|
||||
def test_bad_file(self):
|
||||
rc, stdout, stderr = run_ifcquery("/nonexistent.ifc", "summary")
|
||||
assert rc != 0
|
||||
assert "Error" in stderr
|
||||
|
||||
def test_bad_element_id(self, ifc_path):
|
||||
rc, stdout, stderr = run_ifcquery(ifc_path, "info", "999999")
|
||||
assert rc != 0
|
||||
assert "Error" in stderr
|
||||
|
||||
def test_no_command(self, ifc_path):
|
||||
rc, stdout, stderr = run_ifcquery(ifc_path)
|
||||
assert rc != 0
|
||||
@@ -0,0 +1,52 @@
|
||||
import ifcopenshell.api.material
|
||||
import ifcopenshell.api.project
|
||||
|
||||
from ifcquery.materials import materials
|
||||
|
||||
|
||||
class TestMaterials:
|
||||
def test_empty_model(self, model):
|
||||
result = materials(model)
|
||||
assert isinstance(result, list)
|
||||
assert len(result) == 0
|
||||
|
||||
def test_single_material(self, model):
|
||||
ifcopenshell.api.material.add_material(model, name="Concrete", category="concrete")
|
||||
result = materials(model)
|
||||
assert len(result) == 1
|
||||
m = result[0]
|
||||
assert m["type"] == "IfcMaterial"
|
||||
assert m["name"] == "Concrete"
|
||||
assert m["category"] == "concrete"
|
||||
assert isinstance(m["id"], int)
|
||||
|
||||
def test_material_layer_set(self, model):
|
||||
mat = ifcopenshell.api.material.add_material(model, name="Brick")
|
||||
layer_set = ifcopenshell.api.material.add_material_set(model, name="BrickSet", set_type="IfcMaterialLayerSet")
|
||||
ifcopenshell.api.material.add_layer(model, layer_set=layer_set, material=mat)
|
||||
result = materials(model)
|
||||
layer_sets = [e for e in result if e["type"] == "IfcMaterialLayerSet"]
|
||||
assert len(layer_sets) == 1
|
||||
ls = layer_sets[0]
|
||||
assert ls["name"] == "BrickSet"
|
||||
assert isinstance(ls["layers"], list)
|
||||
assert len(ls["layers"]) == 1
|
||||
layer = ls["layers"][0]
|
||||
assert layer["material"] == "Brick"
|
||||
|
||||
def test_material_constituent_set(self, model):
|
||||
mat = ifcopenshell.api.material.add_material(model, name="Steel")
|
||||
cs = ifcopenshell.api.material.add_material_set(model, name="CompSet", set_type="IfcMaterialConstituentSet")
|
||||
ifcopenshell.api.material.add_constituent(model, constituent_set=cs, material=mat)
|
||||
result = materials(model)
|
||||
constituent_sets = [e for e in result if e["type"] == "IfcMaterialConstituentSet"]
|
||||
assert len(constituent_sets) == 1
|
||||
entry = constituent_sets[0]
|
||||
assert entry["name"] == "CompSet"
|
||||
assert isinstance(entry["constituents"], list)
|
||||
|
||||
def test_ids_are_integers(self, model):
|
||||
ifcopenshell.api.material.add_material(model, name="Wood")
|
||||
result = materials(model)
|
||||
for entry in result:
|
||||
assert isinstance(entry["id"], int)
|
||||
@@ -0,0 +1,265 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.aggregate
|
||||
import ifcopenshell.api.context
|
||||
import ifcopenshell.api.geometry
|
||||
import ifcopenshell.api.owner.settings
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.spatial
|
||||
import ifcopenshell.api.unit
|
||||
import pytest
|
||||
|
||||
from ifcquery.plot import _highlight_css_from_ids, plot
|
||||
|
||||
try:
|
||||
import ifcopenshell.draw # noqa: F401
|
||||
|
||||
HAS_DRAW = True
|
||||
except ImportError:
|
||||
HAS_DRAW = False
|
||||
|
||||
try:
|
||||
import cairosvg # noqa: F401
|
||||
|
||||
HAS_CAIROSVG = True
|
||||
except ImportError:
|
||||
HAS_CAIROSVG = False
|
||||
|
||||
pytestmark = pytest.mark.skipif(not HAS_DRAW, reason="ifcopenshell.draw not available")
|
||||
|
||||
SVG_MAGIC = b"<?xml"
|
||||
PNG_MAGIC = b"\x89PNG"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def model_with_annotations():
|
||||
"""IFC4 model with walls and explicit 2D annotation geometry (Plan/PLAN_VIEW context)."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
site = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSite", name="TestSite")
|
||||
building = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuilding", name="TestBuilding")
|
||||
storey = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="Ground Floor")
|
||||
storey.Elevation = 0.0 # required for setSectionHeightsFromStoreys() to create a cut plane
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[site], relating_object=project)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[building], relating_object=site)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[storey], relating_object=building)
|
||||
|
||||
model_ctx = ifcopenshell.api.context.add_context(f, context_type="Model")
|
||||
body = ifcopenshell.api.context.add_context(
|
||||
f, context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model_ctx
|
||||
)
|
||||
|
||||
wall = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall001")
|
||||
rep = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall, representation=rep)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall], relating_structure=storey)
|
||||
|
||||
return f, wall
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def model_no_plan(model_with_annotations):
|
||||
"""Model whose SVG output will be empty (wall geometry only, no plan annotation group)."""
|
||||
return model_with_annotations
|
||||
|
||||
|
||||
class TestHighlightCSS:
|
||||
def test_css_for_valid_element(self, model_with_annotations):
|
||||
model, wall = model_with_annotations
|
||||
css = _highlight_css_from_ids(model, [wall.id()])
|
||||
assert wall.GlobalId in css
|
||||
assert "opacity: 0.10" in css
|
||||
assert "opacity: 1.0" in css
|
||||
assert "#d00" in css
|
||||
|
||||
def test_css_empty_for_no_ids(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
css = _highlight_css_from_ids(model, [])
|
||||
assert css == ""
|
||||
|
||||
def test_css_skips_unknown_ids(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
css = _highlight_css_from_ids(model, [999999])
|
||||
assert css == ""
|
||||
|
||||
|
||||
class TestPlotSVG:
|
||||
def test_returns_svg_bytes(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
result = plot(model, output_format="svg")
|
||||
assert isinstance(result, bytes)
|
||||
assert result[:5] == SVG_MAGIC
|
||||
|
||||
def test_svg_contains_xml(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
result = plot(model, output_format="svg")
|
||||
assert b"<svg" in result
|
||||
|
||||
def test_invalid_format_raises(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
with pytest.raises(ValueError, match="output_format"):
|
||||
plot(model, output_format="xyz")
|
||||
|
||||
def test_invalid_view_raises(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
with pytest.raises(ValueError, match="view"):
|
||||
plot(model, output_format="svg", view="bogus")
|
||||
|
||||
def test_selector_no_match_raises(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
with pytest.raises(ValueError, match="matched no elements"):
|
||||
plot(model, output_format="svg", selector="IfcDoor")
|
||||
|
||||
def test_selector_filters_elements(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
result = plot(model, output_format="svg", selector="IfcWall")
|
||||
assert isinstance(result, bytes)
|
||||
assert b"<svg" in result
|
||||
|
||||
|
||||
class TestPlotEmptySVG:
|
||||
"""When draw produces no <g> elements, PNG/base64 should raise a clear error."""
|
||||
|
||||
def test_empty_drawing_png_raises(self, model_no_plan):
|
||||
"""PNG format raises ValueError (not silently returns None) for empty drawings."""
|
||||
model, _ = model_no_plan
|
||||
svg = plot(model, output_format="svg")
|
||||
has_groups = b"<g " in svg or b"<g>" in svg
|
||||
if not has_groups:
|
||||
pytest.raises(ValueError, plot, model, output_format="png")
|
||||
else:
|
||||
pytest.skip("Model produced non-empty SVG — empty path not triggered")
|
||||
|
||||
def test_empty_drawing_base64_raises(self, model_no_plan):
|
||||
"""base64 format raises ValueError (not silently returns None) for empty drawings."""
|
||||
model, _ = model_no_plan
|
||||
svg = plot(model, output_format="svg")
|
||||
has_groups = b"<g " in svg or b"<g>" in svg
|
||||
if not has_groups:
|
||||
pytest.raises(ValueError, plot, model, output_format="base64")
|
||||
else:
|
||||
pytest.skip("Model produced non-empty SVG — empty path not triggered")
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_CAIROSVG, reason="cairosvg not installed")
|
||||
class TestPlotPNG:
|
||||
"""PNG and base64 require cairosvg."""
|
||||
|
||||
def test_png_returns_bytes_or_raises_on_empty(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
svg = plot(model, output_format="svg")
|
||||
has_groups = b"<g " in svg or b"<g>" in svg
|
||||
if has_groups:
|
||||
result = plot(model, output_format="png")
|
||||
assert isinstance(result, bytes)
|
||||
assert result[:4] == PNG_MAGIC
|
||||
else:
|
||||
with pytest.raises(ValueError, match="No plan geometry"):
|
||||
plot(model, output_format="png")
|
||||
|
||||
def test_base64_returns_dict(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
svg = plot(model, output_format="svg")
|
||||
has_groups = b"<g " in svg or b"<g>" in svg
|
||||
if has_groups:
|
||||
result = plot(model, output_format="base64")
|
||||
assert isinstance(result, dict)
|
||||
assert result["mime"] == "image/png"
|
||||
assert "png_b64" in result
|
||||
assert "width" in result
|
||||
assert "height" in result
|
||||
assert "view" in result
|
||||
# Verify the base64 is valid PNG
|
||||
decoded = base64.b64decode(result["png_b64"])
|
||||
assert decoded[:4] == PNG_MAGIC
|
||||
else:
|
||||
with pytest.raises(ValueError, match="No plan geometry"):
|
||||
plot(model, output_format="base64")
|
||||
|
||||
def test_base64_view_field_matches_requested(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
svg = plot(model, output_format="svg")
|
||||
has_groups = b"<g " in svg or b"<g>" in svg
|
||||
if not has_groups:
|
||||
pytest.skip("Model produces empty SVG")
|
||||
result = plot(model, output_format="base64", view="floorplan")
|
||||
assert result["view"] == "floorplan"
|
||||
|
||||
def test_png_custom_size(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
svg = plot(model, output_format="svg")
|
||||
has_groups = b"<g " in svg or b"<g>" in svg
|
||||
if not has_groups:
|
||||
pytest.skip("Model produces empty SVG")
|
||||
result = plot(model, output_format="png", png_width=512, png_height=512)
|
||||
assert isinstance(result, bytes)
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
|
||||
class TestCLI:
|
||||
@staticmethod
|
||||
def _ifc_path(model):
|
||||
f = tempfile.NamedTemporaryFile(suffix=".ifc", delete=False)
|
||||
model.write(f.name)
|
||||
f.close()
|
||||
return f.name
|
||||
|
||||
def test_plot_svg_writes_file(self, model_with_annotations):
|
||||
model, _ = model_with_annotations
|
||||
ifc_path = self._ifc_path(model)
|
||||
out_path = ifc_path.replace(".ifc", "_out.svg")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", ifc_path, "plot", "--out-format", "svg", "-o", out_path],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert os.path.exists(out_path)
|
||||
with open(out_path, "rb") as f:
|
||||
assert f.read(5) == SVG_MAGIC
|
||||
finally:
|
||||
for path in (ifc_path, out_path):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
@pytest.mark.skipif(not HAS_CAIROSVG, reason="cairosvg not installed")
|
||||
def test_plot_base64_prints_json(self, model_with_annotations):
|
||||
"""base64 format prints JSON to stdout instead of writing a file."""
|
||||
model, _ = model_with_annotations
|
||||
ifc_path = self._ifc_path(model)
|
||||
try:
|
||||
# First check if the model would produce geometry
|
||||
svg = plot(model, output_format="svg")
|
||||
has_groups = b"<g " in svg or b"<g>" in svg
|
||||
if not has_groups:
|
||||
pytest.skip("Model produces empty SVG — base64 would raise ValueError")
|
||||
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", ifc_path, "plot", "--out-format", "base64"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
# Output should be JSON (not an error) and contain base64 key
|
||||
assert "png_b64" in result.stdout
|
||||
finally:
|
||||
try:
|
||||
os.unlink(ifc_path)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -0,0 +1,158 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from ifcquery.relations import relations
|
||||
|
||||
|
||||
class TestWallRelations:
|
||||
def test_wall_has_container(self, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = relations(model, wall)
|
||||
assert result["id"] == wall.id()
|
||||
assert result["type"] == "IfcWall"
|
||||
assert result["hierarchy"]["container"]["type"] == "IfcBuildingStorey"
|
||||
assert result["hierarchy"]["container"]["name"] == "Ground Floor"
|
||||
|
||||
def test_wall_has_parent(self, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = relations(model, wall)
|
||||
assert result["hierarchy"]["parent"]["type"] == "IfcBuildingStorey"
|
||||
|
||||
def test_wall_no_children(self, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = relations(model, wall)
|
||||
assert "children" not in result
|
||||
|
||||
def test_wall_empty_categories_omitted(self, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = relations(model, wall)
|
||||
assert "groups" not in result
|
||||
assert "systems" not in result
|
||||
assert "zones" not in result
|
||||
assert "connections" not in result
|
||||
assert "referenced_structures" not in result
|
||||
|
||||
|
||||
class TestStoreyRelations:
|
||||
def test_storey_has_contained(self, model):
|
||||
storey = model.by_type("IfcBuildingStorey")[0]
|
||||
result = relations(model, storey)
|
||||
contained_types = {e["type"] for e in result["children"]["contained"]}
|
||||
assert "IfcWall" in contained_types
|
||||
assert "IfcSlab" in contained_types
|
||||
|
||||
def test_storey_has_aggregate_parent(self, model):
|
||||
storey = model.by_type("IfcBuildingStorey")[0]
|
||||
result = relations(model, storey)
|
||||
assert result["hierarchy"]["aggregate"]["type"] == "IfcBuilding"
|
||||
assert result["hierarchy"]["aggregate"]["name"] == "TestBuilding"
|
||||
|
||||
|
||||
class TestProjectRelations:
|
||||
def test_project_has_parts(self, model):
|
||||
project = model.by_type("IfcProject")[0]
|
||||
result = relations(model, project)
|
||||
parts = result["children"]["parts"]
|
||||
assert any(p["type"] == "IfcSite" for p in parts)
|
||||
|
||||
def test_project_no_hierarchy(self, model):
|
||||
project = model.by_type("IfcProject")[0]
|
||||
result = relations(model, project)
|
||||
assert "hierarchy" not in result
|
||||
|
||||
|
||||
class TestTraverseUp:
|
||||
def test_wall_to_project(self, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
chain = relations(model, wall, traverse="up")
|
||||
assert isinstance(chain, list)
|
||||
assert chain[0]["type"] == "IfcWall"
|
||||
assert chain[-1]["type"] == "IfcProject"
|
||||
types = [e["type"] for e in chain]
|
||||
assert "IfcBuildingStorey" in types
|
||||
assert "IfcBuilding" in types
|
||||
assert "IfcSite" in types
|
||||
|
||||
def test_project_traverse(self, model):
|
||||
project = model.by_type("IfcProject")[0]
|
||||
chain = relations(model, project, traverse="up")
|
||||
assert len(chain) == 1
|
||||
assert chain[0]["type"] == "IfcProject"
|
||||
|
||||
def test_storey_to_project(self, model):
|
||||
storey = model.by_type("IfcBuildingStorey")[0]
|
||||
chain = relations(model, storey, traverse="up")
|
||||
assert chain[0]["type"] == "IfcBuildingStorey"
|
||||
assert chain[-1]["type"] == "IfcProject"
|
||||
assert len(chain) == 4 # storey -> building -> site -> project
|
||||
|
||||
|
||||
class TestJsonSerializable:
|
||||
def test_relations_serializable(self, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = relations(model, wall)
|
||||
json.dumps(result)
|
||||
|
||||
def test_traverse_serializable(self, model):
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = relations(model, wall, traverse="up")
|
||||
json.dumps(result)
|
||||
|
||||
|
||||
class TestCLI:
|
||||
@staticmethod
|
||||
def _ifc_path(model):
|
||||
f = tempfile.NamedTemporaryFile(suffix=".ifc", delete=False)
|
||||
model.write(f.name)
|
||||
f.close()
|
||||
return f.name
|
||||
|
||||
def test_relations_json(self, model):
|
||||
path = self._ifc_path(model)
|
||||
try:
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", path, "relations", str(wall.id())],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0
|
||||
data = json.loads(result.stdout)
|
||||
assert data["type"] == "IfcWall"
|
||||
assert "hierarchy" in data
|
||||
finally:
|
||||
os.unlink(path)
|
||||
|
||||
def test_relations_traverse_up(self, model):
|
||||
path = self._ifc_path(model)
|
||||
try:
|
||||
wall = model.by_type("IfcWall")[0]
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", path, "relations", str(wall.id()), "--traverse", "up"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0
|
||||
data = json.loads(result.stdout)
|
||||
assert isinstance(data, list)
|
||||
assert data[0]["type"] == "IfcWall"
|
||||
assert data[-1]["type"] == "IfcProject"
|
||||
finally:
|
||||
os.unlink(path)
|
||||
|
||||
def test_relations_bad_id(self, model):
|
||||
path = self._ifc_path(model)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", path, "relations", "999999"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode != 0
|
||||
assert "Error" in result.stderr
|
||||
finally:
|
||||
os.unlink(path)
|
||||
@@ -0,0 +1,355 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.aggregate
|
||||
import ifcopenshell.api.context
|
||||
import ifcopenshell.api.geometry
|
||||
import ifcopenshell.api.owner.settings
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.spatial
|
||||
import ifcopenshell.api.unit
|
||||
import ifcopenshell.guid
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from ifcquery.render import _make_profile_occurrence, _make_type_occurrence, render
|
||||
|
||||
try:
|
||||
import pyvista # noqa: F401
|
||||
|
||||
HAS_PYVISTA = True
|
||||
except ImportError:
|
||||
HAS_PYVISTA = False
|
||||
|
||||
pytestmark = pytest.mark.skipif(not HAS_PYVISTA, reason="pyvista not installed")
|
||||
|
||||
PNG_MAGIC = b"\x89PNG"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def model_with_geometry():
|
||||
"""Create an IFC4 model with walls that have geometric representations."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
site = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSite", name="TestSite")
|
||||
building = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuilding", name="TestBuilding")
|
||||
storey = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="Ground Floor")
|
||||
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[site], relating_object=project)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[building], relating_object=site)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[storey], relating_object=building)
|
||||
|
||||
model_ctx = ifcopenshell.api.context.add_context(f, context_type="Model")
|
||||
body = ifcopenshell.api.context.add_context(
|
||||
f, context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model_ctx
|
||||
)
|
||||
|
||||
wall1 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall001")
|
||||
rep1 = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall1, representation=rep1)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall1], relating_structure=storey)
|
||||
|
||||
wall2 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall002")
|
||||
rep2 = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=4, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall2, representation=rep2)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall2], relating_structure=storey)
|
||||
matrix2 = np.eye(4)
|
||||
matrix2[1, 3] = 3.0
|
||||
ifcopenshell.api.geometry.edit_object_placement(f, product=wall2, matrix=matrix2)
|
||||
|
||||
return f
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def library_with_type():
|
||||
"""IFC4 library file: a WallType with a RepresentationMap but no instances."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="LibProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
model_ctx = ifcopenshell.api.context.add_context(f, context_type="Model")
|
||||
body = ifcopenshell.api.context.add_context(
|
||||
f, context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model_ctx
|
||||
)
|
||||
|
||||
# Build the shape representation and wrap it in an IfcRepresentationMap.
|
||||
shape_rep = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=3, height=2.5, thickness=0.2)
|
||||
origin = f.create_entity("IfcCartesianPoint", Coordinates=(0.0, 0.0, 0.0))
|
||||
z_dir = f.create_entity("IfcDirection", DirectionRatios=(0.0, 0.0, 1.0))
|
||||
x_dir = f.create_entity("IfcDirection", DirectionRatios=(1.0, 0.0, 0.0))
|
||||
map_origin = f.create_entity("IfcAxis2Placement3D", Location=origin, Axis=z_dir, RefDirection=x_dir)
|
||||
rep_map = f.create_entity("IfcRepresentationMap", MappingOrigin=map_origin, MappedRepresentation=shape_rep)
|
||||
|
||||
wall_type = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWallType", name="LibWallType")
|
||||
wall_type.RepresentationMaps = [rep_map]
|
||||
|
||||
return f, wall_type
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def library_with_profile_type():
|
||||
"""IFC4 library: a BeamType with an IfcMaterialProfileSet but no RepresentationMaps."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="ProfileLibProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
model_ctx = ifcopenshell.api.context.add_context(f, context_type="Model")
|
||||
ifcopenshell.api.context.add_context(
|
||||
f, context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model_ctx
|
||||
)
|
||||
|
||||
# Rectangular profile 0.2m x 0.3m
|
||||
profile = f.create_entity(
|
||||
"IfcRectangleProfileDef",
|
||||
ProfileType="AREA",
|
||||
ProfileName="200x300",
|
||||
XDim=0.2,
|
||||
YDim=0.3,
|
||||
)
|
||||
material = f.create_entity("IfcMaterial", Name="Steel")
|
||||
mat_profile = f.create_entity("IfcMaterialProfile", Material=material, Profile=profile)
|
||||
profile_set = f.create_entity("IfcMaterialProfileSet", MaterialProfiles=[mat_profile])
|
||||
|
||||
beam_type = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBeamType", name="200x300 Steel Beam")
|
||||
rel = f.create_entity(
|
||||
"IfcRelAssociatesMaterial",
|
||||
GlobalId=ifcopenshell.guid.new(),
|
||||
RelatedObjects=[beam_type],
|
||||
RelatingMaterial=profile_set,
|
||||
)
|
||||
|
||||
return f, beam_type
|
||||
|
||||
|
||||
class TestRenderBasic:
|
||||
def test_returns_png_bytes(self, model_with_geometry):
|
||||
result = render(model_with_geometry)
|
||||
assert isinstance(result, bytes)
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_iso_view(self, model_with_geometry):
|
||||
result = render(model_with_geometry, view="iso")
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_top_view(self, model_with_geometry):
|
||||
result = render(model_with_geometry, view="top")
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_south_view(self, model_with_geometry):
|
||||
result = render(model_with_geometry, view="south")
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_unknown_view_falls_back_to_iso(self, model_with_geometry):
|
||||
# Unknown view strings fall through to isometric
|
||||
result = render(model_with_geometry, view="diagonal")
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
|
||||
class TestRenderSelector:
|
||||
def test_selector_restricts_elements(self, model_with_geometry):
|
||||
result = render(model_with_geometry, selector="IfcWall")
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_selector_no_match_raises(self, model_with_geometry):
|
||||
with pytest.raises(ValueError, match="matched no elements"):
|
||||
render(model_with_geometry, selector="IfcDoor")
|
||||
|
||||
|
||||
class TestRenderHighlight:
|
||||
def test_highlight_single_element(self, model_with_geometry):
|
||||
wall = model_with_geometry.by_type("IfcWall")[0]
|
||||
result = render(model_with_geometry, element_ids=[wall.id()])
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_highlight_multiple_elements(self, model_with_geometry):
|
||||
walls = model_with_geometry.by_type("IfcWall")
|
||||
result = render(model_with_geometry, element_ids=[w.id() for w in walls])
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
|
||||
class TestRenderTypes:
|
||||
def test_render_type_by_selector(self, library_with_type):
|
||||
"""Selecting a type class renders its RepresentationMap geometry."""
|
||||
model, wall_type = library_with_type
|
||||
result = render(model, selector="IfcWallType")
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_render_type_by_element_id(self, library_with_type):
|
||||
"""Passing a type step-ID via element_ids renders it highlighted."""
|
||||
model, wall_type = library_with_type
|
||||
result = render(model, element_ids=[wall_type.id()])
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_original_model_unmodified(self, library_with_type):
|
||||
"""Rendering a type must not add entities to the original model."""
|
||||
model, wall_type = library_with_type
|
||||
entity_count_before = len(list(model))
|
||||
render(model, selector="IfcWallType")
|
||||
assert len(list(model)) == entity_count_before
|
||||
|
||||
def test_make_type_occurrence_no_rep_maps(self, library_with_type):
|
||||
"""_make_type_occurrence returns None for a type with no RepresentationMaps."""
|
||||
model, _ = library_with_type
|
||||
bare_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWallType", name="Bare")
|
||||
assert _make_type_occurrence(model, bare_type) is None
|
||||
|
||||
def test_type_without_rep_maps_raises(self):
|
||||
"""Selecting a type that has no RepresentationMaps raises ValueError."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="P")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
ifcopenshell.api.root.create_entity(f, ifc_class="IfcWallType", name="Bare")
|
||||
with pytest.raises(ValueError):
|
||||
render(f, selector="IfcWallType")
|
||||
|
||||
|
||||
class TestRenderProfileTypes:
|
||||
def test_render_profile_type_by_element_id(self, library_with_profile_type):
|
||||
"""A type with only a material profile set renders via temporary extrusion."""
|
||||
model, beam_type = library_with_profile_type
|
||||
result = render(model, element_ids=[beam_type.id()])
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_make_profile_occurrence_creates_occurrence(self, library_with_profile_type):
|
||||
"""_make_profile_occurrence returns an occurrence entity for a profile-set type."""
|
||||
model, beam_type = library_with_profile_type
|
||||
occ = _make_profile_occurrence(model, beam_type)
|
||||
assert occ is not None
|
||||
|
||||
def test_make_profile_occurrence_no_profile_returns_none(self, library_with_type):
|
||||
"""_make_profile_occurrence returns None when type has no material profile set."""
|
||||
model, wall_type = library_with_type
|
||||
# wall_type has RepresentationMaps but no material profile set
|
||||
occ = _make_profile_occurrence(model, wall_type)
|
||||
assert occ is None
|
||||
|
||||
def test_original_model_unmodified_for_profile_type(self, library_with_profile_type):
|
||||
"""Rendering a profile-based type does not modify the original model."""
|
||||
model, beam_type = library_with_profile_type
|
||||
entity_count_before = len(list(model))
|
||||
render(model, element_ids=[beam_type.id()])
|
||||
assert len(list(model)) == entity_count_before
|
||||
|
||||
|
||||
class TestRenderNoGeometry:
|
||||
def test_no_geometry_raises(self):
|
||||
"""A model without geometry representations raises ValueError."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="P")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
site = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSite", name="S")
|
||||
building = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuilding", name="B")
|
||||
storey = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="GF")
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[site], relating_object=project)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[building], relating_object=site)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[storey], relating_object=building)
|
||||
wall = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wallless")
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall], relating_structure=storey)
|
||||
|
||||
with pytest.raises(ValueError, match="No renderable geometry"):
|
||||
render(f)
|
||||
|
||||
|
||||
class TestCLI:
|
||||
@staticmethod
|
||||
def _ifc_path(model):
|
||||
f = tempfile.NamedTemporaryFile(suffix=".ifc", delete=False)
|
||||
model.write(f.name)
|
||||
f.close()
|
||||
return f.name
|
||||
|
||||
def test_render_writes_png(self, model_with_geometry):
|
||||
ifc_path = self._ifc_path(model_with_geometry)
|
||||
out_path = ifc_path.replace(".ifc", "_out.png")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", ifc_path, "render", "-o", out_path],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert os.path.exists(out_path)
|
||||
with open(out_path, "rb") as f:
|
||||
assert f.read(4) == PNG_MAGIC
|
||||
finally:
|
||||
for path in (ifc_path, out_path):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_render_default_output_path(self, model_with_geometry):
|
||||
ifc_path = self._ifc_path(model_with_geometry)
|
||||
expected_png = ifc_path.replace(".ifc", ".png")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", ifc_path, "render"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert os.path.exists(expected_png)
|
||||
finally:
|
||||
for path in (ifc_path, expected_png):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_render_with_selector(self, model_with_geometry):
|
||||
ifc_path = self._ifc_path(model_with_geometry)
|
||||
out_path = ifc_path.replace(".ifc", "_sel.png")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", ifc_path, "render", "-o", out_path, "--selector", "IfcWall"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
with open(out_path, "rb") as f:
|
||||
assert f.read(4) == PNG_MAGIC
|
||||
finally:
|
||||
for path in (ifc_path, out_path):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_render_with_view(self, model_with_geometry):
|
||||
ifc_path = self._ifc_path(model_with_geometry)
|
||||
out_path = ifc_path.replace(".ifc", "_top.png")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", ifc_path, "render", "-o", out_path, "--view", "top"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
with open(out_path, "rb") as f:
|
||||
assert f.read(4) == PNG_MAGIC
|
||||
finally:
|
||||
for path in (ifc_path, out_path):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -0,0 +1,121 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.aggregate
|
||||
import ifcopenshell.api.owner.settings
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.sequence
|
||||
import ifcopenshell.api.unit
|
||||
import pytest
|
||||
|
||||
from ifcquery.schedule import schedule
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def schedule_model():
|
||||
"""Create an IFC4 model with a work schedule and nested tasks."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
ws = ifcopenshell.api.sequence.add_work_schedule(f, name="Construction Schedule")
|
||||
|
||||
task1 = ifcopenshell.api.sequence.add_task(f, work_schedule=ws, name="Phase 1", identification="P1")
|
||||
tt1 = ifcopenshell.api.sequence.add_task_time(f, task=task1)
|
||||
ifcopenshell.api.sequence.edit_task_time(
|
||||
f, task_time=tt1, attributes={"ScheduleStart": "2024-01-01", "ScheduleFinish": "2024-06-30"}
|
||||
)
|
||||
|
||||
task2 = ifcopenshell.api.sequence.add_task(f, work_schedule=ws, name="Phase 2", identification="P2")
|
||||
subtask = ifcopenshell.api.sequence.add_task(f, parent_task=task1, name="Sub Task", identification="S1")
|
||||
|
||||
return f
|
||||
|
||||
|
||||
class TestSchedule:
|
||||
def test_returns_list(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
assert isinstance(result, list)
|
||||
|
||||
def test_finds_work_schedule(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_work_schedule_has_name(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
assert result[0]["name"] == "Construction Schedule"
|
||||
|
||||
def test_work_schedule_has_id(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
assert isinstance(result[0]["id"], int)
|
||||
assert result[0]["id"] > 0
|
||||
|
||||
def test_work_schedule_has_tasks(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
tasks = result[0]["tasks"]
|
||||
assert isinstance(tasks, list)
|
||||
assert len(tasks) >= 1
|
||||
|
||||
def test_task_has_required_fields(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
task = result[0]["tasks"][0]
|
||||
assert "id" in task
|
||||
assert "name" in task
|
||||
assert "start" in task
|
||||
assert "finish" in task
|
||||
assert "is_milestone" in task
|
||||
assert "outputs" in task
|
||||
assert "subtasks" in task
|
||||
|
||||
def test_task_name(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
task_names = [t["name"] for t in result[0]["tasks"]]
|
||||
assert "Phase 1" in task_names
|
||||
|
||||
def test_task_start_finish(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
phase1 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 1")
|
||||
assert phase1["start"] is not None
|
||||
assert phase1["finish"] is not None
|
||||
|
||||
def test_subtasks(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
phase1 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 1")
|
||||
assert len(phase1["subtasks"]) == 1
|
||||
assert phase1["subtasks"][0]["name"] == "Sub Task"
|
||||
|
||||
def test_empty_model_returns_empty_list(self, model):
|
||||
result = schedule(model)
|
||||
assert result == []
|
||||
|
||||
def test_max_depth_none_returns_full_tree(self, schedule_model):
|
||||
result = schedule(schedule_model, max_depth=None)
|
||||
phase1 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 1")
|
||||
assert isinstance(phase1["subtasks"], list)
|
||||
assert len(phase1["subtasks"]) == 1
|
||||
|
||||
def test_max_depth_1_truncates_subtasks(self, schedule_model):
|
||||
result = schedule(schedule_model, max_depth=1)
|
||||
phase1 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 1")
|
||||
assert isinstance(phase1["subtasks"], dict)
|
||||
assert phase1["subtasks"]["truncated"] is True
|
||||
assert phase1["subtasks"]["count"] == 1
|
||||
|
||||
def test_max_depth_truncation_shows_count(self, schedule_model):
|
||||
result = schedule(schedule_model, max_depth=1)
|
||||
# Phase 2 has no subtasks — should return empty list, not truncation dict
|
||||
phase2 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 2")
|
||||
assert phase2["subtasks"] == []
|
||||
|
||||
def test_max_depth_2_expands_to_depth_2(self, schedule_model):
|
||||
result = schedule(schedule_model, max_depth=2)
|
||||
phase1 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 1")
|
||||
# subtask at depth 2 should be fully expanded (it has no children)
|
||||
assert isinstance(phase1["subtasks"], list)
|
||||
assert phase1["subtasks"][0]["name"] == "Sub Task"
|
||||
assert phase1["subtasks"][0]["subtasks"] == []
|
||||
@@ -0,0 +1,32 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from ifcquery.schema import schema
|
||||
|
||||
|
||||
class TestSchema:
|
||||
def test_ifc_wall_has_description(self, model):
|
||||
result = schema(model, "IfcWall")
|
||||
assert "description" in result
|
||||
assert isinstance(result["description"], str)
|
||||
assert len(result["description"]) > 0
|
||||
|
||||
def test_ifc_wall_has_attributes(self, model):
|
||||
result = schema(model, "IfcWall")
|
||||
assert "attributes" in result
|
||||
|
||||
def test_ifc_wall_has_spec_url(self, model):
|
||||
result = schema(model, "IfcWall")
|
||||
assert "spec_url" in result
|
||||
|
||||
def test_unknown_entity_returns_error(self, model):
|
||||
result = schema(model, "IfcNonExistentFooBar")
|
||||
assert "error" in result
|
||||
assert "IfcNonExistentFooBar" in result["error"]
|
||||
|
||||
def test_ifc_window_has_description(self, model):
|
||||
result = schema(model, "IfcWindow")
|
||||
assert "description" in result
|
||||
assert len(result["description"]) > 0
|
||||
@@ -0,0 +1,32 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from ifcquery.select import select
|
||||
|
||||
|
||||
class TestSelect:
|
||||
def test_select_by_type(self, model):
|
||||
result = select(model, "IfcWall")
|
||||
assert len(result) == 1
|
||||
assert result[0]["type"] == "IfcWall"
|
||||
assert result[0]["name"] == "Wall001"
|
||||
|
||||
def test_select_multiple_types(self, model):
|
||||
result = select(model, "IfcWall, IfcSlab")
|
||||
assert len(result) == 2
|
||||
types = {r["type"] for r in result}
|
||||
assert types == {"IfcWall", "IfcSlab"}
|
||||
|
||||
def test_select_no_match(self, model):
|
||||
result = select(model, "IfcDoor")
|
||||
assert result == []
|
||||
|
||||
def test_results_sorted_by_id(self, model):
|
||||
result = select(model, "IfcWall, IfcSlab")
|
||||
ids = [r["id"] for r in result]
|
||||
assert ids == sorted(ids)
|
||||
|
||||
def test_result_has_id_type_name(self, model):
|
||||
result = select(model, "IfcWall")
|
||||
entry = result[0]
|
||||
assert "id" in entry
|
||||
assert "type" in entry
|
||||
assert "name" in entry
|
||||
@@ -0,0 +1,34 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.project
|
||||
|
||||
from ifcquery.summary import summary
|
||||
|
||||
|
||||
class TestSummary:
|
||||
def test_schema(self, model):
|
||||
result = summary(model)
|
||||
assert result["schema"] == "IFC4"
|
||||
|
||||
def test_total_entities(self, model):
|
||||
result = summary(model)
|
||||
assert result["total_entities"] == len(list(model))
|
||||
assert result["total_entities"] > 0
|
||||
|
||||
def test_project_info(self, model):
|
||||
result = summary(model)
|
||||
assert result["project"]["name"] == "TestProject"
|
||||
|
||||
def test_type_counts(self, model):
|
||||
result = summary(model)
|
||||
types = result["types"]
|
||||
assert "IfcWall" in types
|
||||
assert types["IfcWall"] == 1
|
||||
assert "IfcSlab" in types
|
||||
assert types["IfcSlab"] == 1
|
||||
|
||||
def test_empty_model(self):
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
result = summary(f)
|
||||
assert result["schema"] == "IFC4"
|
||||
assert "project" not in result
|
||||
@@ -0,0 +1,37 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from ifcquery.tree import tree
|
||||
|
||||
|
||||
class TestTree:
|
||||
def test_root_is_project(self, model):
|
||||
result = tree(model)
|
||||
assert result["type"] == "IfcProject"
|
||||
assert result["name"] == "TestProject"
|
||||
|
||||
def test_spatial_hierarchy(self, model):
|
||||
result = tree(model)
|
||||
# Project > Site > Building > Storey
|
||||
site = result["children"][0]
|
||||
assert site["type"] == "IfcSite"
|
||||
assert site["name"] == "TestSite"
|
||||
|
||||
building = site["children"][0]
|
||||
assert building["type"] == "IfcBuilding"
|
||||
assert building["name"] == "TestBuilding"
|
||||
|
||||
storey = building["children"][0]
|
||||
assert storey["type"] == "IfcBuildingStorey"
|
||||
assert storey["name"] == "Ground Floor"
|
||||
|
||||
def test_contained_elements(self, model):
|
||||
result = tree(model)
|
||||
storey = result["children"][0]["children"][0]["children"][0]
|
||||
elements = storey["elements"]
|
||||
element_types = {e["type"] for e in elements}
|
||||
assert "IfcWall" in element_types
|
||||
assert "IfcSlab" in element_types
|
||||
|
||||
def test_element_ids_present(self, model):
|
||||
result = tree(model)
|
||||
assert "id" in result
|
||||
assert isinstance(result["id"], int)
|
||||
@@ -0,0 +1,47 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.project
|
||||
import pytest
|
||||
|
||||
from ifcquery.validate import validate
|
||||
|
||||
|
||||
class TestValidate:
|
||||
def test_valid_model_returns_valid_true(self, model):
|
||||
result = validate(model)
|
||||
assert result["valid"] is True
|
||||
assert isinstance(result["issues"], list)
|
||||
|
||||
def test_valid_model_has_no_issues(self, model):
|
||||
result = validate(model)
|
||||
assert result["issues"] == []
|
||||
|
||||
def test_empty_model_is_valid(self):
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
result = validate(f)
|
||||
assert result["valid"] is True
|
||||
assert result["issues"] == []
|
||||
|
||||
def test_result_has_expected_keys(self, model):
|
||||
result = validate(model)
|
||||
assert "valid" in result
|
||||
assert "issues" in result
|
||||
|
||||
def test_express_rules_flag_accepted(self, model):
|
||||
# Just verify it runs without error; express rules may add/not add issues
|
||||
result = validate(model, express_rules=True)
|
||||
assert "valid" in result
|
||||
assert isinstance(result["issues"], list)
|
||||
|
||||
def test_issue_has_level_and_message(self, model):
|
||||
# Force an issue by manually breaking the model (invalid IfcWall attribute)
|
||||
f = ifcopenshell.file()
|
||||
# Create a raw IfcWall with deliberately wrong type for GlobalId (use int)
|
||||
# We just check structure if any issues appear; on well-formed models there are none.
|
||||
result = validate(model)
|
||||
# Even if no issues, the structure contract must hold for any issues present
|
||||
for issue in result["issues"]:
|
||||
assert "level" in issue
|
||||
assert "message" in issue
|
||||
Reference in New Issue
Block a user