py-materials 3.7.0__tar.gz → 3.9.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.
- {py_materials-3.7.0 → py_materials-3.9.0}/PKG-INFO +2 -1
- py_materials-3.9.0/clients/python/pymat-mcp/LICENSE +21 -0
- py_materials-3.9.0/clients/python/pymat-mcp/README.md +85 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/pyproject.toml +12 -1
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/__init__.py +1 -1
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/data/metals.toml +2 -2
- py_materials-3.9.0/src/pymat/py.typed +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/search.py +46 -16
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/vis/__init__.py +8 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/vis/_model.py +57 -2
- py_materials-3.9.0/tests/test_eager_imports.py +100 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_lookup.py +39 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_search.py +49 -1
- py_materials-3.9.0/tests/test_vis_deltas.py +190 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/.gitignore +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/LICENSE +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/docs/catalog/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/docs/catalog/ceramics/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/docs/catalog/electronics/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/docs/catalog/gases/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/docs/catalog/liquids/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/docs/catalog/metals/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/docs/catalog/plastics/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/docs/catalog/scintillators/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/docs/decisions/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/mat-rs/data/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/core.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/data/ceramics.toml +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/data/electronics.toml +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/data/gases.toml +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/data/liquids.toml +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/data/plastics.toml +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/data/scintillators.toml +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/elements.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/enrichers.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/factories.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/loader.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/properties.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/registry.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/units.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/src/pymat/vis/adapters.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/__init__.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/_visual_compare.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/baselines/README.md +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/conftest.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/material_preview.html +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_adapters.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_apply_to.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_build123d_integration_examples.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_catalog.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_core.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_e2e_vis.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_enrichers.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_integration.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_loader.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_material_copy.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_properties.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_readme_examples.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_toml_integrity.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_uncertainties.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_vis.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_vis_inheritance.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_vis_override.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_visual_compare.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.0}/tests/test_visual_regression.py +0 -0
- {py_materials-3.7.0 → py_materials-3.9.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
|
+
Version: 3.9.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
|
|
@@ -24,6 +24,7 @@ Requires-Python: >=3.10
|
|
|
24
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
|
+
Requires-Dist: rapidfuzz>=3.0
|
|
27
28
|
Requires-Dist: tomli>=1.0.0; python_version == '3.10'
|
|
28
29
|
Requires-Dist: uncertainties>=3.2
|
|
29
30
|
Provides-Extra: dev
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Lars Gerchow
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# pymat-mcp
|
|
2
|
+
|
|
3
|
+
MCP server exposing the [py-materials](https://github.com/MorePET/mat) curated
|
|
4
|
+
material registry to AI agents — Claude Desktop, Cursor, MCP Inspector, any
|
|
5
|
+
MCP-compatible client.
|
|
6
|
+
|
|
7
|
+
> "Aluminum 6061-T6 yield strength?" — agent calls `get_material` instead of
|
|
8
|
+
> guessing. CAD prompts that need real density / mechanical properties stop
|
|
9
|
+
> hallucinating.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
Zero-install via `uvx`:
|
|
14
|
+
|
|
15
|
+
```json
|
|
16
|
+
{
|
|
17
|
+
"mcpServers": {
|
|
18
|
+
"pymat": {
|
|
19
|
+
"command": "uvx",
|
|
20
|
+
"args": ["pymat-mcp"]
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
That's it. `uvx` fetches `pymat-mcp` (which transitively pulls
|
|
27
|
+
`py-materials`) and runs it in an isolated venv per session.
|
|
28
|
+
|
|
29
|
+
For a pinned version: `"args": ["pymat-mcp@0.1.0"]`.
|
|
30
|
+
|
|
31
|
+
For programmatic use, `pip install pymat-mcp` works too — the package is
|
|
32
|
+
fully a normal Python module.
|
|
33
|
+
|
|
34
|
+
## Tools
|
|
35
|
+
|
|
36
|
+
| Tool | What |
|
|
37
|
+
|---|---|
|
|
38
|
+
| `search_materials(query, limit=10)` | Fuzzy lookup → list of brief rows |
|
|
39
|
+
| `get_material(key_or_name)` | Full property dump (mechanical / thermal / electrical / optical / manufacturing / compliance / sourcing) + visual identity |
|
|
40
|
+
| `list_categories()` | Top-level groups (aluminum, stainless, lyso, …) |
|
|
41
|
+
| `list_grades(material)` | Children (grades / tempers / treatments) |
|
|
42
|
+
| `compute_mass(material, volume_mm3)` | Mass in grams from a build123d-style volume |
|
|
43
|
+
| `get_appearance(material)` | Vis dict — mat-vis identity, finishes, PBR scalars |
|
|
44
|
+
| `to_threejs(material, finish=None)` | Three.js MeshPhysicalMaterial init dict |
|
|
45
|
+
| `to_gltf(material, finish=None)` | glTF 2.0 material node |
|
|
46
|
+
| `compare_materials(keys, properties=None)` | Side-by-side property comparison |
|
|
47
|
+
|
|
48
|
+
All tools are read-only. Errors come back as `{"error": "...", "did_you_mean": [...]}` rather than exceptions.
|
|
49
|
+
|
|
50
|
+
## Example agent prompts
|
|
51
|
+
|
|
52
|
+
- *"What's the yield strength of 17-4 PH H1025? Use the materials database."*
|
|
53
|
+
- *"I have a 50×50×10 mm 6061 plate; what's the mass?"*
|
|
54
|
+
- *"Give me a Three.js material dict for stainless steel with a polished finish."*
|
|
55
|
+
- *"Compare density and thermal conductivity for 6061, 7075, and copper."*
|
|
56
|
+
|
|
57
|
+
## Logging
|
|
58
|
+
|
|
59
|
+
Logs to stderr only (stdout is the MCP transport channel). Bump verbosity:
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
PYMAT_MCP_LOG=DEBUG uvx pymat-mcp
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Development
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
git clone https://github.com/MorePET/mat
|
|
69
|
+
cd mat/clients/python/pymat-mcp
|
|
70
|
+
uv sync --all-extras
|
|
71
|
+
uv run pytest -v
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
To exercise the server interactively:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
uvx mcp dev pymat-mcp # MCP Inspector — point-and-click tool calls
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Links
|
|
81
|
+
|
|
82
|
+
- Source: <https://github.com/MorePET/mat/tree/main/clients/python/pymat-mcp>
|
|
83
|
+
- Issues: <https://github.com/MorePET/mat/issues>
|
|
84
|
+
- py-materials (the wrapped library): <https://github.com/MorePET/mat>
|
|
85
|
+
- MCP spec: <https://spec.modelcontextprotocol.io>
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "py-materials"
|
|
7
|
-
version = "3.
|
|
7
|
+
version = "3.9.0"
|
|
8
8
|
description = "Hierarchical material library for CAD applications with build123d integration"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "MIT"
|
|
@@ -32,6 +32,10 @@ dependencies = [
|
|
|
32
32
|
"periodictable>=1.6.0",
|
|
33
33
|
"uncertainties>=3.2",
|
|
34
34
|
"mat-vis-client>=0.6.3",
|
|
35
|
+
# rapidfuzz: typo-tolerant scoring in pymat.search. Pure-Rust
|
|
36
|
+
# wheel, broad platform support, no compile burden. Replaces the
|
|
37
|
+
# 3.8.0-and-prior substring-containment matcher (#179).
|
|
38
|
+
"rapidfuzz>=3.0",
|
|
35
39
|
"tomli>=1.0.0; python_version == '3.10'",
|
|
36
40
|
]
|
|
37
41
|
|
|
@@ -50,6 +54,13 @@ Issues = "https://github.com/MorePet/py-mat/issues"
|
|
|
50
54
|
[tool.hatch.build.targets.wheel]
|
|
51
55
|
packages = ["src/pymat"]
|
|
52
56
|
|
|
57
|
+
# PEP 561: ship the ``py.typed`` marker so type checkers (mypy/pyright)
|
|
58
|
+
# know to read inline annotations rather than skipping the package as
|
|
59
|
+
# untyped. Required for the ``Unpack[VisDeltas]`` typing on
|
|
60
|
+
# ``Vis.override`` to take effect under ``mypy --strict``.
|
|
61
|
+
[tool.hatch.build.targets.wheel.force-include]
|
|
62
|
+
"src/pymat/py.typed" = "pymat/py.typed"
|
|
63
|
+
|
|
53
64
|
[tool.hatch.build.targets.sdist]
|
|
54
65
|
include = [
|
|
55
66
|
"src/pymat/**",
|
|
@@ -153,9 +153,9 @@ default = "smooth"
|
|
|
153
153
|
smooth = { source = "ambientcg", id = "Metal049A" }
|
|
154
154
|
machined = { source = "ambientcg", id = "Metal055A" }
|
|
155
155
|
|
|
156
|
-
# Aluminum 6061
|
|
156
|
+
# Aluminum 6061 (parent alloy node — tempers hang below)
|
|
157
157
|
[aluminum.a6061]
|
|
158
|
-
name = "Aluminum 6061
|
|
158
|
+
name = "Aluminum 6061"
|
|
159
159
|
grade = "6061"
|
|
160
160
|
composition = {Al = 0.972, Mg = 0.01, Si = 0.006, Cu = 0.004, Cr = 0.002, Fe = 0.003, Zn = 0.003}
|
|
161
161
|
|
|
File without changes
|
|
@@ -6,9 +6,17 @@ instances whose registry key, name, grade, or hierarchy path matches
|
|
|
6
6
|
the query tokens. Complements ``pymat.vis.search(...)`` (visual
|
|
7
7
|
catalog): two axes, same verb, no namespace collision.
|
|
8
8
|
|
|
9
|
-
Algorithm: tokenize query on whitespace; every token must
|
|
10
|
-
least one weighted target on a
|
|
11
|
-
included. Score is the sum of
|
|
9
|
+
Algorithm: tokenize query on whitespace; every token must clear a
|
|
10
|
+
similarity threshold against at least one weighted target on a
|
|
11
|
+
candidate Material for it to be included. Score is the sum of
|
|
12
|
+
per-token best-target weights, scaled by similarity ratio.
|
|
13
|
+
|
|
14
|
+
Similarity is ``rapidfuzz.fuzz.partial_ratio`` — finds the best-aligned
|
|
15
|
+
substring of the longer target whose length equals the token, then
|
|
16
|
+
scores edit distance there. Catches one- and two-character typos
|
|
17
|
+
(``"stinless"`` vs ``"stainless"``, ``"6016"`` vs ``"6061"``) without
|
|
18
|
+
matching arbitrary abbreviations (``"stl"`` won't auto-match
|
|
19
|
+
``"steel"`` — that requires an explicit alias). Closes #179.
|
|
12
20
|
"""
|
|
13
21
|
|
|
14
22
|
from __future__ import annotations
|
|
@@ -16,6 +24,8 @@ from __future__ import annotations
|
|
|
16
24
|
import unicodedata
|
|
17
25
|
from typing import TYPE_CHECKING
|
|
18
26
|
|
|
27
|
+
from rapidfuzz import fuzz
|
|
28
|
+
|
|
19
29
|
if TYPE_CHECKING:
|
|
20
30
|
from .core import Material
|
|
21
31
|
|
|
@@ -37,6 +47,15 @@ _WEIGHT_NAME = 5 # Material.name — "Stainless Steel 316L"
|
|
|
37
47
|
_WEIGHT_GRADE = 5 # Material.grade — "316L"
|
|
38
48
|
_WEIGHT_PATH = 3 # hierarchy parent names
|
|
39
49
|
|
|
50
|
+
# Per-token similarity threshold (0-100 scale, rapidfuzz convention).
|
|
51
|
+
# 75 catches one-edit and most two-edit typos in 6-10 char strings
|
|
52
|
+
# (Levenshtein-bounded partial alignments) while rejecting arbitrary
|
|
53
|
+
# abbreviations like "stl" → "steel" (~67) that would auto-match too
|
|
54
|
+
# many materials. Calibrated against the existing search corpus —
|
|
55
|
+
# see tests/test_search.py for the pinned cases on both sides of
|
|
56
|
+
# the threshold.
|
|
57
|
+
_SIMILARITY_THRESHOLD = 75
|
|
58
|
+
|
|
40
59
|
|
|
41
60
|
def _targets(key: str, material: Material) -> list[tuple[str, int]]:
|
|
42
61
|
"""Return (lowered-target-string, weight) pairs for a Material.
|
|
@@ -63,22 +82,33 @@ def _targets(key: str, material: Material) -> list[tuple[str, int]]:
|
|
|
63
82
|
return pairs
|
|
64
83
|
|
|
65
84
|
|
|
66
|
-
def _score(tokens: list[str], targets: list[tuple[str, int]]) ->
|
|
85
|
+
def _score(tokens: list[str], targets: list[tuple[str, int]]) -> float:
|
|
67
86
|
"""Score a Material against the query tokens.
|
|
68
87
|
|
|
69
|
-
Every token must
|
|
70
|
-
(rejected) if any token misses. Otherwise
|
|
71
|
-
|
|
72
|
-
|
|
88
|
+
Every token must clear ``_SIMILARITY_THRESHOLD`` against at least
|
|
89
|
+
one target. Returns 0 (rejected) if any token misses. Otherwise
|
|
90
|
+
returns the sum of per-token best ``weight × (similarity / 100)``
|
|
91
|
+
— so a perfect key match (10 × 1.0) outranks a fuzzy key match
|
|
92
|
+
(10 × 0.8), which still outranks a perfect path match (3 × 1.0).
|
|
93
|
+
|
|
94
|
+
Token matching uses ``rapidfuzz.fuzz.partial_ratio``: finds the
|
|
95
|
+
best-aligned substring of the target of the token's length, then
|
|
96
|
+
scores Levenshtein-equivalent similarity. This is the natural
|
|
97
|
+
extension of the previous ``token in target`` (substring) check —
|
|
98
|
+
a perfect substring scores 100; a one-edit typo on a short word
|
|
99
|
+
typically scores in the high 80s / low 90s.
|
|
73
100
|
"""
|
|
74
|
-
total = 0
|
|
101
|
+
total = 0.0
|
|
75
102
|
for token in tokens:
|
|
76
|
-
best = 0
|
|
103
|
+
best = 0.0
|
|
77
104
|
for target, weight in targets:
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
105
|
+
ratio = fuzz.partial_ratio(token, target)
|
|
106
|
+
if ratio >= _SIMILARITY_THRESHOLD:
|
|
107
|
+
token_score = weight * (ratio / 100.0)
|
|
108
|
+
if token_score > best:
|
|
109
|
+
best = token_score
|
|
110
|
+
if best == 0.0:
|
|
111
|
+
return 0.0 # token didn't clear threshold anywhere → reject
|
|
82
112
|
total += best
|
|
83
113
|
return total
|
|
84
114
|
|
|
@@ -129,7 +159,7 @@ def search(query: str, *, exact: bool = False, limit: int = 10) -> list[Material
|
|
|
129
159
|
load_all()
|
|
130
160
|
all_materials = registry.list_all()
|
|
131
161
|
|
|
132
|
-
scored: list[tuple[
|
|
162
|
+
scored: list[tuple[float, int, str, Material]] = []
|
|
133
163
|
|
|
134
164
|
if exact:
|
|
135
165
|
# Full-string equality against key / name / grade. Same three
|
|
@@ -141,7 +171,7 @@ def search(query: str, *, exact: bool = False, limit: int = 10) -> list[Material
|
|
|
141
171
|
candidates.append(str(grade))
|
|
142
172
|
if any(_normalize(c) == normalized for c in candidates):
|
|
143
173
|
# Single-match: tie-break by shorter key for determinism.
|
|
144
|
-
scored.append((0, len(key), key, material))
|
|
174
|
+
scored.append((0.0, len(key), key, material))
|
|
145
175
|
else:
|
|
146
176
|
tokens = normalized.split()
|
|
147
177
|
for key, material in all_materials.items():
|
|
@@ -41,6 +41,10 @@ from mat_vis_client import (
|
|
|
41
41
|
from mat_vis_client import get_client as _shared_client
|
|
42
42
|
from mat_vis_client import search as _client_search
|
|
43
43
|
|
|
44
|
+
# Domain types: re-exported so consumers can construct or type-hint
|
|
45
|
+
# without reaching into the private ``_model`` module.
|
|
46
|
+
from pymat.vis._model import FinishEntry, Vis, VisDeltas
|
|
47
|
+
|
|
44
48
|
# Material-accepting adapters: Three.js / glTF / MaterialX.
|
|
45
49
|
# Re-exported at top level so ``from pymat.vis import to_threejs`` works
|
|
46
50
|
# and tab completion on ``pymat.vis.`` surfaces the main cross-tool
|
|
@@ -146,6 +150,10 @@ __all__ = [
|
|
|
146
150
|
"get_manifest",
|
|
147
151
|
"seed_indexes",
|
|
148
152
|
"MatVisClient",
|
|
153
|
+
# Domain types — Vis dataclass + the override-kwargs TypedDict
|
|
154
|
+
"Vis",
|
|
155
|
+
"VisDeltas",
|
|
156
|
+
"FinishEntry",
|
|
149
157
|
# Material → external-format adapters (the main cross-tool handoff)
|
|
150
158
|
"to_threejs",
|
|
151
159
|
"to_gltf",
|
|
@@ -42,7 +42,11 @@ from pathlib import Path
|
|
|
42
42
|
from typing import TYPE_CHECKING, Any, ClassVar, TypedDict
|
|
43
43
|
|
|
44
44
|
if TYPE_CHECKING:
|
|
45
|
+
# ``Unpack`` is in stdlib ``typing`` from 3.11; pull from
|
|
46
|
+
# ``typing_extensions`` (transitive dep, always available in
|
|
47
|
+
# type-check contexts) so 3.10 type-checking also works.
|
|
45
48
|
from mat_vis_client import MatVisClient, MtlxSource
|
|
49
|
+
from typing_extensions import Unpack
|
|
46
50
|
|
|
47
51
|
|
|
48
52
|
class FinishEntry(TypedDict):
|
|
@@ -57,6 +61,49 @@ class FinishEntry(TypedDict):
|
|
|
57
61
|
id: str
|
|
58
62
|
|
|
59
63
|
|
|
64
|
+
class VisDeltas(TypedDict, total=False):
|
|
65
|
+
"""Typed kwargs accepted by :meth:`Vis.override`.
|
|
66
|
+
|
|
67
|
+
Used by static type checkers (pyright, mypy) via ``Unpack`` per PEP
|
|
68
|
+
692. Surfaces every valid override key as IDE completion and flags
|
|
69
|
+
typos like ``roughnes=`` at edit time, not runtime.
|
|
70
|
+
|
|
71
|
+
All keys are optional (``total=False``) — that's the override
|
|
72
|
+
contract. To "leave a field unchanged", *omit* the key. Runtime
|
|
73
|
+
validation of unknown kwargs lives in :meth:`Vis.override`; this
|
|
74
|
+
TypedDict is purely a typing layer and has no runtime effect.
|
|
75
|
+
|
|
76
|
+
Identity fields (``source``, ``material_id``, ``tier``) are typed
|
|
77
|
+
as bare ``str`` here even though the underlying ``Vis`` field is
|
|
78
|
+
``str | None``. Reason: ``override`` routes identity through
|
|
79
|
+
:meth:`Vis.set_identity`, which interprets ``None`` as "leave
|
|
80
|
+
unchanged" rather than "clear" — so passing ``None`` would silently
|
|
81
|
+
no-op. Typing the kwarg as ``str`` enforces the kwargs idiom (omit
|
|
82
|
+
to leave alone) and keeps the type-checker contract honest.
|
|
83
|
+
|
|
84
|
+
Scalar fields (``roughness``, ``metallic``, …) keep the ``| None``
|
|
85
|
+
union — ``None`` is a legitimate reset value there (passes through
|
|
86
|
+
``setattr`` directly).
|
|
87
|
+
|
|
88
|
+
The ``finish`` key is a sugar — not a Vis field but a property
|
|
89
|
+
setter that looks up in the ``finishes`` map and reassigns
|
|
90
|
+
identity. Treated separately by ``override``'s body.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
source: str
|
|
94
|
+
material_id: str
|
|
95
|
+
tier: str
|
|
96
|
+
finishes: dict[str, FinishEntry]
|
|
97
|
+
roughness: float | None
|
|
98
|
+
metallic: float | None
|
|
99
|
+
base_color: tuple[float, float, float, float] | None
|
|
100
|
+
ior: float | None
|
|
101
|
+
transmission: float | None
|
|
102
|
+
clearcoat: float | None
|
|
103
|
+
emissive: tuple[float, float, float] | None
|
|
104
|
+
finish: str # sugar — looks up in finishes map, reassigns identity
|
|
105
|
+
|
|
106
|
+
|
|
60
107
|
# Identity fields whose mutation invalidates the lazy texture cache.
|
|
61
108
|
# Kept as a module-level constant so `__setattr__` can check membership
|
|
62
109
|
# in O(1) without re-allocating a set each call.
|
|
@@ -329,7 +376,7 @@ class Vis:
|
|
|
329
376
|
super().__setattr__("_textures", {})
|
|
330
377
|
super().__setattr__("_fetched", False)
|
|
331
378
|
|
|
332
|
-
def override(self, **deltas:
|
|
379
|
+
def override(self, **deltas: "Unpack[VisDeltas]") -> Vis: # noqa: F821 — TYPE_CHECKING only
|
|
333
380
|
"""Return a new ``Vis`` with the given deltas applied; ``self``
|
|
334
381
|
is unchanged.
|
|
335
382
|
|
|
@@ -342,6 +389,10 @@ class Vis:
|
|
|
342
389
|
polished = steel.vis.override(roughness=0.3, finish="polished")
|
|
343
390
|
# steel.vis is unchanged; polished is independent.
|
|
344
391
|
|
|
392
|
+
For helper functions that build delta dicts at runtime, type
|
|
393
|
+
them as :class:`VisDeltas` (importable from ``pymat.vis``) —
|
|
394
|
+
IDE completion + mypy strict-mode static checks come for free.
|
|
395
|
+
|
|
345
396
|
Note: ``override`` is the runtime mirror of TOML grade override
|
|
346
397
|
(children inherit parent properties unless overridden). It is
|
|
347
398
|
NOT a flat field substitution like ``dataclasses.replace`` —
|
|
@@ -395,7 +446,11 @@ class Vis:
|
|
|
395
446
|
finish_invalidating_keys = identity_keys & {"source", "material_id"}
|
|
396
447
|
finish_invalidating = any(deltas[k] != getattr(new, k) for k in finish_invalidating_keys)
|
|
397
448
|
if identity_keys:
|
|
398
|
-
|
|
449
|
+
# Pop identity values explicitly so each kwarg keeps its
|
|
450
|
+
# declared type (the comprehension form widens to ``object``
|
|
451
|
+
# because the TypedDict has heterogeneous field types).
|
|
452
|
+
id_kwargs: dict[str, Any] = {k: deltas.pop(k) for k in list(identity_keys)}
|
|
453
|
+
new.set_identity(**id_kwargs)
|
|
399
454
|
|
|
400
455
|
for k, v in deltas.items():
|
|
401
456
|
# Caller-supplied ``finishes=`` must be deep-copied — storing
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Eager-import smoke for every public pymat + mat_vis_client submodule.
|
|
2
|
+
|
|
3
|
+
Closes the gap that let mat-vis-client 0.5.0's `StrEnum` import (3.10
|
|
4
|
+
incompatible) escape py-mat's CI in April 2026: py-mat lazy-imports
|
|
5
|
+
``mat_vis_client`` only inside ``Vis._fetch``, so the broken
|
|
6
|
+
``mat_vis_client.schema`` module was never loaded by any test on 3.10.
|
|
7
|
+
build123d's CI imports ``mat_vis_client.adapters`` eagerly at test-
|
|
8
|
+
collection time and blew up; ours stayed green.
|
|
9
|
+
|
|
10
|
+
This test walks every public submodule of both packages and imports it,
|
|
11
|
+
turning the failure-on-touch into a failure at every CI run. Fast
|
|
12
|
+
(sub-second), no maintenance — ``pkgutil.walk_packages`` enumerates
|
|
13
|
+
dynamically.
|
|
14
|
+
|
|
15
|
+
Scope:
|
|
16
|
+
|
|
17
|
+
- pymat — every public submodule (lazy-loaded categories included)
|
|
18
|
+
- mat_vis_client — every public submodule (we coordinate releases with
|
|
19
|
+
this dep; downstream consumers import these eagerly)
|
|
20
|
+
|
|
21
|
+
NOT in scope: ``pint`` / ``periodictable`` / ``uncertainties`` — mature
|
|
22
|
+
deps with their own test suites; we'd be testing other people's CI.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import importlib
|
|
28
|
+
import pkgutil
|
|
29
|
+
|
|
30
|
+
import pytest
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _public_submodules(pkg_name: str) -> list[str]:
|
|
34
|
+
"""Enumerate every importable submodule of ``pkg_name``,
|
|
35
|
+
excluding underscore-prefixed (private) ones at any depth."""
|
|
36
|
+
pkg = importlib.import_module(pkg_name)
|
|
37
|
+
pkg_path = getattr(pkg, "__path__", None)
|
|
38
|
+
if pkg_path is None:
|
|
39
|
+
return [pkg_name] # not a package, just a module
|
|
40
|
+
|
|
41
|
+
found = [pkg_name]
|
|
42
|
+
for module_info in pkgutil.walk_packages(pkg_path, prefix=f"{pkg_name}."):
|
|
43
|
+
# Skip private / internal modules — they're allowed to break
|
|
44
|
+
# in ways that would never surface to a public consumer.
|
|
45
|
+
parts = module_info.name.split(".")
|
|
46
|
+
if any(p.startswith("_") for p in parts):
|
|
47
|
+
continue
|
|
48
|
+
found.append(module_info.name)
|
|
49
|
+
return sorted(found)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# Compute the lists at collection time so pytest -v shows each module.
|
|
53
|
+
PYMAT_MODULES = _public_submodules("pymat")
|
|
54
|
+
MAT_VIS_CLIENT_MODULES = _public_submodules("mat_vis_client")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@pytest.mark.parametrize("module_name", PYMAT_MODULES)
|
|
58
|
+
def test_pymat_submodule_imports(module_name):
|
|
59
|
+
"""Every public ``pymat.*`` submodule imports cleanly.
|
|
60
|
+
|
|
61
|
+
Catches: ``ImportError`` from broken syntax / Python-version-
|
|
62
|
+
specific imports / circular deps / missing optional deps that got
|
|
63
|
+
reached at module load time.
|
|
64
|
+
"""
|
|
65
|
+
importlib.import_module(module_name)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@pytest.mark.parametrize("module_name", MAT_VIS_CLIENT_MODULES)
|
|
69
|
+
def test_mat_vis_client_submodule_imports(module_name):
|
|
70
|
+
"""Every public ``mat_vis_client.*`` submodule imports cleanly.
|
|
71
|
+
|
|
72
|
+
Coordinated with mat-vis-client release cadence — a regression in
|
|
73
|
+
a submodule we don't directly use (``schema``, ``adapters``) still
|
|
74
|
+
breaks downstream consumers like build123d that import them
|
|
75
|
+
eagerly. Pinned here so the next bad release fails our CI before
|
|
76
|
+
landing on PyPI users.
|
|
77
|
+
"""
|
|
78
|
+
importlib.import_module(module_name)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_at_least_some_pymat_modules_found():
|
|
82
|
+
"""Sanity: ``walk_packages`` actually found the expected packages.
|
|
83
|
+
|
|
84
|
+
Defends against a future refactor that accidentally hides
|
|
85
|
+
submodules behind a custom ``__path__`` or strips ``__init__.py``,
|
|
86
|
+
which would silently zero out the test matrix above."""
|
|
87
|
+
assert len(PYMAT_MODULES) >= 5, f"Only found {len(PYMAT_MODULES)} pymat modules"
|
|
88
|
+
assert "pymat" in PYMAT_MODULES
|
|
89
|
+
assert "pymat.vis" in PYMAT_MODULES
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_at_least_some_mat_vis_client_modules_found():
|
|
93
|
+
assert len(MAT_VIS_CLIENT_MODULES) >= 2, (
|
|
94
|
+
f"Only found {len(MAT_VIS_CLIENT_MODULES)} mat_vis_client modules"
|
|
95
|
+
)
|
|
96
|
+
assert "mat_vis_client" in MAT_VIS_CLIENT_MODULES
|
|
97
|
+
# At least one of these submodules should exist post-0.6.x — they
|
|
98
|
+
# are exactly the modules build123d's CI imports eagerly.
|
|
99
|
+
submodules = set(MAT_VIS_CLIENT_MODULES) - {"mat_vis_client"}
|
|
100
|
+
assert submodules, "no mat_vis_client submodules found — refactor regression?"
|
|
@@ -44,6 +44,45 @@ class TestSubscriptBasic:
|
|
|
44
44
|
assert m.grade == "304"
|
|
45
45
|
|
|
46
46
|
|
|
47
|
+
class TestAlloyParentNaming:
|
|
48
|
+
"""Pins the parent-vs-temper naming pattern in TOML.
|
|
49
|
+
|
|
50
|
+
The aluminum tree previously declared ``[aluminum.a6061]`` with
|
|
51
|
+
``name = "Aluminum 6061-T6"`` — a temper-baked name on the parent
|
|
52
|
+
node. That made ``pymat["Aluminum 6061"]`` raise (only the T6 child
|
|
53
|
+
matched, but not at the parent name). Closes #178. The fix is data:
|
|
54
|
+
parent carries the alloy designation; the temper child carries the
|
|
55
|
+
composite name. Mirrors the long-shipped stainless pattern.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def test_aluminum_6061_resolves_to_parent(self):
|
|
59
|
+
m = pymat["Aluminum 6061"]
|
|
60
|
+
assert m.name == "Aluminum 6061"
|
|
61
|
+
assert m.grade == "6061"
|
|
62
|
+
# T6 is a child of the parent
|
|
63
|
+
assert "T6" in m._children
|
|
64
|
+
|
|
65
|
+
def test_aluminum_6061_t6_still_works(self):
|
|
66
|
+
m = pymat["Aluminum 6061-T6"]
|
|
67
|
+
assert m.name == "Aluminum 6061-T6"
|
|
68
|
+
assert m.temper == "T6"
|
|
69
|
+
|
|
70
|
+
def test_aluminum_7075_pattern_consistent(self):
|
|
71
|
+
"""7075 already shipped correctly — pin so a future refactor
|
|
72
|
+
doesn't accidentally regress it the way 6061 was."""
|
|
73
|
+
m = pymat["Aluminum 7075"]
|
|
74
|
+
assert m.name == "Aluminum 7075"
|
|
75
|
+
assert m.grade == "7075"
|
|
76
|
+
|
|
77
|
+
def test_aluminum_6061_vs_t6_distinct(self):
|
|
78
|
+
"""The two names are no longer an alias — they refer to
|
|
79
|
+
distinct nodes in the hierarchy."""
|
|
80
|
+
parent = pymat["Aluminum 6061"]
|
|
81
|
+
t6 = pymat["Aluminum 6061-T6"]
|
|
82
|
+
assert parent is not t6
|
|
83
|
+
assert t6.parent is parent
|
|
84
|
+
|
|
85
|
+
|
|
47
86
|
class TestNormalization:
|
|
48
87
|
def test_leading_trailing_whitespace(self):
|
|
49
88
|
assert pymat[" Stainless Steel 304 "].name == "Stainless Steel 304"
|
|
@@ -71,9 +71,17 @@ class TestNameMatch:
|
|
|
71
71
|
assert any("Steel" in m.name for m in hits)
|
|
72
72
|
|
|
73
73
|
def test_human_word_matches_name(self):
|
|
74
|
+
"""Searching ``aluminum`` finds the aluminum tree.
|
|
75
|
+
|
|
76
|
+
Note: with the rapidfuzz scorer (3.9+), ``aluminum`` also clears
|
|
77
|
+
the similarity threshold against ``alumina`` (related ceramic).
|
|
78
|
+
That's correct fuzzy behavior — pin only that the aluminum tree
|
|
79
|
+
is included, not that hits are exclusively aluminum.
|
|
80
|
+
"""
|
|
74
81
|
hits = search("aluminum")
|
|
75
82
|
assert hits
|
|
76
|
-
|
|
83
|
+
names = [m.name for m in hits]
|
|
84
|
+
assert any("Aluminum" in n for n in names), f"aluminum tree missing from hits: {names}"
|
|
77
85
|
|
|
78
86
|
|
|
79
87
|
class TestGradeMatch:
|
|
@@ -108,6 +116,46 @@ class TestMultiTokenConjunctive:
|
|
|
108
116
|
hits = search("stainless unobtainium_xyz")
|
|
109
117
|
assert hits == []
|
|
110
118
|
|
|
119
|
+
|
|
120
|
+
class TestTypoTolerance:
|
|
121
|
+
"""rapidfuzz partial_ratio scoring (3.9+, closes #179) catches
|
|
122
|
+
one- and two-character typos without auto-matching arbitrary
|
|
123
|
+
abbreviations. Pin both directions of the threshold:
|
|
124
|
+
|
|
125
|
+
- **Inside** (clears 75): mild typos surface their target.
|
|
126
|
+
- **Outside** (below 75): heavy abbreviations / unrelated words
|
|
127
|
+
stay rejected so the conjunctive contract holds.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
def test_one_char_typo_finds_stainless(self):
|
|
131
|
+
"""``Stinless`` (missing 'a') vs ``stainless`` is a single-edit
|
|
132
|
+
typo; partial_ratio is in the high 80s. Should surface
|
|
133
|
+
stainless candidates — the exact failure mode that returned
|
|
134
|
+
``[]`` in 3.8 and surfaced via live MCP testing."""
|
|
135
|
+
hits = search("Stinless 304")
|
|
136
|
+
assert hits, "one-char typo should surface stainless 304"
|
|
137
|
+
assert any("304" in m.name for m in hits)
|
|
138
|
+
|
|
139
|
+
def test_one_char_typo_in_grade(self):
|
|
140
|
+
"""Grade typos are short strings — ``6016`` for ``6061`` is
|
|
141
|
+
a single-edit transposition. Should still find 6061."""
|
|
142
|
+
hits = search("6016")
|
|
143
|
+
assert hits, "transposed-digit grade should still find a match"
|
|
144
|
+
assert any("6061" in m.name for m in hits)
|
|
145
|
+
|
|
146
|
+
def test_substring_substitution_passes(self):
|
|
147
|
+
"""``Stainles`` (one trailing char dropped) is a one-edit
|
|
148
|
+
substitution — exactly the case partial_ratio is tuned to
|
|
149
|
+
catch."""
|
|
150
|
+
hits = search("Stainles 304")
|
|
151
|
+
assert hits, "one-edit drop should still find stainless 304"
|
|
152
|
+
|
|
153
|
+
def test_unrelated_token_still_rejects(self):
|
|
154
|
+
"""The conjunctive contract holds: a single typo-passing
|
|
155
|
+
token doesn't rescue a query with an unrelated token."""
|
|
156
|
+
hits = search("stinless quasarium")
|
|
157
|
+
assert hits == [], "unrelated 'quasarium' should still reject"
|
|
158
|
+
|
|
111
159
|
def test_tokens_across_name_and_hierarchy(self):
|
|
112
160
|
"""Tokens can match different targets on the same Material —
|
|
113
161
|
one in the name, another in the parent chain."""
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Tests for the ``VisDeltas`` TypedDict (#108).
|
|
2
|
+
|
|
3
|
+
``VisDeltas`` is the static-typing surface for ``Vis.override(**deltas)``
|
|
4
|
+
kwargs (PEP 692 ``Unpack``). It has no runtime behavior — the override
|
|
5
|
+
runtime validation is in ``Vis.override`` itself — so these tests pin:
|
|
6
|
+
|
|
7
|
+
- the TypedDict is importable from the public surface
|
|
8
|
+
- it stays in sync with the ``Vis`` field set + ``finish`` property
|
|
9
|
+
- a runtime-constructed dict matching the schema works as **deltas
|
|
10
|
+
(round-trip via ``Vis.override(**delta_dict)``)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import fields
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import pytest
|
|
19
|
+
|
|
20
|
+
from pymat.vis import Vis, VisDeltas
|
|
21
|
+
from pymat.vis._model import FinishEntry
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class TestPublicSurface:
|
|
25
|
+
def test_visdeltas_importable_from_pymat_vis(self):
|
|
26
|
+
"""``from pymat.vis import VisDeltas`` works."""
|
|
27
|
+
assert VisDeltas is not None
|
|
28
|
+
|
|
29
|
+
def test_visdeltas_is_typeddict(self):
|
|
30
|
+
"""``VisDeltas`` is a TypedDict with all keys optional."""
|
|
31
|
+
# TypedDict subclasses expose __total__ (False for total=False)
|
|
32
|
+
assert getattr(VisDeltas, "__total__", True) is False
|
|
33
|
+
|
|
34
|
+
def test_finishentry_importable_too(self):
|
|
35
|
+
"""``FinishEntry`` (used inside VisDeltas) is also exposed."""
|
|
36
|
+
assert FinishEntry is not None
|
|
37
|
+
|
|
38
|
+
def test_vis_re_exported(self):
|
|
39
|
+
"""``Vis`` itself is now reachable from ``pymat.vis``."""
|
|
40
|
+
from pymat.vis._model import Vis as _ModelVis
|
|
41
|
+
|
|
42
|
+
assert Vis is _ModelVis
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class TestVisDeltasMirrorsVisFields:
|
|
46
|
+
"""``VisDeltas`` must enumerate every public Vis field + ``finish``.
|
|
47
|
+
If a future PR adds (or removes) a Vis field but forgets to update
|
|
48
|
+
VisDeltas, this test breaks loudly."""
|
|
49
|
+
|
|
50
|
+
def test_all_public_vis_fields_in_visdeltas(self):
|
|
51
|
+
public_fields = {f.name for f in fields(Vis) if not f.name.startswith("_")}
|
|
52
|
+
delta_keys = set(VisDeltas.__annotations__)
|
|
53
|
+
# Every public Vis field must appear in VisDeltas
|
|
54
|
+
missing = public_fields - delta_keys
|
|
55
|
+
assert not missing, f"Vis fields missing from VisDeltas: {missing}"
|
|
56
|
+
|
|
57
|
+
def test_finish_property_in_visdeltas(self):
|
|
58
|
+
"""``finish=`` is a property setter, not a field — must be in
|
|
59
|
+
the TypedDict explicitly."""
|
|
60
|
+
assert "finish" in VisDeltas.__annotations__
|
|
61
|
+
|
|
62
|
+
def test_no_extra_keys_in_visdeltas(self):
|
|
63
|
+
"""VisDeltas should not contain keys that aren't real override
|
|
64
|
+
targets (private fields, methods, etc.)."""
|
|
65
|
+
public_fields = {f.name for f in fields(Vis) if not f.name.startswith("_")}
|
|
66
|
+
valid_extras = {"finish"} # the property setter
|
|
67
|
+
delta_keys = set(VisDeltas.__annotations__)
|
|
68
|
+
extras = delta_keys - public_fields - valid_extras
|
|
69
|
+
assert not extras, f"VisDeltas has unknown keys: {extras}"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class TestRuntimeRoundTrip:
|
|
73
|
+
"""A dict matching the VisDeltas schema can be unpacked into
|
|
74
|
+
``override(**)`` and produces the expected result."""
|
|
75
|
+
|
|
76
|
+
def test_unpack_partial_deltas_dict(self):
|
|
77
|
+
v = Vis(source="ambientcg", material_id="Metal012", roughness=0.3)
|
|
78
|
+
deltas: VisDeltas = {"roughness": 0.7, "metallic": 0.5}
|
|
79
|
+
v2 = v.override(**deltas)
|
|
80
|
+
assert v2.roughness == 0.7
|
|
81
|
+
assert v2.metallic == 0.5
|
|
82
|
+
assert v.roughness == 0.3 # unchanged
|
|
83
|
+
|
|
84
|
+
def test_unpack_with_finish(self):
|
|
85
|
+
v = Vis(
|
|
86
|
+
source="ambientcg",
|
|
87
|
+
material_id="Metal012",
|
|
88
|
+
finishes={
|
|
89
|
+
"brushed": {"source": "ambientcg", "id": "Metal012"},
|
|
90
|
+
"polished": {"source": "ambientcg", "id": "Metal049A"},
|
|
91
|
+
},
|
|
92
|
+
)
|
|
93
|
+
deltas: VisDeltas = {"finish": "polished", "roughness": 0.05}
|
|
94
|
+
v2 = v.override(**deltas)
|
|
95
|
+
assert v2._finish == "polished"
|
|
96
|
+
assert v2.material_id == "Metal049A"
|
|
97
|
+
assert v2.roughness == 0.05
|
|
98
|
+
|
|
99
|
+
def test_unpack_identity_change(self):
|
|
100
|
+
v = Vis(source="ambientcg", material_id="Metal012")
|
|
101
|
+
deltas: VisDeltas = {"source": "polyhaven", "material_id": "metal_01"}
|
|
102
|
+
v2 = v.override(**deltas)
|
|
103
|
+
assert v2.source == "polyhaven"
|
|
104
|
+
assert v2.material_id == "metal_01"
|
|
105
|
+
|
|
106
|
+
def test_unpack_empty_deltas(self):
|
|
107
|
+
v = Vis(source="ambientcg", material_id="Metal012", roughness=0.3)
|
|
108
|
+
deltas: VisDeltas = {}
|
|
109
|
+
v2 = v.override(**deltas)
|
|
110
|
+
assert v2 == v
|
|
111
|
+
assert v2 is not v
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class TestIdentityFieldsTypedAsStr:
|
|
115
|
+
"""``VisDeltas.source``/``material_id`` are typed as ``str`` (no
|
|
116
|
+
``| None``) even though the underlying Vis field is ``str | None``.
|
|
117
|
+
|
|
118
|
+
Reason: ``override`` routes identity through ``set_identity``, which
|
|
119
|
+
interprets ``None`` as "leave unchanged" — so passing ``source=None``
|
|
120
|
+
would silently no-op, not clear the field. Typing the kwarg as
|
|
121
|
+
bare ``str`` enforces the kwargs idiom (omit to leave alone) and
|
|
122
|
+
keeps the type-checker contract honest. Pin both the TypedDict
|
|
123
|
+
annotation and the runtime no-op behavior so a future "let users
|
|
124
|
+
pass None to clear" change has to update everything in lockstep.
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
def test_visdeltas_source_typed_as_str(self):
|
|
128
|
+
# ``from __future__ import annotations`` means values are stored
|
|
129
|
+
# as forward references — compare the rendered forward-ref arg
|
|
130
|
+
# string. Bare ``str`` (not a union with None).
|
|
131
|
+
anns = VisDeltas.__annotations__
|
|
132
|
+
for field_name in ("source", "material_id", "tier"):
|
|
133
|
+
ann = anns[field_name]
|
|
134
|
+
ann_str = ann.__forward_arg__ if hasattr(ann, "__forward_arg__") else str(ann)
|
|
135
|
+
assert ann_str == "str", f"{field_name}: expected 'str', got {ann_str!r}"
|
|
136
|
+
|
|
137
|
+
def test_runtime_source_none_is_silent_noop(self):
|
|
138
|
+
"""If a user disregards the type and passes ``source=None`` at
|
|
139
|
+
runtime, identity is left unchanged (matches set_identity
|
|
140
|
+
semantics). Documents the lying-type the typing fix prevents
|
|
141
|
+
statically."""
|
|
142
|
+
v = Vis(source="ambientcg", material_id="Metal012", tier="1k")
|
|
143
|
+
# Bypass type checker — this is the runtime path
|
|
144
|
+
v2 = v.override(**{"source": None}) # type: ignore[typeddict-item]
|
|
145
|
+
assert v2.source == "ambientcg" # NOT cleared
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class TestPyTypedMarkerShipped:
|
|
149
|
+
"""PEP 561 marker — without ``py.typed`` mypy refuses to read
|
|
150
|
+
annotations and the whole ``Unpack[VisDeltas]`` effort delivers
|
|
151
|
+
zero value to mypy users."""
|
|
152
|
+
|
|
153
|
+
def test_py_typed_present_in_package(self):
|
|
154
|
+
import pymat
|
|
155
|
+
|
|
156
|
+
pkg_dir = Path(pymat.__file__).parent
|
|
157
|
+
marker = pkg_dir / "py.typed"
|
|
158
|
+
assert marker.exists(), (
|
|
159
|
+
f"PEP 561 marker missing at {marker}. Without it, mypy "
|
|
160
|
+
f"strict-mode users get no benefit from VisDeltas typing."
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class TestRuntimeIsTypingOnly:
|
|
165
|
+
"""``Unpack[VisDeltas]`` is wrapped in ``if TYPE_CHECKING:`` —
|
|
166
|
+
confirm there's no runtime side effect: the actual signature is
|
|
167
|
+
still ``**deltas: Any``, kwarg validation is still done by
|
|
168
|
+
``override``'s body, unknown kwargs still raise ``TypeError``."""
|
|
169
|
+
|
|
170
|
+
def test_unknown_kwarg_still_raises(self):
|
|
171
|
+
"""The TypedDict doesn't enforce at runtime — the override
|
|
172
|
+
body's ``valid_keys`` check does. Unchanged from 3.7.0."""
|
|
173
|
+
v = Vis(source="x", material_id="y")
|
|
174
|
+
with pytest.raises(TypeError, match="roughnes"):
|
|
175
|
+
v.override(roughnes=0.5) # typo
|
|
176
|
+
|
|
177
|
+
def test_typing_extensions_only_imported_under_type_checking(self):
|
|
178
|
+
"""``typing_extensions`` is imported only inside ``if
|
|
179
|
+
TYPE_CHECKING:`` — must not be a runtime dependency. If a
|
|
180
|
+
future refactor accidentally promotes the import, this test
|
|
181
|
+
won't catch it (TYPE_CHECKING is False at runtime, so the
|
|
182
|
+
import never runs in either case), but the assertion below
|
|
183
|
+
documents intent."""
|
|
184
|
+
import pymat.vis._model as model
|
|
185
|
+
|
|
186
|
+
# The Unpack name should NOT exist as a module-level attr at runtime.
|
|
187
|
+
assert not hasattr(model, "Unpack"), (
|
|
188
|
+
"Unpack leaked out of TYPE_CHECKING block — would force "
|
|
189
|
+
"typing_extensions as a runtime dep"
|
|
190
|
+
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|