Debian Codegraph @

src/bonsai/test/bim/test_feature.py

raw
1 # Bonsai - OpenBIM Blender Add-on
2 # Copyright (C) 2021 Dion Moult <[email protected]>
3 #
4 # This file is part of Bonsai.
5 #
6 # Bonsai is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Bonsai is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
18
19 import os
20 import bpy
21 import pytest
22 import traceback
23 import webbrowser
24 import numpy as np
25 import ifcopenshell
26 import ifcopenshell.util.element
27 import ifcopenshell.util.representation
28 import bonsai.tool as tool
29 import bonsai.bim.handler
30 from bonsai.bim.ifc import IfcStore
31 from bonsai.tool.brick import BrickStore
32 from bonsai.bim.module.model.data import AuthoringData
33 from pytest_bdd import scenarios, given, when, then, parsers
34 from mathutils import Vector
35 from math import radians
36 from pathlib import Path
37 from typing import Union, Any
38
39 scenarios("feature")
40
41 variables = {
42 "cwd": Path.cwd().as_posix(),
43 "ifc": "tool.Ifc.get()",
44 "pset_ifc": "IfcStore.pset_template_file",
45 "classification_ifc": "IfcStore.classification_file",
46 }
47
48 # Monkey-patch webbrowser opening since we want to test headlessly
49 webbrowser.open = lambda x: True
50
51
52 class PanelSpy:
53 def __init__(self, panel: type[bpy.types.Panel]):
54 self.is_spy_dirty = True
55 self.panel = panel
56
57 def refresh_spy(self):
58 if self.is_spy_dirty:
59 self.is_spy_dirty = False
60 self.spied_attr: Union[str, None] = None
61 self.spied_labels: list[str] = []
62 self.spied_props: list[dict[str, Any]] = []
63 self.spied_operators: list[dict[str, Any]] = []
64 self.spied_lists: list[dict[str, Any]] = []
65 self.panel.draw(self, bpy.context)
66
67 def __getattr__(self, attr):
68 self.spied_attr = attr
69 if annotation := self.panel.__annotations__.get(attr, None):
70 return annotation.keywords.get("default", None) # An operator property
71 if attr == "layout":
72 return self
73 return self
74
75 def __call__(self, *args, **kwargs):
76 if self.spied_attr in ("row", "column", "box", "separator", "menu", "operator_menu_enum"):
77 return self
78 elif self.spied_attr == "template_list":
79 listtype_name, list_id, dataptr, propname, active_dataptr, active_propname = args
80 spied_data = {
81 "listtype_name": listtype_name,
82 "list_id": list_id,
83 "dataptr": dataptr,
84 "propname": propname,
85 "active_dataptr": active_dataptr,
86 "active_propname": active_propname,
87 }
88 self.spied_lists.append(spied_data)
89 return TemplateListSpy(spied_data)
90 elif self.spied_attr == "context_pointer_set":
91 return lambda *args, **kwargs: None
92 elif self.spied_attr == "label":
93 self.spied_labels.append(kwargs["text"])
94 return self
95 elif self.spied_attr == "prop":
96 props, name = args
97 props: bpy.types.bpy_struct
98 text = kwargs.get("text", props.bl_rna.properties[name].name)
99 icon = kwargs.get("icon", None)
100 prop_type = props.bl_rna.properties[name].type
101 enum_items = []
102 if prop_type == "ENUM":
103 prop_keywords = props.__annotations__[name].keywords
104 items = prop_keywords.get("items")
105 if items is not None:
106 if isinstance(items, (list, tuple)):
107 enum_items = items
108 else:
109 # items are retrieved through a callback, not a static list / tuple :
110 enum_items = items(props, bpy.context)
111 value = getattr(props, name)
112 if text:
113 self.spied_labels.append(text)
114 spied_prop = {
115 "props": props,
116 "name": name,
117 "text": text,
118 "icon": icon,
119 "value": value,
120 "prop_type": prop_type,
121 "enum_items": enum_items,
122 }
123 self.spied_props.append(spied_prop)
124 elif self.spied_attr == "operator":
125 operator = args[0]
126 prefix, op_name = operator.split(".")
127 operator = getattr(getattr(bpy.ops, prefix), op_name)
128 bl_idname = operator.idname()
129 try:
130 bl_label = getattr(bpy.types, bl_idname).bl_label
131 except: # Doesn't work on built-ins, I don't know what to do
132 bl_label = bl_idname
133 text = kwargs.get("text", bl_label)
134 icon = kwargs.get("icon", None)
135 if text:
136 self.spied_labels.append(text)
137 spied_operator = {"operator": operator, "icon": icon, "text": text, "kwargs": {}}
138 self.spied_operators.append(spied_operator)
139 return OperatorSpy(spied_operator)
140 else:
141 getattr(self.panel, self.spied_attr)(self, *args, **kwargs)
142
143
144 class OperatorSpy:
145 def __init__(self, spied_data):
146 self.spied_data = spied_data
147
148 def __setattr__(self, name, value):
149 if name == "spied_data":
150 # Allow direct setting of spied_data only during initialization
151 super().__setattr__(name, value)
152 else:
153 self.spied_data["kwargs"][name] = value
154
155
156 class TemplateListSpy:
157 def __init__(self, spied_data):
158 self.spied_data = spied_data
159
160
161 ui_name_cache = {}
162 panel_spy: PanelSpy = None
163
164
165 def create_ui_name_cache():
166 global ui_name_cache
167 if ui_name_cache:
168 return
169 for bl_idname in dir(bpy.types):
170 try:
171 panel_type = getattr(bpy.types, bl_idname)
172 if panel_type.bl_rna.base.name == "Panel":
173 ui_name_cache[panel_type.bl_label] = panel_type.bl_idname
174 elif panel_type.bl_rna.base.name == "Operator":
175 ui_name_cache[panel_type.bl_label] = bl_idname
176 elif panel_type.bl_rna.base.name == "Menu":
177 if panel_type.bl_label == "Add" and bl_idname != "VIEW3D_MT_add":
178 continue # Non-unique, but "VIEW3D_MT_add" is the one we care about
179 ui_name_cache[panel_type.bl_label] = bl_idname
180 except:
181 pass
182
183
184 def replace_variables(value):
185 for key, new_value in variables.items():
186 value = value.replace("{" + key + "}", str(new_value))
187 return value
188
189
190 def is_x(number, x):
191 return abs(number - x) < 1e-5
192
193
194 def vectors_are_equal(v1, v2):
195 assert len(v1) == len(v2), f"Compared vectors are not equal length: {v1}, {v2}"
196 return all(is_x(v1[i], v2[i]) for i in range(len(v1)))
197
198
199 @given("an untestable scenario")
200 def an_untestable_scenario():
201 pass
202
203
204 @given("an empty Blender session")
205 @when("an empty Blender session is started")
206 def an_empty_blender_session():
207 IfcStore.purge()
208 bpy.ops.wm.read_homefile(app_template="")
209 if len(bpy.data.objects) > 0:
210 bpy.data.batch_remove(bpy.data.objects)
211 bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
212 if len(bpy.data.materials) > 0:
213 bpy.data.batch_remove(bpy.data.materials)
214
215 # default project settings
216 bpy.context.scene.unit_settings.system = "METRIC"
217 bpy.context.scene.unit_settings.length_unit = "MILLIMETERS"
218 props = tool.Project.get_project_props()
219 props.template_file = "0"
220 tool.Blender.get_addon_preferences().should_play_chaching_sound = False
221
222
223 @given("an empty IFC project")
224 def an_empty_ifc_project():
225 an_empty_blender_session()
226 bpy.ops.bim.create_project()
227
228
229 @given("an empty IFC2X3 project")
230 def an_empty_ifc_2x3_project():
231 an_empty_blender_session()
232 props = tool.Project.get_project_props()
233 props.export_schema = "IFC2X3"
234 bpy.ops.bim.create_project()
235
236
237 @given("the Brickschema is stubbed")
238 def the_brickschema_is_stubbed():
239 # This makes things run faster since we don't need to load the entire brick schema
240 cwd = os.path.dirname(os.path.realpath(__file__))
241 BrickStore.schema = os.path.join(cwd, "..", "files", "BrickStub.ttl")
242
243
244 @given(parsers.parse('I look at the "{panel}" panel'))
245 @when(parsers.parse('I look at the "{panel}" panel'))
246 @then(parsers.parse('I look at the "{panel}" panel'))
247 def i_look_at_the_panel_panel(panel):
248 global ui_name_cache
249 global panel_spy
250 create_ui_name_cache()
251 if panel not in ui_name_cache:
252 assert False, f"Panel {panel} not found in {ui_name_cache}"
253 panel_spy = PanelSpy(getattr(bpy.types, ui_name_cache[panel]))
254 panel_spy.refresh_spy()
255
256
257 @given(parsers.parse('I open the "{name}" menu'))
258 @when(parsers.parse('I open the "{name}" menu'))
259 @then(parsers.parse('I open the "{name}" menu'))
260 def i_open_the_name_menu(name):
261 global ui_name_cache
262 global panel_spy
263 create_ui_name_cache()
264 if name not in ui_name_cache:
265 assert False, f"Menu {name} not found in {ui_name_cache}"
266 panel_spy = PanelSpy(getattr(bpy.types, ui_name_cache[name]))
267 panel_spy.refresh_spy()
268
269
270 @given(parsers.parse('I trigger "{operator}"'))
271 @when(parsers.parse('I trigger "{operator}"'))
272 @then(parsers.parse('I trigger "{operator}"'))
273 def i_trigger_operator(operator):
274 global ui_name_cache
275 global panel_spy
276 create_ui_name_cache()
277 if operator not in ui_name_cache:
278 assert False, f"Operator {operator} not found in {ui_name_cache}"
279 panel_spy = PanelSpy(getattr(bpy.types, ui_name_cache[operator]))
280 panel_spy.refresh_spy()
281
282
283 @given(parsers.parse('I see "{text}"'))
284 @when(parsers.parse('I see "{text}"'))
285 @then(parsers.parse('I see "{text}"'))
286 def i_see_text(text):
287 panel_spy.refresh_spy()
288 assert [l for l in panel_spy.spied_labels if text in l], f"Text {text} not found in {panel_spy.spied_labels}"
289
290
291 @given(parsers.parse('I don\'t see "{text}"'))
292 @when(parsers.parse('I don\'t see "{text}"'))
293 @then(parsers.parse('I don\'t see "{text}"'))
294 def i_dont_see_text(text):
295 panel_spy.refresh_spy()
296 assert not [l for l in panel_spy.spied_labels if text in l], f"Text {text} found in {panel_spy.spied_labels}"
297
298
299 @given(parsers.parse('I don\'t see the "{name}" list'))
300 @when(parsers.parse('I don\'t see the "{name}" list'))
301 @then(parsers.parse('I don\'t see the "{name}" list'))
302 def i_dont_see_the_name_list(name):
303 panel_spy.refresh_spy()
304 assert name not in [l["listtype_name"] for l in panel_spy.spied_lists]
305
306
307 @given(parsers.parse('I see the "{prop}" property'))
308 @when(parsers.parse('I see the "{prop}" property'))
309 @then(parsers.parse('I see the "{prop}" property'))
310 def i_see_the_prop_property(prop):
311 panel_spy.refresh_spy()
312 assert [
313 p for p in panel_spy.spied_props if prop in (p["name"], p["text"], p["icon"])
314 ], f"Property {prop} not found in {panel_spy.spied_props}"
315
316
317 @given(parsers.parse('I don\'t see the "{prop}" property'))
318 @when(parsers.parse('I don\'t see the "{prop}" property'))
319 @then(parsers.parse('I don\'t see the "{prop}" property'))
320 def i_dont_see_the_prop_property(prop):
321 panel_spy.refresh_spy()
322 assert not [
323 p for p in panel_spy.spied_props if prop in (p["name"], p["text"], p["icon"])
324 ], f"Property {prop} not found in {panel_spy.spied_props}"
325
326
327 @given(parsers.parse('I see the "{prop}" property is "{value}"'))
328 @when(parsers.parse('I see the "{prop}" property is "{value}"'))
329 @then(parsers.parse('I see the "{prop}" property is "{value}"'))
330 def i_see_the_prop_property_is_value(prop, value):
331 panel_spy.refresh_spy()
332 for spied_prop in panel_spy.spied_props:
333 if prop in (spied_prop["name"], spied_prop["text"], spied_prop["icon"]):
334 assert (
335 spied_prop["value"] == value
336 ), f"Property {prop} value is not {value} - it is actually {spied_prop['value']}"
337 return
338 assert False, f"Property {prop} not found in {panel_spy.spied_props}"
339
340
341 @given(parsers.parse('I set the "{prop}" property to "{value}"'))
342 @when(parsers.parse('I set the "{prop}" property to "{value}"'))
343 @then(parsers.parse('I set the "{prop}" property to "{value}"'))
344 def i_set_the_prop_property_to_value(prop, value):
345 value = value.strip()
346 panel_spy.refresh_spy()
347 is_nth = False
348 if prop[0].isnumeric() and (prop.endswith("st") or prop.endswith("nd") or prop.endswith("th")):
349 is_nth = True
350 for nth, spied_prop in enumerate(panel_spy.spied_props):
351 if is_nth and nth != int(prop[:-2]) - 1:
352 continue
353 if not is_nth and prop not in (spied_prop["name"], spied_prop["text"], spied_prop["icon"]):
354 continue
355 if spied_prop["prop_type"] == "BOOLEAN":
356 if value == "TRUE":
357 setattr(spied_prop["props"], spied_prop["name"], True)
358 elif value == "FALSE":
359 setattr(spied_prop["props"], spied_prop["name"], False)
360 elif spied_prop["prop_type"] == "FLOAT":
361 setattr(spied_prop["props"], spied_prop["name"], float(value))
362 elif spied_prop["prop_type"] == "INT":
363 setattr(spied_prop["props"], spied_prop["name"], int(value))
364 elif spied_prop["prop_type"] == "ENUM":
365 enum_identifier = [i for i in spied_prop["enum_items"] if i is not None and i[1] == value]
366 if not enum_identifier:
367 assert False, f"Could not find value {value} in enum {spied_prop['enum_items']}"
368 setattr(spied_prop["props"], spied_prop["name"], enum_identifier[0][0])
369 elif spied_prop["prop_type"] == "POINTER":
370 setattr(spied_prop["props"], spied_prop["name"], bpy.data.objects.get(value))
371 else:
372 setattr(spied_prop["props"], spied_prop["name"], value)
373 panel_spy.is_spy_dirty = True
374 return
375 debug = "\n".join([f"{i} {v}" for i, v in enumerate(panel_spy.spied_props)])
376 assert False, f"Property {prop} not found in:\n{debug}"
377
378
379 @then(parsers.parse('The "{name}" list has {total} items'))
380 def the_name_list_has_total_items(name, total):
381 total = int(total)
382 panel_spy.refresh_spy()
383 for spied_list in panel_spy.spied_lists:
384 if name == spied_list["listtype_name"]:
385 actual_total = len(getattr(spied_list["dataptr"], spied_list["propname"]))
386 assert actual_total == total, f"The actual number of items in {name} is {actual_total} not {total}"
387 return
388 assert False, f"List {name} not found in {panel_spy.spied_lists}"
389
390
391 @given(parsers.parse('I select the "{item_name}" item in the "{list_name}" list'))
392 @when(parsers.parse('I select the "{item_name}" item in the "{list_name}" list'))
393 def i_select_the_item_name_item_in_the_list_name_list(item_name, list_name):
394 panel_spy.refresh_spy()
395 for spied_list in panel_spy.spied_lists:
396 if list_name == spied_list["listtype_name"]:
397 item_names = []
398 for i, item in enumerate(getattr(spied_list["dataptr"], spied_list["propname"])):
399 item_names.append(item.name)
400 if item.name == item_name:
401 setattr(spied_list["active_dataptr"], spied_list["active_propname"], i)
402 panel_spy.is_spy_dirty = True
403 return
404 assert False, f"Could not find item {item_name} in {item_names}"
405 assert False, f"List {list_name} not found in {panel_spy.spied_lists}"
406
407
408 @when("I load a new pset template file")
409 def i_load_a_new_pset_template_file():
410 props = tool.PsetTemplate.get_pset_template_props()
411 IfcStore.pset_template_path = props.pset_template_files
412 IfcStore.pset_template_file = ifcopenshell.open(IfcStore.pset_template_path)
413
414
415 @given("I create default MEP types")
416 def i_create_default_mep_types():
417 model_props = tool.Model.get_model_props()
418
419 # add couple segments types
420 i_trigger_operator("Add Element")
421 i_set_the_prop_property_to_value("Name", "RECT1")
422 i_set_the_prop_property_to_value("Class", "IfcDuctSegmentType")
423 i_set_the_prop_property_to_value("Representation", "Rectangular Distribution Segment")
424 i_click_button("OK")
425
426 i_trigger_operator("Add Element")
427 i_set_the_prop_property_to_value("Name", "CIRCLE1")
428 i_set_the_prop_property_to_value("Class", "IfcDuctSegmentType")
429 i_set_the_prop_property_to_value("Representation", "Circular Distribution Segment")
430 i_click_button("OK")
431
432 # add an actuator type
433 i_trigger_operator("Add Element")
434 i_set_the_prop_property_to_value("Name", "ACTUATOR")
435 i_set_the_prop_property_to_value("Class", "IfcActuatorType")
436 i_set_the_prop_property_to_value("Representation", "Custom Tessellation")
437 i_click_button("OK")
438
439 with bpy.context.temp_override(active_object=bpy.data.objects["IfcActuatorType/ACTUATOR"]):
440 bpy.ops.bim.add_port()
441 # port at cube's left side
442 bpy.data.objects["IfcDistributionPort/Port"].location = (-0.5, 0, 0)
443 bpy.ops.bim.hide_ports()
444
445
446 @given("I add a cube")
447 @when("I add a cube")
448 def i_add_a_cube():
449 bpy.ops.mesh.primitive_cube_add()
450
451
452 @given("I add an empty")
453 @when("I add an empty")
454 def i_add_an_empty():
455 bpy.ops.object.empty_add()
456
457
458 @given("I add a sun")
459 @when("I add a sun")
460 def i_add_a_sun():
461 bpy.ops.object.light_add(type="SUN")
462
463
464 @given("I add a material")
465 @when("I add a material")
466 def i_add_a_material():
467 bpy.context.active_object.active_material = bpy.data.materials.new("Material")
468
469
470 @given(parsers.parse('I add a new item to "{collection}"'))
471 @when(parsers.parse('I add a new item to "{collection}"'))
472 def i_add_a_new_collection_item(collection):
473 try:
474 eval(f"bpy.context.{collection}.add()")
475 except:
476 assert False, "Collection does not exist"
477
478
479 @given(parsers.parse('the material "{name}" colour is set to "{colour}"'))
480 @when(parsers.parse('the material "{name}" colour is set to "{colour}"'))
481 def the_material_name_colour_is_set_to_colour(name, colour):
482 obj = the_material_name_exists(name)
483 obj.diffuse_color = [float(c) for c in colour.split(",")]
484
485
486 @given("I add an array modifier")
487 def i_add_an_array_modifier():
488 bpy.ops.object.modifier_add(type="ARRAY")
489
490
491 @given(parsers.parse('I add a cube of size "{size}" at "{location}"'))
492 @when(parsers.parse('I add a cube of size "{size}" at "{location}"'))
493 def i_add_a_cube_of_size_size_at_location(size, location):
494 bpy.ops.mesh.primitive_cube_add(size=float(size), location=[float(co) for co in location.split(",")])
495
496
497 @given(parsers.parse('I add a plane of size "{size}" at "{location}"'))
498 @when(parsers.parse('I add a plane of size "{size}" at "{location}"'))
499 def i_add_a_plane_of_size_size_at_location(size, location):
500 bpy.ops.mesh.primitive_plane_add(size=float(size), location=[float(co) for co in location.split(",")])
501
502
503 @then(parsers.parse('I expect an error "{error_msg}" when "{function}"'))
504 def i_expect_an_error_msg_when_function(error_msg, function):
505 try:
506 exec(function)
507 except Exception as e:
508 actual_error_msg = str(e).strip()
509 if str(e).strip() != error_msg:
510 traceback.print_exc()
511 msg = f"Got different exception running {function} - '{actual_error_msg}' instead of '{error_msg}'"
512 assert False, msg
513 return
514 assert False, f"Function {function} ran without exception '{error_msg}'"
515
516
517 @then(parsers.parse('I press "{operator}" and expect error "{error_msg}"'))
518 def i_press_operator_and_expect_error(operator, error_msg):
519 operator = replace_variables(operator)
520 try:
521 if "(" in operator:
522 exec(f"bpy.ops.{operator}")
523 else:
524 exec(f"bpy.ops.{operator}()")
525 except Exception as e:
526 actual_error_msg = str(e).strip()
527 if str(e).strip() != error_msg:
528 traceback.print_exc()
529 msg = f"Got different exception running bpy.ops.{operator} - '{actual_error_msg}' instead of '{error_msg}'"
530 assert False, msg
531 return
532 assert False, f"Operator bpy.ops.{operator} ran without exception '{error_msg}'"
533
534
535 @given(parsers.parse('I press "{operator}"'))
536 @when(parsers.parse('I press "{operator}"'))
537 def i_press_operator(operator):
538 operator = replace_variables(operator)
539 try:
540 if "(" in operator:
541 exec(f"bpy.ops.{operator}")
542 else:
543 exec(f"bpy.ops.{operator}()")
544 except Exception as e:
545 traceback.print_exc()
546 assert False, f"Failed to run operator bpy.ops.{operator} because of {e}"
547
548
549 @given(parsers.parse('I click "{button}"'))
550 @when(parsers.parse('I click "{button}"'))
551 @then(parsers.parse('I click "{button}"'))
552 def i_click_button(button):
553 panel_spy.refresh_spy()
554 for spied_operator in panel_spy.spied_operators:
555 if spied_operator["text"] == button or spied_operator["icon"] == button:
556 spied_operator["operator"]("INVOKE_DEFAULT", **spied_operator["kwargs"])
557 panel_spy.is_spy_dirty = True
558 return
559 # Users can also "click" on booleans to toggle them
560 for spied_prop in panel_spy.spied_props:
561 if button in (spied_prop["name"], spied_prop["text"], spied_prop["icon"]):
562 val = getattr(spied_prop["props"], spied_prop["name"])
563 setattr(spied_prop["props"], spied_prop["name"], not bool(val))
564 return
565 if button == "OK" and panel_spy.panel.bl_rna.base.name == "Operator":
566 # Clicked confirm on an operator's draw dialog
567 return i_press_operator(panel_spy.panel.bl_idname)
568 debug = "\n".join([f"{i} {v}" for i, v in enumerate(panel_spy.spied_operators)])
569 debug += f"\nHere is the text we see: {panel_spy.spied_labels}"
570 assert False, f"Could not find {button}:\n{debug}"
571
572
573 @given(parsers.parse('I click "{button}" and expect error "{error_msg}"'))
574 @when(parsers.parse('I click "{button}" and expect error "{error_msg}"'))
575 def i_click_button_and_expect_error_error_msg(button, error_msg):
576 try:
577 i_click_button(button)
578 except Exception as e:
579 actual_error_msg = str(e).strip()
580 if str(e).strip() != error_msg:
581 traceback.print_exc()
582 msg = f"Got different exception clickign {button} - '{actual_error_msg}' instead of '{error_msg}'"
583 assert False, msg
584 return
585 assert False, f"No error message {error_msg} raised when I pressed {button}"
586
587
588 @given(parsers.parse('I evaluate expression "{expression}"'))
589 @when(parsers.parse('I evaluate expression "{expression}"'))
590 def i_evaluate_expression(expression):
591 expression = replace_variables(expression)
592 exec(expression)
593
594
595 @given("I duplicate the selected objects")
596 @when("I duplicate the selected objects")
597 def i_duplicate_the_selected_objects():
598 bpy.ops.bim.override_object_duplicate_move()
599 bonsai.bim.handler.active_object_callback()
600
601
602 @when("I duplicate linked aggregate the selected objects")
603 def i_duplicate_linked_aggregate_the_selected_objects():
604 bpy.ops.bim.object_duplicate_move_linked_aggregate()
605 bonsai.bim.handler.active_object_callback()
606
607
608 @when("I refresh linked aggregate the selected object")
609 def i_refresh_the_selected_objects():
610 bpy.ops.bim.refresh_linked_aggregate()
611 bonsai.bim.handler.active_object_callback()
612
613
614 @given("I deselect all objects")
615 @when("I deselect all objects")
616 def i_deselect_all_objects():
617 bpy.context.view_layer.objects.active = None
618 bpy.ops.object.select_all(action="DESELECT")
619
620
621 @given(parsers.parse('the object "{name}" is selected'))
622 @when(parsers.parse('the object "{name}" is selected'))
623 @given(parsers.parse('I select the object "{name}"'))
624 @when(parsers.parse('I select the object "{name}"'))
625 def the_object_name_is_selected(name):
626 i_deselect_all_objects()
627 additionally_the_object_name_is_selected(name)
628
629
630 @then(parsers.parse('the object "{name}" is selected'))
631 def then_the_object_name_is_selected(name):
632 obj = the_object_name_exists(name)
633 assert obj in bpy.context.selected_objects
634
635
636 @given(parsers.parse('the object "{name}" is rotated by "{rotation_deg}" deg'))
637 @when(parsers.parse('the object "{name}" is rotated by "{rotation_deg}" deg'))
638 def the_object_name_is_rotated_by(name, rotation_deg):
639 rotation_deg = [radians(float(rot)) for rot in rotation_deg.split(",")]
640 obj = the_object_name_exists(name)
641 obj.rotation_euler[0] += rotation_deg[0]
642 obj.rotation_euler[1] += rotation_deg[1]
643 obj.rotation_euler[2] += rotation_deg[2]
644 bpy.context.view_layer.update() # make sure matrix is updated
645
646
647 @given(parsers.parse('the object "{name}" is moved to "{location}"'))
648 @when(parsers.parse('the object "{name}" is moved to "{location}"'))
649 def the_object_name_is_moved_to_location(name, location):
650 location = [float(co) for co in location.split(",")]
651 obj = the_object_name_exists(name)
652 obj.matrix_world.translation = location
653
654
655 @given(parsers.parse('the object "{name}" is scaled to "{scale}"'))
656 @when(parsers.parse('the object "{name}" is scaled to "{scale}"'))
657 def the_object_name_is_scaled_to_scale(name, scale):
658 the_object_name_exists(name).scale *= float(scale)
659
660
661 @given(parsers.parse('the object "{name}" is placed in the collection "{collection}"'))
662 @when(parsers.parse('the object "{name}" is placed in the collection "{collection}"'))
663 def the_object_name_is_placed_in_the_collection_collection(name: str, collection: str) -> None:
664 obj = the_object_name_exists(name)
665 [c.objects.unlink(obj) for c in obj.users_collection]
666 bpy.data.collections.get(collection).objects.link(obj)
667
668
669 @then(parsers.parse('the object "{name}" is placed in the collection "{collection}"'))
670 def then_the_object_name_is_placed_in_the_collection_collection(name: str, collection: str) -> None:
671 obj = the_object_name_exists(name)
672 assert obj in bpy.data.collections.get(collection).objects[:]
673
674
675 @given(parsers.parse('additionally the object "{name}" is selected'))
676 @when(parsers.parse('additionally the object "{name}" is selected'))
677 def additionally_the_object_name_is_selected(name):
678 obj = bpy.context.scene.objects.get(name)
679 if not obj:
680 total = len(bpy.context.scene.objects)
681 debug = "\n".join([o.name for o in bpy.context.scene.objects])
682 assert False, f'The object "{name}" could not be selected. Available objects ({total} total):\n{debug}'
683 bpy.context.view_layer.objects.active = obj
684 obj.select_set(True)
685
686
687 @given(parsers.parse('I rename the object "{name1}" to "{name2}"'))
688 @when(parsers.parse('I rename the object "{name1}" to "{name2}"'))
689 def i_rename_the_object_name1_to_name2(name1, name2):
690 the_object_name_exists(name1).name = name2
691
692
693 @given(parsers.parse('I set "{prop}" to "{value}"'))
694 @when(parsers.parse('I set "{prop}" to "{value}"'))
695 def i_set_prop_to_value(prop: str, value: str) -> None:
696 value = replace_variables(value)
697 try:
698 eval(f"bpy.context.{prop}")
699 except:
700 assert False, f"Property {prop} does not exist when trying to set to value {value}"
701 try:
702 exec(f'bpy.context.{prop} = r"{value}"')
703 except:
704 exec(f"bpy.context.{prop} = {value}")
705
706
707 @given(parsers.parse('I set "{prop}" to ""'))
708 @when(parsers.parse('I set "{prop}" to ""'))
709 def i_set_prop_to_empty_string(prop):
710 try:
711 eval(f"bpy.context.{prop}")
712 except:
713 assert False, f"Property {prop} does not exist"
714 try:
715 exec(f'bpy.context.{prop} = r""')
716 except:
717 pass
718
719
720 @when(parsers.parse('I am on frame "{number}"'))
721 def i_am_on_frame_number(number):
722 bpy.context.scene.frame_set(int(number))
723
724
725 @given("I delete the selected objects")
726 @when("I delete the selected objects")
727 def i_delete_the_selected_objects():
728 bpy.ops.bim.override_object_delete()
729
730
731 @given(parsers.parse('the variable "{key}" is "{value}"'))
732 @when(parsers.parse('the variable "{key}" is "{value}"'))
733 @then(parsers.parse('the variable "{key}" is "{value}"'))
734 def the_variable_key_is_value(key, value):
735 variables[key] = eval(replace_variables(value))
736
737
738 @then("nothing happens")
739 def nothing_happens():
740 pass
741
742
743 @given(parsers.parse('the object "{name}" exists'))
744 @when(parsers.parse('the object "{name}" exists'))
745 @then(parsers.parse('the object "{name}" exists'))
746 def the_object_name_exists(name: str) -> bpy.types.Object:
747 # Some objects from linked collections may share the same name. This disambiguates them.
748 if name.startswith("Col:"):
749 _, collection_name, name = name.split(":")
750 obj = bpy.data.collections.get(collection_name).objects.get(name)
751 else:
752 obj = bpy.data.objects.get(name)
753 if not obj:
754 debug = "\n".join([o.name for o in bpy.data.objects])
755 assert False, f'The object "{name}" does not exist:\n{debug}'
756 return obj
757
758
759 @then(parsers.parse('the object "{name}" does not exist'))
760 def the_object_name_does_not_exist(name) -> bpy.types.Object:
761 obj = bpy.data.objects.get(name)
762 if not obj:
763 assert True, f'The object "{name}" exists'
764 return obj
765
766
767 @given(parsers.parse('the collection "{name}" exists'))
768 @when(parsers.parse('the collection "{name}" exists'))
769 @then(parsers.parse('the collection "{name}" exists'))
770 def the_collection_name_exists(name) -> bpy.types.Collection:
771 obj = bpy.data.collections.get(name)
772 if not obj:
773 assert False, f'The collection "{name}" does not exist'
774 return obj
775
776
777 @then(parsers.parse('the collection "{name}" is selectable'))
778 def the_collection_name_is_selectable(name: str) -> None:
779 col = the_collection_name_exists(name)
780 assert col.hide_select == False
781
782
783 @then(parsers.parse('the collection "{name}" is unselectable'))
784 def the_collection_name_is_unselectable(name: str) -> None:
785 col = the_collection_name_exists(name)
786 assert col.hide_select == True
787
788
789 @then(parsers.parse('the collection "{name}" exists in viewlayer'))
790 def the_collection_exists_in_viewlayer(name: str) -> bpy.types.LayerCollection:
791 col = the_collection_name_exists(name)
792 results = tool.Blender.get_layer_collections_mapping([col])
793 if not (layer_collection := results.get(col, None)):
794 assert False, f'The collection "{name}" is not present in the current viewlayer'
795 return layer_collection
796
797
798 @then(parsers.parse('the collection "{name}" exclude status is "{exclude}"'))
799 def the_collection_exclude_status_is(name: str, exclude: str) -> None:
800 layer = the_collection_exists_in_viewlayer(name)
801 assert layer.exclude == (exclude == "True")
802
803
804 @then(parsers.parse('the object "{name1}" and "{name2}" are different elements'))
805 def the_object_name1_and_name2_are_different_elements(name1, name2):
806 ifc = an_ifc_file_exists()
807 element1 = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name1)))
808 element2 = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name2)))
809 assert element1 != element2, f"Objects {name1} and {name2} have same elements {element1} and {element2}"
810
811
812 @then(parsers.parse('the object "{name}" has a body of "{value}"'))
813 def the_object_name_has_a_body_of_value(name, value):
814 assert the_object_name_exists(name).data.body == value
815
816
817 @given(parsers.parse('the object "{name}" has a "{type}" representation of "{context}"'))
818 @then(parsers.parse('the object "{name}" has a "{type}" representation of "{context}"'))
819 def the_object_name_has_a_representation_type_of_context(name, type, context):
820 ifc = an_ifc_file_exists()
821 element = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name)))
822 context, subcontext, target_view = context.split("/")
823 rep = ifcopenshell.util.representation.get_representation(element, context, subcontext or None, target_view or None)
824 assert rep
825 assert rep.RepresentationType == type, f"The object {name} does not have a {type} representation"
826
827
828 @given(parsers.parse('the object "{name}" data is a "{type}" representation of "{context}"'))
829 @then(parsers.parse('the object "{name}" data is a "{type}" representation of "{context}"'))
830 def the_object_name_data_is_a_type_representation_of_context(name, type, context):
831 ifc = an_ifc_file_exists()
832 context, subcontext, target_view = context.split("/")
833 rep = ifc.by_id(tool.Geometry.get_mesh_props(the_object_name_exists(name).data).ifc_definition_id)
834 assert rep
835 assert rep.RepresentationType == type, f"The object {name} is not a {type} representation"
836 assert rep.ContextOfItems.ContextType == context
837 assert rep.ContextOfItems.ContextIdentifier == subcontext
838 assert rep.ContextOfItems.TargetView == target_view
839
840
841 @then(parsers.parse('the material "{name}" exists'))
842 def the_material_name_exists(name: str) -> bpy.types.Material:
843 obj = bpy.data.materials.get(name)
844 if not obj:
845 assert False, f'The material "{name}" does not exist'
846 return obj
847
848
849 @then(parsers.parse('the material "{name}" does not exist'))
850 def the_material_name_does_not_exist(name):
851 assert bpy.data.materials.get(name) is None, "Material exists"
852
853
854 def get_ifc_material_by_name(name: str) -> Union[ifcopenshell.entity_instance, None]:
855 ifc_file = tool.Ifc.get()
856 material = next((m for m in ifc_file.by_type("IfcMaterial") if m.Name == name), None)
857 return material
858
859
860 @then(parsers.parse('the IFC material "{name}" exists'))
861 def the_ifc_material_name_exists(name: str) -> ifcopenshell.entity_instance:
862 material = get_ifc_material_by_name(name)
863 if not material:
864 assert False, f'The IFC material "{name}" does not exist'
865 return material
866
867
868 @then(parsers.parse('the material "{name}" does not exist'))
869 def the_ifc_material_name_does_not_exist(name):
870 assert get_ifc_material_by_name(name) is None, "IFC Material exists"
871
872
873 @then("an IFC file does not exist")
874 def an_ifc_file_does_not_exist():
875 ifc = tool.Ifc.get()
876 if ifc:
877 assert False, "An IFC is available"
878
879
880 @then("an IFC file exists")
881 def an_ifc_file_exists():
882 ifc = tool.Ifc.get()
883 if not ifc:
884 assert False, "No IFC file is available"
885 return ifc
886
887
888 @then(parsers.parse('the object "{name}" should display as "{mode}"'))
889 def the_object_name_should_display_as_mode(name, mode):
890 obj = the_object_name_exists(name)
891 assert obj.display_type == mode
892
893
894 @then(parsers.parse('the object "{name}" is voided by "{void}"'))
895 def the_object_name_is_voided_by_void(name, void):
896 ifc = tool.Ifc.get()
897 element = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name)))
898 assert any((rel for rel in element.HasOpenings if rel.RelatedOpeningElement.Name == void)), "No void found"
899
900
901 @then(parsers.parse('the object "{name}" is not voided by "{void}"'))
902 def the_object_name_is_not_voided_by_void(name, void):
903 try:
904 the_object_name_is_voided_by_void(name, void)
905 except AssertionError:
906 return
907 assert False, "A void was found"
908
909
910 @then(parsers.parse('the object "{name}" is not voided'))
911 def the_object_name_is_not_voided(name):
912 ifc = tool.Ifc.get()
913 element = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name)))
914 assert not element.HasOpenings, "A void was found"
915
916
917 @then(parsers.parse('the object "{name}" is a void'))
918 def the_object_name_is_a_void(name):
919 ifc = tool.Ifc.get()
920 obj = the_object_name_exists(name)
921 element = ifc.by_id(tool.Blender.get_ifc_definition_id(obj))
922 assert any((element.VoidsElements)), "No void was found"
923
924
925 @then(parsers.parse('the object "{name}" is not a void'))
926 def the_object_name_is_not_a_void(name):
927 try:
928 the_object_name_is_a_void(name)
929 except AssertionError:
930 return
931 assert False, "A void was found"
932
933
934 @given(parsers.parse('the object "{name}" is visible'))
935 def given_the_object_name_is_visible(name):
936 obj = the_object_name_exists(name)
937 obj.hide_set(False)
938
939
940 @given(parsers.parse('the object "{name}" is not visible'))
941 def given_the_object_name_is_not_visible(name):
942 obj = the_object_name_exists(name)
943 obj.hide_set(True)
944
945
946 @then(parsers.parse('the object "{name}" is visible'))
947 def the_object_name_is_visible(name):
948 obj = the_object_name_exists(name)
949 assert obj.hide_get() == False
950
951
952 @then(parsers.parse('the object "{name}" is not visible'))
953 def the_object_name_is_not_visible(name):
954 obj = the_object_name_exists(name)
955 assert obj.hide_get() == True
956
957
958 @then(parsers.parse('the object "{name}" is an "{ifc_class}"'))
959 def the_object_name_is_an_ifc_class(name, ifc_class):
960 ifc = an_ifc_file_exists()
961 element = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name)))
962 assert element.is_a(ifc_class), f'Object "{name}" is an {element.is_a()}'
963
964
965 @then(parsers.parse('the object "{name}" is not an IFC element'))
966 def the_object_name_is_not_an_ifc_element(name):
967 obj = the_object_name_exists(name)
968 ifc_definition_id = tool.Blender.get_ifc_definition_id(obj)
969 assert ifc_definition_id == 0, f"The object {obj} has an ID of {ifc_definition_id}"
970
971
972 @then(parsers.parse('the object "{name}" has no data'))
973 def the_object_name_has_no_data(name):
974 assert the_object_name_exists(name).data is None
975
976
977 @then(parsers.parse('the object "{name}" has data which is an IFC representation'))
978 def the_object_name_has_ifc_representation_data(name):
979 id = tool.Geometry.get_mesh_props(the_object_name_exists(name).data).ifc_definition_id
980 assert id != 0, f"The ID is {id}"
981
982
983 @then(parsers.parse('the material "{name}" is an IFC material'))
984 def the_material_name_is_an_ifc_material(name):
985 obj = the_material_name_exists(name)
986 ifc_definition_id = tool.Blender.get_ifc_definition_id(obj)
987 assert ifc_definition_id != 0, f"The material {obj} has no ID: {ifc_definition_id}"
988
989
990 @then(parsers.parse('the material "{name}" is not an IFC material'))
991 def the_material_name_is_not_an_ifc_material(name):
992 obj = the_material_name_exists(name)
993 ifc_definition_id = tool.Blender.get_ifc_definition_id(obj)
994 assert ifc_definition_id == 0, f"The material {obj} has an ID of {ifc_definition_id}"
995
996
997 @then(parsers.parse('the material "{name}" is an IFC style'))
998 def the_material_name_is_an_ifc_style(name):
999 obj = the_material_name_exists(name)
1000 ifc_definition_id = tool.Blender.get_ifc_definition_id(obj)
1001 assert ifc_definition_id != 0, f"The material {obj} has a style ID of {ifc_definition_id}"
1002
1003
1004 @then(parsers.parse('the material "{name}" is not an IFC style'))
1005 def the_material_name_is_not_an_ifc_style(name):
1006 obj = the_material_name_exists(name)
1007 ifc_definition_id = tool.Blender.get_ifc_definition_id(obj)
1008 assert ifc_definition_id == 0, f"The material {obj} has a style ID of {ifc_definition_id}"
1009
1010
1011 @then(parsers.parse('the material "{name}" colour is "{colour}"'))
1012 def then_the_material_name_colour_is_set_to_colour(name, colour):
1013 diffuse_color = list(the_material_name_exists(name).diffuse_color)
1014 assert diffuse_color == [float(c) for c in colour.split(",")], f"The colour is {diffuse_color}"
1015
1016
1017 @then(parsers.parse('the object "{name}" has "{number}" vertices'))
1018 def the_object_name_has_number_vertices(name, number):
1019 total = len(the_object_name_exists(name).data.vertices)
1020 assert total == int(number), f"We found {total} vertices"
1021
1022
1023 @then(parsers.parse('the void "{name}" is filled by "{filling}"'))
1024 def the_void_name_is_filled_by_filling(name, filling):
1025 ifc = tool.Ifc.get()
1026 element = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name)))
1027 assert any((rel.RelatedBuildingElement.Name == filling for rel in element.HasFillings)), "No filling found"
1028
1029
1030 @then(parsers.parse('the void "{name}" is not filled by "{filling}"'))
1031 def the_void_name_is_not_filled_by_filling(name, filling):
1032 try:
1033 the_void_name_is_filled_by_filling(name, filling)
1034 except AssertionError:
1035 return
1036 assert False, "A filling was found"
1037
1038
1039 @when(parsers.parse('the object "{name}" is not a filling'))
1040 @then(parsers.parse('the object "{name}" is not a filling'))
1041 def the_object_name_is_not_a_filling(name):
1042 ifc = tool.Ifc.get()
1043 element = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name)))
1044 assert not any(element.FillsVoids), "A filling was found"
1045
1046
1047 @then(parsers.parse('"{prop}" is "{value}"'))
1048 def prop_is_value(prop, value):
1049 prop = replace_variables(prop)
1050 value = replace_variables(value)
1051 is_value = False
1052 try:
1053 exec(f'assert bpy.context.{prop} == "{value}"')
1054 is_value = True
1055 except:
1056 try:
1057 exec(f"assert bpy.context.{prop} == {value}")
1058 is_value = True
1059 except:
1060 try:
1061 exec(f"assert list(bpy.context.{prop}) == {value}")
1062 is_value = True
1063 except:
1064 try:
1065 exec(f"assert vectors_are_equal(bpy.context.{prop}, {value})")
1066 is_value = True
1067 except:
1068 pass
1069 if not is_value:
1070 print(f"bpy.context.{prop}")
1071 actual_value = eval(f"bpy.context.{prop}")
1072 assert False, f"Value is {actual_value}"
1073
1074
1075 @then(parsers.parse('"{prop}" is roughly "{value}"'))
1076 def prop_is_roughly_value(prop, value):
1077 prop = replace_variables(prop)
1078 value = replace_variables(value)
1079 is_value = False
1080 try:
1081 exec(f'assert round(bpy.context.{prop}, 3) == "{value}"')
1082 is_value = True
1083 except:
1084 try:
1085 exec(f"assert round(bpy.context.{prop}, 3) == {value}")
1086 is_value = True
1087 except:
1088 pass
1089 if not is_value:
1090 print(f"bpy.context.{prop}")
1091 actual_value = round(eval(f"bpy.context.{prop}"), 3)
1092 assert False, f"Value is {actual_value}"
1093
1094
1095 @then(parsers.parse('the object "{name}" has a cartesian point offset of "{offset}"'))
1096 def the_object_name_has_a_cartesian_point_offset_of_offset(name: str, offset: str) -> None:
1097 offset = replace_variables(offset)
1098 obj = the_object_name_exists(name)
1099 props = tool.Blender.get_object_bim_props(obj)
1100 assert props.blender_offset_type == "CARTESIAN_POINT"
1101 obj_offset = np.array(tuple(map(float, props.cartesian_point_offset.split(","))))
1102 offset = np.array(tuple(map(float, offset.split(","))))
1103 assert np.allclose(obj_offset, offset)
1104
1105
1106 @then(parsers.parse('the object "{name}" has the material "{material}"'))
1107 def the_object_name_has_the_material_material(name: str, material: str) -> None:
1108 assert material in [ms.material.name for ms in the_object_name_exists(name).material_slots if ms.material]
1109
1110
1111 @then(parsers.parse('the object "{name}" has the IFC material "{material_name}"'))
1112 def the_object_name_has_the_ifc_material_material_name(name: str, material_name: str):
1113 element = tool.Ifc.get_entity(the_object_name_exists(name))
1114 material = ifcopenshell.util.element.get_material(element)
1115 assert material and material.Name == material_name
1116
1117
1118 @then(
1119 parsers.parse(
1120 'the object "{name}" has a "{thickness}" thick layered material containing the material "{material_name}"'
1121 )
1122 )
1123 def the_object_name_has_a_thickness_thick_layered_material_containing_the_material_material(
1124 name, thickness, material_name
1125 ):
1126 element = tool.Ifc.get_entity(the_object_name_exists(name))
1127 material = ifcopenshell.util.element.get_material(element)
1128 assert material and "LayerSet" in material.is_a()
1129 if material.is_a("IfcMaterialLayerSetUsage"):
1130 material = material.ForLayerSet
1131 total_thickness = 0
1132 material_names = []
1133 for layer in material.MaterialLayers or []:
1134 total_thickness += layer.LayerThickness
1135 material_names.append(layer.Material.Name)
1136 assert is_x(total_thickness, float(thickness))
1137 assert material_name in material_names
1138
1139
1140 @then(parsers.parse('the object "{name}" has no IFC materials'))
1141 def the_object_has_no_ifc_materials(name: str) -> None:
1142 element = tool.Ifc.get_entity(the_object_name_exists(name))
1143 material = ifcopenshell.util.element.get_material(element)
1144 assert material is None
1145
1146
1147 @then(
1148 parsers.parse(
1149 'the object "{name}" has a profiled material containing the material "{material_name}" and profile "{profile_name}"'
1150 )
1151 )
1152 def the_object_name_has_a_profiled_material_containing_the_material_material_and_profile_profile(
1153 name, material_name, profile_name
1154 ):
1155 element = tool.Ifc.get_entity(the_object_name_exists(name))
1156 material = ifcopenshell.util.element.get_material(element)
1157 assert material and "ProfileSet" in material.is_a()
1158 if material.is_a("IfcMaterialProfileSetUsage"):
1159 material = material.ForProfileSet
1160 material_names = []
1161 profile_names = []
1162 for profile in material.MaterialProfiles or []:
1163 material_names.append(profile.Material.Name)
1164 profile_names.append(profile.Profile.ProfileName)
1165 assert material_name in material_names, f"No material {material_name} found in profiled materials: {material_names}"
1166 assert profile_name in profile_names, f"No profile {profile_name} found in material profiles: {profile_names}"
1167
1168
1169 @then(parsers.parse('the object "{name}" does not have the material "{material}"'))
1170 def the_object_name_does_not_have_the_material_material(name, material):
1171 assert material not in [ms.material.name for ms in the_object_name_exists(name).material_slots]
1172
1173
1174 @then(parsers.parse('the object "{name}" is in the collection "{collection}"'))
1175 def the_object_name_is_in_the_collection_collection(name, collection):
1176 assert collection in [c.name for c in the_object_name_exists(name).users_collection]
1177
1178
1179 @then(parsers.parse('the collection "{name1}" is in the collection "{name2}"'))
1180 def the_collection_name1_is_in_the_collection_name2(name1, name2):
1181 assert bpy.data.collections.get(name2).children.get(name1)
1182
1183
1184 @then(parsers.parse('the collection "{name}" does not exist'))
1185 def the_collection_name_does_not_exist(name):
1186 obj = bpy.data.collections.get(name)
1187 assert obj is None, f"Collection {name} exists"
1188
1189
1190 @then(parsers.parse('objects starting with "{name}" do not exist'))
1191 def objects_not_exist_starting_with(name):
1192 objs = [obj for obj in bpy.data.objects if obj.name.startswith(name) and len(obj.users_collection) > 0]
1193 if len(objs) > 0:
1194 assert False, f'{len(objs)} objects starting with "{name}" exist'
1195 assert True
1196
1197
1198 @then(parsers.parse('the object "{name}" is at "{location}"'))
1199 def the_object_name_is_at_location(name, location):
1200 obj_location = the_object_name_exists(name).location
1201 assert (
1202 obj_location - Vector([float(co) for co in location.split(",")])
1203 ).length < 0.1, f"Object is at {obj_location} instead of {location}"
1204
1205
1206 @then(parsers.parse('the object "{name}" has a vertex at "{location}"'))
1207 def the_object_name_has_a_vertex_at_location(name, location):
1208 obj = the_object_name_exists(name)
1209 is_pass = False
1210 target = Vector([float(co) for co in location.split(",")])
1211 verts = []
1212 for v in obj.data.vertices:
1213 verts.append((obj.matrix_world @ v.co))
1214 if (verts[-1] - target).length < 0.001:
1215 is_pass = True
1216 assert is_pass, f"No verts found at {location}: {verts}"
1217
1218
1219 @then(parsers.parse('the object "{name}" has no scale'))
1220 def the_object_name_has_no_scale(name):
1221 assert the_object_name_exists(name).scale == Vector(
1222 (
1223 1.0,
1224 1.0,
1225 1.0,
1226 )
1227 )
1228
1229
1230 @then(parsers.parse('the object "{name}" dimensions are "{dimensions}"'))
1231 def the_object_name_dimensions_are_dimensions(name, dimensions):
1232 actual_dimensions = list(the_object_name_exists(name).dimensions)
1233 expected_dimensions = [float(co) for co in dimensions.split(",")]
1234 for i, number in enumerate(actual_dimensions):
1235 assert is_x(number, expected_dimensions[i]), f"Expected {expected_dimensions} but got {actual_dimensions}"
1236
1237
1238 @then(parsers.parse('the object "{name}" top right corner is at "{location}"'))
1239 def the_object_name_top_right_corner_is_at_location(name, location):
1240 obj = the_object_name_exists(name)
1241 obj_corner = obj.matrix_world @ Vector(obj.bound_box[6])
1242 assert (
1243 obj_corner - Vector([float(co) for co in location.split(",")])
1244 ).length < 0.1, f"Object has top right corner {obj_corner} instead of {location}"
1245
1246
1247 @then(parsers.parse('the object "{name}" bottom left corner is at "{location}"'))
1248 def the_object_name_bottom_left_corner_is_at_location(name, location):
1249 obj = the_object_name_exists(name)
1250 obj_corner = obj.matrix_world @ Vector(obj.bound_box[0])
1251 assert (
1252 obj_corner - Vector([float(co) for co in location.split(",")])
1253 ).length < 0.1, f"Object has bottom left corner {obj_corner} instead of {location}"
1254
1255
1256 @then(parsers.parse('the object "{name}" is contained in "{container_name}"'))
1257 def the_object_name_is_contained_in_container_name(name, container_name):
1258 ifc = an_ifc_file_exists()
1259 element = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name)))
1260 container = ifcopenshell.util.element.get_container(element)
1261 if not container:
1262 assert False, f'Object "{name}" is not in any container'
1263 assert container.Name == container_name, f'Object "{name}" is in {container}'
1264
1265
1266 @then(parsers.parse('the object "{name}" is contained in object "{container_name}"'))
1267 def the_object_name_is_contained_in_object_container_name(name: str, container_name: str) -> None:
1268 ifc = an_ifc_file_exists()
1269 element = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name)))
1270 container = ifcopenshell.util.element.get_container(element)
1271 if not container:
1272 assert False, f'Object "{name}" is not in any container'
1273 container_obj = tool.Ifc.get_object(container)
1274 assert container_obj.name == container_name, f'Object "{name}" is in {container_obj}'
1275
1276
1277 @then(parsers.parse('the object "{name}" is aggregated by object "{aggregate_name}"'))
1278 def the_object_name_is_aggregated_by_object_aggregate_name(name: str, aggregate_name: str) -> None:
1279 ifc = an_ifc_file_exists()
1280 element = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name)))
1281 aggregate = ifcopenshell.util.element.get_aggregate(element)
1282 if not aggregate:
1283 assert False, f'Object "{name}" is not aggregated by any element'
1284 aggregate_obj = tool.Ifc.get_object(aggregate)
1285 assert aggregate_obj.name == aggregate_name, f'Object "{name}" is aggregated by {aggregate_obj}'
1286
1287
1288 @then(parsers.parse('the object "{name}" has no aggregate'))
1289 def the_object_name_has_no_aggregate(name: str) -> None:
1290 ifc = an_ifc_file_exists()
1291 element = ifc.by_id(tool.Blender.get_ifc_definition_id(the_object_name_exists(name)))
1292 aggregate = ifcopenshell.util.element.get_aggregate(element)
1293 if aggregate:
1294 assert False, f'Object "{name}" is aggregated by element "{aggregate}"'
1295
1296
1297 @then(parsers.parse('the file "{name}" should contain "{value}"'))
1298 def the_file_name_should_contain_value(name, value):
1299 name = replace_variables(name)
1300 with open(name, "r") as f:
1301 assert value in f.read()
1302
1303
1304 @then(parsers.parse('the object "{name}" has no modifiers'))
1305 def the_object_name_has_no_modifiers(name):
1306 assert len(the_object_name_exists(name).modifiers) == 0
1307
1308
1309 @given(parsers.parse('I load the IFC test file "{filepath}"'))
1310 def i_load_the_ifc_test_file(filepath):
1311 filepath = f"{variables['cwd']}{filepath}"
1312 bpy.ops.bim.load_project(filepath=filepath)
1313
1314
1315 @given("I load the demo construction library")
1316 @when("I load the demo construction library")
1317 def i_add_a_construction_library():
1318 lib_path = "./bonsai/bim/data/libraries/IFC4 Demo Library.ifc"
1319 bpy.ops.bim.select_library_file(filepath=lib_path, append_all=True)
1320
1321
1322 @given(parsers.parse('the cursor is at "{location}"'))
1323 def the_cursor_is_at_location(location):
1324 bpy.context.scene.cursor.location = [float(co) for co in location.split(",")]
1325
1326
1327 @given("I display the construction type browser")
1328 @when("I display the construction type browser")
1329 def i_display_the_construction_type_browser():
1330 bpy.ops.bim.display_constr_types("INVOKE_DEFAULT")
1331
1332
1333 @given("I add the construction type")
1334 @when("I add the construction type")
1335 def i_add_the_active_construction_type():
1336 props = tool.Model.get_model_props()
1337 bpy.ops.bim.add_occurrence(relating_type_id=int(props.relating_type_id))
1338
1339
1340 @then(parsers.parse("construction type is {relating_type_name}"))
1341 def construction_type(relating_type_name):
1342 props = tool.Model.get_model_props()
1343 relating_type = AuthoringData.relating_type_name_by_id(props.ifc_class, props.relating_type_id)
1344 assert relating_type == relating_type_name, f"Construction Type is a {relating_type}, not a {relating_type_name}"
1345
1346
1347 @given("I toggle edit mode")
1348 @when("I toggle edit mode")
1349 @then("I toggle edit mode")
1350 def i_toggle_edit_mode():
1351 props = tool.Geometry.get_geometry_props()
1352 print(f"Toggling from {bpy.context.mode} / {props.mode} ...")
1353 print("Selected items:", bpy.context.active_object, bpy.context.selected_objects)
1354 if bpy.context.mode == "OBJECT":
1355 bpy.ops.bim.override_mode_set_edit()
1356 else:
1357 bpy.ops.bim.override_mode_set_object()
1358 print(f"... mode is now {bpy.context.mode} / {props.mode}")
1359
1360
1361 @when("I move the cursor to the bottom left corner")
1362 def move_cursor_bottom_left():
1363 bpy.context.window.cursor_warp(10, 10)
1364
1365
1366 @given(parsers.parse("I prepare to undo"))
1367 @when(parsers.parse("I prepare to undo"))
1368 @then(parsers.parse("I prepare to undo"))
1369 def prepare_undo():
1370 bpy.ops.ed.undo_push(message="UNDO STEP")
1371
1372
1373 @given(parsers.parse("I undo"))
1374 @when(parsers.parse("I undo"))
1375 @then(parsers.parse("I undo"))
1376 def hit_undo():
1377 bpy.ops.ed.undo_push(message="UNDO STEP")
1378 bpy.ops.ed.undo()
1379 # override = tool.Blender.get_viewport_context()
1380 # with bpy.context.temp_override(**override):
1381 # bpy.ops.ed.undo()
1382
1383
1384 @then(parsers.parse('the object "{obj_name1}" has a connection with "{obj_name2}"'))
1385 def the_obj1_has_a_connection_with_obj2(obj_name1, obj_name2):
1386 element1 = replace_variables(obj_name1)
1387 element1 = tool.Ifc.get_entity(the_object_name_exists(element1))
1388 element2 = replace_variables(obj_name2)
1389 element2 = tool.Ifc.get_entity(the_object_name_exists(element2))
1390 connections = []
1391 if hasattr(element1, "ConnectedTo") and element1.ConnectedTo:
1392 connections = [connection for connection in element1.ConnectedTo]
1393 elif hasattr(element1, "ConnectedFrom") and element1.ConnectedFrom:
1394 connections = [connection for connection in element1.ConnectedFrom]
1395 else:
1396 assert False, f'Object "{obj_name1}" has no connections'
1397
1398 relationships = {}
1399 for conn in connections:
1400 relationships[conn.RelatedElement] = conn.RelatingElement
1401
1402 for key, value in relationships.items():
1403 assert (key.id() == element1.id() and value.id() == element2.id()) or (
1404 key.id() == element2.id() and value.id() == element1.id()
1405 ), f"The object {obj_name1} is connected to {obj_name2}"
1406
1407
1408 @then(parsers.parse('the object "{obj_name1}" and "{obj_name2}" belong to the same Linked Aggregate Group'))
1409 def the_obj1_and_obj2_belong_the_same_linked_aggregate_group(obj_name1, obj_name2):
1410 element1 = replace_variables(obj_name1)
1411 element1 = tool.Ifc.get_entity(the_object_name_exists(element1))
1412 element2 = replace_variables(obj_name2)
1413 element2 = tool.Ifc.get_entity(the_object_name_exists(element2))
1414
1415 elements = [element1, element2]
1416 groups = []
1417 for element in elements:
1418 product_linked_agg_group = [
1419 r.RelatingGroup
1420 for r in getattr(element, "HasAssignments", []) or []
1421 if r.is_a("IfcRelAssignsToGroup")
1422 if "BBIM_Linked_Aggregate" in r.RelatingGroup.Name
1423 ]
1424 try:
1425 groups.append(product_linked_agg_group[0].id())
1426 except:
1427 assert False, "Object is not part of a Linked Aggregate."
1428
1429 assert groups[0] == groups[1], "Objects do not belong to the same Linked Aggregate group"
1430
1431
1432 @when(parsers.parse('the object layer length is set to "{value}"'))
1433 def the_obj_layer_lenght_is_set_to(value):
1434 value = float(value)
1435 try:
1436 eval("bpy.context.scene.BIMModelProperties.length")
1437 except:
1438 assert False, f"Property BIMModelProperties.length does not exist when trying to set to value {value}"
1439 props = tool.Model.get_model_props()
1440 props.length = value
1441 bpy.ops.bim.change_layer_length(length=value)
1442
1443
1444 # These definitions are not to be used in tests but simply in debugging failing tests
1445
1446
1447 @given(parsers.parse("I run test code"))
1448 @when(parsers.parse("I run test code"))
1449 @then(parsers.parse("I run test code"))
1450 def run_test_code():
1451 pass
1452
1453
1454 @given(parsers.parse("I fail"))
1455 @when(parsers.parse("I fail"))
1456 @then(parsers.parse("I fail"))
1457 def i_fail():
1458 assert False
1459
1460
1461 @given(parsers.parse("I save sample test files"))
1462 @when(parsers.parse("I save sample test files"))
1463 @then(parsers.parse("I save sample test files"))
1464 def saving_sample_test_files(and_open_in_blender=None):
1465 filepath = f"{variables['cwd']}/test/files/temp/sample_test_file"
1466 print(f"Saved to {filepath}")
1467 bpy.ops.bim.save_project(filepath=f"{filepath}.ifc", should_save_as=True)
1468 bpy.ops.wm.save_as_mainfile(filepath=f"{filepath}.blend")
1469
1470
1471 @given(parsers.parse("I load test blend file"))
1472 @when(parsers.parse("I load test blend file"))
1473 @then(parsers.parse("I load test blend file"))
1474 def opening_sample_test_files_in_blender():
1475 filepath = f"{variables['cwd']}/test/files/temp/sample_test_file.blend"
1476 bpy.ops.wm.open_mainfile(filepath=filepath, display_file_selector=False)
1477
1478
1479 # TODO: merge to single fixture with `saving_sample_test_files`; add "and wait"
1480 @given(parsers.parse("I save sample test files and open in blender"))
1481 @when(parsers.parse("I save sample test files and open in blender"))
1482 @then(parsers.parse("I save sample test files and open in blender"))
1483 def saving_sample_test_files_and_open_in_blender():
1484 saving_sample_test_files()
1485 filepath = f"{variables['cwd']}/test/files/temp/sample_test_file.blend"
1486 import subprocess
1487
1488 subprocess.Popen([bpy.app.binary_path, f"{filepath}"])
1489
1490
1491 @given(parsers.parse("I run pdb"))
1492 @when(parsers.parse("I run pdb"))
1493 @then(parsers.parse("I run pdb"))
1494 def run_pdb():
1495 import pdb
1496
1497 pdb.set_trace()