Files
Lyrebird/Tests/LyrebirdTests/MusicXMLTests.swift
T
2026-06-01 18:27:40 -07:00

585 lines
20 KiB
Swift

// MusicXMLTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@Suite("Score ↔ MusicXML bidirectional bridge")
struct MusicXMLTests {
// MARK: - 1. Encode shape
@Test func encodeProducesScorePartwiseRoot() {
let score: Score = Score(bpm: 120) {
Part("Test") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<score-partwise version=\"4.0\">"))
#expect(xml.contains("<part-list>"))
#expect(xml.contains("<score-part id=\"P1\">"))
#expect(xml.contains("<part-name>Test</part-name>"))
#expect(xml.contains("<part id=\"P1\">"))
#expect(xml.contains("<measure number=\"1\">"))
#expect(xml.contains("</score-partwise>"))
}
@Test func encodePitchEmitsStepAlterOctave() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.cFlat, 4, dur: .quarter)
Note(.fSharp, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// C♭4 — step C, alter -1, octave 4
#expect(xml.contains("<step>C</step>"))
#expect(xml.contains("<alter>-1</alter>"))
// F♯5 — step F, alter 1, octave 5
#expect(xml.contains("<step>F</step>"))
#expect(xml.contains("<alter>1</alter>"))
#expect(xml.contains("<octave>4</octave>"))
#expect(xml.contains("<octave>5</octave>"))
}
@Test func encodeQuarterToneEmitsFractionalAlter() {
let score: Score = Score(bpm: 120) {
Part("p") { Note(.cQuarterSharp, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<alter>0.5</alter>"))
}
@Test func encodeNaturalEmitsNoAlter() {
let score: Score = Score(bpm: 120) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
// No <alter> for natural pitches.
#expect(!xml.contains("<alter>"))
}
@Test func encodeRestEmitsRestElement() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter)
Rest(dur: .quarter)
Note(.d, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<rest/>"))
}
@Test func encodeChordEmitsChordFlag() {
let score: Score = Score(bpm: 120) {
Part("p") {
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .half)
}
}
let xml: String = score.toMusicXMLString()
// Chord flag emitted on second + third notes only.
let chordCount: Int = xml.components(separatedBy: "<chord/>").count - 1
#expect(chordCount == 2)
}
@Test func encodeArticulationEmitsNotations() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, art: .staccato)
Note(.d, 4, dur: .quarter, art: .accent)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<staccato/>"))
#expect(xml.contains("<accent/>"))
}
@Test func encodeTempoAndTimeSignature() {
let score: Score = Score(bpm: 88, timeSignature: (3, 4)) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<beats>3</beats>"))
#expect(xml.contains("<beat-type>4</beat-type>"))
#expect(xml.contains("<per-minute>88</per-minute>"))
#expect(xml.contains("<sound tempo=\"88\"/>"))
}
@Test func encodeMidiPitchUsesSharpSpelling() {
let score: Score = Score(bpm: 120) {
Part("p") {
Note(midi: 61, dur: .quarter) // → C♯4 spelling
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<step>C</step>"))
#expect(xml.contains("<alter>1</alter>"))
#expect(xml.contains("<octave>4</octave>"))
}
@Test func encodePartNameEscapesXMLEntities() {
let score: Score = Score(bpm: 120) {
Part("Lead & <Synth>") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("Lead &amp; &lt;Synth&gt;"))
}
// MARK: - 2. Parse → Score
@Test func parseSimpleNote() throws {
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1">
<part-name>Test</part-name>
</score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes>
<divisions>1</divisions>
<time><beats>4</beats><beat-type>4</beat-type></time>
</attributes>
<note>
<pitch>
<step>C</step>
<octave>4</octave>
</pitch>
<duration>1</duration>
<voice>1</voice>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.parts.count == 1)
#expect(score.parts[0].name == "Test")
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 1)
#expect(events[0].pitch.midiNote == 60) // C4
}
@Test func parsePreservesSpelling() throws {
let xml: String = """
<?xml version="1.0"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>p</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes>
<divisions>1</divisions>
<time><beats>4</beats><beat-type>4</beat-type></time>
</attributes>
<note>
<pitch>
<step>C</step>
<alter>-1</alter>
<octave>4</octave>
</pitch>
<duration>1</duration>
<voice>1</voice>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = score.parts[0].flatten()
guard case .named(let name, let octave) = events[0].pitch else {
Issue.record("expected .named, got \(events[0].pitch)")
return
}
#expect(name == NoteName.cFlat,
"C♭ spelling preserved (not collapsed to B)")
#expect(octave == 4,
"octave from <octave>4</octave> stays 4 even though pitch sounds at MIDI 59")
#expect(events[0].pitch.midiNote == 59)
}
@Test func parseQuarterToneAlter() throws {
let xml: String = """
<?xml version="1.0"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>p</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes><divisions>1</divisions></attributes>
<note>
<pitch>
<step>D</step>
<alter>0.5</alter>
<octave>4</octave>
</pitch>
<duration>1</duration>
<voice>1</voice>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = score.parts[0].flatten()
guard case .named(let name, _) = events[0].pitch else {
Issue.record("expected .named pitch")
return
}
#expect(name.accidental == .quarterSharp)
}
@Test func parseTempoFromPerMinute() throws {
let xml: String = """
<?xml version="1.0"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>p</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes><divisions>1</divisions></attributes>
<direction>
<direction-type>
<metronome>
<beat-unit>quarter</beat-unit>
<per-minute>144</per-minute>
</metronome>
</direction-type>
</direction>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.bpm == 144.0)
}
@Test func parseTimeSignature() throws {
let xml: String = """
<?xml version="1.0"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>p</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes>
<divisions>1</divisions>
<time><beats>6</beats><beat-type>8</beat-type></time>
</attributes>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.timeSignature == (6, 8))
}
@Test func parseTimewiseRootRejected() {
let xml: String = """
<?xml version="1.0"?>
<score-timewise version="4.0">
<part-list></part-list>
</score-timewise>
"""
#expect(throws: MusicXMLError.unsupportedTimewiseDocument) {
_ = try Score.fromMusicXML(data: Data(xml.utf8))
}
}
@Test func parseRest() throws {
let xml: String = """
<?xml version="1.0"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>p</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes><divisions>1</divisions></attributes>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
</note>
<note>
<rest/>
<duration>1</duration>
<voice>1</voice>
</note>
<note>
<pitch><step>D</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 2)
#expect(events[0].beat == 0.0)
#expect(events[1].beat == 2.0)
}
@Test func parseChordSharesOnset() throws {
let xml: String = """
<?xml version="1.0"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>p</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes><divisions>1</divisions></attributes>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>2</duration>
<voice>1</voice>
</note>
<note>
<chord/>
<pitch><step>E</step><octave>4</octave></pitch>
<duration>2</duration>
<voice>1</voice>
</note>
<note>
<chord/>
<pitch><step>G</step><octave>4</octave></pitch>
<duration>2</duration>
<voice>1</voice>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 3)
// All three chord-mates share onset beat 0.
for e: ScoreEvent in events {
#expect(e.beat == 0.0)
}
let pitches: [Int] = events.compactMap { $0.pitch.midiNote }.sorted()
#expect(pitches == [60, 64, 67])
}
@Test func parseArticulation() throws {
let xml: String = """
<?xml version="1.0"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>p</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes><divisions>1</divisions></attributes>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
<notations>
<articulations>
<staccato/>
</articulations>
</notations>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events[0].articulation == .staccato)
}
// MARK: - 3. Round-trip preserves spelling
@Test func roundTripPreservesSpelling() throws {
let original: Score = Score(bpm: 120, timeSignature: (4, 4)) {
Part("Melody") {
Note(.cFlat, 4, dur: .quarter) // distinct from B3
Note(.bSharp, 3, dur: .quarter) // distinct from C4
Note(.eSharp, 4, dur: .quarter) // distinct from F4
Note(.fFlat, 4, dur: .quarter) // distinct from E4
Note(.cQuarterSharp, 4, dur: .eighth) // 24-TET
Note(.dThreeQuarterFlat, 4, dur: .eighth)
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(recovered.parts.count == 1)
let originalEvents: [ScoreEvent] = original.parts[0].flatten()
let recoveredEvents: [ScoreEvent] = recovered.parts[0].flatten()
#expect(originalEvents.count == recoveredEvents.count)
for (orig, rec) in zip(originalEvents, recoveredEvents) {
// Pitch values must match exactly — including spelling.
#expect(orig.pitch == rec.pitch,
"spelling lost: \(orig.pitch) → \(rec.pitch)")
}
}
@Test func roundTripPreservesTempoAndTimeSignature() throws {
let original: Score = Score(bpm: 144, timeSignature: (5, 8)) {
Part("p") { Note(.c, 4, dur: .eighth) }
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(abs(recovered.bpm - 144.0) < 1e-3)
#expect(recovered.timeSignature == (5, 8))
}
@Test func roundTripPreservesChord() throws {
let original: Score = Score(bpm: 120) {
Part("p") {
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .half)
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = recovered.parts[0].flatten()
#expect(events.count == 3)
for e: ScoreEvent in events {
#expect(e.beat == 0.0)
}
}
@Test func roundTripPreservesArticulation() throws {
let original: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, art: .staccato)
Note(.d, 4, dur: .quarter, art: .marcato)
Note(.e, 4, dur: .quarter, art: .tenuto)
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = recovered.parts[0].flatten()
#expect(events.count == 3)
// Articulation: staccato (with .durationScale = 0.5) shortens
// duration during flatten. Compare articulation field rather
// than duration.
#expect(events[0].articulation == .staccato)
#expect(events[1].articulation == .marcato)
#expect(events[2].articulation == .tenuto)
}
// MARK: - 4. Sound-attribute tempo (MuseScore-style)
@Test func parseTempoFromSoundAttribute() throws {
// No <metronome> block — tempo carried only via <sound tempo="X"/>.
let xml: String = """
<?xml version="1.0"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>p</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes><divisions>1</divisions></attributes>
<direction placement="above">
<direction-type>
<words>Allegro</words>
</direction-type>
<sound tempo="156"/>
</direction>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.bpm == 156.0,
"tempo should be parsed from <sound tempo=\"156\"/> attribute even without metronome")
}
@Test func legatoRoundTripsAsSlurStart() throws {
let original: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, art: .legato)
}
}
let xml: String = original.toMusicXMLString()
// <slur> must be a direct child of <notations>, NOT inside <articulations>.
#expect(xml.contains("<slur"))
#expect(!xml.contains("<articulations>\n <slur"),
"<slur> must NOT be inside <articulations> per MusicXML 4.0 DTD")
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = recovered.parts[0].flatten()
#expect(events[0].articulation == .legato,
"single-note legato round-trip via <slur type=\"start\"/>")
}
@Test func firstTimeSignatureWinsOnMultiTimeDocument() throws {
// Two <time> elements — only the first should be applied.
let xml: String = """
<?xml version="1.0"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>p</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes>
<divisions>1</divisions>
<time><beats>3</beats><beat-type>4</beat-type></time>
</attributes>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
</note>
</measure>
<measure number="2">
<attributes>
<time><beats>6</beats><beat-type>8</beat-type></time>
</attributes>
<note>
<pitch><step>D</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.timeSignature == (3, 4),
"first <time> wins; second <time> ignored on multi-time-sig documents")
}
@Test func malformedXMLThrows() {
let xml: String = "<not-musicxml>nope</not-musicxml>"
#expect(throws: MusicXMLError.self) {
_ = try Score.fromMusicXML(data: Data(xml.utf8))
}
}
}