// MusicXMLTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@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(""))
#expect(xml.contains(""))
#expect(xml.contains(""))
#expect(xml.contains("Test"))
#expect(xml.contains(""))
#expect(xml.contains(""))
#expect(xml.contains(""))
}
@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("C"))
#expect(xml.contains("-1"))
// F♯5 — step F, alter 1, octave 5
#expect(xml.contains("F"))
#expect(xml.contains("1"))
#expect(xml.contains("4"))
#expect(xml.contains("5"))
}
@Test func encodeQuarterToneEmitsFractionalAlter() {
let score: Score = Score(bpm: 120) {
Part("p") { Note(.cQuarterSharp, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("0.5"))
}
@Test func encodeNaturalEmitsNoAlter() {
let score: Score = Score(bpm: 120) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
// No for natural pitches.
#expect(!xml.contains(""))
}
@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(""))
}
@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: "").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(""))
#expect(xml.contains(""))
}
@Test func encodeTempoAndTimeSignature() {
let score: Score = Score(bpm: 88, timeSignature: TimeSignature(3, 4)) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("3"))
#expect(xml.contains("4"))
#expect(xml.contains("88"))
#expect(xml.contains(""))
}
@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("C"))
#expect(xml.contains("1"))
#expect(xml.contains("4"))
}
@Test func encodePartNameEscapesXMLEntities() {
let score: Score = Score(bpm: 120) {
Part("Lead & ") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("Lead & <Synth>"))
}
// MARK: - 2. Parse → Score
@Test func parseSimpleNote() throws {
let xml: String = """
Test
1
C
4
1
1
"""
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 = """
p
1
C
-1
4
1
1
"""
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 4 stays 4 even though pitch sounds at MIDI 59")
#expect(events[0].pitch.midiNote == 59)
}
@Test func parseQuarterToneAlter() throws {
let xml: String = """
p
1
D
0.5
4
1
1
"""
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 = """
p
1
quarter
144
C4
1
1
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.bpm == 144.0)
}
@Test func parseTimeSignature() throws {
let xml: String = """
p
1
C4
1
1
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.timeSignature.tuple == (6, 8))
}
@Test func parseTimewiseRootRejected() {
let xml: String = """
"""
#expect(throws: MusicXMLError.unsupportedTimewiseDocument) {
_ = try Score.fromMusicXML(data: Data(xml.utf8))
}
}
@Test func parseRest() throws {
let xml: String = """
p
1
C4
1
1
1
1
D4
1
1
"""
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 = """
p
1
C4
2
1
E4
2
1
G4
2
1
"""
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 = """
p
1
C4
1
1
"""
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: 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: 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.tuple == (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)
// duration is the NOTATED value — articulation scaling is not baked in.
// A staccato quarter note still has duration == 1.0; use performedDuration
// for sounding length.
#expect(events[0].articulation == .staccato)
#expect(events[1].articulation == .marcato)
#expect(events[2].articulation == .tenuto)
// Notated durations must all be 1.0 (quarter note), regardless of articulation.
for e: ScoreEvent in events {
#expect(e.duration == 1.0,
"MusicXML round-trip must preserve notated duration (\(e.articulation))")
}
}
// MARK: - 4. Sound-attribute tempo (MuseScore-style)
@Test func parseTempoFromSoundAttribute() throws {
// No block — tempo carried only via .
let xml: String = """
p
1
Allegro
C4
1
1
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.bpm == 156.0,
"tempo should be parsed from attribute even without metronome")
}
@Test func legatoRoundTripsAsSlurStart() throws {
// An isolated legato note slurs to the NEXT note.
// Provide a following note so the slur span can be closed.
let original: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, art: .legato)
Note(.d, 4, dur: .quarter) // slur stop goes here
}
}
let xml: String = original.toMusicXMLString()
// must be a direct child of , NOT inside .
#expect(xml.contains("; got:\n\(xml)")
#expect(!xml.contains("\n must NOT be inside per MusicXML 4.0 DTD")
// start on legato note, stop on the following note
#expect(xml.contains(""),
"legato note must carry ; got:\n\(xml)")
#expect(xml.contains(""),
"following note must carry ; got:\n\(xml)")
// No dangling slur: slur start count must equal stop count.
// Count only elements (not ties or tuplets) to avoid false inflation.
let startCount: Int = xml.components(
separatedBy: ""
).count - 1
let stopCount: Int = xml.components(
separatedBy: ""
).count - 1
#expect(startCount == stopCount,
"every must have a matching stop; starts=\(startCount) stops=\(stopCount)")
// Span model: no continue elements anywhere.
#expect(!xml.contains(""),
"span-model encoder must never emit ; got:\n\(xml)")
// Round-trip: legato note must come back as .legato (carries slur start),
// following note must NOT become legato (it carries only slur stop).
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = recovered.parts[0].flatten()
#expect(events.count == 2,
"round-trip must yield 2 events; got \(events.count)")
if events.count == 2 {
#expect(events[0].articulation == .legato,
"legato note must round-trip as .legato (carries slur start)")
#expect(events[1].articulation == .normal,
"following note (slur stop target) must NOT become .legato; got \(events[1].articulation)")
}
}
// MARK: - 5. On-grid duration encoding
@Test func staccatoQuarterEncodesDivisionNotHalf() {
// Articulation scaling must NOT affect .
// A staccato quarter note at divisions=480 should encode 480
// (the notated quarter), NOT 240 (the played half).
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, art: .staccato)
Note(.d, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString(divisions: 480)
// Both pitched notes should encode as 480 (quarter = 1 × 480 divisions).
let duration480Count: Int = xml.components(separatedBy: "480").count - 1
#expect(duration480Count == 2,
"staccato quarter must encode as 480, not 240; got xml:\n\(xml)")
// There must be no 240 (the old bug produced this).
#expect(!xml.contains("240"),
"off-grid 240 must not appear; got xml:\n\(xml)")
// The staccato note must appear before the D quarter note (no gap rest between them).
// A padding rest at the end of the measure is acceptable — verify no rest appears
// between the C and D pitch blocks by checking their relative order.
let cNoteRange: Range? = xml.range(of: "C")
let dNoteRange: Range? = xml.range(of: "D")
let restRange: Range? = xml.range(of: "")
if let cIdx: Range = cNoteRange,
let dIdx: Range = dNoteRange {
#expect(cIdx.lowerBound < dIdx.lowerBound,
"C note must appear before D note; got xml:\n\(xml)")
// There should be no rest between the C and D pitch blocks.
if let rIdx: Range = restRange {
#expect(rIdx.lowerBound > dIdx.lowerBound,
"no gap rest between C and D notes; got xml:\n\(xml)")
}
}
}
@Test func legatoHalfEncodesTwoDivisions() {
// Legato ×1.05 on a half note must NOT produce
// 1008 — it must be the notated 2 × 480 = 960.
let score: Score = Score(bpm: 120) {
Part("p") { Note(.c, 4, dur: .half, art: .legato) }
}
let xml: String = score.toMusicXMLString(divisions: 480)
#expect(xml.contains("960"),
"legato half must encode as 960, not 1008; got xml:\n\(xml)")
#expect(!xml.contains("1008"),
"off-grid 1008 must not appear; got xml:\n\(xml)")
}
@Test func midPieceTimeSignatureParsesIntoMeterMap() throws {
// Two