232 lines
8.3 KiB
Python
232 lines
8.3 KiB
Python
"""Real registry/preflight/MIDI checks, not SDP serialization or SD3 acceptance."""
|
|
|
|
import shutil
|
|
import uuid
|
|
from collections.abc import Iterator
|
|
from dataclasses import asdict
|
|
from pathlib import Path
|
|
from unittest.mock import Mock
|
|
|
|
import pytest
|
|
from mido import MidiFile # type: ignore[import-untyped]
|
|
|
|
from riff_groove_builder.articulations import compile_score
|
|
from riff_groove_builder.compose import compose_score
|
|
from riff_groove_builder.description import resolve_description
|
|
from riff_groove_builder.errors import (
|
|
DomainError,
|
|
InvalidRequestError,
|
|
NativeFormatUnavailableError,
|
|
)
|
|
from riff_groove_builder.formats.sdp import check_sdp_capability, require_sdp_capability
|
|
from riff_groove_builder.midi import validate_midi_file, write_midi
|
|
from riff_groove_builder.profiles import (
|
|
InstrumentProfile,
|
|
InvalidProfileError,
|
|
ProfilePartMismatchError,
|
|
load_profile_registry,
|
|
)
|
|
from riff_groove_builder.schemas import GenerateMusicRequest, Part, ProfileSelection
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
pytestmark = pytest.mark.integration
|
|
|
|
|
|
@pytest.fixture
|
|
def workspace() -> Iterator[Path]:
|
|
path = ROOT / ".test-artifacts" / f"sdp-capability-{uuid.uuid4().hex}"
|
|
path.mkdir(parents=True)
|
|
try:
|
|
yield path
|
|
finally:
|
|
shutil.rmtree(path)
|
|
|
|
|
|
def test_checks_and_require_perform_no_output_io(
|
|
workspace: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
profile = load_profile_registry().select(
|
|
["drums"], ProfileSelection(drums="standard.gm-drums.v1")
|
|
)["drums"]
|
|
sentinel = workspace / "existing_drums.sdp"
|
|
content = b"operator-owned sentinel; NOT an SDP fixture"
|
|
sentinel.write_bytes(content)
|
|
before = sentinel.stat()
|
|
missing_parent = workspace / "never-created"
|
|
io = Mock(side_effect=AssertionError("Capability boundary attempted filesystem IO"))
|
|
with monkeypatch.context() as guard:
|
|
for method in (
|
|
"open",
|
|
"mkdir",
|
|
"touch",
|
|
"write_bytes",
|
|
"write_text",
|
|
"read_bytes",
|
|
"read_text",
|
|
"stat",
|
|
"rename",
|
|
"replace",
|
|
"unlink",
|
|
):
|
|
guard.setattr(Path, method, io)
|
|
guard.setattr("builtins.open", io)
|
|
guard.setattr("os.open", io)
|
|
capability = check_sdp_capability("drums", profile)
|
|
with pytest.raises(NativeFormatUnavailableError) as caught:
|
|
require_sdp_capability("drums", profile)
|
|
io.assert_not_called()
|
|
assert asdict(capability) == {
|
|
"part": "drums",
|
|
"format": "sdp",
|
|
"available": False,
|
|
"reason": "sdp_profile_not_supported",
|
|
}
|
|
assert caught.value.details == {
|
|
"format": "sdp",
|
|
"part": "drums",
|
|
"reason": capability.reason,
|
|
}
|
|
assert not missing_parent.exists()
|
|
assert list(workspace.iterdir()) == [sentinel]
|
|
assert sentinel.read_bytes() == content
|
|
after = sentinel.stat()
|
|
assert (after.st_ino, after.st_size, after.st_mtime_ns) == (
|
|
before.st_ino,
|
|
before.st_size,
|
|
before.st_mtime_ns,
|
|
)
|
|
|
|
|
|
def test_native_preflight_leaves_empty_output(workspace: Path) -> None:
|
|
profile = load_profile_registry().select(
|
|
["drums"], ProfileSelection(drums="standard.gm-drums.v1")
|
|
)["drums"]
|
|
with pytest.raises(NativeFormatUnavailableError):
|
|
require_sdp_capability("drums", profile)
|
|
assert list(workspace.iterdir()) == []
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("description", "parts"),
|
|
[
|
|
("drums only 1 bar quarter", ["drums"]),
|
|
("lead and bass and drums 1 bar quarter", ["lead", "bass", "drums"]),
|
|
],
|
|
)
|
|
def test_explicit_independent_standard_midi_remains_available_without_sdp(
|
|
workspace: Path, description: str, parts: list[Part]
|
|
) -> None:
|
|
request = GenerateMusicRequest(
|
|
description=description, basename="explicit-midi", formats=["mid"]
|
|
)
|
|
resolved = resolve_description(request)
|
|
assert resolved.intent.parts == parts
|
|
selected = load_profile_registry().select(
|
|
resolved.intent.parts,
|
|
ProfileSelection(
|
|
**{
|
|
part: "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1"
|
|
for part in parts
|
|
}
|
|
),
|
|
)
|
|
drums = selected["drums"]
|
|
assert drums.id == "standard.gm-drums.v1"
|
|
assert drums.summary.mapping_kind == "standard_midi"
|
|
with pytest.raises(NativeFormatUnavailableError) as caught:
|
|
require_sdp_capability("drums", drums)
|
|
assert caught.value.code == "NATIVE_FORMAT_UNAVAILABLE"
|
|
assert caught.value.details["part"] == "drums"
|
|
assert list(workspace.iterdir()) == []
|
|
|
|
score = compose_score(resolved.intent, selected)
|
|
plan = compile_score(score, selected)
|
|
midi = workspace / "explicit-midi.mid"
|
|
assert write_midi(midi, plan) == midi
|
|
validate_midi_file(midi, plan)
|
|
assert midi.read_bytes().startswith(b"MThd")
|
|
saved = MidiFile(midi)
|
|
assert saved.type == 1
|
|
assert saved.ticks_per_beat == 960
|
|
assert [track.name for track in saved.tracks] == ["Conductor"] + [p.title() for p in parts]
|
|
drum_track = saved.tracks[-1]
|
|
hits = [message for message in drum_track if message.type == "note_on"]
|
|
assert len(hits) == 8
|
|
assert {message.note for message in hits} == {36, 38, 42}
|
|
assert {message.channel for message in hits} == {9}
|
|
assert all(1 <= message.velocity <= 127 for message in hits)
|
|
assert all(sum(message.time for message in track) == 3840 for track in saved.tracks)
|
|
assert list(workspace.iterdir()) == [midi]
|
|
assert not list(workspace.rglob("*.sdp"))
|
|
assert not list(workspace.rglob("*.agp"))
|
|
assert check_sdp_capability("drums", drums).available is False
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("case", "expected_error", "details"),
|
|
[
|
|
(
|
|
"lead_request",
|
|
InvalidRequestError,
|
|
{"format": "sdp", "reason": "unsupported_sdp_part"},
|
|
),
|
|
(
|
|
"wrong_profile",
|
|
ProfilePartMismatchError,
|
|
{"format": "sdp", "part": "drums", "reason": "wrong_part"},
|
|
),
|
|
("wrong_target", InvalidProfileError, {"reason": "invalid_profile_model"}),
|
|
("deep_mutation", InvalidProfileError, {"reason": "invalid_profile_model"}),
|
|
("native_flag", InvalidProfileError, {"reason": "invalid_profile_model"}),
|
|
("unchecked_model", InvalidProfileError, {"reason": "invalid_profile_model"}),
|
|
],
|
|
)
|
|
def test_invalid_input_is_not_fallback_and_leaves_existing_output_untouched(
|
|
workspace: Path,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
case: str,
|
|
expected_error: type[DomainError],
|
|
details: dict[str, str],
|
|
) -> None:
|
|
sentinel = workspace / "existing_drums.sdp"
|
|
sentinel.write_bytes(b"existing operator data, NOT a native fixture")
|
|
before = sentinel.stat()
|
|
registry = load_profile_registry()
|
|
profile = registry.select(["drums"], ProfileSelection(drums="standard.gm-drums.v1"))["drums"]
|
|
part: Part = "drums"
|
|
if case == "lead_request":
|
|
part = "lead"
|
|
elif case == "wrong_profile":
|
|
profile = registry.select(["bass"], ProfileSelection(bass="standard.bass.v1"))["bass"]
|
|
elif case == "wrong_target":
|
|
profile.summary.instrument = "ray"
|
|
elif case == "deep_mutation":
|
|
profile.drum_voices[0].note = 128
|
|
elif case == "native_flag":
|
|
profile.summary.native_available = True
|
|
else:
|
|
profile = InstrumentProfile.model_construct(id="incomplete")
|
|
|
|
io = Mock(side_effect=AssertionError("Invalid input attempted filesystem IO"))
|
|
with monkeypatch.context() as guard:
|
|
guard.setattr(Path, "open", io)
|
|
guard.setattr(Path, "mkdir", io)
|
|
guard.setattr(Path, "stat", io)
|
|
guard.setattr("builtins.open", io)
|
|
guard.setattr("os.open", io)
|
|
for boundary in (check_sdp_capability, require_sdp_capability):
|
|
with pytest.raises(expected_error) as caught:
|
|
boundary(part, profile)
|
|
assert type(caught.value) is expected_error
|
|
assert caught.value.details == details
|
|
assert caught.value.code != "NATIVE_FORMAT_UNAVAILABLE"
|
|
io.assert_not_called()
|
|
assert sentinel.read_bytes() == b"existing operator data, NOT a native fixture"
|
|
after = sentinel.stat()
|
|
assert (after.st_ino, after.st_size, after.st_mtime_ns) == (
|
|
before.st_ino,
|
|
before.st_size,
|
|
before.st_mtime_ns,
|
|
)
|
|
assert list(workspace.iterdir()) == [sentinel]
|