684 lines
23 KiB
Python
684 lines
23 KiB
Python
"""Synthetic SMF mechanics only; no plugin mappings or application claims."""
|
|
|
|
import math
|
|
import shutil
|
|
import struct
|
|
import uuid
|
|
from collections.abc import Iterator
|
|
from fractions import Fraction
|
|
from pathlib import Path
|
|
from typing import Literal, cast
|
|
from unittest.mock import MagicMock
|
|
|
|
import mido # type: ignore[import-untyped]
|
|
import pytest
|
|
|
|
from riff_groove_builder import midi
|
|
from riff_groove_builder.errors import OutputExistsError, OutputIOError, SerializationError
|
|
from riff_groove_builder.schemas import (
|
|
MAX_SCHEDULED_EVENTS,
|
|
ControlChangeEvent,
|
|
EventPlan,
|
|
EventTrack,
|
|
MusicalIntent,
|
|
NoteOffEvent,
|
|
NoteOnEvent,
|
|
Part,
|
|
PitchedNote,
|
|
PositiveBeat,
|
|
RationalBeat,
|
|
ScheduledEvent,
|
|
Score,
|
|
ScoreTrack,
|
|
TimeSignature,
|
|
)
|
|
|
|
Role = Literal["musical_note", "keyswitch"]
|
|
|
|
|
|
@pytest.fixture
|
|
def workspace() -> Iterator[Path]:
|
|
root = Path(__file__).resolve().parents[2] / ".test-artifacts" / f"midi-unit-{uuid.uuid4().hex}"
|
|
root.mkdir(parents=True)
|
|
try:
|
|
yield root
|
|
finally:
|
|
shutil.rmtree(root)
|
|
|
|
|
|
def on(
|
|
tick: int = 120,
|
|
note: int = 60,
|
|
*,
|
|
part: Part = "lead",
|
|
channel: int = 2,
|
|
role: Role = "musical_note",
|
|
priority: int = 30,
|
|
sequence: int = 0,
|
|
) -> NoteOnEvent:
|
|
return NoteOnEvent(
|
|
tick=tick,
|
|
part=part,
|
|
channel=channel,
|
|
role=role,
|
|
note=note,
|
|
velocity=91,
|
|
priority=priority,
|
|
sequence=sequence,
|
|
)
|
|
|
|
|
|
def off(
|
|
tick: int = 1080,
|
|
note: int = 60,
|
|
*,
|
|
part: Part = "lead",
|
|
channel: int = 2,
|
|
role: Role = "musical_note",
|
|
priority: int = 10,
|
|
sequence: int = 0,
|
|
) -> NoteOffEvent:
|
|
return NoteOffEvent(
|
|
tick=tick,
|
|
part=part,
|
|
channel=channel,
|
|
role=role,
|
|
note=note,
|
|
velocity=17,
|
|
priority=priority,
|
|
sequence=sequence,
|
|
)
|
|
|
|
|
|
def cc(
|
|
tick: int = 120,
|
|
*,
|
|
part: Part = "lead",
|
|
channel: int = 2,
|
|
priority: int = 20,
|
|
sequence: int = 0,
|
|
value: int = 63,
|
|
) -> ControlChangeEvent:
|
|
return ControlChangeEvent(
|
|
tick=tick,
|
|
part=part,
|
|
channel=channel,
|
|
controller=21,
|
|
value=value,
|
|
priority=priority,
|
|
sequence=sequence,
|
|
)
|
|
|
|
|
|
def make_plan(
|
|
events: list[ScheduledEvent] | None = None,
|
|
*,
|
|
parts: list[Part] | None = None,
|
|
ppq: int = 960,
|
|
musical_start: int = 120,
|
|
tail: int = 30,
|
|
meter: TimeSignature | None = None,
|
|
bpm: float = 120,
|
|
score_start: Fraction = Fraction(0),
|
|
) -> EventPlan:
|
|
selected: list[Part] = parts if parts is not None else ["lead"]
|
|
signature = meter if meter is not None else TimeSignature(numerator=4, denominator=4)
|
|
duration = signature.beats_per_bar
|
|
end = score_start + duration
|
|
score = Score(
|
|
intent=MusicalIntent(
|
|
description="Synthetic writer test, not an instrument profile",
|
|
parts=selected,
|
|
tempo_bpm=bpm,
|
|
bars=1,
|
|
time_signature=signature,
|
|
key="E minor",
|
|
seed=0,
|
|
),
|
|
start=RationalBeat(numerator=score_start.numerator, denominator=score_start.denominator),
|
|
end=RationalBeat(numerator=end.numerator, denominator=end.denominator),
|
|
tracks=[ScoreTrack(part=part, notes=[]) for part in selected],
|
|
)
|
|
musical_end = musical_start + int(duration * ppq)
|
|
return EventPlan(
|
|
score=score,
|
|
ticks_per_quarter=ppq,
|
|
musical_start_tick=musical_start,
|
|
musical_end_tick=musical_end,
|
|
end_tick=musical_end + tail,
|
|
tracks=[
|
|
EventTrack(part=part, events=[event for event in events or [] if event.part == part])
|
|
for part in selected
|
|
],
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("numerator", "denominator", "expected"),
|
|
[(4, 4, 3840), (3, 4, 2880), (6, 8, 2880), (7, 8, 3360), (5, 16, 1200)],
|
|
)
|
|
def test_bar_math(numerator: int, denominator: int, expected: int) -> None:
|
|
meter = TimeSignature.model_validate({"numerator": numerator, "denominator": denominator})
|
|
assert midi.bar_ticks(meter) == expected
|
|
assert midi.bar_ticks(meter, bars=3) == expected * 3
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("beats", "expected"),
|
|
[
|
|
(Fraction(0), 0),
|
|
(Fraction(1), 960),
|
|
(Fraction(1, 2), 480),
|
|
(Fraction(1, 4), 240),
|
|
(Fraction(1, 3), 320),
|
|
(Fraction(2, 3), 640),
|
|
(Fraction(7, 12), 560),
|
|
],
|
|
)
|
|
def test_exact_beats(beats: Fraction, expected: int) -> None:
|
|
assert midi.beats_to_ticks(beats) == expected
|
|
assert (
|
|
midi.beats_to_ticks(RationalBeat(numerator=beats.numerator, denominator=beats.denominator))
|
|
== expected
|
|
)
|
|
|
|
|
|
def test_ppq_and_fraction_boundaries() -> None:
|
|
assert midi.beats_to_ticks(1, 1) == 1
|
|
assert midi.beats_to_ticks(1, midi.MAX_PPQ) == 32767
|
|
assert midi.beats_to_ticks(Fraction(1, 960)) == 1
|
|
assert midi.beats_to_ticks(Fraction(1, 7), 7) == 1
|
|
for beats in (Fraction(1, 7), Fraction(1, 1920)):
|
|
with pytest.raises(SerializationError, match="serialization") as failure:
|
|
midi.beats_to_ticks(beats)
|
|
assert failure.value.details["reason"] == "off_grid_beats"
|
|
with pytest.raises(SerializationError):
|
|
midi.bar_ticks(TimeSignature(numerator=3, denominator=8), ppq=1)
|
|
|
|
|
|
@pytest.mark.parametrize("value", [True, False, 1.0, "1", -1, math.nan, math.inf])
|
|
def test_strict_beats(value: object) -> None:
|
|
with pytest.raises(SerializationError):
|
|
midi.beats_to_ticks(cast(Fraction, value))
|
|
|
|
|
|
@pytest.mark.parametrize("value", [0, -1, True, 960.0, "960", 32768, 65535])
|
|
def test_illegal_ppq(value: object) -> None:
|
|
with pytest.raises(SerializationError):
|
|
midi.beats_to_ticks(1, cast(int, value))
|
|
|
|
|
|
@pytest.mark.parametrize("bars", [0, -1, True, 1.0, "1"])
|
|
def test_strict_bars(bars: object) -> None:
|
|
with pytest.raises(SerializationError):
|
|
midi.bar_ticks(TimeSignature(numerator=4, denominator=4), cast(int, bars))
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("bpm", "expected"),
|
|
[
|
|
(120.0, 500000),
|
|
(120.125, 499480),
|
|
(137.5, 436364),
|
|
(300.0, 200000),
|
|
(102.4, 585938),
|
|
(61.44, 976562),
|
|
],
|
|
)
|
|
def test_quarter_tempo(bpm: float, expected: int) -> None:
|
|
assert midi.quarter_tempo(bpm) == expected
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"bpm", [True, "120", 0, -1, math.nan, math.inf, 0.001, 200_000_000, 10**400]
|
|
)
|
|
def test_invalid_or_unrepresentable_tempo(bpm: object) -> None:
|
|
with pytest.raises(SerializationError):
|
|
midi.quarter_tempo(cast(float, bpm))
|
|
|
|
|
|
def test_priority_sequence_preserved_not_pitch_sorted(workspace: Path) -> None:
|
|
events: list[ScheduledEvent] = [
|
|
off(1080, 60),
|
|
on(note=60, priority=9),
|
|
cc(priority=8, sequence=2, value=2),
|
|
cc(priority=8, sequence=1, value=1),
|
|
off(1080, 72, sequence=1),
|
|
on(note=72, priority=7),
|
|
]
|
|
path = midi.write_midi(workspace / "ordered.mid", make_plan(events))
|
|
loaded = mido.MidiFile(path)
|
|
assert [(message.type, message.time) for message in loaded.tracks[1]] == [
|
|
("track_name", 0),
|
|
("note_on", 120),
|
|
("control_change", 0),
|
|
("control_change", 0),
|
|
("note_on", 0),
|
|
("note_off", 960),
|
|
("note_off", 0),
|
|
("end_of_track", 2910),
|
|
]
|
|
assert [message.value for message in loaded.tracks[1] if message.type == "control_change"] == [
|
|
1,
|
|
2,
|
|
]
|
|
assert [message.note for message in loaded.tracks[1] if message.type == "note_on"] == [72, 60]
|
|
assert events[0].tick == 1080 # Input list is not sorted or mutated in place.
|
|
|
|
|
|
@pytest.mark.parametrize("role", ["musical_note", "keyswitch"])
|
|
def test_off_on_retrigger(workspace: Path, role: Role) -> None:
|
|
plan = make_plan([on(role=role), off(role=role), on(1080, role=role), off(2040, role=role)])
|
|
path = midi.write_midi(workspace / "retrigger.mid", plan)
|
|
assert [message.type for message in mido.MidiFile(path).tracks[1]][1:-1] == [
|
|
"note_on",
|
|
"note_off",
|
|
"note_on",
|
|
"note_off",
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("events", "reason"),
|
|
[
|
|
([off()], "orphan_note_off"),
|
|
([on()], "dangling_note"),
|
|
([on(role="keyswitch")], "dangling_note"),
|
|
([off(role="keyswitch")], "orphan_note_off"),
|
|
([on(), on(480), off(1080), off(2040)], "same_pitch_overlap"),
|
|
([on(), on(480, role="keyswitch"), off()], "same_pitch_overlap"),
|
|
([on(role="keyswitch"), on(480), off()], "same_pitch_overlap"),
|
|
([on(), off(role="keyswitch")], "note_role_mismatch"),
|
|
([on(role="keyswitch"), off()], "note_role_mismatch"),
|
|
([on(), off(channel=3)], "orphan_note_off"),
|
|
([on(), off(120, priority=31)], "nonpositive_note_duration"),
|
|
([on(), on(1080, priority=1), off(), off(2040)], "same_pitch_overlap"),
|
|
([on(), off(120)], "orphan_note_off"),
|
|
],
|
|
)
|
|
def test_unsafe_pairing(events: list[ScheduledEvent], reason: str) -> None:
|
|
with pytest.raises(SerializationError) as failure:
|
|
midi.validate_event_plan(make_plan(events))
|
|
assert failure.value.details["reason"] == reason
|
|
assert failure.value.details["part"] == "lead"
|
|
assert failure.value.details["role"] in ("musical_note", "keyswitch")
|
|
|
|
|
|
def test_roles_may_reuse_pitch_only_after_release() -> None:
|
|
midi.validate_event_plan(
|
|
make_plan([on(0, role="keyswitch"), off(120, role="keyswitch"), on(), off()])
|
|
)
|
|
|
|
|
|
def test_polyphony_and_channel_independence() -> None:
|
|
midi.validate_event_plan(
|
|
make_plan([on(note=60), on(note=64, sequence=1), off(note=60), off(note=64, sequence=1)])
|
|
)
|
|
midi.validate_event_plan(
|
|
make_plan([on(), on(channel=3, sequence=1), off(), off(channel=3, sequence=1)])
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("control_only", [False, True])
|
|
def test_distinct_parts_cannot_share_channel_even_at_different_times(control_only: bool) -> None:
|
|
bass: list[ScheduledEvent] = (
|
|
[cc(2040, part="bass")] if control_only else [on(2040, part="bass"), off(3000, part="bass")]
|
|
)
|
|
with pytest.raises(SerializationError) as failure:
|
|
midi.validate_event_plan(make_plan([on(), off(), *bass], parts=["lead", "bass"]))
|
|
assert failure.value.details["reason"] == "shared_channel"
|
|
|
|
|
|
def test_empty_tracks_metadata_and_shared_tail(workspace: Path) -> None:
|
|
plan = make_plan(parts=["drums", "lead", "bass"], bpm=137.5)
|
|
path = midi.write_midi(workspace / "rests.mid", plan)
|
|
loaded = mido.MidiFile(path)
|
|
assert loaded.type == 1
|
|
assert loaded.ticks_per_beat == 960
|
|
assert [track.name for track in loaded.tracks] == ["Conductor", "Drums", "Lead", "Bass"]
|
|
assert [message.tempo for message in loaded.tracks[0] if message.type == "set_tempo"] == [
|
|
436364
|
|
]
|
|
for track in loaded.tracks:
|
|
assert sum(message.time for message in track) == 3990
|
|
assert sum(message.type == "end_of_track" for message in track) == 1
|
|
assert track[-1].type == "end_of_track"
|
|
assert [message.type for message in loaded.tracks[1]] == ["track_name", "end_of_track"]
|
|
|
|
|
|
def test_keyswitch_release_may_use_shared_tail(workspace: Path) -> None:
|
|
plan = make_plan(
|
|
[
|
|
on(0, note=5, role="keyswitch"),
|
|
off(3990, note=5, role="keyswitch"),
|
|
on(),
|
|
off(3960),
|
|
cc(3990),
|
|
]
|
|
)
|
|
path = midi.write_midi(workspace / "tail.mid", plan)
|
|
track = mido.MidiFile(path).tracks[1]
|
|
assert [(message.type, message.time) for message in track][-3:] == [
|
|
("note_off", 30),
|
|
("control_change", 0),
|
|
("end_of_track", 0),
|
|
]
|
|
|
|
|
|
def test_mutable_beat_and_meter_helpers_revalidate() -> None:
|
|
beat = RationalBeat(numerator=1)
|
|
beat.denominator = 0
|
|
with pytest.raises(SerializationError):
|
|
midi.beats_to_ticks(beat)
|
|
meter = TimeSignature(numerator=4, denominator=4)
|
|
meter.numerator = True
|
|
with pytest.raises(SerializationError):
|
|
midi.bar_ticks(meter)
|
|
|
|
|
|
def test_nonzero_score_origin_is_not_an_extra_part_shift(workspace: Path) -> None:
|
|
plan = make_plan([on(), off()], score_start=Fraction(11, 3))
|
|
plan.score.tracks[0].notes.append(
|
|
PitchedNote(
|
|
part="lead",
|
|
pitch=60,
|
|
start=RationalBeat(numerator=11, denominator=3),
|
|
duration=PositiveBeat(numerator=1),
|
|
intensity=0.5,
|
|
articulation="synthetic",
|
|
)
|
|
)
|
|
path = midi.write_midi(workspace / "origin.mid", plan)
|
|
assert mido.MidiFile(path).tracks[1][1].time == 120
|
|
assert plan.score.start.value == Fraction(11, 3)
|
|
assert plan.musical_end_tick - plan.musical_start_tick == 3840
|
|
|
|
|
|
def test_logical_note_offsets_and_durations_must_be_on_grid() -> None:
|
|
plan = make_plan()
|
|
note = PitchedNote(
|
|
part="lead",
|
|
pitch=60,
|
|
start=RationalBeat(numerator=1, denominator=7),
|
|
duration=PositiveBeat(numerator=1),
|
|
intensity=0.5,
|
|
articulation="synthetic",
|
|
)
|
|
plan.score.tracks[0].notes.append(note)
|
|
with pytest.raises(SerializationError) as failure:
|
|
midi.validate_event_plan(plan)
|
|
assert failure.value.details["reason"] == "off_grid_beats"
|
|
note.start = RationalBeat(numerator=0)
|
|
note.duration = PositiveBeat(numerator=1, denominator=7)
|
|
with pytest.raises(SerializationError) as failure:
|
|
midi.validate_event_plan(plan)
|
|
assert failure.value.details["reason"] == "off_grid_beats"
|
|
|
|
|
|
def test_maximum_conductor_delta_and_overflow(workspace: Path) -> None:
|
|
plan = make_plan(musical_start=midi.MAX_DELTA - 3840, tail=0)
|
|
path = midi.write_midi(workspace / "max-delta.mid", plan)
|
|
assert mido.MidiFile(path).tracks[0][-1].time == midi.MAX_DELTA
|
|
plan.end_tick += 1
|
|
with pytest.raises(SerializationError) as failure:
|
|
midi.validate_event_plan(plan)
|
|
assert failure.value.details["reason"] == "delta_out_of_range"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("field", "value"),
|
|
[
|
|
("tick", -1),
|
|
("tick", 120.0),
|
|
("tick", True),
|
|
("note", 128),
|
|
("velocity", 0),
|
|
("channel", 16),
|
|
("priority", -1),
|
|
("sequence", True),
|
|
("kind", "program_change"),
|
|
("role", "unknown"),
|
|
("part", "bass"),
|
|
],
|
|
)
|
|
def test_mutated_event_graph_is_revalidated(field: str, value: object) -> None:
|
|
plan = make_plan([on(), off()])
|
|
setattr(plan.tracks[0].events[0], field, value)
|
|
with pytest.raises(SerializationError) as failure:
|
|
midi.validate_event_plan(plan)
|
|
assert failure.value.details["reason"] == "invalid_event_plan"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"mutation",
|
|
["end_on", "early_on", "late_off", "late_control", "bad_span", "bad_ppq", "tempo", "keys"],
|
|
)
|
|
def test_shared_timeline_and_schema_guards(mutation: str) -> None:
|
|
plan = make_plan([on(), off()])
|
|
if mutation == "end_on":
|
|
plan.tracks[0].events[0].tick = plan.musical_end_tick
|
|
elif mutation == "early_on":
|
|
plan.tracks[0].events[0].tick = 0
|
|
elif mutation == "late_off":
|
|
plan.tracks[0].events[1].tick = plan.musical_end_tick + 1
|
|
elif mutation == "late_control":
|
|
plan.tracks[0].events.append(cc(plan.end_tick + 1))
|
|
elif mutation == "bad_span":
|
|
plan.musical_end_tick += 1
|
|
elif mutation == "bad_ppq":
|
|
plan.ticks_per_quarter = True
|
|
elif mutation == "tempo":
|
|
plan.score.intent.tempo_bpm = math.nan
|
|
else:
|
|
plan.tracks[0].events.append(on())
|
|
with pytest.raises(SerializationError) as failure:
|
|
midi.validate_event_plan(plan)
|
|
assert failure.value.details["reason"] == "invalid_event_plan"
|
|
|
|
|
|
def test_ppq_header_limit_is_stricter_than_internal_positive_resolution() -> None:
|
|
with pytest.raises(SerializationError) as failure:
|
|
midi.validate_event_plan(make_plan(ppq=32768))
|
|
assert failure.value.details["reason"] == "invalid_ppq"
|
|
|
|
|
|
@pytest.mark.parametrize("ppq", [1, 32767])
|
|
def test_legal_ppq_limits_survive_disk_header(workspace: Path, ppq: int) -> None:
|
|
path = midi.write_midi(workspace / "ppq.mid", make_plan(ppq=ppq, musical_start=0, tail=0))
|
|
loaded = mido.MidiFile(path)
|
|
assert loaded.ticks_per_beat == ppq
|
|
assert loaded.tracks[0][-1].time == 4 * ppq
|
|
|
|
|
|
@pytest.mark.parametrize(("channel", "note", "velocity"), [(0, 0, 1), (15, 127, 127)])
|
|
def test_midi_payload_limits_survive_disk(
|
|
workspace: Path, channel: int, note: int, velocity: int
|
|
) -> None:
|
|
onset = on(channel=channel, note=note)
|
|
onset.velocity = velocity
|
|
release = off(channel=channel, note=note)
|
|
release.velocity = 127
|
|
control = cc(channel=channel, value=127)
|
|
control.controller = 0
|
|
path = midi.write_midi(workspace / "payloads.mid", make_plan([onset, release, control]))
|
|
messages = [message for message in mido.MidiFile(path).tracks[1] if not message.is_meta]
|
|
assert messages[0].type == "control_change"
|
|
assert (messages[0].channel, messages[0].control, messages[0].value) == (channel, 0, 127)
|
|
assert (messages[1].channel, messages[1].note, messages[1].velocity) == (
|
|
channel,
|
|
note,
|
|
velocity,
|
|
)
|
|
assert (messages[2].channel, messages[2].note, messages[2].velocity) == (channel, note, 127)
|
|
|
|
|
|
def test_event_budget_exact_boundary() -> None:
|
|
events: list[ScheduledEvent] = [cc(sequence=index) for index in range(MAX_SCHEDULED_EVENTS - 1)]
|
|
plan = make_plan(events)
|
|
midi.validate_event_plan(plan)
|
|
plan.tracks[0].events.append(cc(sequence=MAX_SCHEDULED_EVENTS - 1))
|
|
midi.validate_event_plan(plan)
|
|
plan.tracks[0].events.append(cc(sequence=MAX_SCHEDULED_EVENTS))
|
|
with pytest.raises(SerializationError) as failure:
|
|
midi.validate_event_plan(plan)
|
|
assert failure.value.details["reason"] == "invalid_event_plan"
|
|
|
|
|
|
def test_no_overwrite_or_directory_creation(workspace: Path) -> None:
|
|
path = workspace / "existing.mid"
|
|
path.write_bytes(b"unrelated original data")
|
|
with pytest.raises(OutputExistsError):
|
|
midi.write_midi(path, make_plan())
|
|
assert path.read_bytes() == b"unrelated original data"
|
|
with pytest.raises(OutputExistsError):
|
|
midi.write_midi(workspace, make_plan())
|
|
missing = workspace / "not-created" / "song.mid"
|
|
with pytest.raises(OutputIOError) as failure:
|
|
midi.write_midi(missing, make_plan())
|
|
assert failure.value.details == {"reason": "midi_create_failed"}
|
|
assert not missing.parent.exists()
|
|
|
|
|
|
def test_exclusive_create_protects_against_collision_after_precheck(
|
|
workspace: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
path = workspace / "raced.mid"
|
|
path.write_bytes(b"keep")
|
|
monkeypatch.setattr(Path, "exists", lambda self: False)
|
|
with pytest.raises(OutputExistsError):
|
|
midi.write_midi(path, make_plan())
|
|
assert path.read_bytes() == b"keep"
|
|
|
|
|
|
def test_invalid_path_fails_with_safe_named_error(workspace: Path) -> None:
|
|
with pytest.raises(OutputIOError) as failure:
|
|
midi.write_midi(workspace / "invalid\0.mid", make_plan())
|
|
assert failure.value.details == {"reason": "midi_create_failed"}
|
|
assert not list(workspace.iterdir())
|
|
|
|
|
|
def test_serialization_failure_is_explicit_before_creation(
|
|
workspace: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
def fail_save(self: object, **kwargs: object) -> None:
|
|
raise struct.error("private detail")
|
|
|
|
monkeypatch.setattr(mido.MidiFile, "save", fail_save)
|
|
path = workspace / "bad.mid"
|
|
with pytest.raises(SerializationError) as failure:
|
|
midi.write_midi(path, make_plan())
|
|
assert failure.value.details == {"reason": "smf_encoding_failed"}
|
|
assert not path.exists()
|
|
assert "private detail" not in str(failure.value)
|
|
|
|
|
|
@pytest.mark.parametrize("short_write", [False, True])
|
|
def test_write_failure_removes_only_new_file(
|
|
workspace: Path, monkeypatch: pytest.MonkeyPatch, short_write: bool
|
|
) -> None:
|
|
path = workspace / "failed.mid"
|
|
sentinel = workspace / "sentinel"
|
|
sentinel.write_bytes(b"keep")
|
|
original_open = Path.open
|
|
|
|
def failing_open(self: Path, mode: str = "r", **kwargs: object) -> object:
|
|
assert self == path and mode == "xb"
|
|
real = original_open(self, "xb")
|
|
proxy = MagicMock()
|
|
proxy.__enter__.return_value = proxy
|
|
proxy.__exit__.side_effect = real.__exit__
|
|
proxy.fileno.return_value = real.fileno()
|
|
if short_write:
|
|
proxy.write.return_value = 1
|
|
else:
|
|
proxy.write.side_effect = OSError("private disk failure")
|
|
return proxy
|
|
|
|
monkeypatch.setattr(Path, "open", failing_open)
|
|
with pytest.raises(OutputIOError) as failure:
|
|
midi.write_midi(path, make_plan())
|
|
assert failure.value.details == {
|
|
"reason": "midi_short_write" if short_write else "midi_write_failed"
|
|
}
|
|
assert not path.exists()
|
|
monkeypatch.undo()
|
|
assert sentinel.read_bytes() == b"keep"
|
|
|
|
|
|
@pytest.mark.parametrize("read_failure", [True, False])
|
|
def test_readback_failure_cleans_owned_file(
|
|
workspace: Path, monkeypatch: pytest.MonkeyPatch, read_failure: bool
|
|
) -> None:
|
|
path = workspace / "failed.mid"
|
|
|
|
def fail_read(self: Path) -> bytes:
|
|
assert self == path
|
|
if read_failure:
|
|
raise PermissionError("private read error")
|
|
return b"truncated"
|
|
|
|
monkeypatch.setattr(Path, "read_bytes", fail_read)
|
|
error = OutputIOError if read_failure else SerializationError
|
|
with pytest.raises(error):
|
|
midi.write_midi(path, make_plan())
|
|
assert not path.exists()
|
|
|
|
|
|
def test_cleanup_failure_is_not_hidden(workspace: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
path = workspace / "failed.mid"
|
|
|
|
def fail_read(self: Path) -> bytes:
|
|
raise OSError("read failed")
|
|
|
|
def fail_unlink(self: Path, missing_ok: bool = False) -> None:
|
|
raise PermissionError("cannot delete")
|
|
|
|
monkeypatch.setattr(Path, "read_bytes", fail_read)
|
|
monkeypatch.setattr(Path, "unlink", fail_unlink)
|
|
with pytest.raises(OutputIOError) as failure:
|
|
midi.write_midi(path, make_plan())
|
|
assert failure.value.details == {"reason": "midi_cleanup_failed"}
|
|
monkeypatch.undo()
|
|
assert path.exists()
|
|
path.unlink()
|
|
|
|
|
|
def test_replaced_file_is_not_deleted(workspace: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
path = workspace / "song.mid"
|
|
replacement = workspace / "foreign"
|
|
replacement.write_bytes(b"not ours")
|
|
read_bytes = Path.read_bytes
|
|
|
|
def replace_and_fail(self: Path) -> bytes:
|
|
replacement.replace(path)
|
|
raise OSError("read failed")
|
|
|
|
monkeypatch.setattr(Path, "read_bytes", replace_and_fail)
|
|
with pytest.raises(OutputIOError) as failure:
|
|
midi.write_midi(path, make_plan())
|
|
assert failure.value.details == {"reason": "midi_cleanup_ownership_changed"}
|
|
assert read_bytes(path) == b"not ours"
|
|
|
|
|
|
def test_unexpected_failure_is_not_silently_translated_or_published(
|
|
workspace: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
def fail_read(self: Path) -> bytes:
|
|
raise RuntimeError("programming defect")
|
|
|
|
monkeypatch.setattr(Path, "read_bytes", fail_read)
|
|
path = workspace / "unexpected.mid"
|
|
with pytest.raises(RuntimeError, match="programming defect"):
|
|
midi.write_midi(path, make_plan())
|
|
assert not path.exists()
|
|
|
|
|
|
def test_validator_does_not_delete_its_input(workspace: Path) -> None:
|
|
path = workspace / "not-midi.mid"
|
|
path.write_bytes(b"not MIDI")
|
|
with pytest.raises(SerializationError):
|
|
midi.validate_midi_file(path, make_plan())
|
|
assert path.read_bytes() == b"not MIDI"
|
|
with pytest.raises(OutputIOError):
|
|
midi.validate_midi_file(workspace / "missing.mid", make_plan())
|