tests: replace the multi-body Part tests by tests of the one-solid rule (and of what the audit found broken)

DECISION: test_multi_body_part.py becomes test_one_solid_part.py (git rename), and test_body_appearance.py is
rewritten for the single body of a Part. The tests now state the rule of this series instead of the withdrawn
design.

WHY - THE DISCUSSION (owner and assistant, 2026-11-10; full account in design-docs/part-holds-one-solid.md)
The owner's need was several solids side by side in one notebook with no assembly constraint (pattern a tool
and cut); the multi-body Part was a wrong way to give it, because it made assembly hard; the agreed rule is
Part = one solid, the editor shows loose solids, an Assembly delivers several. A rule that is not tested
comes back: the audit of 2.2.8 found a multi-body Part refusing connectors and crashing explode_rassembly,
and nothing had said so. So the tests include those two cases, now for every Part.

test_one_solid_part.py
- a Part has one body; several solids / `bodies=` are refused with the guidance; one solid in a list or a
  Body is accepted; pickle keeps body and tags; the mass report has one row; the removed helpers are gone;
- every Part takes connectors, and an assembly of such Parts flattens, explodes (the audit's crash) and
  previews; several solids are delivered as an Assembly of Parts;
- replay: a recorded Part replays, and a model recorded with several solids in one Part is refused;
- preview: compile_open_bodies draws each open solid as its own node and entity namespace (two same-shape
  solids stay two), a Part is one node, nothing to draw is an error;
- notebook: one open solid is the implicit Part; several raise SeveralOpenBodiesError naming them and saying
  what to do; the tool-cut-into-body example of the design leaves one open solid; a Part made of the chosen
  solid is the product, its package holds one solid (profile 2, no solid_cache.bodies) and exports one STEP
  solid, and the cell cache restores it; the live preview shows the open solids (OpenBodies);
- split cuts still give Pieces (they are notebook values): the old Pieces tests are kept, and a Part takes
  one piece, not several.

test_body_appearance.py: the appearance tests of a single body (colour, opacity, name, reset, material kept,
pickle, replay, preview, legacy scene compiler, package scene with ONE node and no child solid nodes, STEP
colour). The multi-body definition test is gone with profile 3.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ni Jingzhe
2026-11-10 04:07:57 +08:00
parent 910df75260
commit 0307aaa40f
2 changed files with 285 additions and 361 deletions
+63 -116
View File
@@ -1,8 +1,11 @@
"""Body appearance: a display colour, opacity and name per body of a Part (``set_body_appearance_rpart``).
"""Body appearance: a display colour, opacity and name for the body of a Part (``set_body_appearance_rpart``).
The material colour is the default; a body colour overrides it for display. The appearance reaches the live preview,
the legacy scene compiler, the product package (part definition and package scene), STEP, the cell cache (pickle)
and graph replay. A Part whose bodies have no appearance is byte for byte what it was.
and graph replay. A Part whose body has no appearance is byte for byte what it was.
A Part holds exactly one solid, so its body id is always ``"body"``; the display of several solids is the business of
several Parts (an Assembly) or of loose notebook values (see ``test_one_solid_part.py``).
"""
from __future__ import annotations
@@ -29,66 +32,56 @@ RED = (0.9, 0.2, 0.1)
BLUE = (0.1, 0.3, 0.8)
def _case() -> scad.Part:
return scad.make_part_rpart(
part_id="case",
bodies={
"base": scad.make_box_rsolid(20.0, 20.0, 10.0, tag_prefix="base"),
"lid": scad.make_box_rsolid(20.0, 20.0, 2.0, (40.0, 0.0, 0.0), tag_prefix="lid"),
},
)
def _plate() -> scad.Part:
return scad.make_part_rpart(part_id="plate", body=scad.make_box_rsolid(10.0, 10.0, 2.0))
class TestOperation(unittest.TestCase):
def test_sets_colour_opacity_and_name_of_one_body(self) -> None:
case = _case()
painted = scad.set_body_appearance_rpart(case, "lid", color=RED, opacity=0.5, name="Lid")
lid = painted.get_body("lid")
self.assertEqual(lid.color, RED)
self.assertEqual(lid.opacity, 0.5)
self.assertEqual(lid.name, "Lid")
self.assertIsNone(painted.get_body("base").color)
self.assertIsNone(case.get_body("lid").color) # values are immutable
self.assertEqual(painted.body_ids(), ("base", "lid"))
def test_sets_colour_opacity_and_name_of_the_body(self) -> None:
plate = _plate()
painted = scad.set_body_appearance_rpart(plate, "body", color=RED, opacity=0.5, name="Plate")
body = painted.get_body("body")
self.assertEqual(body.color, RED)
self.assertEqual(body.opacity, 0.5)
self.assertEqual(body.name, "Plate")
self.assertIsNone(plate.get_body("body").color) # values are immutable
self.assertEqual(painted.body_ids(), ("body",))
self.assertEqual(
painted.to_dict()["bodies"][1], {"body_id": "lid", "name": "Lid", "color": list(RED), "opacity": 0.5}
painted.to_dict()["bodies"], [{"body_id": "body", "name": "Plate", "color": list(RED), "opacity": 0.5}]
)
def test_none_keeps_and_reset_clears(self) -> None:
painted = scad.set_body_appearance_rpart(_case(), "lid", color=RED, name="Lid")
again = scad.set_body_appearance_rpart(painted, "lid", opacity=0.25)
self.assertEqual((again.get_body("lid").color, again.get_body("lid").name), (RED, "Lid"))
cleared = scad.set_body_appearance_rpart(again, "lid", reset=True)
lid = cleared.get_body("lid")
self.assertEqual((lid.color, lid.opacity, lid.name), (None, None, None))
self.assertEqual(cleared.to_dict()["bodies"][1], {"body_id": "lid", "name": None})
painted = scad.set_body_appearance_rpart(_plate(), "body", color=RED, name="Plate")
again = scad.set_body_appearance_rpart(painted, "body", opacity=0.25)
self.assertEqual((again.bodies[0].color, again.bodies[0].name), (RED, "Plate"))
cleared = scad.set_body_appearance_rpart(again, "body", reset=True)
body = cleared.bodies[0]
self.assertEqual((body.color, body.opacity, body.name), (None, None, None))
self.assertNotIn("bodies", cleared.to_dict()) # a plain body keeps the dict it always had
def test_one_body_part_uses_the_default_body(self) -> None:
def test_the_body_id_defaults_to_body(self) -> None:
plate = scad.set_body_appearance_rpart(_plate(), color=BLUE)
self.assertFalse(plate.multi_body)
self.assertEqual(plate.bodies[0].color, BLUE)
self.assertEqual(plate.to_dict()["bodies"], [{"body_id": "body", "name": None, "color": list(BLUE)}])
self.assertNotIn("bodies", _plate().to_dict()) # a plain one-body part keeps its dict
self.assertNotIn("bodies", _plate().to_dict()) # a plain part keeps its dict
def test_material_is_kept_and_overridden_for_display_only(self) -> None:
steel = scad.make_material_rmaterial("steel", color=(0.5, 0.5, 0.5), density=7.85, density_unit="g/cm^3")
case = scad.set_body_appearance_rpart(scad.assign_material_rpart(_case(), steel), "lid", color=RED)
self.assertEqual(case.material.material_id, "steel")
mass = scad.measure_part_mass_rmassreport(case)
self.assertAlmostEqual(mass.body("lid").mass_kg, 800.0 * 7.85e-6, places=12)
colors = {node.node_id: node.color for node in compile_preview(case).nodes}
self.assertEqual(colors, {"node/case/body:base": (0.5, 0.5, 0.5), "node/case/body:lid": RED})
plate = scad.set_body_appearance_rpart(scad.assign_material_rpart(_plate(), steel), color=RED)
self.assertEqual(plate.material.material_id, "steel")
mass = scad.measure_part_mass_rmassreport(plate)
self.assertAlmostEqual(mass.mass_kg, 200.0 * 7.85e-6, places=12) # the density is the material's, not the colour's
colors = {node.node_id: node.color for node in compile_preview(plate).nodes}
self.assertEqual(colors, {"node/plate": RED})
plain = scad.assign_material_rpart(_plate(), steel)
self.assertEqual({node.color for node in compile_preview(plain).nodes}, {(0.5, 0.5, 0.5)})
def test_errors(self) -> None:
for kwargs in ({"color": (1.5, 0, 0)}, {"color": (1, 0)}, {"opacity": 2.0}, {"name": " "}):
with self.subTest(kwargs=kwargs), self.assertRaises(scad.SimpleCADError):
scad.set_body_appearance_rpart(_case(), "lid", **kwargs)
scad.set_body_appearance_rpart(_plate(), "body", **kwargs)
with self.assertRaisesRegex(scad.SimpleCADError, "hinge"):
scad.set_body_appearance_rpart(_case(), "hinge", color=RED)
scad.set_body_appearance_rpart(_plate(), "hinge", color=RED)
with self.assertRaises(scad.SimpleCADError):
scad.set_body_appearance_rpart("not a part", color=RED)
with self.assertRaises(Exception):
@@ -107,38 +100,31 @@ class TestOperation(unittest.TestCase):
class TestCacheAndReplay(unittest.TestCase):
def test_pickle_and_deepcopy_keep_the_appearance(self) -> None:
case = scad.set_body_appearance_rpart(_case(), "lid", color=RED, opacity=0.5, name="Lid")
plate = scad.set_body_appearance_rpart(_plate(), color=BLUE, name="Plate")
for again in (pickle.loads(pickle.dumps(case)), copy.deepcopy(case)):
lid = again.get_body("lid")
self.assertEqual((lid.color, lid.opacity, lid.name), (RED, 0.5, "Lid"))
one = pickle.loads(pickle.dumps(plate))
self.assertFalse(one.multi_body)
self.assertEqual((one.bodies[0].color, one.bodies[0].name), (BLUE, "Plate"))
plate = scad.set_body_appearance_rpart(_plate(), color=BLUE, opacity=0.5, name="Plate")
for again in (pickle.loads(pickle.dumps(plate)), copy.deepcopy(plate)):
body = again.bodies[0]
self.assertEqual((body.color, body.opacity, body.name), (BLUE, 0.5, "Plate"))
plain = pickle.loads(pickle.dumps(_plate()))
self.assertIsNone(plain.bodies[0].color)
self.assertEqual(plain.body_ids(), ("body",))
def test_recorded_and_replayed(self) -> None:
with scad.GraphSession() as session:
case = scad.set_body_appearance_rpart(_case(), "lid", color=RED, opacity=0.5, name="Lid")
scad.set_body_appearance_rpart(case, "base", color=BLUE)
plate = scad.set_body_appearance_rpart(_plate(), color=RED, opacity=0.5, name="Plate")
scad.set_body_appearance_rpart(plate, color=BLUE)
model = scad.export_model_json(session)
self.assertIn("make_set_body_appearance_rpart", model)
parts = [item for item in scad.replay_model_json(model) if isinstance(item, scad.Part)]
final = parts[-1]
self.assertEqual(final.get_body("base").color, BLUE)
lid = final.get_body("lid")
self.assertEqual((lid.color, lid.opacity, lid.name), (RED, 0.5, "Lid"))
body = parts[-1].bodies[0]
self.assertEqual((body.color, body.opacity, body.name), (BLUE, 0.5, "Plate"))
class TestPreviewAndScene(unittest.TestCase):
def test_preview_header_carries_colour_and_opacity(self) -> None:
case = scad.set_body_appearance_rpart(_case(), "lid", color=RED, opacity=0.5, name="Lid")
nodes = {n["node_id"]: n for n in decode_preview_header(encode_preview(compile_preview(case)))["nodes"]}
self.assertEqual(nodes["node/case/body:lid"]["color"], list(RED))
self.assertEqual(nodes["node/case/body:lid"]["opacity"], 0.5)
self.assertEqual(nodes["node/case/body:lid"]["display_name"], "case / Lid")
self.assertNotIn("color", nodes["node/case/body:base"])
plate = scad.set_body_appearance_rpart(_plate(), color=RED, opacity=0.5, name="Plate")
(node,) = decode_preview_header(encode_preview(compile_preview(plate)))["nodes"]
self.assertEqual(node["color"], list(RED))
self.assertEqual(node["opacity"], 0.5)
def test_a_plain_preview_header_is_unchanged(self) -> None:
header = decode_preview_header(encode_preview(compile_preview(_plate())))
@@ -154,25 +140,6 @@ class TestPreviewAndScene(unittest.TestCase):
self.assertIn([*BLUE, 1], colors)
PAINTED = notebook_text(
cell(
"""
base = scad.make_box_rsolid(20.0, 20.0, 10.0, tag_prefix="base")
lid = scad.make_box_rsolid(20.0, 20.0, 2.0, (40.0, 0.0, 0.0), tag_prefix="lid")
""",
returns="base, lid",
),
cell(
"""
case = scad.make_part_rpart(part_id=scad.notebook_id(), bodies={"base": base, "lid": lid})
case = scad.set_body_appearance_rpart(case, "lid", color=(0.9, 0.2, 0.1), opacity=0.5, name="Lid")
""",
reads="base, lid",
returns="case",
),
table='id = "case"',
)
PLATE = notebook_text(
cell(
"""
@@ -191,32 +158,18 @@ PLAIN = notebook_text(
class TestPackage(NotebookTestCase):
def test_multi_body_definition_round_trip(self) -> None:
path = self.write("case.py", PAINTED)
def test_definition_keeps_profile_2_and_round_trips(self) -> None:
path = self.write("plate.py", PLATE)
first = run_notebook(path)
second = run_notebook(path)
self.assertEqual(self.statuses(second)[-1], "cached")
# (the content hash of a cached multi-body run differs from the first run on this branch already:
# test_multi_body_part's cache test, known WIP of the stable-refs merge; the appearance is the same)
self.assertEqual(first.definition.to_dict()["appearance"], second.definition.to_dict()["appearance"])
self.assertEqual(first.definition.content_hash, second.definition.content_hash)
manifest = second.definition.to_dict()
self.assertEqual(manifest["profile"], "simplecad-part-definition-3")
self.assertEqual(manifest["appearance"], {"bodies": [{"body_id": "lid", "color": list(RED), "opacity": 0.5}]})
self.assertEqual([row["name"] for row in manifest["solid_cache"]["bodies"]], [None, "Lid"])
validate_manifest(manifest, "part_definition")
part = materialize_definition(load_product_package(encode_product_package(build_product_package(second.definition))))
lid = part.get_body("lid")
self.assertEqual((lid.color, lid.opacity, lid.name), (RED, 0.5, "Lid"))
self.assertIsNone(part.get_body("base").color)
def test_one_body_definition_keeps_profile_2_and_round_trips(self) -> None:
definition = run_notebook(self.write("plate.py", PLATE)).definition
manifest = definition.to_dict()
self.assertEqual(manifest["profile"], "simplecad-part-definition-2")
self.assertEqual(manifest["appearance"], {"bodies": [{"body_id": "body", "color": list(BLUE), "opacity": None, "name": "Plate"}]})
self.assertNotIn("bodies", manifest["solid_cache"])
validate_manifest(manifest, "part_definition")
part = materialize_definition(load_product_package(encode_product_package(build_product_package(definition))))
self.assertFalse(part.multi_body)
part = materialize_definition(load_product_package(encode_product_package(build_product_package(second.definition))))
self.assertEqual((part.bodies[0].color, part.bodies[0].name), (BLUE, "Plate"))
def test_a_plain_definition_has_no_appearance_key(self) -> None:
@@ -227,26 +180,20 @@ class TestPackage(NotebookTestCase):
def test_package_scene_nodes_carry_the_colour(self) -> None:
from simplecadapi.scene.product_scene import compile_product_scene
nodes = {n["node_id"]: n for n in compile_product_scene(run_notebook(self.write("case.py", PAINTED)).definition).manifest["nodes"]}
self.assertEqual(nodes["node/case/body:lid"]["properties"]["color"], list(RED))
self.assertEqual(nodes["node/case/body:lid"]["properties"]["opacity"], 0.5)
self.assertNotIn("color", nodes["node/case/body:base"]["properties"])
plate = compile_product_scene(run_notebook(self.write("plate.py", PLATE)).definition).manifest["nodes"]
self.assertEqual(plate[0]["properties"]["color"], list(BLUE))
self.assertEqual(len(plate), 1) # one node: a Part has no child solid nodes
def test_step_writes_the_body_colours_and_names(self) -> None:
for name, text, expected, label in (("case.py", PAINTED, RED, "Lid"), ("plate.py", PLATE, BLUE, None)):
data = encode_product_package(build_product_package(run_notebook(self.write(name, text)).definition))
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "out.step"
export_product_package_to_step(data, path)
step = path.read_text(encoding="utf-8", errors="replace")
rgb = [tuple(round(float(v), 3) for v in m) for m in re.findall(r"COLOUR_RGB\('[^']*',([\d.Ee+-]+),([\d.Ee+-]+),([\d.Ee+-]+)\)", step)]
# OCCT takes the colour as linear RGB (Quantity_TOC_RGB, as for a material colour) and STEP stores sRGB
srgb = tuple(round(c * 12.92 if c <= 0.0031308 else 1.055 * c ** (1 / 2.4) - 0.055, 3) for c in expected)
self.assertTrue(any(all(abs(a - b) < 2e-3 for a, b in zip(srgb, row)) for row in rgb), (name, rgb))
if label:
self.assertIn(f"'{label}'", step)
def test_step_writes_the_body_colour(self) -> None:
data = encode_product_package(build_product_package(run_notebook(self.write("plate.py", PLATE)).definition))
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "out.step"
export_product_package_to_step(data, path)
step = path.read_text(encoding="utf-8", errors="replace")
rgb = [tuple(round(float(v), 3) for v in m) for m in re.findall(r"COLOUR_RGB\('[^']*',([\d.Ee+-]+),([\d.Ee+-]+),([\d.Ee+-]+)\)", step)]
# OCCT takes the colour as linear RGB (Quantity_TOC_RGB, as for a material colour) and STEP stores sRGB
srgb = tuple(round(c * 12.92 if c <= 0.0031308 else 1.055 * c ** (1 / 2.4) - 0.055, 3) for c in BLUE)
self.assertTrue(any(all(abs(a - b) < 2e-3 for a, b in zip(srgb, row)) for row in rgb), rgb)
if __name__ == "__main__":
+222 -245
View File
@@ -1,27 +1,24 @@
"""Multi-body parts: one Part, several named solids kept apart (not an assembly).
"""A Part holds exactly one solid; several solids side by side are loose notebook values.
The spike of design-docs/multi-solid-design.md: a Part made from ``bodies={"base": ..., "lid": ...}`` keeps both
solids, previews them as two nodes, packages each with its own BRep and topology snapshot, exports one STEP product
holding both, reports the mass of each body, and survives the notebook cell cache. One-body Parts are unchanged.
The decision (design-docs/part-holds-one-solid.md): a Part is the unit an Assembly places, mates and gives connectors
to, so it is one solid. The solids the editor needs next to each other while a model is built (a tool and its target,
the tools of a pattern before the cut) are notebook values: they are previewed side by side, and a notebook that ends
with several of them and no Part has no product (``SeveralOpenBodiesError``) until the author chooses one.
This file replaces ``test_multi_body_part.py``. Its split-cut tests (``Pieces``) stay: pieces are notebook values.
"""
from __future__ import annotations
import copy
import pickle
import re
import tempfile
import unittest
from pathlib import Path
import pytest
import simplecadapi as scad
from simplecadapi.artifacts import materialize_definition
from simplecadapi.exporter.step import export_product_package_to_step
from simplecadapi.product.packages import build_product_package, encode_product_package, load_product_package
from simplecadapi.runtime import run_notebook
from simplecadapi.scene.preview import compile_preview, decode_preview_header, encode_preview, entity_info
from simplecadapi.runtime.projection import SeveralOpenBodiesError
from simplecadapi.scene.preview import compile_open_bodies, compile_preview, decode_preview_header, encode_preview, entity_info
from test_notebook_runtime import NotebookTestCase, cell, notebook_text
@@ -34,220 +31,252 @@ def _lid() -> scad.Solid:
return scad.make_box_rsolid(20.0, 20.0, 2.0, (40.0, 0.0, 0.0), tag_prefix="lid")
def _case() -> scad.Part:
return scad.make_part_rpart(part_id="case", bodies={"base": _base(), "lid": _lid()})
def _tags(solid: scad.Solid) -> set[str]:
return {tag for face in solid.faces() for tag in face._tags}
class TestMultiBodyPartValue(unittest.TestCase):
def test_bodies_are_kept_apart_in_order(self) -> None:
case = _case()
self.assertTrue(case.multi_body)
self.assertEqual(case.body_ids(), ("base", "lid"))
self.assertEqual([type(body).__name__ for body in case.bodies], ["Body", "Body"])
self.assertAlmostEqual(case.get_body("lid").solid.get_volume(), 800.0, places=6)
self.assertIn("lid.face.top", _tags(case.get_body("lid").solid))
self.assertEqual(case.to_dict()["bodies"], [{"body_id": "base", "name": None}, {"body_id": "lid", "name": None}])
def test_body_is_refused_on_a_multi_body_part(self) -> None:
with self.assertRaisesRegex(TypeError, r"has 2 bodies \(base, lid\)"):
_case().body
with self.assertRaises(KeyError):
_case().get_body("hinge")
def test_bodies_may_be_body_values_with_names(self) -> None:
case = scad.make_part_rpart(
part_id="case", bodies=[scad.Body("base", _base(), "Base"), scad.Body("lid", _lid(), name="Lid")]
)
self.assertEqual([body.name for body in case.bodies], ["Base", "Lid"])
def test_bad_bodies_are_refused(self) -> None:
with self.assertRaises(Exception):
scad.make_part_rpart(part_id="case", body=_base(), bodies={"lid": _lid()})
with self.assertRaises(Exception):
scad.make_part_rpart(part_id="case")
with self.assertRaisesRegex(Exception, "duplicate body_id"):
scad.Part(part_id="case", bodies=[scad.Body("a", _base()), scad.Body("a", _lid())])
with self.assertRaises(Exception):
scad.make_part_rpart(part_id="case", bodies={"not an id": _base(), "lid": _lid()})
with self.assertRaises(Exception):
scad.make_part_rpart(part_id="case", bodies={"base": _base(), "lid": "lid"})
def test_a_one_body_part_is_what_it_always_was(self) -> None:
class TestAPartIsOneSolid(unittest.TestCase):
def test_a_part_has_one_body(self) -> None:
part = scad.make_part_rpart(part_id="plate", body=_base())
self.assertFalse(part.multi_body)
self.assertEqual(part.body_ids(), ("body",))
self.assertEqual(len(part.bodies), 1)
self.assertTrue(part.body.same_topology(part.bodies[0].solid))
self.assertFalse(hasattr(part, "multi_body"))
self.assertNotIn("bodies", part.to_dict())
def test_pickle_and_deepcopy_keep_every_body_and_its_tags(self) -> None:
case = _case().with_material(scad.make_material_rmaterial(material_id="pp", density=900.0, density_unit="kg/m^3"))
for again in (pickle.loads(pickle.dumps(case)), copy.deepcopy(case)):
self.assertEqual(again.body_ids(), ("base", "lid"))
self.assertEqual(again.material.material_id, "pp")
self.assertEqual(_tags(again.get_body("lid").solid), _tags(case.get_body("lid").solid))
one = pickle.loads(pickle.dumps(scad.make_part_rpart(part_id="plate", body=_base())))
self.assertFalse(one.multi_body)
def test_several_solids_are_refused_with_what_to_do(self) -> None:
for build in (
lambda: scad.make_part_rpart(part_id="case", body=[_base(), _lid()]), # the pieces of a split cut
lambda: scad.Part(part_id="case", body=[_base(), _lid()]),
):
with self.assertRaisesRegex(Exception, r"exactly one solid.*one Part per"):
build()
def test_material_and_connectors(self) -> None:
def test_the_bodies_argument_no_longer_exists(self) -> None:
with self.assertRaises(TypeError):
scad.make_part_rpart(part_id="case", bodies={"base": _base(), "lid": _lid()})
with self.assertRaises(TypeError):
scad.Part(part_id="case", bodies=[scad.Body("a", _base())])
with self.assertRaises(Exception):
scad.make_part_rpart(part_id="case") # a body is required
def test_one_solid_in_a_list_or_a_body_is_accepted(self) -> None:
self.assertEqual(scad.make_part_rpart(part_id="one", body=[_base()]).body_ids(), ("body",))
named = scad.Part(part_id="one", body=scad.Body("body", _base(), "Base", color=(0.1, 0.2, 0.3), opacity=0.5))
self.assertEqual((named.bodies[0].name, named.bodies[0].color, named.bodies[0].opacity), ("Base", (0.1, 0.2, 0.3), 0.5))
def test_pickle_and_deepcopy_keep_the_body_and_its_tags(self) -> None:
part = scad.make_part_rpart(part_id="plate", body=_base())
again = pickle.loads(pickle.dumps(part))
self.assertEqual(again.body_ids(), ("body",))
self.assertIn("base.face.top", {tag for face in again.body.faces() for tag in face._tags})
def test_the_mass_report_has_one_row(self) -> None:
material = scad.make_material_rmaterial(material_id="al", density=2.7, density_unit="g/cm^3")
case = scad.assign_material_rpart(_case(), material)
self.assertEqual(case.body_ids(), ("base", "lid"))
connector = scad.make_placement_connector_rconnector(
connector_id="mount", placement=scad.identity_placement_rplacement()
)
with self.assertRaisesRegex(Exception, "multi-body"):
scad.add_connector_rpart(case, connector)
def test_an_assembly_of_a_multi_body_part_flattens_every_body(self) -> None:
rig = scad.make_assembly_rassembly(assembly_id="rig")
rig = scad.add_component_rassembly(
assembly=rig, item=_case(), component_id="case", placement=scad.make_placement_rplacement(origin=(0, 0, 5))
)
compound = scad.make_compound_from_assembly_rcompound(assembly=rig)
self.assertEqual(len(compound.solids()), 2)
class TestMultiBodyReplay(unittest.TestCase):
def test_a_recorded_multi_body_part_replays_with_its_bodies(self) -> None:
with scad.GraphSession() as session:
_case()
replayed = [item for item in scad.replay_model_json(scad.export_model_json(session)) if isinstance(item, scad.Part)]
self.assertEqual([part.body_ids() for part in replayed], [("base", "lid")])
self.assertAlmostEqual(replayed[0].get_body("lid").solid.get_volume(), 800.0, places=6)
class TestMultiBodyMass(unittest.TestCase):
def test_mass_of_each_body_and_of_the_part(self) -> None:
material = scad.make_material_rmaterial(material_id="al", density=2.7, density_unit="g/cm^3")
report = scad.measure_part_mass_rmassreport(scad.assign_material_rpart(_case(), material))
self.assertEqual([item.body_id for item in report.bodies], ["base", "lid"])
self.assertAlmostEqual(report.body("base").volume_mm3, 4000.0, places=6)
self.assertAlmostEqual(report.body("base").mass_kg, 4000.0 * 2.7e-6, places=12)
self.assertAlmostEqual(report.body("lid").mass_kg, 800.0 * 2.7e-6, places=12)
self.assertAlmostEqual(report.mass_kg, 4800.0 * 2.7e-6, places=12)
self.assertAlmostEqual(report.body("lid").centroid_mm[0], 40.0, places=6)
self.assertAlmostEqual(report.centroid_mm[0], 800.0 * 40.0 / 4800.0, places=6)
def test_without_a_density_masses_are_none(self) -> None:
report = scad.measure_part_mass_rmassreport(_case())
self.assertIsNone(report.mass_kg)
self.assertAlmostEqual(report.volume_mm3, 4800.0, places=6)
override = scad.measure_part_mass_rmassreport(_case(), density=1000.0)
self.assertAlmostEqual(override.body("lid").mass_kg, 800.0e-6, places=12)
def test_a_one_body_part_has_one_row(self) -> None:
report = scad.measure_part_mass_rmassreport(scad.make_part_rpart(part_id="plate", body=_base()))
report = scad.measure_part_mass_rmassreport(scad.assign_material_rpart(scad.make_part_rpart(part_id="base", body=_base()), material))
self.assertEqual([item.body_id for item in report.bodies], ["body"])
self.assertAlmostEqual(report.mass_kg, 4000.0 * 2.7e-6, places=12)
def test_the_removed_helpers_are_gone(self) -> None:
for name in ("part_shape", "inspect_body_overlaps_rlist", "BodyOverlap", "BodyOverlapWarning"):
self.assertFalse(hasattr(scad, name), name)
class TestMultiBodyPreview(unittest.TestCase):
def test_each_body_is_a_node_with_its_own_entities(self) -> None:
scene = compile_preview(_case())
class TestEveryPartCanJoinAnAssembly(unittest.TestCase):
"""What the multi-body Part could not do (it refused connectors and made explode_rassembly raise)."""
def _rig(self) -> scad.Assembly:
mount = scad.make_placement_connector_rconnector(connector_id="mount", placement=scad.identity_placement_rplacement())
base = scad.add_connector_rpart(scad.make_part_rpart(part_id="base", body=_base()), mount)
lid = scad.add_connector_rpart(scad.make_part_rpart(part_id="lid", body=_lid()), mount)
rig = scad.make_assembly_rassembly(assembly_id="rig")
rig = scad.add_component_rassembly(assembly=rig, item=base, component_id="base", placement=scad.identity_placement_rplacement())
return scad.add_component_rassembly(
assembly=rig, item=lid, component_id="lid", placement=scad.make_placement_rplacement(origin=(0, 0, 10))
)
def test_a_part_takes_connectors(self) -> None:
part = scad.add_connector_rpart(
scad.make_part_rpart(part_id="base", body=_base()),
scad.make_placement_connector_rconnector(connector_id="mount", placement=scad.identity_placement_rplacement()),
)
self.assertEqual(part.connector_ids(), ("mount",))
def test_the_assembly_flattens_explodes_and_previews(self) -> None:
rig = self._rig()
self.assertEqual(len(scad.make_compound_from_assembly_rcompound(assembly=rig).solids()), 2)
exploded = scad.explode_rassembly(rig, 1.0)
self.assertEqual(set(exploded.component_ids()), {"base", "lid"})
header = decode_preview_header(encode_preview(compile_preview(rig)))
self.assertEqual([node["node_id"] for node in header["nodes"]], ["node/rig/base", "node/rig/lid"])
def test_several_solids_are_delivered_as_an_assembly_of_parts(self) -> None:
rig = scad.make_assembly_rassembly(assembly_id="case")
for name, solid in (("base", _base()), ("lid", _lid())):
rig = scad.add_component_rassembly(
assembly=rig,
item=scad.make_part_rpart(part_id=name, body=solid),
component_id=name,
placement=scad.identity_placement_rplacement(),
)
self.assertEqual(len(scad.make_compound_from_assembly_rcompound(assembly=rig).solids()), 2)
class TestReplay(unittest.TestCase):
def test_a_recorded_part_replays(self) -> None:
with scad.GraphSession() as session:
scad.make_part_rpart(part_id="plate", body=_base())
replayed = [item for item in scad.replay_model_json(scad.export_model_json(session)) if isinstance(item, scad.Part)]
self.assertEqual([part.body_ids() for part in replayed], [("body",)])
self.assertAlmostEqual(replayed[0].body.get_volume(), 4000.0, places=6)
def test_a_model_recorded_with_several_solids_in_one_part_is_refused(self) -> None:
import json
with scad.GraphSession() as session:
scad.make_part_rpart(part_id="plate", body=_base())
model = json.loads(scad.export_model_json(session))
node = next(n for n in model["graph"]["nodes"] if n.get("op") == "make_part_rpart") if "graph" in model else None
if node is None:
self.skipTest("the model JSON layout has no graph/nodes with ops to edit")
params = node.setdefault("params", {})
params["bodies"] = [{"body_id": "a", "name": None}, {"body_id": "b", "name": None}]
with self.assertRaisesRegex(Exception, "exactly one solid"):
scad.replay_model_json(json.dumps(model))
class TestOpenBodiesPreview(unittest.TestCase):
"""The editor's several solids side by side: drawn as nodes of the notebook, not as the bodies of a Part."""
def test_each_open_solid_is_a_node_with_its_own_entities(self) -> None:
scene = compile_open_bodies("nb", {"base": _base(), "lid": _lid()})
header = decode_preview_header(encode_preview(scene))
self.assertEqual([node["node_id"] for node in header["nodes"]], ["node/case/body:base", "node/case/body:lid"])
self.assertEqual([node["node_id"] for node in header["nodes"]], ["node/nb/body:base", "node/nb/body:lid"])
self.assertEqual({part["body_id"] for part in header["parts"]}, {"base", "lid"})
lid = next(part for part in header["parts"] if part["body_id"] == "lid")
self.assertTrue(lid["solid_entity_id"].startswith("entity/case/body:lid/solid/"))
self.assertTrue(all(g["entity_id"].startswith("entity/case/body:lid/face/") for g in lid["face_groups"]))
self.assertTrue(lid["solid_entity_id"].startswith("entity/nb/body:lid/solid/"))
info = entity_info(scene, lid["solid_entity_id"])
self.assertAlmostEqual(info["properties"]["volume"], 800.0, places=6)
face = entity_info(scene, lid["face_groups"][0]["entity_id"])
self.assertEqual(face["kind"], "face")
self.assertTrue(any(tag.startswith("lid.face.") for tag in face["tags"]))
def test_two_bodies_of_the_same_shape_stay_two(self) -> None:
a = scad.make_box_rsolid(5.0, 5.0, 5.0)
b = scad.make_box_rsolid(5.0, 5.0, 5.0)
scene = compile_preview(scad.make_part_rpart(part_id="pair", bodies={"a": a, "b": b}))
self.assertEqual(len(scene.nodes), 2)
self.assertEqual(len(scene.parts), 2)
def test_two_solids_of_the_same_shape_stay_two(self) -> None:
scene = compile_open_bodies("pair", {"a": scad.make_box_rsolid(5.0, 5.0, 5.0), "b": scad.make_box_rsolid(5.0, 5.0, 5.0)})
self.assertEqual((len(scene.nodes), len(scene.parts)), (2, 2))
def test_a_one_body_part_previews_as_before(self) -> None:
def test_a_part_previews_as_one_node(self) -> None:
header = decode_preview_header(encode_preview(compile_preview(scad.make_part_rpart(part_id="plate", body=_base()))))
self.assertEqual([node["node_id"] for node in header["nodes"]], ["node/plate"])
self.assertNotIn("body_id", header["parts"][0])
self.assertTrue(header["parts"][0]["solid_entity_id"].startswith("entity/plate/solid/"))
def test_nothing_to_draw_is_an_error(self) -> None:
with self.assertRaises(Exception):
compile_open_bodies("nb", {})
CASE = notebook_text(
def _part_notebook(*cells: str, notebook_id: str = "demo") -> str:
return notebook_text(*cells, table=f'id = "{notebook_id}"\nkind = "part"')
TWO_OPEN = _part_notebook(
cell(
"""
base = scad.make_box_rsolid(20.0, 20.0, 10.0, tag_prefix="base")
lid = scad.make_box_rsolid(20.0, 20.0, 2.0, (40.0, 0.0, 0.0), tag_prefix="lid")
tool = scad.make_cylinder_rsolid(3.0, 30.0, (10.0, 10.0, -5.0))
""",
returns="base, lid",
returns="base, tool",
),
)
ONE_OPEN = _part_notebook(cell("base = scad.make_box_rsolid(20.0, 20.0, 10.0)", returns="base"))
CHOSEN = _part_notebook(
cell(
'case = scad.make_part_rpart(part_id=scad.notebook_id(), bodies={"base": base, "lid": lid})',
reads="base, lid",
returns="case",
"""
base = scad.make_box_rsolid(20.0, 20.0, 10.0, tag_prefix="base")
tool = scad.make_cylinder_rsolid(3.0, 30.0, (10.0, 10.0, -5.0))
""",
returns="base, tool",
),
table='id = "case"',
cell("demo = scad.make_part_rpart(part_id=scad.notebook_id(), body=base)", reads="base", returns="demo"),
)
CUT = _part_notebook(
cell(
"""
base = scad.make_box_rsolid(20.0, 20.0, 10.0)
tool = scad.make_cylinder_rsolid(3.0, 30.0, (10.0, 10.0, -5.0))
""",
returns="base, tool",
),
cell("bored = scad.cut_rsolid(base, tool)", reads="base, tool", returns="bored"),
)
class TestMultiBodyNotebook(NotebookTestCase):
def setUp(self) -> None:
super().setUp()
self.case = self.write("case.py", CASE)
class TestNotebookProduct(NotebookTestCase):
def test_one_open_solid_is_the_implicit_part(self) -> None:
product = run_notebook(self.write("one.py", ONE_OPEN.replace('"demo"', '"one"'))).product
self.assertEqual((product.part_id, product.body_ids()), ("one", ("body",)))
def test_the_cell_cache_restores_a_multi_body_product(self) -> None:
first = run_notebook(self.case)
second = run_notebook(self.case)
self.assertEqual(self.statuses(second), ["ran", "cached", "cached"])
self.assertEqual(first.definition.content_hash, second.definition.content_hash)
self.assertEqual([item.body_id for item in second.definition.bodies], ["base", "lid"])
def test_several_open_solids_have_no_product(self) -> None:
with self.assertRaises(SeveralOpenBodiesError) as caught:
run_notebook(self.write("two.py", TWO_OPEN))
self.assertEqual(caught.exception.names, ("base", "tool"))
message = str(caught.exception)
self.assertIn("exactly one solid", message)
self.assertIn("make_part_rpart", message)
def test_the_package_holds_both_bodies_with_their_tags(self) -> None:
definition = run_notebook(self.case).definition
def test_the_tool_cut_into_the_body_leaves_one_open_solid(self) -> None:
# the example of the design: a tool and its target exist together, then the cut leaves one solid
product = run_notebook(self.write("cut.py", CUT)).product
self.assertEqual(product.body_ids(), ("body",))
self.assertLess(product.body.get_volume(), 20 * 20 * 10)
def test_a_part_made_of_the_chosen_solid_is_the_product(self) -> None:
product = run_notebook(self.write("chosen.py", CHOSEN)).product
self.assertAlmostEqual(product.body.get_volume(), 4000.0, places=6)
self.assertIn("base.face.top", {tag for face in product.body.faces() for tag in face._tags})
def test_the_package_holds_one_solid_and_exports_to_step(self) -> None:
import re
import tempfile
from pathlib import Path
from simplecadapi.exporter.step import export_product_package_to_step
from simplecadapi.product.packages import build_product_package, encode_product_package
definition = run_notebook(self.write("chosen.py", CHOSEN)).definition
manifest = definition.to_dict()
self.assertEqual([row["body_id"] for row in manifest["solid_cache"]["bodies"]], ["base", "lid"])
loaded = load_product_package(encode_product_package(build_product_package(definition)))
part = materialize_definition(loaded) # the package's root definition, read back from its bytes
self.assertEqual(part.body_ids(), ("base", "lid"))
self.assertIn("lid.face.top", _tags(part.get_body("lid").solid))
self.assertIn("base.face.top", _tags(part.get_body("base").solid))
self.assertAlmostEqual(scad.measure_part_mass_rmassreport(part).body("lid").volume_mm3, 800.0, places=6)
def test_the_scene_draws_each_body_as_a_solid_node(self) -> None:
from simplecadapi.scene.product_scene import compile_product_scene
manifest = compile_product_scene(run_notebook(self.case).definition).manifest
nodes = {node["node_id"]: node for node in manifest["nodes"]}
self.assertIsNone(nodes["node/case"]["geometry_asset_id"])
self.assertEqual(nodes["node/case/body:lid"]["node_kind"], "solid")
self.assertEqual(nodes["node/case/body:lid"]["parent_node_id"], "node/case")
self.assertIsNotNone(nodes["node/case/body:base"]["geometry_asset_id"])
self.assertNotEqual(nodes["node/case/body:base"]["entity_asset_id"], nodes["node/case/body:lid"]["entity_asset_id"])
def test_step_export_writes_one_product_with_both_solids(self) -> None:
data = encode_product_package(build_product_package(run_notebook(self.case).definition))
self.assertEqual(manifest["profile"], "simplecad-part-definition-2")
self.assertNotIn("bodies", manifest["solid_cache"])
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "case.step"
export_product_package_to_step(data, path)
path = Path(directory) / "demo.step"
export_product_package_to_step(encode_product_package(build_product_package(definition)), path)
text = path.read_text(encoding="utf-8", errors="replace")
self.assertEqual(len(re.findall(r"MANIFOLD_SOLID_BREP", text)), 2)
self.assertEqual(len(re.findall(r"= PRODUCT\(", text)), 1)
self.assertEqual(len(re.findall(r"MANIFOLD_SOLID_BREP", text)), 1)
def test_a_one_body_definition_has_no_bodies_list(self) -> None:
self.write(
"plate.py",
notebook_text(
cell("plate = scad.make_part_rpart(part_id=scad.notebook_id(), body=scad.make_box_rsolid(5.0, 5.0, 1.0))", returns="plate"),
table='id = "plate"',
),
)
definition = run_notebook(self.root / "plate.py").definition
self.assertNotIn("bodies", definition.to_dict()["solid_cache"])
self.assertEqual(definition.bodies, ())
def test_the_cell_cache_restores_the_product(self) -> None:
path = self.write("chosen.py", CHOSEN)
first = run_notebook(path)
second = run_notebook(path)
self.assertEqual(first.definition.content_hash, second.definition.content_hash)
self.assertIn("cached", self.statuses(second))
def test_the_live_preview_shows_the_open_solids(self) -> None:
from simplecadapi.runtime.live import preview_product
from simplecadapi.runtime.projection import OpenBodies
from simplecadapi.runtime import config as runtime_config
path = self.write("two.py", TWO_OPEN)
config = runtime_config.read_notebook_config(path)
base, tool = _base(), scad.make_cylinder_rsolid(3.0, 30.0, (10.0, 10.0, -5.0))
product, partial = preview_product(config, [], {"base": base, "tool": tool})
self.assertIsInstance(product, OpenBodies)
self.assertIsNone(partial)
self.assertEqual(list(product.bodies), ["base", "tool"])
class TestSplitCutsAndOverlaps(unittest.TestCase):
"""Owner decisions: a splitting cut is not refused; overlapping bodies warn but are allowed."""
class TestSplitCutsStillGivePieces(unittest.TestCase):
"""Pieces are notebook values (where several solids belong); a Part takes one of them."""
@staticmethod
def _bar_and_slot() -> tuple[scad.Solid, scad.Solid]:
@@ -261,75 +290,21 @@ class TestSplitCutsAndOverlaps(unittest.TestCase):
with self.assertRaisesRegex(Exception, "split the body"):
scad.cut_rsolid(*self._bar_and_slot(), on_split="error")
def test_pieces_become_bodies(self) -> None:
def test_a_piece_is_a_part_and_pieces_are_not(self) -> None:
bar, slot = self._bar_and_slot()
pieces = scad.cut_rsolid(bar, slot)
self.assertEqual(scad.make_part_rpart(part_id="bar", body=pieces).body_ids(), ("body_1", "body_2"))
lid = _lid()
part = scad.make_part_rpart(part_id="bar", bodies={"bar": pieces, "lid": lid})
self.assertEqual(part.body_ids(), ("bar_1", "bar_2", "lid"))
self.assertAlmostEqual(part.get_body("bar_2").solid.get_volume(), 1800.0, places=6)
with self.assertRaisesRegex(Exception, "exactly one solid"):
scad.make_part_rpart(part_id="bar", body=pieces)
left = scad.make_part_rpart(part_id="bar_left", body=pieces[0])
self.assertAlmostEqual(left.body.get_volume(), 1800.0, places=6)
def test_a_split_replays_with_the_same_piece_order(self) -> None:
with scad.GraphSession() as session:
bar, slot = self._bar_and_slot()
scad.make_part_rpart(part_id="bar", body=scad.cut_rsolid(bar, slot))
pieces = scad.cut_rsolid(bar, slot)
scad.make_part_rpart(part_id="bar", body=pieces[0])
(part,) = [x for x in scad.replay_model_json(scad.export_model_json(session)) if isinstance(x, scad.Part)]
self.assertEqual(part.body_ids(), ("body_1", "body_2"))
self.assertLess(part.get_body("body_1").solid.get_center().x, part.get_body("body_2").solid.get_center().x)
def test_overlaps_are_reported_and_warned_not_refused(self) -> None:
a = scad.make_box_rsolid(10.0, 10.0, 10.0)
b = scad.make_box_rsolid(10.0, 10.0, 10.0, (5.0, 0.0, 0.0))
c = scad.make_box_rsolid(10.0, 10.0, 10.0, (15.0, 0.0, 0.0)) # touches b only along a face
part = scad.make_part_rpart(part_id="stack", bodies={"a": a, "b": b, "c": c})
overlaps = scad.inspect_body_overlaps_rlist(part)
self.assertEqual([(o.first, o.second) for o in overlaps], [("a", "b")])
self.assertAlmostEqual(overlaps[0].volume_mm3, 500.0, places=6)
@scad.part(id="stack")
def stack() -> scad.Part:
return scad.make_part_rpart(
part_id="stack",
bodies={"a": scad.make_box_rsolid(10.0, 10.0, 10.0), "b": scad.make_box_rsolid(10.0, 10.0, 10.0, (5.0, 0.0, 0.0))},
)
with self.assertWarns(scad.BodyOverlapWarning):
result = stack()
self.assertEqual([item.body_id for item in result.definition.bodies], ["a", "b"])
def test_part_from_bodies_is_the_implicit_part_rule(self) -> None:
from simplecadapi.product.bodies import part_from_bodies
one = part_from_bodies("plate", {"plate": _base()})
self.assertEqual(one.body_ids(), ("body",))
bar, slot = self._bar_and_slot()
split = part_from_bodies("bar", {"bar": scad.cut_rsolid(bar, slot)})
self.assertEqual(split.body_ids(), ("bar_1", "bar_2"))
both = part_from_bodies("case", {"base": _base(), "lid": _lid()})
self.assertEqual(both.body_ids(), ("base", "lid"))
class TestProfileThree(unittest.TestCase):
def test_a_multi_body_definition_is_profile_3_and_a_profile_2_reader_refuses_it(self) -> None:
from simplecadapi.artifacts.canonical import ArtifactValidationError
from simplecadapi.artifacts.validation import _schema_validate, validate_manifest
@scad.part(id="case")
def case() -> scad.Part:
return _case()
manifest = case().definition.to_dict()
self.assertEqual(manifest["profile"], "simplecad-part-definition-3")
validate_manifest(manifest) # this SDK reads it
with self.assertRaises(ArtifactValidationError): # what an SDK that knows only profile 2 does
_schema_validate({**manifest, "profile": "simplecad-part-definition-2"}, "part_definition")
@scad.part(id="plate")
def plate() -> scad.Part:
return scad.make_part_rpart(part_id="plate", body=_base())
self.assertEqual(plate().definition.to_dict()["profile"], "simplecad-part-definition-2")
self.assertLess(part.body.get_center().x, 0.0)
if __name__ == "__main__":
@@ -369,7 +344,9 @@ def test_an_operation_on_the_pieces_of_a_split_body_applies_to_every_piece():
assert len(scad.shell_rsolid(pieces, tops.exactly(2), 1.0)) == 2
with pytest.raises(ValueError, match="found 2"):
scad.shell_rsolid(pieces, tops.exactly(1), 1.0)
assert [b.body_id for b in scad.make_part_rpart(part_id="x", body=moved).bodies] == ["body_1", "body_2"]
# several pieces are not one Part: a Part holds exactly one solid
with pytest.raises(Exception, match="exactly one solid"):
scad.make_part_rpart(part_id="x", body=moved)
assert isinstance(pickle.loads(pickle.dumps(pieces)), scad.Pieces)
# a plain list is still a list of tools: a - b - c
box = scad.make_box_rsolid(10.0, 10.0, 10.0)