Newer
Older
SmTIAS-LightSim / tests / fusion_import / test_mapping.py
"""fusion_import.mapping(ボディ対応表 YAML)の仕様ベーステスト.

仕様出典(Fusion 取り込みの確定事項):
- 対応表 YAML: default_material,led: package_dims_mm / tolerance_mm / direction /
  direction_overrides,boards: 手動基板ラベル,bodies: ボディ名 → id(`{board}` 埋め込み可)・
  material・exclude
- LED 既定寸法 [1.05, 2.8, 3.5] mm,各辺 ±0.15
- 基板ラベルは bottom / right / left / top
"""

from __future__ import annotations

from pathlib import Path

import pytest
import yaml
from pydantic import ValidationError

from sm_tias_lightsim.fusion_import.mapping import FusionMapping, load_mapping

_ROOT = Path(__file__).resolve().parents[2]
_SMTIAS_MAPPING = _ROOT / "configs" / "fusion" / "smtias_v3_mapping.yaml"


def test_led_defaults_are_2835_package():
    m = FusionMapping.model_validate({"default_material": "white"})
    assert tuple(m.led.package_dims_mm) == (1.05, 2.8, 3.5)
    assert m.led.tolerance_mm == pytest.approx(0.15)
    assert m.led.direction is None
    assert m.led.direction_overrides == {}
    assert m.boards == {}
    assert m.bodies == {}


def test_default_material_is_required():
    with pytest.raises(ValidationError):
        FusionMapping.model_validate({})


@pytest.mark.parametrize("label", ["bottom", "right", "left", "top"])
def test_known_board_labels_accepted(label):
    m = FusionMapping.model_validate({"default_material": "w", "boards": {"LEDユニット:1": label}})
    assert m.boards["LEDユニット:1"] == label


@pytest.mark.parametrize("label", ["front", "Bottom", "", "下"])
def test_unknown_board_label_rejected(label):
    with pytest.raises(ValidationError):
        FusionMapping.model_validate({"default_material": "w", "boards": {"LEDユニット:1": label}})


def test_body_rule_without_id_rejected_unless_excluded():
    with pytest.raises(ValidationError):
        FusionMapping.model_validate({"default_material": "w", "bodies": {"前側": {}}})
    m = FusionMapping.model_validate(
        {"default_material": "w", "bodies": {"スイッチカバー下": {"exclude": True}}})
    assert m.bodies["スイッチカバー下"].exclude


@pytest.mark.parametrize("dims", [[0.0, 2.8, 3.5], [-1.0, 2.8, 3.5]])
def test_non_positive_package_dims_rejected(dims):
    with pytest.raises(ValidationError):
        FusionMapping.model_validate({"default_material": "w", "led": {"package_dims_mm": dims}})


def test_non_positive_tolerance_rejected():
    with pytest.raises(ValidationError):
        FusionMapping.model_validate({"default_material": "w", "led": {"tolerance_mm": 0.0}})


def test_bodies_preserve_yaml_order(tmp_path):
    path = tmp_path / "m.yaml"
    path.write_text(
        "default_material: w\nbodies:\n  後側: {id: b}\n  前側: {id: a}\n  SH-02M: {id: c}\n",
        encoding="utf-8")
    assert list(load_mapping(path).bodies) == ["後側", "前側", "SH-02M"]


def test_direction_overrides_parsed(tmp_path):
    path = tmp_path / "m.yaml"
    path.write_text(yaml.safe_dump({
        "default_material": "w",
        "led": {"direction": [0, 0, -1], "direction_overrides": {"LEDユニット:2": [1, 0, 0]}},
    }, allow_unicode=True), encoding="utf-8")
    m = load_mapping(path)
    assert tuple(m.led.direction) == (0, 0, -1)
    assert tuple(m.led.direction_overrides["LEDユニット:2"]) == (1, 0, 0)


def test_load_mapping_missing_file_raises(tmp_path):
    with pytest.raises(FileNotFoundError):
        load_mapping(tmp_path / "none.yaml")


def test_smtias_v3_mapping_is_valid_and_matches_baseline_ids():
    """同梱の SmTIASv3 対応表が読め,id が scene_baseline.yaml のメッシュ id と対応する."""
    m = load_mapping(_SMTIAS_MAPPING)
    base = yaml.safe_load((_ROOT / "configs" / "scene_baseline.yaml").read_text(encoding="utf-8"))
    base_ids = {mesh["id"] for mesh in base["geometry"]["meshes"]}
    base_materials = set(base["materials"])
    expanded = set()
    for rule in m.bodies.values():
        if rule.exclude:
            continue
        ids = ([rule.id.replace("{board}", b) for b in ("bottom", "right", "left")]
               if "{board}" in rule.id else [rule.id])
        expanded.update(ids)
        assert (rule.material or m.default_material) in base_materials
    assert expanded == base_ids
    assert m.default_material in base_materials