py-materials 3.3.0__tar.gz → 3.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. {py_materials-3.3.0 → py_materials-3.5.0}/PKG-INFO +2 -2
  2. {py_materials-3.3.0 → py_materials-3.5.0}/pyproject.toml +2 -2
  3. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/__init__.py +66 -1
  4. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/loader.py +11 -2
  5. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/search.py +51 -24
  6. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/vis/__init__.py +27 -50
  7. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/vis/_model.py +64 -0
  8. py_materials-3.5.0/tests/test_build123d_integration_examples.py +64 -0
  9. py_materials-3.5.0/tests/test_lookup.py +196 -0
  10. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_vis.py +75 -117
  11. py_materials-3.5.0/tests/test_vis_inheritance.py +309 -0
  12. {py_materials-3.3.0 → py_materials-3.5.0}/.gitignore +0 -0
  13. {py_materials-3.3.0 → py_materials-3.5.0}/LICENSE +0 -0
  14. {py_materials-3.3.0 → py_materials-3.5.0}/README.md +0 -0
  15. {py_materials-3.3.0 → py_materials-3.5.0}/docs/catalog/README.md +0 -0
  16. {py_materials-3.3.0 → py_materials-3.5.0}/docs/catalog/ceramics/README.md +0 -0
  17. {py_materials-3.3.0 → py_materials-3.5.0}/docs/catalog/electronics/README.md +0 -0
  18. {py_materials-3.3.0 → py_materials-3.5.0}/docs/catalog/gases/README.md +0 -0
  19. {py_materials-3.3.0 → py_materials-3.5.0}/docs/catalog/liquids/README.md +0 -0
  20. {py_materials-3.3.0 → py_materials-3.5.0}/docs/catalog/metals/README.md +0 -0
  21. {py_materials-3.3.0 → py_materials-3.5.0}/docs/catalog/plastics/README.md +0 -0
  22. {py_materials-3.3.0 → py_materials-3.5.0}/docs/catalog/scintillators/README.md +0 -0
  23. {py_materials-3.3.0 → py_materials-3.5.0}/docs/decisions/README.md +0 -0
  24. {py_materials-3.3.0 → py_materials-3.5.0}/mat-rs/data/README.md +0 -0
  25. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/core.py +0 -0
  26. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/data/ceramics.toml +0 -0
  27. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/data/electronics.toml +0 -0
  28. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/data/gases.toml +0 -0
  29. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/data/liquids.toml +0 -0
  30. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/data/metals.toml +0 -0
  31. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/data/plastics.toml +0 -0
  32. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/data/scintillators.toml +0 -0
  33. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/elements.py +0 -0
  34. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/enrichers.py +0 -0
  35. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/factories.py +0 -0
  36. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/properties.py +0 -0
  37. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/registry.py +0 -0
  38. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/units.py +0 -0
  39. {py_materials-3.3.0 → py_materials-3.5.0}/src/pymat/vis/adapters.py +0 -0
  40. {py_materials-3.3.0 → py_materials-3.5.0}/tests/__init__.py +0 -0
  41. {py_materials-3.3.0 → py_materials-3.5.0}/tests/_visual_compare.py +0 -0
  42. {py_materials-3.3.0 → py_materials-3.5.0}/tests/baselines/README.md +0 -0
  43. {py_materials-3.3.0 → py_materials-3.5.0}/tests/conftest.py +0 -0
  44. {py_materials-3.3.0 → py_materials-3.5.0}/tests/material_preview.html +0 -0
  45. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_adapters.py +0 -0
  46. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_apply_to.py +0 -0
  47. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_catalog.py +0 -0
  48. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_core.py +0 -0
  49. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_e2e_vis.py +0 -0
  50. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_enrichers.py +0 -0
  51. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_integration.py +0 -0
  52. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_loader.py +0 -0
  53. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_properties.py +0 -0
  54. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_readme_examples.py +0 -0
  55. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_search.py +0 -0
  56. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_toml_integrity.py +0 -0
  57. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_uncertainties.py +0 -0
  58. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_visual_compare.py +0 -0
  59. {py_materials-3.3.0 → py_materials-3.5.0}/tests/test_visual_regression.py +0 -0
  60. {py_materials-3.3.0 → py_materials-3.5.0}/tests/visual_render.html +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: py-materials
3
- Version: 3.3.0
3
+ Version: 3.5.0
4
4
  Summary: Hierarchical material library for CAD applications with build123d integration
5
5
  Project-URL: Homepage, https://github.com/MorePet/py-mat
6
6
  Project-URL: Repository, https://github.com/MorePet/py-mat
@@ -21,7 +21,7 @@ Classifier: Programming Language :: Python :: 3.13
21
21
  Classifier: Topic :: Scientific/Engineering
22
22
  Classifier: Topic :: Scientific/Engineering :: Physics
23
23
  Requires-Python: >=3.10
24
- Requires-Dist: mat-vis-client>=0.5.0
24
+ Requires-Dist: mat-vis-client>=0.6.3
25
25
  Requires-Dist: periodictable>=1.6.0
26
26
  Requires-Dist: pint>=0.20
27
27
  Requires-Dist: tomli>=1.0.0; python_version == '3.10'
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "py-materials"
7
- version = "3.3.0"
7
+ version = "3.5.0"
8
8
  description = "Hierarchical material library for CAD applications with build123d integration"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -31,7 +31,7 @@ dependencies = [
31
31
  "pint>=0.20",
32
32
  "periodictable>=1.6.0",
33
33
  "uncertainties>=3.2",
34
- "mat-vis-client>=0.5.0",
34
+ "mat-vis-client>=0.6.3",
35
35
  "tomli>=1.0.0; python_version == '3.10'",
36
36
  ]
37
37
 
@@ -57,7 +57,7 @@ from .properties import (
57
57
  from .search import search
58
58
  from .units import ureg
59
59
 
60
- __version__ = "3.3.0" # x-release-please-version
60
+ __version__ = "3.5.0" # x-release-please-version
61
61
  __all__ = [
62
62
  "Material",
63
63
  "AllProperties",
@@ -182,6 +182,71 @@ def __getattr__(name: str) -> Material:
182
182
  raise AttributeError(f"module 'pymat' has no attribute '{name}'")
183
183
 
184
184
 
185
+ def _lookup(name_or_key: str) -> Material:
186
+ """Exact-lookup implementation for ``pymat["..."]``.
187
+
188
+ Resolves ``name_or_key`` against the registered material library via
189
+ ``search(..., exact=True)``. Raises ``KeyError`` for empty queries,
190
+ misses, and ambiguous matches — the candidate list is attached to
191
+ the error message so the user can pick.
192
+
193
+ Backing the subscript form (``pymat["Stainless Steel 304"]``) is the
194
+ idiomatic Python-registry pattern (see ``os.environ``, ``sys.modules``,
195
+ ``collections.ChainMap``) — raises on miss by convention, unlike
196
+ ``dict.get`` which returns None.
197
+ """
198
+ if not isinstance(name_or_key, str):
199
+ raise TypeError(f"pymat[...] takes a string key or name, got {type(name_or_key).__name__}")
200
+ if not name_or_key.strip():
201
+ raise KeyError("pymat[...] requires a non-empty material name or key; got empty/whitespace")
202
+
203
+ hits = search(name_or_key, exact=True, limit=50)
204
+ if not hits:
205
+ # Offer the closest fuzzy matches so the user can see what was
206
+ # close — far more useful than a bare KeyError.
207
+ fuzzy = search(name_or_key, limit=5)
208
+ if fuzzy:
209
+ suggestions = ", ".join(repr(m.name) for m in fuzzy)
210
+ raise KeyError(
211
+ f"No material matches {name_or_key!r} exactly. "
212
+ f"Close matches: {suggestions}. "
213
+ f"Use pymat.search({name_or_key!r}) for the full fuzzy list."
214
+ )
215
+ raise KeyError(f"No material matches {name_or_key!r}")
216
+ if len(hits) > 1:
217
+ names = ", ".join(repr(m.name) for m in hits[:8])
218
+ raise KeyError(
219
+ f"Ambiguous: {len(hits)} materials match {name_or_key!r} "
220
+ f"(key, name, or grade). Candidates: {names}"
221
+ f"{' …' if len(hits) > 8 else ''}. "
222
+ f"Use a more specific query or index by key."
223
+ )
224
+ return hits[0]
225
+
226
+
227
+ # Install module-level __getitem__ so ``pymat["Stainless Steel 304"]`` works.
228
+ # PEP 562 covers module-level __getattr__ but not __getitem__; the standard
229
+ # pattern is to swap the module's __class__ for a subtype of ModuleType that
230
+ # defines __getitem__. Python's import machinery is unaffected.
231
+ import sys as _sys # noqa: E402 — must run after _lookup / Material definitions
232
+ import types as _types # noqa: E402 — same reason
233
+
234
+
235
+ class _PymatModule(_types.ModuleType):
236
+ def __getitem__(self, key: str) -> Material: # type: ignore[override]
237
+ return _lookup(key)
238
+
239
+ def __contains__(self, key: str) -> bool: # type: ignore[override]
240
+ try:
241
+ _lookup(key)
242
+ except KeyError:
243
+ return False
244
+ return True
245
+
246
+
247
+ _sys.modules[__name__].__class__ = _PymatModule
248
+
249
+
185
250
  def __dir__() -> list[str]:
186
251
  """
187
252
  Help IDE discover available materials.
@@ -256,12 +256,21 @@ def _resolve_material_node(
256
256
  _key=key,
257
257
  )
258
258
 
259
- # Populate vis from [vis] section if present
259
+ # Populate vis — inherit from parent, overlay any TOML overrides (#88).
260
+ # A grade TOML with no [vis] section gets a deep-copy of parent's vis;
261
+ # a partial [vis] table overrides individual fields on top of the copy.
262
+ # Root materials (no parent) always get a fresh Vis built from their
263
+ # own [vis] table (or an empty Vis when the table is absent).
260
264
  vis_data = data.get("vis")
265
+ parent_vis = parent_material._vis if parent_material is not None else None
261
266
  if vis_data and isinstance(vis_data, dict):
262
267
  from pymat.vis._model import Vis
263
268
 
264
- material._vis = Vis.from_toml(vis_data)
269
+ material._vis = Vis.merge_from_toml(parent_vis, vis_data)
270
+ elif parent_vis is not None:
271
+ from copy import deepcopy
272
+
273
+ material._vis = deepcopy(parent_vis)
265
274
 
266
275
  # Register for direct access
267
276
  registry.register(key, material)
@@ -13,12 +13,22 @@ included. Score is the sum of per-token best-target weights.
13
13
 
14
14
  from __future__ import annotations
15
15
 
16
+ import unicodedata
16
17
  from typing import TYPE_CHECKING
17
18
 
18
19
  if TYPE_CHECKING:
19
20
  from .core import Material
20
21
 
21
22
 
23
+ def _normalize(s: str) -> str:
24
+ """Normalize a lookup/search input: NFKC + lowercase + collapse whitespace.
25
+
26
+ Picks up pasted curly quotes, em-dashes, non-breaking spaces, and other
27
+ lookalikes that users paste from browser UIs.
28
+ """
29
+ return " ".join(unicodedata.normalize("NFKC", s).lower().split())
30
+
31
+
22
32
  # Target weights — higher is a stronger match. Order matters: when a
23
33
  # query token matches multiple targets on the same Material, the
24
34
  # highest-weight hit counts.
@@ -73,14 +83,21 @@ def _score(tokens: list[str], targets: list[tuple[str, int]]) -> int:
73
83
  return total
74
84
 
75
85
 
76
- def search(query: str, *, limit: int = 10) -> list[Material]:
77
- """Fuzzy-find Materials in the loaded library by name, key, or grade.
86
+ def search(query: str, *, exact: bool = False, limit: int = 10) -> list[Material]:
87
+ """Find Materials in the loaded library by name, key, or grade.
78
88
 
79
- Tokenizes ``query`` on whitespace (case-insensitive). Every token
80
- must match somewhere — registry key, ``Material.name``,
81
- ``Material.grade``, or a hierarchy parent name — for a Material
82
- to be included. Ranks by summed match weight; returns at most
83
- ``limit`` best hits.
89
+ - **Fuzzy (default)**: tokenize ``query`` on whitespace; every token
90
+ must match somewhere (registry key, ``Material.name``, ``grade``,
91
+ or a hierarchy parent name). Ranked by summed target weight.
92
+ - **Exact** (``exact=True``): the whole normalized query must equal
93
+ the registry key OR ``Material.name`` OR ``Material.grade`` — same
94
+ three targets the fuzzy path uses, but full-string equality. Use
95
+ this to resolve a single known material without the list noise of
96
+ fuzzy mode.
97
+
98
+ Normalization: NFKC + case-fold + whitespace-collapse. Curly quotes,
99
+ em-dashes, non-breaking spaces, leading/trailing and internal-run
100
+ whitespace all fold away before comparison.
84
101
 
85
102
  Returns an empty list for an empty / whitespace-only query.
86
103
 
@@ -89,20 +106,20 @@ def search(query: str, *, limit: int = 10) -> list[Material]:
89
106
  pymat.search("stainless")
90
107
  # → [stainless, s304, s316L, s410, ...]
91
108
 
92
- pymat.search("316")
93
- # → [s316L, s316, ...] — grades match, parent doesn't
94
-
95
109
  pymat.search("stainless 316")
96
- # → [s316L] — all tokens must match, grade wins
110
+ # → [s316L] — all tokens must match
97
111
 
98
- pymat.search("lyso ce saint")
99
- # → [prelude420, ...] — deep hierarchy via tokenization
112
+ pymat.search("304", exact=True)
113
+ # → [s304] — grade match, no fuzz
114
+
115
+ pymat.search("Stainless Steel", exact=True)
116
+ # → [stainless] — exact parent name
100
117
 
101
118
  Triggers ``load_all()`` on first call so results are exhaustive
102
119
  across categories.
103
120
  """
104
- tokens = query.lower().split()
105
- if not tokens:
121
+ normalized = _normalize(query)
122
+ if not normalized:
106
123
  return []
107
124
 
108
125
  # Import lazily to avoid circular import at module load: pymat's
@@ -113,15 +130,25 @@ def search(query: str, *, limit: int = 10) -> list[Material]:
113
130
  all_materials = registry.list_all()
114
131
 
115
132
  scored: list[tuple[int, int, str, Material]] = []
116
- for key, material in all_materials.items():
117
- targets = _targets(key, material)
118
- s = _score(tokens, targets)
119
- if s > 0:
120
- # Tie-break tuple: primary by score DESC (via -s), then by
121
- # key length ASC (shorter key wins — "s316L" before
122
- # "electropolished" when both score the same), then by key
123
- # alphabetical for determinism.
124
- scored.append((-s, len(key), key, material))
133
+
134
+ if exact:
135
+ # Full-string equality against key / name / grade. Same three
136
+ # targets the fuzzy path cares about.
137
+ for key, material in all_materials.items():
138
+ candidates = [key, material.name or ""]
139
+ grade = getattr(material, "grade", None)
140
+ if grade:
141
+ candidates.append(str(grade))
142
+ if any(_normalize(c) == normalized for c in candidates):
143
+ # Single-match: tie-break by shorter key for determinism.
144
+ scored.append((0, len(key), key, material))
145
+ else:
146
+ tokens = normalized.split()
147
+ for key, material in all_materials.items():
148
+ targets = _targets(key, material)
149
+ s = _score(tokens, targets)
150
+ if s > 0:
151
+ scored.append((-s, len(key), key, material))
125
152
 
126
153
  scored.sort()
127
154
  return [m for _, _, _, m in scored[:limit]]
@@ -39,6 +39,7 @@ from mat_vis_client import (
39
39
  # Shared-singleton accessor: ``get_client`` became public in
40
40
  # mat-vis-client 0.5.0 (see mat-vis#84). Pinned in pyproject.toml.
41
41
  from mat_vis_client import get_client as _shared_client
42
+ from mat_vis_client import search as _client_search
42
43
 
43
44
  # Material-accepting adapters: Three.js / glTF / MaterialX.
44
45
  # Re-exported at top level so ``from pymat.vis import to_threejs`` works
@@ -71,6 +72,7 @@ def search(
71
72
  roughness: float | None = None,
72
73
  metalness: float | None = None,
73
74
  source: str | None = None,
75
+ tier: str = "1k",
74
76
  limit: int = 20,
75
77
  ) -> list[dict[str, Any]]:
76
78
  """Search the mat-vis index by category, tags, and scalar similarity.
@@ -78,60 +80,35 @@ def search(
78
80
  Args:
79
81
  category: filter by canonical category (metal, wood, stone, ...)
80
82
  tags: require ALL these tags to be present in the entry's tags list
81
- roughness / metalness: score by scalar distance (if set in index)
83
+ roughness / metalness: score by scalar distance (widened ±0.2)
82
84
  source: limit to one source
85
+ tier: only return entries that have this tier available (default 1k);
86
+ scalar-only sources (e.g. physicallybased) are tier-independent
83
87
  limit: max results
84
88
 
85
- Does NOT filter by tier — search is for finding materials,
86
- tier is a fetch-time concern.
89
+ Thin forwarder to ``mat_vis_client.search`` for the category / scalar /
90
+ tier / scoring path; adds the ``tags`` post-filter (not in upstream).
91
+
92
+ Index entries follow the mat-vis 0.6.x schema: scalars and category
93
+ live under ``entry["mat_vis"]["category"]`` / ``["pbr"]["roughness"]``.
87
94
  """
88
- client = _shared_client()
89
-
90
- roughness_range = None
91
- if roughness is not None:
92
- roughness_range = (max(0.0, roughness - 0.2), min(1.0, roughness + 0.2))
93
-
94
- metalness_range = None
95
- if metalness is not None:
96
- metalness_range = (max(0.0, metalness - 0.2), min(1.0, metalness + 0.2))
97
-
98
- required_tags = set(t.lower() for t in (tags or []))
99
-
100
- # Search all sources, no tier filter
101
- sources = [source] if source else client.sources()
102
- results: list[dict] = []
103
- for src in sources:
104
- try:
105
- for entry in client.index(src):
106
- if category and entry.get("category") != category:
107
- continue
108
- entry_tags = set(t.lower() for t in entry.get("tags", []))
109
- if required_tags and not required_tags.issubset(entry_tags):
110
- continue
111
- if roughness_range and not (
112
- entry.get("roughness") is not None
113
- and roughness_range[0] <= entry["roughness"] <= roughness_range[1]
114
- ):
115
- continue
116
- if metalness_range and not (
117
- entry.get("metalness") is not None
118
- and metalness_range[0] <= entry["metalness"] <= metalness_range[1]
119
- ):
120
- continue
121
- results.append(entry)
122
- except Exception:
123
- continue
124
-
125
- # Score by scalar distance
126
- for r in results:
127
- score = 0.0
128
- if roughness is not None and r.get("roughness") is not None:
129
- score += abs(r["roughness"] - roughness)
130
- if metalness is not None and r.get("metalness") is not None:
131
- score += abs(r["metalness"] - metalness)
132
- r["score"] = score
133
-
134
- results.sort(key=lambda r: r["score"])
95
+ results = _client_search(
96
+ category=category,
97
+ roughness=roughness,
98
+ metalness=metalness,
99
+ source=source,
100
+ tier=tier,
101
+ limit=None, # apply limit after tags post-filter
102
+ )
103
+
104
+ if tags:
105
+ required = {t.lower() for t in tags}
106
+ results = [
107
+ e
108
+ for e in results
109
+ if required.issubset({t.lower() for t in (e.get("mat_vis") or {}).get("tags") or []})
110
+ ]
111
+
135
112
  return results[:limit]
136
113
 
137
114
 
@@ -531,6 +531,70 @@ class Vis:
531
531
 
532
532
  # ── TOML loader ──────────────────────────────────────────────
533
533
 
534
+ @classmethod
535
+ def merge_from_toml(cls, base: Vis | None, vis_data: dict[str, Any]) -> Vis:
536
+ """Inherit from ``base`` (parent's Vis), then overlay TOML overrides.
537
+
538
+ Rules:
539
+
540
+ - If ``base`` is None and ``vis_data`` is empty → fresh ``Vis()``.
541
+ - If ``base`` is provided, start with ``deepcopy(base)`` so the child
542
+ inherits identity, finishes, scalars, and the ``_finish`` pick.
543
+ - If ``vis_data`` is provided, overlay its keys on top:
544
+ * ``finishes`` (if set) replaces the inherited map. This is the
545
+ semantically correct call: a grade that declares *any* finishes
546
+ wants its own set, not a concatenation.
547
+ * ``default`` (if set) picks a starting finish from the merged
548
+ map and writes ``source``/``material_id``/``_finish`` from it,
549
+ matching ``from_toml`` behavior.
550
+ * Any PBR scalar in ``vis_data`` overwrites the inherited value.
551
+ * Bare ``source`` / ``material_id`` / ``tier`` keys overwrite
552
+ directly (supports TOML that pins identity without finishes).
553
+ - Cache fields (``_textures``, ``_fetched``) are zeroed by
554
+ ``Vis.__post_init__`` regardless.
555
+
556
+ Used by the TOML loader so grades inherit parent vis without needing
557
+ to re-declare identity + scalars. Closes #88.
558
+ """
559
+ from copy import deepcopy
560
+
561
+ if base is None:
562
+ return cls.from_toml(vis_data or {})
563
+
564
+ merged = deepcopy(base)
565
+
566
+ if not vis_data:
567
+ return merged
568
+
569
+ if "finishes" in vis_data:
570
+ # Re-route through from_toml just for the finishes validation
571
+ # path — it raises on the 3.0 slashed-string form + malformed
572
+ # entries, and we want to keep that guard.
573
+ finishes_only = {"finishes": vis_data["finishes"]}
574
+ if "default" in vis_data:
575
+ finishes_only["default"] = vis_data["default"]
576
+ fresh = cls.from_toml(finishes_only)
577
+ merged.finishes = fresh.finishes
578
+ # If the TOML picked a new default finish, apply it (which will
579
+ # flip source/material_id/_finish through Vis's setters).
580
+ if fresh._finish is not None:
581
+ object.__setattr__(merged, "_finish", fresh._finish)
582
+ merged.source = fresh.source
583
+ merged.material_id = fresh.material_id
584
+
585
+ for field_name in ("source", "material_id", "tier"):
586
+ if field_name in vis_data:
587
+ setattr(merged, field_name, vis_data[field_name])
588
+
589
+ for fname in cls._PBR_SCALAR_FIELDS:
590
+ if fname in vis_data:
591
+ val = vis_data[fname]
592
+ if isinstance(val, list):
593
+ val = tuple(val)
594
+ setattr(merged, fname, val)
595
+
596
+ return merged
597
+
534
598
  @classmethod
535
599
  def from_toml(cls, vis_data: dict[str, Any]) -> Vis:
536
600
  """Construct from a TOML ``[vis]`` section.
@@ -0,0 +1,64 @@
1
+ """Execute ``examples/build123d_integration.py`` top-to-bottom as a test.
2
+
3
+ The examples file is a cell-style script (``# %%`` markers) mirroring
4
+ how build123d's author writes his own examples. Running the full script
5
+ in pytest keeps it honest: if any API drifts, the example — which is
6
+ what consumers are copy-pasting — goes red before they do.
7
+
8
+ We shell out via ``runpy.run_path`` rather than splitting cells because
9
+ cell-order matters (later cells use objects defined earlier). The
10
+ network-touching cells catch their own exceptions so a flaky mat-vis
11
+ CDN doesn't redline the whole example suite.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import runpy
17
+ from pathlib import Path
18
+
19
+ EXAMPLE_PATH = Path(__file__).parent.parent / "examples" / "build123d_integration.py"
20
+
21
+
22
+ def test_example_script_runs_end_to_end(capsys):
23
+ """Every cell in ``examples/build123d_integration.py`` must execute
24
+ without error. Assertions inside the cells are part of the contract
25
+ — this test fails the moment any of them regress."""
26
+ assert EXAMPLE_PATH.exists(), f"missing example: {EXAMPLE_PATH}"
27
+
28
+ # Execute as a fresh script (mimics user running it top-to-bottom).
29
+ # ``runpy.run_path`` gives us an isolated namespace and real exception
30
+ # propagation — unlike ``exec`` which can hide import errors.
31
+ result = runpy.run_path(str(EXAMPLE_PATH), run_name="__main__")
32
+
33
+ # Smoke: the script should have defined the key bindings used in
34
+ # cell 4 / 5 / 6. If a refactor silently drops one of these the
35
+ # test fails with a clean "missing name" rather than a stack trace
36
+ # buried inside runpy.
37
+ for name in ("s304", "housing_mat", "stainless"):
38
+ assert name in result, (
39
+ f"example script didn't define {name!r} — cell order may have drifted"
40
+ )
41
+
42
+ # The completion line from the last cell should have reached stdout.
43
+ out = capsys.readouterr().out
44
+ assert "All cells completed." in out, (
45
+ "example script did not reach its final cell — a middle cell likely errored"
46
+ )
47
+
48
+
49
+ def test_example_is_up_to_date_with_api():
50
+ """Guard that the example file references APIs that actually exist.
51
+ Prevents stale copy-paste when module exports change."""
52
+ import pymat
53
+ from pymat import Material, search # noqa: F401 — shape assertions
54
+
55
+ # The cells touch these in order; if any is missing on the public
56
+ # surface the script will fail at import time.
57
+ assert hasattr(pymat, "search")
58
+ assert callable(pymat.search)
59
+ assert callable(getattr(pymat.__class__, "__getitem__", None))
60
+
61
+ # Method-form adapters the example exercises.
62
+ m = Material(name="probe")
63
+ for method in ("to_threejs", "to_gltf", "export_mtlx"):
64
+ assert callable(getattr(m.vis, method)), f"Vis.{method} missing — example will break"