"""SDP capability contracts; mapping fixtures are not native files or vendor evidence.""" from collections.abc import Callable from dataclasses import FrozenInstanceError, asdict from pathlib import Path from typing import cast import pytest from riff_groove_builder.errors import ( DomainError, InvalidRequestError, NativeFormatUnavailableError, ) from riff_groove_builder.formats import NativeCapability from riff_groove_builder.formats.sdp import check_sdp_capability, require_sdp_capability from riff_groove_builder.profiles import ( InstrumentProfile, InvalidProfileError, ProfilePartMismatchError, load_profile_registry, parse_profile, ) from riff_groove_builder.schemas import Part, ProfileSelection Boundary = Callable[[Part, InstrumentProfile], NativeCapability] BOUNDARIES: list[Boundary] = [check_sdp_capability, require_sdp_capability] FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "profiles" def standard(part: Part = "drums") -> InstrumentProfile: identifier = "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" return load_profile_registry().select([part], ProfileSelection(**{part: identifier}))[part] def test_gm_profile_returns_explicit_typed_immutable_unavailable() -> None: profile = standard() before = profile.model_dump() capability: NativeCapability = check_sdp_capability("drums", profile) assert type(capability) is NativeCapability assert asdict(capability) == { "part": "drums", "format": "sdp", "available": False, "reason": "sdp_profile_not_supported", } assert profile.id == "standard.gm-drums.v1" assert profile.summary.mapping_kind == "standard_midi" assert profile.summary.native_available is False assert profile.provenance.status == "standard_midi" assert profile.model_dump() == before assert check_sdp_capability("drums", profile) == capability assert not hasattr(capability, "__dict__") for field, value in ( ("part", "lead"), ("format", "agp"), ("available", True), ("reason", "forged"), ): with pytest.raises(FrozenInstanceError): setattr(capability, field, value) def test_synthetic_instrument_mapping_does_not_establish_a_codec() -> None: profile = parse_profile((FIXTURES / "synthetic-drums.json").read_bytes()) assert profile.summary.mapping_kind == "instrument" assert profile.provenance.status == "test_only" assert check_sdp_capability("drums", profile) == check_sdp_capability("drums", standard()) def test_mapping_attestation_and_product_version_are_not_native_evidence() -> None: data = parse_profile((FIXTURES / "synthetic-drums.json").read_bytes()).model_dump() data["id"] = data["summary"]["id"] = "harness.mapping.only" data["summary"]["product_name"] = "TEST HARNESS mapping attestation, NOT vendor evidence" data["summary"]["product_version"] = data["provenance"]["product_version"] = "unknown-build" data["provenance"]["status"] = "verified" data["provenance"]["sources"] = [ { "kind": "lawful_local", "reference": "TEST-HARNESS-NOT-VENDOR-EVIDENCE", "aspects": [ "identity", "range_or_voices", "channels", "actions", "state_reset", "timing", "velocity", ], } ] profile = InstrumentProfile.model_validate(data) assert check_sdp_capability("drums", profile).available is False with pytest.raises(NativeFormatUnavailableError) as caught: require_sdp_capability("drums", profile) assert caught.value.details["reason"] == "sdp_profile_not_supported" @pytest.mark.parametrize("boundary", BOUNDARIES) def test_native_metadata_cannot_enable_instrument_support(boundary: Boundary) -> None: profile = parse_profile((FIXTURES / "synthetic-drums.json").read_bytes()) profile.summary.native_available = True with pytest.raises(InvalidProfileError) as caught: boundary("drums", profile) assert caught.value.details == {"reason": "invalid_profile_model"} def test_require_raises_named_error_with_safe_complete_context() -> None: with pytest.raises(NativeFormatUnavailableError) as caught: require_sdp_capability("drums", standard()) assert caught.value.code == "NATIVE_FORMAT_UNAVAILABLE" assert caught.value.details == { "format": "sdp", "part": "drums", "reason": "sdp_profile_not_supported", } @pytest.mark.parametrize("boundary", BOUNDARIES) @pytest.mark.parametrize( "invalid", ["lead", "bass", "sd3", "drum", "DRUMS", "", None, 1, True, [], {}] ) def test_invalid_parts_are_bad_requests_not_unavailable( boundary: Boundary, invalid: object ) -> None: with pytest.raises(InvalidRequestError) as caught: boundary(cast(Part, invalid), standard()) assert caught.value.code == "INVALID_REQUEST" assert caught.value.details == {"format": "sdp", "reason": "unsupported_sdp_part"} @pytest.mark.parametrize("boundary", BOUNDARIES) @pytest.mark.parametrize("profile_part", ["lead", "bass"]) def test_valid_wrong_part_profiles_are_selection_errors( boundary: Boundary, profile_part: Part ) -> None: with pytest.raises(ProfilePartMismatchError) as caught: boundary("drums", standard(profile_part)) assert caught.value.code == "PROFILE_REQUIRED" assert caught.value.details == {"format": "sdp", "part": "drums", "reason": "wrong_part"} @pytest.mark.parametrize("boundary", BOUNDARIES) @pytest.mark.parametrize( "mutation", [ "instrument", "part", "format", "native_flag", "channel", "voice_note", "duplicate_note", "voice_alias", "empty_voices", "range", "aliases", "layer", "provenance", "mapping_kind", "version", "schema", "unchecked_copy", "unchecked_construct", ], ) def test_mutated_profiles_are_invalid_not_native_unavailable( boundary: Boundary, mutation: str ) -> None: profile = standard() if mutation == "instrument": profile.summary.instrument = "eclips" elif mutation == "part": profile.summary.part = "lead" elif mutation == "format": profile.summary.native_format = "griff" elif mutation == "native_flag": profile.summary.native_available = True elif mutation == "channel": profile.channel = 128 elif mutation == "voice_note": profile.drum_voices[0].note = 128 elif mutation == "duplicate_note": profile.drum_voices[1].note = profile.drum_voices[0].note elif mutation == "voice_alias": profile.drum_voices[0].aliases.append(profile.drum_voices[1].name) elif mutation == "empty_voices": profile.drum_voices.clear() elif mutation == "range": profile.playable_range = standard("lead").playable_range elif mutation == "aliases": profile.articulations[0].aliases.append("slide") elif mutation == "layer": profile.articulations[0].layers[0].velocity_high = 128 elif mutation == "provenance": profile.provenance.sources[0].aspects.clear() elif mutation == "mapping_kind": profile.summary.mapping_kind = "instrument" elif mutation == "version": profile.provenance.mapping_version = "private-inconsistent-version" elif mutation == "schema": profile = profile.model_copy(update={"schema_version": "private-invalid-version"}) elif mutation == "unchecked_copy": profile = profile.model_copy(update={"drum_voices": ["private-invalid-voice"]}) else: profile = InstrumentProfile.model_construct(id="private-incomplete-profile") with pytest.raises(InvalidProfileError) as caught: boundary("drums", profile) assert caught.value.code == "SERIALIZATION_ERROR" assert caught.value.details == {"reason": "invalid_profile_model"} assert "private" not in str(caught.value) @pytest.mark.parametrize("boundary", BOUNDARIES) @pytest.mark.parametrize("invalid", [None, {}, "not a profile"]) def test_wrong_profile_model_type_is_corrupted_input(boundary: Boundary, invalid: object) -> None: with pytest.raises(InvalidProfileError) as caught: boundary("drums", cast(InstrumentProfile, invalid)) assert caught.value.code == "SERIALIZATION_ERROR" assert caught.value.details == {"reason": "invalid_profile_model"} def test_mutating_a_profile_after_check_cannot_authorize_require() -> None: profile = standard() capability = check_sdp_capability("drums", profile) profile.drum_voices.clear() with pytest.raises(InvalidProfileError): require_sdp_capability("drums", profile) assert capability.available is False @pytest.mark.parametrize("boundary", BOUNDARIES) def test_unexpected_validation_errors_are_not_fallback( monkeypatch: pytest.MonkeyPatch, boundary: Boundary ) -> None: profile = standard() def broken_check(profile: InstrumentProfile) -> InstrumentProfile: raise RuntimeError("test-only unexpected programming failure") monkeypatch.setattr("riff_groove_builder.formats.sdp.checked_profile", broken_check) with pytest.raises(RuntimeError): boundary("drums", profile) @pytest.mark.parametrize("boundary", BOUNDARIES) def test_invalid_request_takes_precedence_over_invalid_profile(boundary: Boundary) -> None: with pytest.raises(DomainError) as caught: boundary("lead", cast(InstrumentProfile, None)) assert type(caught.value) is InvalidRequestError