Files
Lyrebird/Tests/LyrebirdTests/MusicXMLTests.swift
T

5068 lines
227 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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("<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: 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.tuple == (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: 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 <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 {
// 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()
// <slur> must be a direct child of <notations>, NOT inside <articulations>.
#expect(xml.contains("<slur"),
"isolated legato+following note must emit a <slur>; got:\n\(xml)")
#expect(!xml.contains("<articulations>\n <slur"),
"<slur> must NOT be inside <articulations> per MusicXML 4.0 DTD")
// start on legato note, stop on the following note
#expect(xml.contains("<slur number=\"1\" type=\"start\"/>"),
"legato note must carry <slur type=\"start\"/>; got:\n\(xml)")
#expect(xml.contains("<slur number=\"1\" type=\"stop\"/>"),
"following note must carry <slur type=\"stop\"/>; got:\n\(xml)")
// No dangling slur: slur start count must equal stop count.
// Count only <slur …> elements (not ties or tuplets) to avoid false inflation.
let startCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"start\"/>"
).count - 1
let stopCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"stop\"/>"
).count - 1
#expect(startCount == stopCount,
"every <slur type=\"start\"> must have a matching stop; starts=\(startCount) stops=\(stopCount)")
// Span model: no continue elements anywhere.
#expect(!xml.contains("<slur number=\"1\" type=\"continue\"/>"),
"span-model encoder must never emit <slur type=\"continue\"/>; 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 <duration>.
// A staccato quarter note at divisions=480 should encode <duration>480</duration>
// (the notated quarter), NOT <duration>240</duration> (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: "<duration>480</duration>").count - 1
#expect(duration480Count == 2,
"staccato quarter must encode as <duration>480</duration>, not 240; got xml:\n\(xml)")
// There must be no <duration>240</duration> (the old bug produced this).
#expect(!xml.contains("<duration>240</duration>"),
"off-grid <duration>240</duration> 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<String.Index>? = xml.range(of: "<step>C</step>")
let dNoteRange: Range<String.Index>? = xml.range(of: "<step>D</step>")
let restRange: Range<String.Index>? = xml.range(of: "<rest/>")
if let cIdx: Range<String.Index> = cNoteRange,
let dIdx: Range<String.Index> = 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<String.Index> = 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
// <duration>1008</duration> — 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("<duration>960</duration>"),
"legato half must encode as <duration>960</duration>, not 1008; got xml:\n\(xml)")
#expect(!xml.contains("<duration>1008</duration>"),
"off-grid <duration>1008</duration> must not appear; got xml:\n\(xml)")
}
@Test func midPieceTimeSignatureParsesIntoMeterMap() throws {
// Two <time> elements — the first sets the back-compat
// timeSignature tuple AND bar-1 segment; the second populates a bar-2
// segment so the parsed MeterMap carries both changes.
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))
// Back-compat: the timeSignature tuple still reflects the FIRST <time>.
#expect(score.timeSignature.tuple == (3, 4),
"back-compat timeSignature tuple must still reflect the first <time>")
// Both <time> elements appear as MeterMap segments.
let map: MeterMap = score.meterMap
#expect(!map.isConstant,
"meterMap must NOT be constant when two different <time> elements are present")
let segmentCount: Int = map.segments.count
#expect(segmentCount == 2,
"meterMap must have exactly 2 segments (bar 1 = 3/4, bar 2 = 6/8); got \(segmentCount)")
let bar1TS: TimeSignature = map.timeSignature(atBar: 1)
#expect(bar1TS.tuple == (3, 4),
"bar-1 signature must be (3, 4); got \(bar1TS.tuple)")
let bar2TS: TimeSignature = map.timeSignature(atBar: 2)
#expect(bar2TS.tuple == (6, 8),
"bar-2 signature must be (6, 8); got \(bar2TS.tuple)")
}
@Test func malformedXMLThrows() {
let xml: String = "<not-musicxml>nope</not-musicxml>"
#expect(throws: MusicXMLError.self) {
_ = try Score.fromMusicXML(data: Data(xml.utf8))
}
}
// MARK: - 6. Notation-aware encoding
@Test func plainNoteHasTypeElement() {
// Every pitched note and rest must carry a <type> element.
let score: Score = Score(bpm: 120) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<type>quarter</type>"),
"quarter note must emit <type>quarter</type>; got:\n\(xml)")
}
@Test func dottedQuarterEmitsTypeAndDot() {
// A dotted quarter note must emit <type>quarter</type> + <dot/>.
let score: Score = Score(bpm: 120) {
Part("p") { Note(.c, 4, dur: NoteDuration.dotted(.quarter)) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<type>quarter</type>"),
"dotted quarter must emit <type>quarter</type>; got:\n\(xml)")
let dotCount: Int = xml.components(separatedBy: "<dot/>").count - 1
#expect(dotCount == 1,
"dotted quarter must emit exactly one <dot/>; got:\n\(xml)")
}
@Test func tupletEmitsTimeModificationAndBracket() {
// Triplet quarter notes must emit <time-modification actual=3 normal=2>
// and <tuplet type="start"/>/<type="stop"> brackets.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Tuplet(3, inTimeOf: 2) {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<actual-notes>3</actual-notes>"),
"triplet must emit <actual-notes>3</actual-notes>; got:\n\(xml)")
#expect(xml.contains("<normal-notes>2</normal-notes>"),
"triplet must emit <normal-notes>2</normal-notes>; got:\n\(xml)")
#expect(xml.contains("<tuplet type=\"start\" number=\"1\"/>"),
"triplet must emit <tuplet type=\"start\" number=\"1\"/>; got:\n\(xml)")
#expect(xml.contains("<tuplet type=\"stop\" number=\"1\"/>"),
"triplet must emit <tuplet type=\"stop\" number=\"1\"/>; got:\n\(xml)")
// Each triplet member also needs a <type> element.
let timeModCount: Int = xml.components(separatedBy: "<time-modification>").count - 1
#expect(timeModCount == 3,
"all 3 triplet members must carry <time-modification>; got:\n\(xml)")
}
@Test func multiBeatScoreEmitsMultipleMeasures() {
// A score longer than one bar must emit multiple <measure number="N"> elements.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
// 8 quarter notes = 2 bars of 4/4
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
Note(.g, 4, dur: .quarter)
Note(.a, 4, dur: .quarter)
Note(.b, 4, dur: .quarter)
Note(.c, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<measure number=\"1\">"),
"first measure must be number 1; got:\n\(xml)")
#expect(xml.contains("<measure number=\"2\">"),
"second measure must be number 2; got:\n\(xml)")
let measureCount: Int = xml.components(separatedBy: "<measure number=").count - 1
#expect(measureCount == 2,
"exactly 2 measures expected for 8 quarter notes in 4/4; got:\n\(xml)")
}
@Test func barlineCrossingSplitsWithTies() {
// A whole note in a 3/4 bar must be split into a dotted-half tied to
// a half (or equivalent representable split), with <tie> elements.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(3, 4)) {
Part("p") {
Note(.c, 4, dur: .whole) // 4 beats in a 3-beat bar
}
}
let xml: String = score.toMusicXMLString()
// The split must produce a tie start on the head piece.
#expect(xml.contains("<tie type=\"start\"/>"),
"barline-crossing note must emit <tie type=\"start\"/>; got:\n\(xml)")
#expect(xml.contains("<tie type=\"stop\"/>"),
"barline-crossing tail must emit <tie type=\"stop\"/>; got:\n\(xml)")
// Two measures.
let measureCount: Int = xml.components(separatedBy: "<measure number=").count - 1
#expect(measureCount == 2,
"whole note in 3/4 must produce 2 measures; got:\n\(xml)")
}
@Test func barlineCrossedNoteRoundTrips() throws {
// A note that crosses a barline when encoded must parse back to a
// single element of the original duration after tie-merge.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(3, 4)) {
Part("p") {
Note(.c, 4, dur: .whole) // 4 beats in a 3-beat bar
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let origEvents: [ScoreEvent] = original.parts[0].flatten()
let recEvents: [ScoreEvent] = recovered.parts[0].flatten()
#expect(origEvents.count == recEvents.count,
"round-trip must restore the original event count; orig=\(origEvents.count) rec=\(recEvents.count)")
if let orig: ScoreEvent = origEvents.first, let rec: ScoreEvent = recEvents.first {
#expect(abs(orig.duration - rec.duration) < 1e-9,
"round-trip must restore the original note duration; orig=\(orig.duration) rec=\(rec.duration)")
#expect(orig.pitch == rec.pitch,
"round-trip must preserve pitch; orig=\(orig.pitch) rec=\(rec.pitch)")
}
}
@Test func fullRoundTripMultiBarTupletArticulated() throws {
// Full round-trip of a multi-bar, tuplet-containing, articulated score
// preserves flattened (beat, pitch, duration, velocity) within FP tolerance.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, art: .staccato)
Note(.e, 4, dur: .quarter)
Tuplet(3, inTimeOf: 2) {
Note(.g, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
}
Note(.d, 4, dur: .half, art: .legato)
Note(.c, 5, dur: .whole)
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let origEvents: [ScoreEvent] = original.parts[0].flatten()
let recEvents: [ScoreEvent] = recovered.parts[0].flatten()
#expect(origEvents.count == recEvents.count,
"event count must round-trip; orig=\(origEvents.count) rec=\(recEvents.count)")
let tolerance: Double = 1e-6
for (idx, (orig, rec)) in zip(origEvents, recEvents).enumerated() {
#expect(abs(orig.beat - rec.beat) < tolerance,
"beat mismatch at event \(idx): orig=\(orig.beat) rec=\(rec.beat)")
#expect(abs(orig.duration - rec.duration) < tolerance,
"duration mismatch at event \(idx): orig=\(orig.duration) rec=\(rec.duration)")
#expect(orig.pitch == rec.pitch,
"pitch mismatch at event \(idx): orig=\(orig.pitch) rec=\(rec.pitch)")
}
}
// MARK: - 7. Notation-aware encoding review fixes
@Test func threeMeasureTieChainRoundTrips() throws {
// A whole note in 2/4 (= 4 beats > 2-beat bar) spans multiple measures.
// With timeSignature (2, 4), a whole note (4 beats) splits across 2 bars
// with a tie chain. The round-trip must collapse all tied pieces back to
// a single event with the original 4-beat duration.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(2, 4)) {
Part("p") {
Note(.c, 4, dur: .whole) // 4 beats in a 2-beat bar → spans 2 bars
}
}
let xml: String = original.toMusicXMLString()
// Must contain both tie start and stop.
#expect(xml.contains("<tie type=\"start\"/>"),
"multi-measure note must emit tie-start; got:\n\(xml)")
#expect(xml.contains("<tie type=\"stop\"/>"),
"multi-measure note must emit tie-stop; got:\n\(xml)")
// Must produce 2 measures.
let measureCount: Int = xml.components(separatedBy: "<measure number=").count - 1
#expect(measureCount == 2,
"whole note in 2/4 must produce 2 measures; got:\n\(xml)")
// Every <note> must carry a <type>.
let noteCount: Int = xml.components(separatedBy: "<note>").count - 1
let typeCount: Int = xml.components(separatedBy: "<type>").count - 1
#expect(noteCount == typeCount,
"every <note> must have a <type>; notes=\(noteCount) types=\(typeCount)")
// Round-trip: must recover exactly one event of duration 4 beats.
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let recEvents: [ScoreEvent] = recovered.parts[0].flatten()
#expect(recEvents.count == 1,
"tie-chain must round-trip to a single event; got \(recEvents.count) events")
if let rec: ScoreEvent = recEvents.first {
#expect(abs(rec.duration - 4.0) < 1e-9,
"round-trip duration must be 4.0; got \(rec.duration)")
#expect(rec.pitch == .named(NoteName(letter: .c, accidental: .natural), 4),
"round-trip pitch must be C4; got \(rec.pitch)")
}
}
// MARK: - 8. Clef support
@Test func clefMusicXMLMappingTreble() {
let mapping: (sign: String, line: Int?, octaveChange: Int?) = Clef.treble.musicXMLClef
#expect(mapping.sign == "G")
#expect(mapping.line == 2)
#expect(mapping.octaveChange == nil)
}
@Test func clefMusicXMLMappingBass() {
let mapping: (sign: String, line: Int?, octaveChange: Int?) = Clef.bass.musicXMLClef
#expect(mapping.sign == "F")
#expect(mapping.line == 4)
#expect(mapping.octaveChange == nil)
}
@Test func clefMusicXMLMappingAlto() {
let mapping: (sign: String, line: Int?, octaveChange: Int?) = Clef.alto.musicXMLClef
#expect(mapping.sign == "C")
#expect(mapping.line == 3)
#expect(mapping.octaveChange == nil)
}
@Test func clefMusicXMLMappingTenor() {
let mapping: (sign: String, line: Int?, octaveChange: Int?) = Clef.tenor.musicXMLClef
#expect(mapping.sign == "C")
#expect(mapping.line == 4)
#expect(mapping.octaveChange == nil)
}
@Test func clefMusicXMLMappingTreble8vb() {
let mapping: (sign: String, line: Int?, octaveChange: Int?) = Clef.treble8vb.musicXMLClef
#expect(mapping.sign == "G")
#expect(mapping.line == 2)
#expect(mapping.octaveChange == -1)
}
@Test func clefMusicXMLMappingPercussion() {
let mapping: (sign: String, line: Int?, octaveChange: Int?) = Clef.percussion.musicXMLClef
#expect(mapping.sign == "percussion")
#expect(mapping.line == nil)
#expect(mapping.octaveChange == nil)
}
@Test func clefInferredLowMedianReturnsBass() {
// Median MIDI 48 (C3) < threshold 57 → bass.
let clef: Clef = Clef.inferred(forMedianMidi: 48)
#expect(clef == .bass,
"median C3 (48) should infer .bass; got \(clef)")
}
@Test func clefInferredHighMedianReturnsTreble() {
// Median MIDI 72 (C5) ≥ threshold 57 → treble.
let clef: Clef = Clef.inferred(forMedianMidi: 72)
#expect(clef == .treble,
"median C5 (72) should infer .treble; got \(clef)")
}
@Test func clefInferredAtThresholdReturnsTreble() {
// Median exactly at threshold (57 — A3) → treble.
let clef: Clef = Clef.inferred(forMedianMidi: Clef.autoBassThresholdMidi)
#expect(clef == .treble,
"median at threshold (57) should infer .treble; got \(clef)")
}
@Test func clefInferredNilReturnsTreble() {
// No pitched notes (nil) → treble.
let clef: Clef = Clef.inferred(forMedianMidi: nil)
#expect(clef == .treble,
"nil median should infer .treble; got \(clef)")
}
@Test func encodeExplicitBassClefEmitsFSignLine4() {
// A .bass part must emit <sign>F</sign><line>4</line>.
let score: Score = Score(bpm: 120) {
Part("bass", channel: 1, clef: .bass) {
Note(.c, 2, dur: .whole, dyn: .mp)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<sign>F</sign>"),
"bass clef must emit <sign>F</sign>; got:\n\(xml)")
#expect(xml.contains("<line>4</line>"),
"bass clef must emit <line>4</line>; got:\n\(xml)")
#expect(!xml.contains("<clef-octave-change>"),
"bass clef must NOT emit <clef-octave-change>; got:\n\(xml)")
}
@Test func encodeTreble8vbEmitsOctaveChange() {
// .treble8vb must emit <sign>G</sign><line>2</line><clef-octave-change>-1</clef-octave-change>.
let score: Score = Score(bpm: 120) {
Part("tenor", clef: .treble8vb) {
Note(.c, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<sign>G</sign>"),
"treble8vb must emit <sign>G</sign>; got:\n\(xml)")
#expect(xml.contains("<line>2</line>"),
"treble8vb must emit <line>2</line>; got:\n\(xml)")
#expect(xml.contains("<clef-octave-change>-1</clef-octave-change>"),
"treble8vb must emit <clef-octave-change>-1</clef-octave-change>; got:\n\(xml)")
}
@Test func encodePercussionClefOmitsLine() {
// .percussion must emit <sign>percussion</sign> without <line>.
let score: Score = Score(bpm: 120) {
Part("drums", clef: .percussion) {
Note(midi: 36, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<sign>percussion</sign>"),
"percussion clef must emit <sign>percussion</sign>; got:\n\(xml)")
// Verify no <line> follows the sign in the clef block.
// (There may be a <line> elsewhere in the doc from another element, so
// check the absence of <line> immediately after <sign>percussion</sign>.)
let clefBlock: Bool = xml.contains(
"<sign>percussion</sign>\n <line>"
)
#expect(!clefBlock,
"percussion clef must NOT emit <line>; got:\n\(xml)")
}
@Test func autoClefInfersBassFLowPitchPart() {
// A part with all pitches in C2–C3 range (median well below 57) should
// auto-infer .bass and emit <sign>F</sign>.
let score: Score = Score(bpm: 120) {
Part("low") { // clef: .auto (default)
Note(.c, 2, dur: .quarter)
Note(.d, 2, dur: .quarter)
Note(.e, 2, dur: .quarter)
Note(.f, 2, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<sign>F</sign>"),
".auto on low-pitched part must infer .bass → <sign>F</sign>; got:\n\(xml)")
}
@Test func autoClefInfersTrebleForHighPitchPart() {
// A part with all pitches in C5–C6 range (median well above 57) should
// auto-infer .treble and emit <sign>G</sign>.
let score: Score = Score(bpm: 120) {
Part("high") { // clef: .auto (default)
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<sign>G</sign>"),
".auto on high-pitched part must infer .treble → <sign>G</sign>; got:\n\(xml)")
}
@Test func roundTripPreservesExplicitBassClef() throws {
// A Score with a .bass part and .treble part round-trips with both
// clefs preserved on fromMusicXML decode.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("melody", clef: .treble) {
Note(.c, 5, dur: .whole)
}
Part("bass", channel: 1, clef: .bass) {
Note(.c, 2, dur: .whole)
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(recovered.parts.count == 2,
"round-trip must preserve 2 parts; got \(recovered.parts.count)")
#expect(recovered.parts[0].clef == .treble,
"lead part clef must round-trip as .treble; got \(recovered.parts[0].clef)")
#expect(recovered.parts[1].clef == .bass,
"bass part clef must round-trip as .bass; got \(recovered.parts[1].clef)")
}
@Test func roundTripPreservesAltoTenorTreble8vbClefs() throws {
// Alto (C/3), tenor (C/4), and treble8vb (G/2 + octave-change -1) each
// round-trip end-to-end through clefFromParsed.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("viola", clef: .alto) { Note(.c, 4, dur: .whole) }
Part("cello", channel: 1, clef: .tenor) { Note(.c, 3, dur: .whole) }
Part("tenorVox", channel: 2, clef: .treble8vb) { Note(.c, 4, dur: .whole) }
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(recovered.parts.count == 3)
#expect(recovered.parts[0].clef == .alto,
"alto clef must round-trip; got \(recovered.parts[0].clef)")
#expect(recovered.parts[1].clef == .tenor,
"tenor clef must round-trip; got \(recovered.parts[1].clef)")
#expect(recovered.parts[2].clef == .treble8vb,
"treble8vb clef must round-trip; got \(recovered.parts[2].clef)")
}
@Test func parseFirstClefIsPartClefAndMidClefBecomesClefChange() throws {
// A treble-first part with a later <clef>F/4</clef> change keeps the
// FIRST clef (.treble) as the part-level clef, AND captures the mid-part
// <clef> as an inline `.clefChange(.bass)` element (the prior
// "mid-part clef ignored" limitation is lifted).
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<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>480</divisions>
<clef><sign>G</sign><line>2</line></clef>
</attributes>
<note><pitch><step>C</step><octave>5</octave></pitch><duration>480</duration><voice>1</voice><type>quarter</type></note>
<attributes>
<clef><sign>F</sign><line>4</line></clef>
</attributes>
<note><pitch><step>C</step><octave>3</octave></pitch><duration>480</duration><voice>1</voice><type>quarter</type></note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.parts.count == 1)
#expect(score.parts[0].clef == .treble,
"first clef is the part-level clef; got \(score.parts[0].clef)")
let elements: [ScoreElement] = score.parts[0].elements
let clefChanges: [Clef] = elements.compactMap {
if case .clefChange(let c) = $0 { return c }
return nil
}
#expect(clefChanges == [.bass],
"mid-part <clef>F/4</clef> must become a single .clefChange(.bass); got \(clefChanges)")
}
@Test func clefChangeDSLProducesElement() {
// ClefChange(_:) maps to a .clefChange element for an explicit clef.
guard case .clefChange(let c) = ClefChange(.tenor) else {
Issue.record("ClefChange(.tenor) must produce .clefChange(.tenor)")
return
}
#expect(c == .tenor)
}
@Test func encodeInlineClefChangeEmitsMidMeasureAttributes() {
// A bass part with a mid-stream ClefChange(.tenor) emits TWO <clef> blocks:
// the part-level bass (F/4) in measure-1 attributes, then a mid-measure
// <attributes><clef><sign>C</sign><line>4</line></clef></attributes>.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("cello", clef: .bass) {
Note(.c, 2, dur: .half, dyn: .mf)
ClefChange(.tenor)
Note(.c, 4, dur: .half, dyn: .mf)
}
}
let xml: String = score.toMusicXMLString()
// Two clef blocks total (part-level bass + mid-measure tenor).
let clefCount: Int = xml.components(separatedBy: "<clef>").count - 1
#expect(clefCount == 2,
"expected 2 <clef> blocks (part bass + mid tenor); got \(clefCount)")
// The tenor clef (C/4) is present.
#expect(xml.contains("<sign>C</sign>") && xml.contains("<line>4</line>"),
"tenor clef <sign>C</sign><line>4</line> must be emitted")
// The mid-measure tenor clef appears AFTER the first (bass-clef) note.
if let firstNote: Range<String.Index> = xml.range(of: "<note>"),
let tenorClef: Range<String.Index> = xml.range(of: "<sign>C</sign>") {
#expect(tenorClef.lowerBound > firstNote.lowerBound,
"mid-voice clef change must be emitted after the first note")
} else {
Issue.record("expected both a <note> and the tenor <sign>C</sign> in the output")
}
}
@Test func flattenIgnoresClefChange() {
// A clef change is display-only: flatten()/allEvents are identical with
// and without the inline ClefChange — same beats, durations, pitches.
let withChange: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("cello", clef: .bass) {
Note(.c, 2, dur: .half)
ClefChange(.tenor)
Note(.c, 4, dur: .half)
}
}
let withoutChange: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("cello", clef: .bass) {
Note(.c, 2, dur: .half)
Note(.c, 4, dur: .half)
}
}
let a: [ScoreEvent] = withChange.allEvents
let b: [ScoreEvent] = withoutChange.allEvents
#expect(a.count == b.count,
"clef change must not add/remove events; \(a.count) vs \(b.count)")
for (x, y): (ScoreEvent, ScoreEvent) in zip(a, b) {
#expect(x.beat == y.beat && x.duration == y.duration,
"clef change must not shift beats/durations: \(x.beat)/\(x.duration) vs \(y.beat)/\(y.duration)")
}
}
@Test func roundTripPreservesInlineClefChange() throws {
// Author a bass part with a mid ClefChange(.tenor); encode → parse →
// the recovered part keeps part clef .bass and contains .clefChange(.tenor)
// between the two notes, with the surrounding notes unchanged.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("cello", clef: .bass) {
Note(.c, 2, dur: .half, dyn: .mf)
ClefChange(.tenor)
Note(.c, 4, dur: .half, dyn: .mf)
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(recovered.parts.count == 1)
#expect(recovered.parts[0].clef == .bass,
"part-level clef must round-trip as .bass; got \(recovered.parts[0].clef)")
let elements: [ScoreElement] = recovered.parts[0].elements
let clefChanges: [Clef] = elements.compactMap {
if case .clefChange(let c) = $0 { return c }
return nil
}
#expect(clefChanges == [.tenor],
"round-tripped part must contain exactly one .clefChange(.tenor); got \(clefChanges)")
// Sounding events unchanged by the round-trip.
#expect(original.allEvents.count == recovered.allEvents.count,
"clef-change round-trip must preserve event count")
}
@Test func clefChangeDoesNotBreakAuthoredTie() throws {
// A clef change interleaved between a tie:true note and its same-pitch
// continuation must NOT clear the authored tie (annotateTieAuthored skips
// zero-duration atoms — the grace bug class).
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("cello", clef: .bass) {
Note(.c, 3, dur: .half, dyn: .mf, tie: true)
ClefChange(.tenor)
Note(.c, 3, dur: .half, dyn: .mf)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<tie type=\"start\"/>"),
"authored tie across a clef change must still emit <tie type=\"start\"/>")
#expect(xml.contains("<tie type=\"stop\"/>"),
"authored tie across a clef change must still emit <tie type=\"stop\"/>")
}
@Test func chordBarlineCrossingRoundTrips() throws {
// A whole-note chord (4 beats) in 3/4 (3-beat bar) splits across barlines.
// Round-trip must restore a chord onset with both pitches and summed
// duration of 4 beats.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(3, 4)) {
Part("p") {
Chord([(.c, 4), (.e, 4)], dur: .whole) // 4 beats in a 3-beat bar
}
}
let xml: String = original.toMusicXMLString()
// Must contain tie elements.
#expect(xml.contains("<tie type=\"start\"/>"),
"barline-crossing chord must emit tie-start; got:\n\(xml)")
// Every <note> must carry a <type>.
let noteCount: Int = xml.components(separatedBy: "<note>").count - 1
let typeCount: Int = xml.components(separatedBy: "<type>").count - 1
#expect(noteCount == typeCount,
"every <note> in chord split must have a <type>; notes=\(noteCount) types=\(typeCount)")
// Round-trip.
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let recEvents: [ScoreEvent] = recovered.parts[0].flatten()
// Both pitches must be present.
#expect(recEvents.count == 2,
"round-trip must yield 2 events (one per chord pitch); got \(recEvents.count)")
// All events share the same onset.
for e: ScoreEvent in recEvents {
#expect(e.beat == 0.0,
"round-tripped chord event must have beat 0; got \(e.beat)")
}
// Summed duration check (each event should have the full merged duration ≈ 4).
for e: ScoreEvent in recEvents {
#expect(abs(e.duration - 4.0) < 1e-9,
"round-tripped chord pitch must have duration 4.0; got \(e.duration)")
}
// Both pitches preserved.
let midiNotes: [Int] = recEvents.compactMap { $0.pitch.midiNote }.sorted()
#expect(midiNotes == [60, 64],
"C4 and E4 must round-trip; got \(midiNotes)")
}
// MARK: - 9. Decode fixes
// Fix 1 — Fraction-exact decode
@Test func tripletQuarterDecodesAsExactFraction() throws {
// A triplet-quarter encoded at divisions=3 has <duration>2</duration>
// with <divisions>3</divisions>. Parsing must yield NoteDuration.fraction(2/3),
// NOT .beats(0.6666...). Verify by checking that two merged triplet-stop
// durations sum exactly (no sub-ULP drift).
//
// Build a score with a triplet quarter crossing a barline (impossible in
// standard notation, but serves as a sum-precision test): instead, test that
// the tie-merge of two 2/3-beat notes produces exactly 4/3 beats (not
// 0.6667 + 0.6667 = 1.3334 with round-trip error).
//
// We do this by encoding a tie-split note whose two halves are each 2/3:
// a whole-note in 2/3-beat measure is non-standard; instead use a note
// that parses directly.
//
// Approach: encode a raw MusicXML snippet with divisions=3 and a tied
// pair of duration=2 notes (each 2/3 beat). The merged duration must
// be 4/3 = 1.333... beats.
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>3</divisions>
<time><beats>4</beats><beat-type>4</beat-type></time>
</attributes>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>2</duration>
<voice>1</voice>
<tie type="start"/>
</note>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>2</duration>
<voice>1</voice>
<tie type="stop"/>
</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 == 1,
"tie pair must merge to one event; got \(events.count)")
if let ev: ScoreEvent = events.first {
// Expected: 2/3 + 2/3 = 4/3 exactly.
let expected: Double = 4.0 / 3.0
#expect(abs(ev.duration - expected) < 1e-12,
"merged triplet durations must be exactly 4/3; got \(ev.duration)")
}
}
@Test func fractionDecodePreservesExactRoundTrip() throws {
// A note parsed as Fraction(2, 3) and then re-encoded must produce the
// same <duration> tick value as the original. Confirms Fix 1 is lossless
// in the encode → decode → encode cycle.
let xml1: 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>3</divisions>
<time><beats>4</beats><beat-type>4</beat-type></time>
</attributes>
<note>
<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(xml1.utf8))
// Re-encode at the SAME divisions=3 to verify the tick is preserved.
let xml2: String = score.toMusicXMLString(divisions: 3)
// The original <duration>2</duration> must survive the round-trip.
#expect(xml2.contains("<duration>2</duration>"),
"re-encoded duration must remain 2 at divisions=3; got:\n\(xml2)")
}
// Fix 2 — Bounded backward scan
@Test func strayTieStopDoesNotMergeUnrelatedEarlierNote() throws {
// Part contains: A4 quarter, B4 quarter, then a stray A4 quarter with
// <tie type="stop"/>. The stray tie-stop must NOT be merged into the
// first A4 (they are separated by B4). The result must be 3 events.
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>A</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
</note>
<note>
<pitch><step>B</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
</note>
<note>
<pitch><step>A</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
<tie type="stop"/>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = score.parts[0].flatten()
// Must be 3 separate events — the stray tie-stop is treated as a normal note.
#expect(events.count == 3,
"stray tie-stop must not merge across an intervening different-pitch note; got \(events.count) events")
// All durations must be 1 beat (no merging occurred).
for (i, ev) in events.enumerated() {
#expect(abs(ev.duration - 1.0) < 1e-9,
"event \(i) duration must be 1.0; got \(ev.duration)")
}
}
@Test func adjacentTieStillMerges() throws {
// A properly formed tied pair — A4 with tie-start followed immediately
// by A4 with tie-stop — must still merge to a single 2-beat event.
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>A</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
<tie type="start"/>
</note>
<note>
<pitch><step>A</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
<tie type="stop"/>
</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 == 1,
"adjacent tie pair must merge to one event; got \(events.count)")
if let ev: ScoreEvent = events.first {
#expect(abs(ev.duration - 2.0) < 1e-9,
"merged tie must be 2 beats; got \(ev.duration)")
}
}
// Fix 3 — Whole-measure rest
@Test func wholeMeasureRestEmitsMeasureYesAttribute() {
// A score whose part has exactly one whole-note rest spanning a full
// 4/4 bar must encode as <rest measure="yes"/> without a <type>.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Rest(dur: .whole) // exactly 4 beats in a 4/4 bar
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<rest measure=\"yes\"/>"),
"whole-measure rest must emit <rest measure=\"yes\"/>; got:\n\(xml)")
// Whole-measure rests must NOT carry a <type> element.
#expect(!xml.contains("<type>whole</type>"),
"whole-measure rest must NOT emit <type>; got:\n\(xml)")
}
@Test func partialBarRestDecomposesWithType() {
// A rest that spans only part of a bar (half note in a 4/4 bar)
// must still emit a typed rest — NOT measure="yes".
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .half)
Rest(dur: .half) // partial bar
}
}
let xml: String = score.toMusicXMLString()
// Must have a typed rest for the half-rest.
#expect(xml.contains("<rest/>"),
"partial-bar rest must emit plain <rest/>; got:\n\(xml)")
// Must NOT have measure="yes" since it's only half the bar.
#expect(!xml.contains("<rest measure=\"yes\"/>"),
"partial-bar rest must NOT emit measure=\"yes\"; got:\n\(xml)")
#expect(xml.contains("<type>half</type>"),
"partial-bar rest must carry <type>half</type>; got:\n\(xml)")
}
@Test func wholeMeasureRestRoundTrips() throws {
// A whole-measure rest encoded as <rest measure="yes"/> must parse back
// advancing the cursor by the correct beat count.
// Verify by placing a note AFTER the rest and checking its beat position.
// 16 ticks at divisions=4 = 4.0 beats (full 4/4 bar).
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>4</divisions>
<time><beats>4</beats><beat-type>4</beat-type></time>
</attributes>
<note>
<rest measure="yes"/>
<duration>16</duration>
<voice>1</voice>
</note>
</measure>
<measure number="2">
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>4</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()
// flatten() skips rest events; the C4 note must land at beat 4.
let pitchedEvents: [ScoreEvent] = events.filter { !$0.isRest }
#expect(pitchedEvents.count == 1,
"only the C4 note should be in flatten() output; got \(pitchedEvents.count)")
if let noteEvent: ScoreEvent = pitchedEvents.first {
#expect(abs(noteEvent.beat - 4.0) < 1e-9,
"C4 note after a 4-beat whole-measure rest must land at beat 4; got \(noteEvent.beat)")
}
}
@Test func emptyPartPadsMeasureWithWholeMeasureRest() {
// A part with no events at all produces one measure padded with a
// whole-measure rest (measure="yes").
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("empty") {
// Intentionally no elements.
}
}
let xml: String = score.toMusicXMLString()
// The pad-rest for the empty bar must be a whole-measure rest.
#expect(xml.contains("<rest measure=\"yes\"/>"),
"empty part must pad with <rest measure=\"yes\"/>; got:\n\(xml)")
// Must NOT carry a <type>.
#expect(!xml.contains("<type>"),
"whole-measure pad rest must NOT emit <type>; got:\n\(xml)")
}
// Fix 4 — Nested-tuplet brackets
@Test func nestedTupletEmitsTwoDistinctBrackets() {
// A 3:2 triplet nested inside another 3:2 triplet must emit TWO
// <tuplet> bracket elements with distinct number= attributes (1 and 2)
// and a non-degenerate cumulative <time-modification> (9:4 inner).
//
// The nested tuplet must fit WITHIN a single measure: tuplet brackets
// are dropped when a tuplet crosses a barline (the same tuplet-across-
// barline limitation documented for single-level tuplets). The outer
// triplet here sounds for ~1.33 beats, well inside the 4/4 bar.
//
// Both bracket starts use the FULL form with <tuplet-type>eighth</tuplet-type>
// (inner-first nesting: cumulative 9:4 ≠ outer local 3:2, plus partHasNestedTuplet).
// Both stop brackets remain bare self-closing.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
// Outer triplet: 3 in the time of 2.
Tuplet(3, inTimeOf: 2) {
// Inner triplet: 3 in the time of 2 (cumulative 9:4).
Tuplet(3, inTimeOf: 2) {
Note(.c, 4, dur: .eighth)
Note(.d, 4, dur: .eighth)
Note(.e, 4, dur: .eighth)
}
Note(.f, 4, dur: .eighth)
Note(.g, 4, dur: .eighth)
}
}
}
let xml: String = score.toMusicXMLString()
// Inner-FIRST nesting (3:2 ⊃ 3:2): partHasNestedTuplet == true forces
// all bracket starts to full form. Both number=1 and number=2 starts
// are full form; both stops are bare.
let outer1Start: Range<String.Index>? = xml.range(
of: "<tuplet type=\"start\" number=\"1\">"
)
let inner2Start: Range<String.Index>? = xml.range(
of: "<tuplet type=\"start\" number=\"2\">"
)
#expect(outer1Start != nil,
"inner-first outer bracket (number=1) must use full form; got:\n\(xml)")
#expect(inner2Start != nil,
"inner bracket (number=2) must use full form; got:\n\(xml)")
// Both stop brackets bare.
#expect(xml.contains("<tuplet type=\"stop\" number=\"1\"/>"),
"outer bracket stop must be bare; got:\n\(xml)")
#expect(xml.contains("<tuplet type=\"stop\" number=\"2\"/>"),
"inner bracket stop must be bare; got:\n\(xml)")
// Both brackets display local number 3 (both levels are 3:2).
let tupletNumber3Count: Int = xml.components(
separatedBy: "<tuplet-number>3</tuplet-number>"
).count - 1
#expect(tupletNumber3Count >= 2,
"both bracket starts must carry <tuplet-number>3</tuplet-number>; got \(tupletNumber3Count);\n\(xml)")
// Both brackets must carry <tuplet-type>eighth</tuplet-type>
// (notes are eighths; typeInfo?.0 == "eighth").
#expect(xml.contains("<tuplet-type>eighth</tuplet-type>"),
"brackets must contain <tuplet-type>eighth</tuplet-type>; got:\n\(xml)")
// Outer bracket start must precede the inner bracket start.
if let o: Range<String.Index> = outer1Start,
let i: Range<String.Index> = inner2Start {
#expect(o.lowerBound < i.lowerBound,
"outer bracket start (number=1) must precede inner bracket start (number=2)")
}
}
@Test func singleLevelTupletStillUsesNumber1() {
// Ensure the fix for nested tuplets does not regress single-level
// tuplets — they must still emit number="1" only.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Tuplet(3, inTimeOf: 2) {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<tuplet type=\"start\" number=\"1\"/>"),
"single-level triplet must emit start number=1; got:\n\(xml)")
#expect(xml.contains("<tuplet type=\"stop\" number=\"1\"/>"),
"single-level triplet must emit stop number=1; got:\n\(xml)")
// Must NOT emit number=2 for a single-level tuplet.
#expect(!xml.contains("number=\"2\""),
"single-level tuplet must NOT emit number=2; got:\n\(xml)")
}
// MARK: - 10. Slur span pairing
@Test func isolatedLegatoNoteSlursToNextNote() throws {
// An isolated single .legato note must emit <slur type="start"/> on itself
// and <slur type="stop"/> on the immediately following note.
// The following non-legato note must NOT round-trip as legato.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .half, art: .legato)
Note(.d, 4, dur: .half) // receives slur stop
}
}
let xml: String = original.toMusicXMLString()
#expect(xml.contains("<slur number=\"1\" type=\"start\"/>"),
"isolated legato note must emit slur start; got:\n\(xml)")
#expect(xml.contains("<slur number=\"1\" type=\"stop\"/>"),
"following note must emit slur stop; got:\n\(xml)")
// Balance: one slur start, one slur stop (count only <slur …> elements).
let startCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"start\"/>"
).count - 1
let stopCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"stop\"/>"
).count - 1
#expect(startCount == stopCount,
"slur must be closed: starts=\(startCount) stops=\(stopCount)")
// Span model: no continue elements.
#expect(!xml.contains("<slur number=\"1\" type=\"continue\"/>"),
"span-model encoder must never emit <slur type=\"continue\"/>; got:\n\(xml)")
// Round-trip.
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = recovered.parts[0].flatten()
#expect(events.count == 2)
if events.count == 2 {
#expect(events[0].articulation == .legato,
"slur-start note must round-trip as .legato")
#expect(events[1].articulation == .normal,
"bare slur-stop target must NOT become .legato; got \(events[1].articulation)")
}
}
@Test func threeNoteLegatoRunRoundTrips() throws {
// Span-based slur model:
// A 3-note legato run [A, B, C] followed by non-legato D must emit:
// A → <slur type="start"/>
// B → no slur element (interior span member)
// C → no slur element (interior span member)
// D → <slur type="stop"/> (span closed on the follower)
//
// Round-trip via the span parser:
// start on A → A marked .legato, slurActive = true
// B (no slur element, slurActive true, no stop) → B marked .legato
// C (no slur element, slurActive true, no stop) → C marked .legato
// stop on D → slurActive = false, D NOT marked .legato
//
// All three legato source notes round-trip as .legato; D stays .normal.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.a, 4, dur: .quarter, art: .legato)
Note(.b, 4, dur: .quarter, art: .legato)
Note(.c, 5, dur: .quarter, art: .legato)
Note(.d, 5, dur: .quarter) // not in run — receives slur stop
}
}
let xml: String = original.toMusicXMLString()
// Must have exactly one start (on A) and one stop (on D).
#expect(xml.contains("<slur number=\"1\" type=\"start\"/>"),
"run must emit slur start on first note; got:\n\(xml)")
#expect(xml.contains("<slur number=\"1\" type=\"stop\"/>"),
"run must emit slur stop on follower note; got:\n\(xml)")
// No continue elements — this is the key MusicXML-validity fix.
#expect(!xml.contains("<slur number=\"1\" type=\"continue\"/>"),
"span model must NOT emit <slur type=\"continue\"/>; got:\n\(xml)")
// Balance: exactly one start and one stop (count only <slur …> elements).
let startCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"start\"/>"
).count - 1
let stopCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"stop\"/>"
).count - 1
#expect(startCount == 1,
"run must emit exactly one slur start; got \(startCount); xml:\n\(xml)")
#expect(stopCount == 1,
"run must emit exactly one slur stop; got \(stopCount); xml:\n\(xml)")
#expect(startCount == stopCount,
"slur must be closed: starts=\(startCount) stops=\(stopCount)")
// Round-trip.
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = recovered.parts[0].flatten()
#expect(events.count == 4)
if events.count == 4 {
// The three legato notes must all come back as legato (span tracking).
#expect(events[0].articulation == .legato, "run note 0 (slur start) must be legato")
#expect(events[1].articulation == .legato, "run note 1 (interior, slurActive) must be legato")
#expect(events[2].articulation == .legato, "run note 2 (interior, slurActive) must be legato")
// The non-legato following note receives slur stop — must NOT become legato.
#expect(events[3].articulation == .normal,
"non-legato note after run (slur stop) must stay .normal; got \(events[3].articulation)")
}
}
@Test func loneSingleLegatoNoteWithNoFollowerEmitsNoSlur() {
// A part whose ONLY note is legato and has no following note in the part
// must NOT emit a dangling <slur type="start"/> (cannot form a closed span).
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, art: .legato)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<slur"),
"lone legato with no following note must emit NO slur; got:\n\(xml)")
}
@Test func slurBalanceInvariant() throws {
// Every <slur type="start"> in the document must have a matching
// <slur type="stop"> (same count). Applies to any score with legato notes.
// Count ONLY <slur …> elements (not <tie> or <tuplet>) to avoid inflation.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, art: .legato)
Note(.d, 4, dur: .quarter, art: .legato)
Note(.e, 4, dur: .quarter, art: .legato)
Note(.f, 4, dur: .quarter)
Note(.g, 4, dur: .quarter, art: .legato)
Note(.a, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Use specific <slur number="1" type=…/> substrings so ties/tuplets are excluded.
let startCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"start\"/>"
).count - 1
let stopCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"stop\"/>"
).count - 1
#expect(startCount == stopCount,
"every slur start must have a stop: starts=\(startCount) stops=\(stopCount); got:\n\(xml)")
#expect(startCount > 0,
"legato notes must produce at least one slur; got:\n\(xml)")
// Span model: zero continue elements.
#expect(!xml.contains("<slur number=\"1\" type=\"continue\"/>"),
"span-model encoder must never emit <slur type=\"continue\"/>; got:\n\(xml)")
}
@Test func legatoRunCrossingBarlineRoundTrips() throws {
// A legato run that starts in measure 1 and has its stop in measure 2
// (because the follower note is in measure 2) must still round-trip
// correctly: all run notes come back as .legato, the follower stays .normal.
//
// Layout in 2/4: [A half legato | B half legato | C quarter] — the
// two legato halves fill two separate measures; the stop lands on C.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(2, 4)) {
Part("p") {
Note(.a, 4, dur: .half, art: .legato) // measure 1 (2 beats)
Note(.b, 4, dur: .half, art: .legato) // measure 2 (2 beats)
Note(.c, 5, dur: .half) // measure 3 — receives slur stop
}
}
let xml: String = original.toMusicXMLString()
// Exactly one slur start (on A) and one slur stop (on C in measure 3).
let startCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"start\"/>"
).count - 1
let stopCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"stop\"/>"
).count - 1
#expect(startCount == 1,
"barline-crossing run must emit exactly one slur start; got \(startCount);\n\(xml)")
#expect(stopCount == 1,
"barline-crossing run must emit exactly one slur stop; got \(stopCount);\n\(xml)")
#expect(startCount == stopCount,
"slur must be balanced: starts=\(startCount) stops=\(stopCount)")
// No continue — span model is continue-free.
#expect(!xml.contains("<slur number=\"1\" type=\"continue\"/>"),
"span model must never emit <slur type=\"continue\"/>; got:\n\(xml)")
// Round-trip: both run notes come back as .legato; follower stays .normal.
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = recovered.parts[0].flatten()
#expect(events.count == 3,
"round-trip must yield 3 events; got \(events.count)")
if events.count == 3 {
#expect(events[0].articulation == .legato,
"first run note (slur start, measure 1) must be .legato")
#expect(events[1].articulation == .legato,
"second run note (interior, slurActive, measure 2) must be .legato")
#expect(events[2].articulation == .normal,
"follower note (slur stop, measure 3) must stay .normal; got \(events[2].articulation)")
}
}
@Test func legatoRunAtEndOfPartHasBalancedSlur() {
// A legato run that reaches the END of the part with no following note
// must still emit exactly one start and one stop (balanced). The stop is
// placed on the last legato note itself (best-effort). The last note reads
// non-legato after round-trip (documented lossy edge — the start+stop on
// the same note makes the parser emit stop without legato for that note).
//
// This test verifies:
// 1. Exactly one start + one stop are emitted (balanced).
// 2. No continue elements.
// 3. No dangling start without stop.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, art: .legato)
Note(.d, 4, dur: .quarter, art: .legato)
Note(.e, 4, dur: .quarter, art: .legato)
// No non-legato follower — run ends at the part boundary.
}
}
let xml: String = score.toMusicXMLString()
let startCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"start\"/>"
).count - 1
let stopCount: Int = xml.components(
separatedBy: "<slur number=\"1\" type=\"stop\"/>"
).count - 1
#expect(startCount == 1,
"end-of-part run must emit exactly one slur start; got \(startCount);\n\(xml)")
#expect(stopCount == 1,
"end-of-part run must emit exactly one slur stop; got \(stopCount);\n\(xml)")
#expect(startCount == stopCount,
"end-of-part run slur must be balanced: starts=\(startCount) stops=\(stopCount)")
#expect(!xml.contains("<slur number=\"1\" type=\"continue\"/>"),
"end-of-part run must not emit <slur type=\"continue\"/>; got:\n\(xml)")
}
@Test func noContinueElementsEverEmitted() {
// Assert that <slur type="continue"/> is NEVER present in any encoded score,
// regardless of run length or structure. Span model invariant.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .eighth, art: .legato)
Note(.d, 4, dur: .eighth, art: .legato)
Note(.e, 4, dur: .eighth, art: .legato)
Note(.f, 4, dur: .eighth, art: .legato)
Note(.g, 4, dur: .eighth, art: .legato)
Note(.a, 4, dur: .eighth) // follower — receives stop
Note(.b, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("type=\"continue\""),
"span model must never emit any type=\"continue\" (slur or otherwise); got:\n\(xml)")
#expect(!xml.contains("<slur number=\"1\" type=\"continue\"/>"),
"span model must never emit <slur type=\"continue\"/>; got:\n\(xml)")
}
// MARK: - 11. Beaming
@Test func beamableEighthsInSameBeatGetBeamGroup() {
// Two consecutive eighth notes in the same beat must get beam begin + end.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .eighth)
Note(.d, 4, dur: .eighth)
Note(.e, 4, dur: .quarter) // not beamable
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<beam number=\"1\">begin</beam>"),
"first beamable eighth must emit beam begin; got:\n\(xml)")
#expect(xml.contains("<beam number=\"1\">end</beam>"),
"last beamable eighth must emit beam end; got:\n\(xml)")
// Quarter must not be beamed.
#expect(!xml.contains("<beam number=\"1\">continue</beam>"),
"only two eighths: no continue expected; got:\n\(xml)")
}
@Test func singleEighthIsNotBeamed() {
// A lone eighth note (group size 1) must NOT carry a <beam> element.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .eighth) // lone eighth — no beam partner
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<beam"),
"lone eighth note must NOT carry a <beam>; got:\n\(xml)")
}
@Test func fourEighthsInSameBeatForm3ContinueGroup() {
// Four consecutive eighths in beat 0 of a 4/4 bar form one beam group:
// begin + 2× continue + end.
// NB: 4 eighths = 2 quarter-beats; they all fall in beat 0 (quarter-beat 0).
// Actually beats are integer quarter-beat floors: eighths at positions
// 0, 0.5, 1, 1.5 have floors 0, 0, 1, 1 — so groups of 2, not 4.
// The test checks that the grouping boundary is correct.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .eighth)
Note(.d, 4, dur: .eighth)
Note(.e, 4, dur: .eighth)
Note(.f, 4, dur: .eighth)
Note(.g, 4, dur: .half) // rest of bar
}
}
let xml: String = score.toMusicXMLString()
// Each pair of eighths sharing the same beat-floor should beam together.
// Pair 1 (beat 0): begin + end.
// Pair 2 (beat 1): begin + end.
let beginCount: Int = xml.components(separatedBy: "<beam number=\"1\">begin</beam>").count - 1
let endCount: Int = xml.components(separatedBy: "<beam number=\"1\">end</beam>").count - 1
#expect(beginCount == endCount,
"beam begin and end counts must match; begins=\(beginCount) ends=\(endCount); got:\n\(xml)")
#expect(beginCount >= 1,
"at least one beam group must be formed; got:\n\(xml)")
}
@Test func beamDoesNotCrossRestBoundary() {
// A rest between two eighths must prevent them from beaming together.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .eighth)
Rest(dur: .eighth)
Note(.d, 4, dur: .eighth)
Note(.e, 4, dur: .eighth) // only these two can beam (same beat)
}
}
let xml: String = score.toMusicXMLString()
// The C note has no beamable neighbour (rest breaks the group).
// D and E are at positions 0.5 and 0.75 in beat 0? Actually:
// C=0, rest=0.5, D=1.0, E=1.5. D and E both have floor 1 → they beam.
// C is isolated → no beam.
let beginCount: Int = xml.components(separatedBy: "<beam number=\"1\">begin</beam>").count - 1
#expect(beginCount <= 1,
"rest between eighths must prevent a shared beam; got:\n\(xml)")
}
@Test func quarterNotesAreNotBeamable() {
// Quarter notes must never carry <beam> elements.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<beam"),
"quarter notes must NOT carry <beam> elements; got:\n\(xml)")
}
@Test func beamElementAppearsBeforeNotations() {
// <beam> must appear AFTER <type> and BEFORE <notations>
// per MusicXML 4.0 §3.3 note content order.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .eighth, art: .staccato)
Note(.d, 4, dur: .eighth, art: .staccato)
Note(.e, 4, dur: .half)
}
}
let xml: String = score.toMusicXMLString()
guard let typeRange: Range<String.Index> = xml.range(of: "<type>eighth</type>"),
let beamRange: Range<String.Index> = xml.range(of: "<beam number=\"1\">begin</beam>"),
let notationsRange: Range<String.Index> = xml.range(of: "<notations>") else {
Issue.record("<type>, <beam>, or <notations> not found in:\n\(xml)")
return
}
#expect(typeRange.lowerBound < beamRange.lowerBound,
"<beam> must appear after <type>; got:\n\(xml)")
#expect(beamRange.lowerBound < notationsRange.lowerBound,
"<beam> must appear before <notations>; got:\n\(xml)")
}
@Test func beamRoundTripIgnoredByParser() throws {
// The parser must not create any elements from <beam> markup.
// Encoding a beamed score and re-parsing must yield the same
// pitches and durations (beam elements are silently ignored).
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .eighth)
Note(.d, 4, dur: .eighth)
Note(.e, 4, dur: .quarter)
Note(.f, 4, dur: .half)
}
}
let xml: String = original.toMusicXMLString()
#expect(xml.contains("<beam"),
"score with beamable notes must emit <beam>; got:\n\(xml)")
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let origEvents: [ScoreEvent] = original.parts[0].flatten()
let recEvents: [ScoreEvent] = recovered.parts[0].flatten()
#expect(origEvents.count == recEvents.count,
"beam round-trip must preserve event count; orig=\(origEvents.count) rec=\(recEvents.count)")
for (idx, (orig, rec)) in zip(origEvents, recEvents).enumerated() {
#expect(orig.pitch == rec.pitch,
"pitch mismatch at \(idx): orig=\(orig.pitch) rec=\(rec.pitch)")
#expect(abs(orig.duration - rec.duration) < 1e-9,
"duration mismatch at \(idx): orig=\(orig.duration) rec=\(rec.duration)")
}
}
// MARK: - 12. Multi-voice / Voice DSL
// --- flatten ---
@Test func voiceFlattenTwoVoicesOverlay() {
// Two Voice blocks overlay from beat 0 — events share beat space rather
// than sequencing end-to-end.
let part: ScorePart = Part("piano") {
Voice(1) {
Note(.e, 5, dur: .half) // beat 0–2, voice 1
Note(.d, 5, dur: .half) // beat 2–4, voice 1
}
Voice(2) {
Note(.c, 4, dur: .whole) // beat 0–4, voice 2
}
}
let events: [ScoreEvent] = part.flatten()
#expect(events.count == 3, "two Voice blocks must yield 3 events (2 + 1); got \(events.count)")
// Voice 1 events start at 0 and 2.
let v1: [ScoreEvent] = events.filter { $0.voice == 1 }.sorted { $0.beat < $1.beat }
let v2: [ScoreEvent] = events.filter { $0.voice == 2 }.sorted { $0.beat < $1.beat }
#expect(v1.count == 2, "voice 1 must have 2 events; got \(v1.count)")
#expect(v2.count == 1, "voice 2 must have 1 event; got \(v2.count)")
#expect(abs(v1[0].beat - 0.0) < 1e-9, "voice 1 first note must start at beat 0")
#expect(abs(v1[1].beat - 2.0) < 1e-9, "voice 1 second note must start at beat 2")
#expect(abs(v2[0].beat - 0.0) < 1e-9, "voice 2 note must start at beat 0")
}
@Test func bareElementsDefaultToVoice0() {
// Elements without a Voice wrapper keep the existing single-cursor behavior
// with voiceFallback = 0.
let part: ScorePart = Part("lead") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
}
let events: [ScoreEvent] = part.flatten()
#expect(events.count == 2)
for e: ScoreEvent in events {
#expect(e.voice == 0, "bare elements must default to voice 0; got \(e.voice)")
}
}
@Test func voiceLastBeatMaxOverAllVoices() {
// lastBeat() reflects the max across all voices.
let part: ScorePart = Part("piano") {
Voice(1) {
Note(.e, 5, dur: .half) // ends at beat 2
}
Voice(2) {
Note(.c, 4, dur: .whole) // ends at beat 4
}
}
let lb: Double = part.lastBeat()
#expect(abs(lb - 4.0) < 1e-9, "lastBeat must be 4.0 (max over voices); got \(lb)")
}
@Test func singleVoiceNoBackupInXML() {
// A single-voice part must NOT emit any <backup> element.
// This is the critical byte-identical invariant.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Note(.c, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.g, 4, dur: .half)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<backup"),
"single-voice part must NOT emit <backup>; got:\n\(xml)")
#expect(!xml.contains("<forward"),
"single-voice part must NOT emit <forward>; got:\n\(xml)")
}
// --- encoder ---
@Test func twoVoicePartEmitsBackupAndVoice2() {
// A 2-voice part must emit <backup> between voices and tag notes with
// <voice>1</voice> / <voice>2</voice>.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("piano") {
Voice(1) {
Note(.e, 5, dur: .half)
Note(.d, 5, dur: .half)
}
Voice(2) {
Note(.c, 4, dur: .whole)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<backup>"),
"2-voice part must emit <backup>; got:\n\(xml)")
#expect(xml.contains("<voice>1</voice>"),
"voice 1 notes must carry <voice>1</voice>; got:\n\(xml)")
#expect(xml.contains("<voice>2</voice>"),
"voice 2 notes must carry <voice>2</voice>; got:\n\(xml)")
}
@Test func backupDurationEqualsCapacity() {
// <backup><duration>D</duration> must equal the measure capacity in
// divisions (480 quarters at divisions=480 for a 4/4 bar = 1920).
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("piano") {
Voice(1) {
Note(.e, 5, dur: .half)
Note(.d, 5, dur: .half)
}
Voice(2) {
Note(.c, 4, dur: .whole)
}
}
}
let xml: String = score.toMusicXMLString(divisions: 480)
// 4/4 at divisions=480 → measure capacity = 4 × 480 = 1920 ticks.
#expect(xml.contains("<backup>\n <duration>1920</duration>\n </backup>"),
"backup duration must equal 1920 for 4/4 at div=480; got:\n\(xml)")
}
// --- parser ---
@Test func parseBackupProducesMultipleVoices() throws {
// A MusicXML document with <backup> must parse into a part whose
// flattened events cover both voices at the correct beats.
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>piano</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes>
<divisions>4</divisions>
<time><beats>4</beats><beat-type>4</beat-type></time>
</attributes>
<note>
<pitch><step>E</step><octave>5</octave></pitch>
<duration>8</duration>
<voice>1</voice>
</note>
<note>
<pitch><step>D</step><octave>5</octave></pitch>
<duration>8</duration>
<voice>1</voice>
</note>
<backup><duration>16</duration></backup>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>16</duration>
<voice>2</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,
"backup+2-voice must yield 3 events; got \(events.count)")
let v1: [ScoreEvent] = events
.filter { $0.voice == 1 }
.sorted { $0.beat < $1.beat }
let v2: [ScoreEvent] = events
.filter { $0.voice == 2 }
.sorted { $0.beat < $1.beat }
#expect(v1.count == 2, "voice 1 must have 2 events; got \(v1.count)")
#expect(v2.count == 1, "voice 2 must have 1 event; got \(v2.count)")
if v1.count >= 2 {
#expect(abs(v1[0].beat - 0.0) < 1e-9, "v1[0] beat must be 0; got \(v1[0].beat)")
#expect(abs(v1[1].beat - 2.0) < 1e-9, "v1[1] beat must be 2; got \(v1[1].beat)")
}
if v2.count >= 1 {
#expect(abs(v2[0].beat - 0.0) < 1e-9, "v2[0] beat must be 0; got \(v2[0].beat)")
#expect(abs(v2[0].duration - 4.0) < 1e-9, "v2[0] duration must be 4; got \(v2[0].duration)")
}
}
@Test func forwardAdvancesCursor() throws {
// <forward> must advance the cursor so subsequent notes land
// at the correct absolute beat.
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<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>4</divisions></attributes>
<forward><duration>8</duration></forward>
<note>
<pitch><step>G</step><octave>4</octave></pitch>
<duration>8</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()
let pitched: [ScoreEvent] = events.filter { !$0.isRest }
#expect(pitched.count == 1, "one note expected; got \(pitched.count)")
if let ev: ScoreEvent = pitched.first {
// <forward> of 8 divisions at divisions=4 = 2 beats.
#expect(abs(ev.beat - 2.0) < 1e-9,
"note after <forward>8</forward> must land at beat 2; got \(ev.beat)")
}
}
// --- round-trip ---
@Test func twoVoiceRoundTrip() throws {
// A 2-voice score encodes and parses back with matching flattened events.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("piano") {
Voice(1) {
Note(.e, 5, dur: .half)
Note(.d, 5, dur: .half)
}
Voice(2) {
Note(.c, 4, dur: .whole)
}
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let origEvents: [ScoreEvent] = original.parts[0].flatten().sorted {
$0.beat != $1.beat ? $0.beat < $1.beat : (($0.pitch.midiNote ?? 0) < ($1.pitch.midiNote ?? 0))
}
let recEvents: [ScoreEvent] = recovered.parts[0].flatten().sorted {
$0.beat != $1.beat ? $0.beat < $1.beat : (($0.pitch.midiNote ?? 0) < ($1.pitch.midiNote ?? 0))
}
#expect(origEvents.count == recEvents.count,
"round-trip must preserve event count; orig=\(origEvents.count) rec=\(recEvents.count)")
let tolerance: Double = 1e-6
for (idx, (orig, rec)) in zip(origEvents, recEvents).enumerated() {
#expect(abs(orig.beat - rec.beat) < tolerance,
"beat mismatch at \(idx): orig=\(orig.beat) rec=\(rec.beat)")
#expect(abs(orig.duration - rec.duration) < tolerance,
"duration mismatch at \(idx): orig=\(orig.duration) rec=\(rec.duration)")
#expect(orig.pitch == rec.pitch,
"pitch mismatch at \(idx): orig=\(orig.pitch) rec=\(rec.pitch)")
#expect(orig.voice == rec.voice,
"voice mismatch at \(idx): orig=\(orig.voice) rec=\(rec.voice)")
}
}
// MARK: - 13. Multi-voice / Voice DSL review fixes
// Fix 1 — per-voice slur isolation
@Test func crossVoiceSlurIsolation() throws {
// A MusicXML document where voice 1 opens a slur span and a `<backup>`
// rewinds to let voice 2 write plain notes. Voice 2 notes must NOT receive
// `.legato` — the slur active in voice 1 must not contaminate voice 2.
//
// The hand-written snippet below has:
// voice 1: C4 quarter with <slur type="start"/>, then D4 quarter (span still open)
// <backup> full measure
// voice 2: E4 half (plain, no slur markup)
//
// Expected: voice-2 E4 event has articulation == .normal.
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<score-partwise version="4.0">
<part-list>
<score-part id="P1"><part-name>piano</part-name></score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes>
<divisions>4</divisions>
<time><beats>4</beats><beat-type>4</beat-type></time>
</attributes>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>4</duration>
<voice>1</voice>
<notations>
<slur number="1" type="start"/>
</notations>
</note>
<note>
<pitch><step>D</step><octave>4</octave></pitch>
<duration>4</duration>
<voice>1</voice>
</note>
<backup><duration>16</duration></backup>
<note>
<pitch><step>E</step><octave>4</octave></pitch>
<duration>8</duration>
<voice>2</voice>
</note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = score.parts[0].flatten()
let v2Events: [ScoreEvent] = events.filter { $0.voice == 2 }
#expect(v2Events.count == 1,
"voice 2 must have 1 event; got \(v2Events.count)")
if let e: ScoreEvent = v2Events.first {
#expect(e.articulation == .normal,
"voice 2 note must NOT be .legato when only voice 1 has an open slur; got \(e.articulation)")
}
// Voice 1 notes: C4 should be legato (slur start), D4 should also be
// legato (interior — slurActive in voice 1 carries over since no stop
// was emitted). The slur-active state in voice 1 is independent of voice 2.
let v1Events: [ScoreEvent] = events.filter { $0.voice == 1 }.sorted { $0.beat < $1.beat }
#expect(v1Events.count == 2,
"voice 1 must have 2 events; got \(v1Events.count)")
if v1Events.count >= 1 {
#expect(v1Events[0].articulation == .legato,
"voice 1 first note (slur start) must be .legato; got \(v1Events[0].articulation)")
}
}
// Fix 6 — unequal-length voice round-trip
@Test func unequalLengthVoicesRoundTrip() throws {
// A 2-voice part where voice 1 is longer than voice 2:
// voice 1: 2 whole notes (2 bars / 8 beats total)
// voice 2: 1 whole note (1 bar / 4 beats total)
//
// The encoder pads voice 2's second bar with a whole-measure rest.
// On the parse side that rest is skipped by flatten(), so the sounding
// event count + beats + pitches must match exactly.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("piano") {
Voice(1) {
Note(.g, 4, dur: .whole) // bar 1
Note(.f, 4, dur: .whole) // bar 2
}
Voice(2) {
Note(.c, 4, dur: .whole) // bar 1 only
}
}
}
let xml: String = original.toMusicXMLString()
// Encode sanity: 2 measures must be present (longest voice = 2 bars).
let measureCount: Int = xml.components(separatedBy: "<measure number=").count - 1
#expect(measureCount == 2,
"unequal-voice score must emit 2 measures (voice 1 length); got \(measureCount)")
// Parse and flatten.
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let origEvents: [ScoreEvent] = original.parts[0].flatten()
.filter { !$0.isRest }
.sorted { $0.beat != $1.beat ? $0.beat < $1.beat : (($0.pitch.midiNote ?? 0) < ($1.pitch.midiNote ?? 0)) }
let recEvents: [ScoreEvent] = recovered.parts[0].flatten()
.filter { !$0.isRest }
.sorted { $0.beat != $1.beat ? $0.beat < $1.beat : (($0.pitch.midiNote ?? 0) < ($1.pitch.midiNote ?? 0)) }
// Sounding event count must match (3 sounding notes: G4, F4, C4).
#expect(origEvents.count == 3,
"original must have 3 sounding notes (G4 bar1, F4 bar2, C4 bar1); got \(origEvents.count)")
#expect(recEvents.count == origEvents.count,
"round-trip must preserve sounding event count; orig=\(origEvents.count) rec=\(recEvents.count)")
let tolerance: Double = 1e-6
for (idx, (orig, rec)) in zip(origEvents, recEvents).enumerated() {
#expect(orig.pitch == rec.pitch,
"pitch mismatch at \(idx): orig=\(orig.pitch) rec=\(rec.pitch)")
#expect(abs(orig.beat - rec.beat) < tolerance,
"beat mismatch at \(idx): orig=\(orig.beat) rec=\(rec.beat)")
#expect(abs(orig.duration - rec.duration) < tolerance,
"duration mismatch at \(idx): orig=\(orig.duration) rec=\(rec.duration)")
}
}
@Test func singleVoiceScoreStructureUnchanged() throws {
// Regression guard: the original lead+bass demo score (single-voice parts)
// must produce NO <backup> elements and the same flattened events as before.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead", clef: .treble) {
Note(.c, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Tuplet(3, inTimeOf: 2) {
Note(.g, 5, dur: .quarter)
Note(.a, 5, dur: .quarter)
Note(.b, 5, dur: .quarter)
}
Note(.g, 5, dur: .half)
}
Part("bass", channel: 1, clef: .bass) {
Note(.c, 2, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
// Single-voice invariant: no <backup> anywhere.
#expect(!xml.contains("<backup"),
"single-voice score must NOT emit <backup>; got:\n\(xml)")
// Round-trip must preserve events.
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
for (pIdx, part) in score.parts.enumerated() {
let origEvents: [ScoreEvent] = part.flatten()
let recEvents: [ScoreEvent] = recovered.parts[pIdx].flatten()
#expect(origEvents.count == recEvents.count,
"part \(pIdx) event count must survive round-trip; orig=\(origEvents.count) rec=\(recEvents.count)")
}
}
// MARK: - 14. Dynamic directions
// Dynamic.musicXMLDynamic / fromMusicXMLName mapping
@Test func dynamicMusicXMLNameAllNamedCases() {
// All 8 named cases map to their expected MusicXML element names.
#expect(Dynamic.ppp.musicXMLDynamic == "ppp")
#expect(Dynamic.pp.musicXMLDynamic == "pp")
#expect(Dynamic.p.musicXMLDynamic == "p")
#expect(Dynamic.mp.musicXMLDynamic == "mp")
#expect(Dynamic.mf.musicXMLDynamic == "mf")
#expect(Dynamic.f.musicXMLDynamic == "f")
#expect(Dynamic.ff.musicXMLDynamic == "ff")
#expect(Dynamic.fff.musicXMLDynamic == "fff")
}
@Test func dynamicMusicXMLNameRawReturnsNil() {
// .raw(_) must return nil — caller uses <other-dynamics> instead.
#expect(Dynamic.raw(0.5).musicXMLDynamic == nil)
#expect(Dynamic.raw(0.0).musicXMLDynamic == nil)
#expect(Dynamic.raw(1.0).musicXMLDynamic == nil)
}
@Test func dynamicFromMusicXMLNameAllNamedCases() {
// fromMusicXMLName round-trips all 8 standard names.
#expect(Dynamic.fromMusicXMLName("ppp") == .ppp)
#expect(Dynamic.fromMusicXMLName("pp") == .pp)
#expect(Dynamic.fromMusicXMLName("p") == .p)
#expect(Dynamic.fromMusicXMLName("mp") == .mp)
#expect(Dynamic.fromMusicXMLName("mf") == .mf)
#expect(Dynamic.fromMusicXMLName("f") == .f)
#expect(Dynamic.fromMusicXMLName("ff") == .ff)
#expect(Dynamic.fromMusicXMLName("fff") == .fff)
}
@Test func dynamicFromMusicXMLNameUnknownReturnsNil() {
// Unrecognised names return nil.
#expect(Dynamic.fromMusicXMLName("sfz") == nil)
#expect(Dynamic.fromMusicXMLName("fp") == nil)
#expect(Dynamic.fromMusicXMLName("") == nil)
#expect(Dynamic.fromMusicXMLName("MF") == nil, "lookup is case-sensitive")
}
// Encoder: direction emission
@Test func ffNoteEmitsDynamicDirection() {
// A single note with dyn: .ff must produce a <direction placement="below">
// element containing <dynamics><ff/></dynamics>.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .ff)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<direction placement=\"below\">"),
"note with dyn:.ff must emit <direction placement=\"below\">; got:\n\(xml)")
#expect(xml.contains("<dynamics>"),
"direction must contain <dynamics>; got:\n\(xml)")
#expect(xml.contains("<ff/>"),
"direction must contain <ff/>; got:\n\(xml)")
}
@Test func sameDynamicRunEmitsOneDirection() {
// Three consecutive notes all at .mf must emit exactly ONE <direction>
// (change-only emission: emit on the first, skip the rest).
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .mf)
Note(.d, 4, dur: .quarter, dyn: .mf)
Note(.e, 4, dur: .quarter, dyn: .mf)
Note(.f, 4, dur: .quarter, dyn: .mf)
}
}
let xml: String = score.toMusicXMLString()
let directionCount: Int = xml.components(
separatedBy: "<direction placement=\"below\">"
).count - 1
#expect(directionCount == 1,
"4 identical-dynamic notes must emit exactly 1 <direction>; got \(directionCount);\n\(xml)")
}
@Test func dynamicChangeMidRunEmitsSecondDirection() {
// pp (×2) then ff (×2) must emit exactly 2 directions: one at start (pp),
// one at the dynamic change (ff).
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .pp)
Note(.d, 4, dur: .quarter, dyn: .pp)
Note(.e, 4, dur: .quarter, dyn: .ff)
Note(.f, 4, dur: .quarter, dyn: .ff)
}
}
let xml: String = score.toMusicXMLString()
let directionCount: Int = xml.components(
separatedBy: "<direction placement=\"below\">"
).count - 1
#expect(directionCount == 2,
"pp→ff mid-run must emit exactly 2 directions; got \(directionCount);\n\(xml)")
#expect(xml.contains("<pp/>"),
"first direction must contain <pp/>; got:\n\(xml)")
#expect(xml.contains("<ff/>"),
"second direction must contain <ff/>; got:\n\(xml)")
}
@Test func restDoesNotEmitDynamicDirection() {
// A rest in the middle of a dynamic run must NOT emit a <direction> and
// must NOT reset the last-emitted dynamic tracker. The note after the rest
// at the SAME dynamic must also not emit a second direction.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .mf)
Rest(dur: .quarter)
Note(.d, 4, dur: .quarter, dyn: .mf)
Note(.e, 4, dur: .quarter, dyn: .mf)
}
}
let xml: String = score.toMusicXMLString()
// Only one direction should be emitted (for the first note).
let directionCount: Int = xml.components(
separatedBy: "<direction placement=\"below\">"
).count - 1
#expect(directionCount == 1,
"rest must not emit direction and must not reset tracker; expected 1, got \(directionCount);\n\(xml)")
}
@Test func rawDynamicEmitsOtherDynamics() {
// A .raw(0.42) dynamic must emit <other-dynamics>0.42</other-dynamics>
// (not a standard named element, not empty).
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .raw(0.42))
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<other-dynamics>"),
".raw must emit <other-dynamics>; got:\n\(xml)")
#expect(xml.contains("</other-dynamics>"),
".raw must close </other-dynamics>; got:\n\(xml)")
// The text must be parseable as 0.42 (within FP tolerance).
// Extract the text between the tags.
if let start: Range<String.Index> = xml.range(of: "<other-dynamics>"),
let end: Range<String.Index> = xml.range(of: "</other-dynamics>") {
let text: String = String(xml[start.upperBound..<end.lowerBound])
let parsed: Double? = Double(text)
#expect(parsed != nil, "<other-dynamics> text must be parseable as Double; text='\(text)'")
if let v: Double = parsed {
#expect(abs(v - 0.42) < 1e-6,
"<other-dynamics> value must be ≈0.42; got \(v); text='\(text)'")
}
} else {
Issue.record("<other-dynamics> tags not found in:\n\(xml)")
}
}
@Test func noteXMLDurationUnchangedWithDirection() {
// Inserting <direction> elements must NOT alter the existing <duration>
// tick values of the surrounding notes.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .mf)
Note(.d, 4, dur: .half, dyn: .f)
Note(.e, 4, dur: .quarter, dyn: .p)
}
}
let xml: String = score.toMusicXMLString(divisions: 480)
// quarter = 480, half = 960.
#expect(xml.contains("<duration>480</duration>"),
"quarter note must still encode as <duration>480</duration>; got:\n\(xml)")
#expect(xml.contains("<duration>960</duration>"),
"half note must still encode as <duration>960</duration>; got:\n\(xml)")
}
@Test func directionAppearsBeforeNote() {
// The <direction> element must appear BEFORE the <note> it precedes.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .ff)
Note(.d, 4, dur: .quarter, dyn: .p)
}
}
let xml: String = score.toMusicXMLString()
// First direction (ff) must appear before its note (step C).
if let ffDirRange: Range<String.Index> = xml.range(of: "<ff/>"),
let cNoteRange: Range<String.Index> = xml.range(of: "<step>C</step>") {
#expect(ffDirRange.lowerBound < cNoteRange.lowerBound,
"<ff/> direction must appear before <step>C</step>; got:\n\(xml)")
} else {
Issue.record("<ff/> or <step>C</step> not found in:\n\(xml)")
}
// Second direction (p) must appear before its note (step D).
if let pDirRange: Range<String.Index> = xml.range(of: "<p/>"),
let dNoteRange: Range<String.Index> = xml.range(of: "<step>D</step>") {
#expect(pDirRange.lowerBound < dNoteRange.lowerBound,
"<p/> direction must appear before <step>D</step>; got:\n\(xml)")
} else {
Issue.record("<p/> or <step>D</step> not found in:\n\(xml)")
}
}
// Parser: <dynamics> reading
@Test func parseDynamicsDirectionSetsCurrentDynamic() throws {
// A <direction> containing <dynamics><ff/></dynamics> before a note
// must cause that note to be parsed with Dynamic.ff.
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<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>
<direction placement="below">
<direction-type>
<dynamics><ff/></dynamics>
</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))
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 1, "must parse one note; got \(events.count)")
// Velocity from .ff dynamic.
if let ev: ScoreEvent = events.first {
#expect(abs(ev.velocity - Dynamic.ff.velocity) < 1e-6,
"parsed note must have .ff velocity; got \(ev.velocity)")
}
}
@Test func parseDynamicsStickyAcrossNotes() throws {
// A single <direction><dynamics><mp/></dynamics></direction> before note 1
// must apply to note 2 as well (sticky — no second direction).
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<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="below">
<direction-type>
<dynamics><mp/></dynamics>
</direction-type>
</direction>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<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, "must parse 2 notes; got \(events.count)")
if events.count == 2 {
// Both notes inherit the mp dynamic (sticky).
#expect(abs(events[0].velocity - Dynamic.mp.velocity) < 1e-6,
"note 0 must have .mp velocity; got \(events[0].velocity)")
#expect(abs(events[1].velocity - Dynamic.mp.velocity) < 1e-6,
"note 1 must inherit .mp dynamic (sticky); got \(events[1].velocity)")
}
}
@Test func parseDynamicsChangeMidPart() throws {
// A second <direction> mid-part must override the current dynamic.
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<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="below">
<direction-type><dynamics><pp/></dynamics></direction-type>
</direction>
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>1</duration>
<voice>1</voice>
</note>
<direction placement="below">
<direction-type><dynamics><fff/></dynamics></direction-type>
</direction>
<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, "must parse 2 notes; got \(events.count)")
if events.count == 2 {
#expect(abs(events[0].velocity - Dynamic.pp.velocity) < 1e-6,
"first note must have .pp velocity; got \(events[0].velocity)")
#expect(abs(events[1].velocity - Dynamic.fff.velocity) < 1e-6,
"second note must have .fff velocity after direction change; got \(events[1].velocity)")
}
}
@Test func parseOtherDynamicsRoundTrips() throws {
// A .raw(0.42) note encodes to <other-dynamics>0.42</other-dynamics>
// and parses back to a note whose velocity ≈ 0.42.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .raw(0.42))
}
}
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 == 1, "must parse 1 note; got \(events.count)")
if let ev: ScoreEvent = events.first {
#expect(abs(ev.velocity - 0.42) < 1e-6,
".raw(0.42) must round-trip to velocity ≈ 0.42; got \(ev.velocity)")
}
}
@Test func parseNoDirectionDefaultsToMF() throws {
// A note with no preceding <direction> must default to .mf velocity.
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<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>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 1, "must parse 1 note; got \(events.count)")
if let ev: ScoreEvent = events.first {
#expect(abs(ev.velocity - Dynamic.mf.velocity) < 1e-6,
"note with no direction must default to .mf velocity; got \(ev.velocity)")
}
}
// Round-trip: dynamic preserved end-to-end
@Test func roundTripPreservesDynamic() throws {
// A score with varied per-note dynamics must round-trip so that each
// event's velocity matches the original event's velocity.
//
// Change-only + sticky encoding means consecutive same-dynamic notes
// all carry the same velocity after round-trip.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .ppp)
Note(.d, 4, dur: .quarter, dyn: .mf)
Note(.e, 4, dur: .quarter, dyn: .ff)
Note(.f, 4, dur: .quarter, dyn: .ff) // same as previous
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let origEvents: [ScoreEvent] = original.parts[0].flatten()
let recEvents: [ScoreEvent] = recovered.parts[0].flatten()
#expect(origEvents.count == recEvents.count,
"round-trip must preserve event count; orig=\(origEvents.count) rec=\(recEvents.count)")
for (idx, (orig, rec)) in zip(origEvents, recEvents).enumerated() {
#expect(abs(orig.velocity - rec.velocity) < 1e-6,
"velocity mismatch at event \(idx): orig=\(orig.velocity) rec=\(rec.velocity)")
}
}
@Test func singleVoiceAllSameDynamicOneDirectionNoRegression() throws {
// A single-voice part where every note has the same dynamic must emit
// exactly ONE <direction> at the head. All <duration> tick values must
// be unchanged from the pre-dynamics-direction encoding.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .mf)
Note(.d, 4, dur: .quarter, dyn: .mf)
Note(.e, 4, dur: .half, dyn: .mf)
}
}
let xml: String = score.toMusicXMLString(divisions: 480)
// Exactly one direction.
let dirCount: Int = xml.components(
separatedBy: "<direction placement=\"below\">"
).count - 1
#expect(dirCount == 1,
"all-same-dynamic part must emit exactly 1 direction; got \(dirCount);\n\(xml)")
// Tick values unchanged: quarter=480, half=960.
let quarterCount: Int = xml.components(
separatedBy: "<duration>480</duration>"
).count - 1
let halfCount: Int = xml.components(
separatedBy: "<duration>960</duration>"
).count - 1
#expect(quarterCount == 2,
"must have 2 quarter-note <duration>480</duration>; got \(quarterCount);\n\(xml)")
#expect(halfCount == 1,
"must have 1 half-note <duration>960</duration>; got \(halfCount);\n\(xml)")
// Round-trip preserves events.
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let recEvents: [ScoreEvent] = recovered.parts[0].flatten()
#expect(recEvents.count == 3,
"round-trip must yield 3 events; got \(recEvents.count)")
}
@Test func barlineSplitNoteEmitsDirectionOnlyOnFirstPiece() {
// A .ff whole note (4 beats) in 3/4 splits across a barline into tied
// head + tail. The dynamic <direction> must be emitted ONCE (before the
// head in measure 1), NOT again before the tied continuation in measure
// 2 — the isTiedContinuation flag suppresses the duplicate.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(3, 4)) {
Part("p") {
Note(.c, 4, dur: .whole, dyn: .ff)
}
}
let xml: String = score.toMusicXMLString()
let dirCount: Int = xml.components(
separatedBy: "<direction placement=\"below\">"
).count - 1
#expect(dirCount == 1,
"barline-split note must emit exactly 1 dynamic direction; got \(dirCount);\n\(xml)")
}
@Test func multiVoiceIdenticalDynamicCollapsesByDefaultButNotWhenDisabled() {
// Both voices open at the SAME dynamic (.mf) on the same staff and onset.
// By default (collapseRedundantDynamics: true) they merge into ONE
// <direction>; with the flag disabled the per-voice change-only tracker
// emits one direction per voice (voice 1's tracker does not suppress
// voice 2's first).
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("piano") {
Voice(1) { Note(.e, 5, dur: .whole, dyn: .mf) }
Voice(2) { Note(.c, 4, dur: .whole, dyn: .mf) }
}
}
let needle: String = "<direction placement=\"below\">"
let collapsed: String = score.toMusicXMLString()
let collapsedCount: Int = collapsed.components(separatedBy: needle).count - 1
#expect(collapsedCount == 1,
"identical dynamics on one staff must collapse to 1 direction; got \(collapsedCount);\n\(collapsed)")
let raw: String = score.toMusicXMLString(collapseRedundantDynamics: false)
let rawCount: Int = raw.components(separatedBy: needle).count - 1
#expect(rawCount == 2,
"with collapse disabled each voice emits its own direction; got \(rawCount);\n\(raw)")
}
@Test func rawDynamicWithManyDigitsRoundTripsExactly() throws {
// .raw values with more than 3 significant digits must round-trip
// within tight tolerance — the encoder uses Swift's shortest
// round-trippable Double description, not a fixed 3dp format.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .raw(0.123456))
Note(.d, 4, dur: .quarter, dyn: .raw(0.987654))
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let recEvents: [ScoreEvent] = recovered.parts[0].flatten()
let origEvents: [ScoreEvent] = original.parts[0].flatten()
#expect(recEvents.count == origEvents.count)
for (o, r): (ScoreEvent, ScoreEvent) in zip(origEvents, recEvents) {
#expect(abs(o.velocity - r.velocity) < 1e-9,
"raw dynamic velocity must round-trip exactly; \(o.velocity) vs \(r.velocity)")
}
}
// MARK: - KeySignature
// MARK: KeySignature init and named statics
@Test func keySignatureInitPreconditionRange() {
// Named statics: spot-check fifths values.
#expect(KeySignature.cMajor.fifths == 0)
#expect(KeySignature.gMajor.fifths == 1)
#expect(KeySignature.fMajor.fifths == -1)
#expect(KeySignature.dMajor.fifths == 2)
#expect(KeySignature.bFlatMajor.fifths == -2)
#expect(KeySignature.eFlatMajor.fifths == -3)
#expect(KeySignature.cSharpMajor.fifths == 7)
#expect(KeySignature.cFlatMajor.fifths == -7)
#expect(KeySignature.aMinor.fifths == 0)
#expect(KeySignature.aMinor.mode == .minor)
#expect(KeySignature.eMinor.fifths == 1)
#expect(KeySignature.gMinor.fifths == -2)
#expect(KeySignature.aFlatMinor.fifths == -7)
#expect(KeySignature.aFlatMinor.mode == .minor)
}
@Test func keySignatureHashableAndSendable() {
// KeySignature is Hashable — two instances with same fifths+mode must be equal.
let a: KeySignature = KeySignature(fifths: 1, mode: .major)
let b: KeySignature = KeySignature.gMajor
#expect(a == b)
let c: KeySignature = KeySignature(fifths: 1, mode: .minor)
#expect(a != c)
}
@Test func keySignatureDefaultOnScore() {
// Score.keySignature defaults to .cMajor when omitted.
let score: Score = Score(bpm: 120) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
#expect(score.keySignature == .cMajor)
#expect(score.keySignature.fifths == 0)
#expect(score.keySignature.mode == .major)
}
// MARK: Encoder — <key> element placement and content
@Test func encodeGMajorEmitsKeyElement() {
let score: Score = Score(bpm: 120, keySignature: .gMajor) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<key>"), "must emit <key> element; got:\n\(xml)")
#expect(xml.contains("<fifths>1</fifths>"), "gMajor must emit <fifths>1</fifths>; got:\n\(xml)")
#expect(xml.contains("<mode>major</mode>"), "gMajor must emit <mode>major</mode>; got:\n\(xml)")
}
@Test func encodeCMajorEmitsFifthsZero() {
// Default C major must still emit <fifths>0</fifths>.
let score: Score = Score(bpm: 120) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<fifths>0</fifths>"), "cMajor must emit <fifths>0</fifths>; got:\n\(xml)")
#expect(xml.contains("<mode>major</mode>"), "cMajor must emit <mode>major</mode>; got:\n\(xml)")
}
@Test func encodeKeyPositionedAfterDivisionsAndBeforeTime() {
// MusicXML 4.0 <attributes> child order: divisions, key, time, clef.
let score: Score = Score(bpm: 120, keySignature: .gMajor) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
let divisionsRange: Range<String.Index>? = xml.range(of: "<divisions>")
let keyRange: Range<String.Index>? = xml.range(of: "<key>")
let timeRange: Range<String.Index>? = xml.range(of: "<time>")
#expect(divisionsRange != nil, "<divisions> must be present")
#expect(keyRange != nil, "<key> must be present")
#expect(timeRange != nil, "<time> must be present")
if let divIdx: Range<String.Index> = divisionsRange,
let keyIdx: Range<String.Index> = keyRange,
let timeIdx: Range<String.Index> = timeRange {
#expect(divIdx.lowerBound < keyIdx.lowerBound,
"<divisions> must appear before <key>; got:\n\(xml)")
#expect(keyIdx.lowerBound < timeIdx.lowerBound,
"<key> must appear before <time>; got:\n\(xml)")
}
}
@Test func encodeMinorKeyEmitsMinorMode() {
let score: Score = Score(bpm: 120, keySignature: .aMinor) {
Part("p") { Note(.a, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<fifths>0</fifths>"), "aMinor must emit <fifths>0</fifths>; got:\n\(xml)")
#expect(xml.contains("<mode>minor</mode>"), "aMinor must emit <mode>minor</mode>; got:\n\(xml)")
}
@Test func encodeFlatMajorKeyEmitsNegativeFifths() {
let score: Score = Score(bpm: 120, keySignature: .eFlatMajor) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<fifths>-3</fifths>"),
"eFlatMajor must emit <fifths>-3</fifths>; got:\n\(xml)")
}
@Test func encodeKeyAppearsInAllParts() {
// Score-level key: every part's measure-1 attributes must contain <key>.
let score: Score = Score(bpm: 120, keySignature: .dMajor) {
Part("lead") { Note(.d, 5, dur: .quarter) }
Part("bass", channel: 1, clef: .bass) { Note(.d, 2, dur: .whole) }
}
let xml: String = score.toMusicXMLString()
// Count occurrences of <fifths>2</fifths> — should be 2 (one per part).
let fifthsCount: Int = xml.components(separatedBy: "<fifths>2</fifths>").count - 1
#expect(fifthsCount == 2,
"dMajor (fifths=2) must appear in every part's attributes; count=\(fifthsCount) in:\n\(xml)")
}
// MARK: Parser — <key> element reading
@Test func parseKeySignatureGMajor() 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>
<key><fifths>1</fifths><mode>major</mode></key>
<time><beats>4</beats><beat-type>4</beat-type></time>
</attributes>
<note>
<pitch><step>G</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.keySignature.fifths == 1)
#expect(score.keySignature.mode == .major)
}
@Test func parseKeySignatureMinor() 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>
<key><fifths>-2</fifths><mode>minor</mode></key>
</attributes>
<note>
<pitch><step>G</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.keySignature.fifths == -2)
#expect(score.keySignature.mode == .minor)
}
@Test func parseKeylessDocumentDefaultsCMajor() throws {
// A document with no <key> element must default to .cMajor.
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>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.keySignature == .cMajor,
"key-less document must default to cMajor; got \(score.keySignature)")
}
@Test func parseModeDefaultsMajorWhenAbsent() throws {
// <key> with only <fifths> — no <mode> — should default to .major.
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>
<key><fifths>3</fifths></key>
</attributes>
<note>
<pitch><step>A</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.keySignature.fifths == 3)
#expect(score.keySignature.mode == .major,
"missing <mode> should default to .major")
}
// MARK: Round-trip — KeySignature
@Test func roundTripKeySignatureEFlatMajor() throws {
let original: Score = Score(bpm: 120, keySignature: .eFlatMajor) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(recovered.keySignature == .eFlatMajor,
"eFlatMajor must round-trip; got \(recovered.keySignature)")
#expect(recovered.keySignature.fifths == -3)
#expect(recovered.keySignature.mode == .major)
}
@Test func roundTripKeySignatureMinorKey() throws {
// Minor key round-trip preserves mode.
let original: Score = Score(bpm: 120, keySignature: .gSharpMinor) {
Part("p") { Note(.g, 4, dur: .quarter) }
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(recovered.keySignature.fifths == 5)
#expect(recovered.keySignature.mode == .minor,
"minor mode must survive round-trip; got \(recovered.keySignature.mode)")
}
@Test func keySignatureDoesNotPerturpDurations() {
// Adding a key signature must not change <duration> tick values.
let noKey: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .eighth)
Note(.e, 4, dur: .half)
}
}
let withKey: Score = Score(bpm: 120, keySignature: .bFlatMajor) {
Part("p") {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .eighth)
Note(.e, 4, dur: .half)
}
}
// Extract <duration> values from both XMLs and compare.
let xmlNoKey: String = noKey.toMusicXMLString(divisions: 480)
let xmlWithKey: String = withKey.toMusicXMLString(divisions: 480)
#expect(xmlNoKey.contains("<duration>480</duration>"))
#expect(xmlWithKey.contains("<duration>480</duration>"))
#expect(xmlNoKey.contains("<duration>240</duration>"))
#expect(xmlWithKey.contains("<duration>240</duration>"))
#expect(xmlNoKey.contains("<duration>960</duration>"))
#expect(xmlWithKey.contains("<duration>960</duration>"))
}
// MARK: - Wedge (hairpin) support
@Test func wedgeFlattenTransparency() {
// A Crescendo{N notes} must flatten to EXACTLY the same events as
// the unwrapped notes — wedge is purely notational.
let withWedge: Score = Score(bpm: 120) {
Part("p") {
Crescendo {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
}
}
let withoutWedge: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
}
let wedgeEvents: [ScoreEvent] = withWedge.parts[0].flatten()
let plainEvents: [ScoreEvent] = withoutWedge.parts[0].flatten()
#expect(wedgeEvents.count == plainEvents.count,
"Crescendo must produce same event count as unwrapped notes")
for i: Int in 0..<wedgeEvents.count {
#expect(wedgeEvents[i].beat == plainEvents[i].beat,
"beat at index \(i) must match; wedge must not alter timing")
#expect(wedgeEvents[i].pitch.midiNote == plainEvents[i].pitch.midiNote,
"pitch at index \(i) must match")
#expect(wedgeEvents[i].velocity == plainEvents[i].velocity,
"velocity at index \(i) must match; wedge must not alter dynamics")
}
}
@Test func diminuendoFlattenTransparency() {
// Diminuendo must also be transparent to flatten.
let withWedge: Score = Score(bpm: 120) {
Part("p") {
Diminuendo {
Note(.f, 5, dur: .quarter, dyn: .f)
Note(.e, 5, dur: .quarter)
Note(.d, 5, dur: .quarter, dyn: .p)
}
}
}
let withoutWedge: Score = Score(bpm: 120) {
Part("p") {
Note(.f, 5, dur: .quarter, dyn: .f)
Note(.e, 5, dur: .quarter)
Note(.d, 5, dur: .quarter, dyn: .p)
}
}
let wedgeEvents: [ScoreEvent] = withWedge.parts[0].flatten()
let plainEvents: [ScoreEvent] = withoutWedge.parts[0].flatten()
#expect(wedgeEvents.count == plainEvents.count)
for i: Int in 0..<wedgeEvents.count {
#expect(wedgeEvents[i].beat == plainEvents[i].beat)
#expect(wedgeEvents[i].pitch.midiNote == plainEvents[i].pitch.midiNote)
#expect(wedgeEvents[i].velocity == plainEvents[i].velocity)
}
}
@Test func crescendoEmitsWedgeCrescendoStart() {
// Crescendo must emit <wedge type="crescendo"/> before the first note.
let score: Score = Score(bpm: 120) {
Part("p") {
Crescendo {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter, dyn: .f)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<wedge type=\"crescendo\"/>"),
"Crescendo must emit <wedge type=\"crescendo\"/>; got:\n\(xml)")
#expect(xml.contains("<wedge type=\"stop\"/>"),
"Crescendo must emit matching <wedge type=\"stop\"/>; got:\n\(xml)")
}
@Test func diminuendoEmitsWedgeDiminuendoStart() {
// Diminuendo must emit <wedge type="diminuendo"/> before the first note.
let score: Score = Score(bpm: 120) {
Part("p") {
Diminuendo {
Note(.f, 5, dur: .quarter, dyn: .f)
Note(.e, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.c, 5, dur: .quarter, dyn: .p)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<wedge type=\"diminuendo\"/>"),
"Diminuendo must emit <wedge type=\"diminuendo\"/>; got:\n\(xml)")
#expect(xml.contains("<wedge type=\"stop\"/>"),
"Diminuendo must emit matching <wedge type=\"stop\"/>; got:\n\(xml)")
}
@Test func wedgeStartAppearsBeforeFirstNoteStop() {
// The wedge-start direction must appear BEFORE the first note's <pitch>;
// the wedge-stop direction must appear AFTER the last note's <pitch>.
let score: Score = Score(bpm: 120) {
Part("p") {
Crescendo {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
}
}
}
let xml: String = score.toMusicXMLString()
let startRange: Range<String.Index>? = xml.range(of: "<wedge type=\"crescendo\"/>")
let stopRange: Range<String.Index>? = xml.range(of: "<wedge type=\"stop\"/>")
let firstPitchRange: Range<String.Index>? = xml.range(of: "<step>C</step>")
let lastPitchRange: Range<String.Index>? = xml.range(of: "<step>D</step>")
guard let s: Range<String.Index> = startRange,
let stop: Range<String.Index> = stopRange,
let fp: Range<String.Index> = firstPitchRange,
let lp: Range<String.Index> = lastPitchRange else {
Issue.record("Missing expected wedge or pitch elements in:\n\(xml)")
return
}
#expect(s.lowerBound < fp.lowerBound,
"wedge-start must appear before first note pitch")
#expect(stop.lowerBound > lp.lowerBound,
"wedge-stop must appear after last note pitch")
}
@Test func wedgeCountIsBalanced() {
// For a single wedge span, the number of start events must equal
// the number of stop events (one of each).
let score: Score = Score(bpm: 120) {
Part("p") {
Crescendo {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
}
}
let xml: String = score.toMusicXMLString()
let crescendoCount: Int = xml.components(separatedBy: "<wedge type=\"crescendo\"/>").count - 1
let stopCount: Int = xml.components(separatedBy: "<wedge type=\"stop\"/>").count - 1
#expect(crescendoCount == 1, "exactly one crescendo wedge-start expected; got \(crescendoCount)")
#expect(stopCount == 1, "exactly one wedge-stop expected; got \(stopCount)")
}
@Test func singleNoteWedgeIsBalanced() {
// A one-note wedge span exercises the start+stop-on-same-atom path
// (withWedgeStartStop): exactly one start and one stop must be emitted.
let score: Score = Score(bpm: 120) {
Part("p") {
Diminuendo {
Note(.c, 5, dur: .quarter)
}
}
}
let xml: String = score.toMusicXMLString()
let dimCount: Int = xml.components(separatedBy: "<wedge type=\"diminuendo\"/>").count - 1
let stopCount: Int = xml.components(separatedBy: "<wedge type=\"stop\"/>").count - 1
#expect(dimCount == 1, "single-note wedge must emit one diminuendo start; got \(dimCount);\n\(xml)")
#expect(stopCount == 1, "single-note wedge must emit one stop; got \(stopCount);\n\(xml)")
}
@Test func wedgeDoesNotAffectDurations() {
// A Crescendo{notes} must produce the SAME <duration> values as the
// unwrapped notes — the wedge annotation is notational only.
let withWedge: Score = Score(bpm: 120) {
Part("p") {
Crescendo {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .half)
}
}
}
let withoutWedge: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .half)
}
}
let xmlW: String = withWedge.toMusicXMLString(divisions: 480)
let xmlN: String = withoutWedge.toMusicXMLString(divisions: 480)
// Extract all <duration> values.
func durations(from xml: String) -> [String] {
let pattern: String = "<duration>"
var result: [String] = []
var remaining: String = xml
while let start: Range<String.Index> = remaining.range(of: "<duration>"),
let end: Range<String.Index> = remaining.range(of: "</duration>",
range: start.upperBound..<remaining.endIndex) {
result.append(String(remaining[start.upperBound..<end.lowerBound]))
remaining = String(remaining[end.upperBound...])
}
return result
}
#expect(durations(from: xmlW) == durations(from: xmlN),
"wedge must not alter <duration> values")
}
@Test func wedgeCoexistsWithDynamicDirection() {
// A note with both a dynamic and a wedge-start must emit BOTH
// a <dynamics> direction and a <wedge> direction, in either order.
let score: Score = Score(bpm: 120) {
Part("p") {
Crescendo {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.f, 5, dur: .quarter, dyn: .f)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<dynamics>"), "dynamic direction must be present")
#expect(xml.contains("<wedge type=\"crescendo\"/>"), "wedge start must be present")
#expect(xml.contains("<wedge type=\"stop\"/>"), "wedge stop must be present")
// The XML must be well-formed: no doubled start without stop.
let crescendoCount: Int = xml.components(separatedBy: "<wedge type=\"crescendo\"/>").count - 1
let stopCount: Int = xml.components(separatedBy: "<wedge type=\"stop\"/>").count - 1
#expect(crescendoCount == stopCount, "wedge starts and stops must be balanced")
}
@Test func wedgeEventRoundTrip() throws {
// A Crescendo{N notes} must round-trip (encode→decode) to the same
// flattened EVENT count and pitches. Wedges are transparent to flatten.
let original: Score = Score(bpm: 120) {
Part("p") {
Crescendo {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter, dyn: .f)
}
}
}
let data: Data = original.toMusicXMLData()
let recovered: Score = try Score.fromMusicXML(data: data)
let origEvents: [ScoreEvent] = original.allEvents
let rtEvents: [ScoreEvent] = recovered.allEvents
#expect(origEvents.count == rtEvents.count,
"event count must be preserved across encode→decode round-trip")
for i: Int in 0..<min(origEvents.count, rtEvents.count) {
#expect(origEvents[i].pitch.midiNote == rtEvents[i].pitch.midiNote,
"pitch at index \(i) must be preserved")
#expect(abs(origEvents[i].beat - rtEvents[i].beat) < 1e-9,
"beat at index \(i) must be preserved")
}
}
@Test func multipleCrescendoDiminuendoRoundTrip() throws {
// Two separate wedge spans (one crescendo, one diminuendo) must both
// encode and round-trip correctly.
let original: Score = Score(bpm: 120) {
Part("p") {
Crescendo {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.d, 5, dur: .quarter)
}
Diminuendo {
Note(.e, 5, dur: .quarter, dyn: .f)
Note(.c, 5, dur: .quarter, dyn: .mp)
}
}
}
let xml: String = original.toMusicXMLString()
#expect(xml.contains("<wedge type=\"crescendo\"/>"),
"crescendo wedge must be present")
#expect(xml.contains("<wedge type=\"diminuendo\"/>"),
"diminuendo wedge must be present")
let stopCount: Int = xml.components(separatedBy: "<wedge type=\"stop\"/>").count - 1
#expect(stopCount == 2, "two wedge spans require two stops; got \(stopCount)")
// Event round-trip.
let data: Data = original.toMusicXMLData()
let recovered: Score = try Score.fromMusicXML(data: data)
#expect(original.allEvents.count == recovered.allEvents.count,
"event count must survive encode→decode round-trip")
}
@Test func wedgeInMultiVoicePart() {
// A Crescendo inside a Voice block must still emit wedge directions.
let score: Score = Score(bpm: 120) {
Part("piano") {
Voice(1) {
Crescendo {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.d, 5, dur: .quarter, dyn: .f)
}
}
Voice(2) {
Note(.c, 4, dur: .half, dyn: .mp)
}
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<wedge type=\"crescendo\"/>"),
"crescendo wedge must appear in multi-voice part; got:\n\(xml)")
#expect(xml.contains("<wedge type=\"stop\"/>"),
"wedge stop must appear in multi-voice part; got:\n\(xml)")
// Flatten must be transparent regardless of voice context.
let events: [ScoreEvent] = score.parts[0].flatten()
// Voice 1: 2 notes; Voice 2: 1 note = 3 total.
#expect(events.count == 3, "multi-voice with wedge must flatten to 3 events")
}
// MARK: - Authored ties
// MARK: Flatten merge
@Test func tiedPairFlattensToOneEventWithSummedDuration() {
// Quarter tied to eighth → one event of 1.5 beats.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, tie: true)
Note(.c, 4, dur: .eighth)
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 1, "tied pair must collapse to one event; got \(events.count)")
let expectedDur: Double = 1.5 // quarter (1.0) + eighth (0.5)
#expect(abs(events[0].duration - expectedDur) < 1e-9,
"merged duration must be 1.5 beats; got \(events[0].duration)")
#expect(events[0].beat == 0.0, "merged event starts at beat 0")
#expect(events[0].pitch == Pitch.named(.c, 4), "merged pitch must be C4")
}
@Test func threeNoteTieChainFlattensToOneEventWithSummedDuration() {
// Quarter → eighth → sixteenth = 1.0 + 0.5 + 0.25 = 1.75 beats.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.g, 5, dur: .quarter, tie: true)
Note(.g, 5, dur: .eighth, tie: true)
Note(.g, 5, dur: .sixteenth)
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 1, "three-note tie chain must collapse to one event; got \(events.count)")
let expectedDur: Double = 1.75
#expect(abs(events[0].duration - expectedDur) < 1e-9,
"three-note tied duration must be 1.75 beats; got \(events[0].duration)")
}
@Test func tieTruePitchMismatchProducesTwoSeparateEvents() {
// tie==true but next note has a DIFFERENT pitch → no merge, two events.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, tie: true)
Note(.d, 4, dur: .quarter)
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 2, "pitch-mismatch tie must produce 2 events; got \(events.count)")
#expect(abs(events[0].duration - 1.0) < 1e-9, "first event duration 1.0; got \(events[0].duration)")
#expect(abs(events[1].duration - 1.0) < 1e-9, "second event duration 1.0; got \(events[1].duration)")
}
@Test func untiedNoteEncodingUnchanged() {
// A note without tie: false must produce identical output to the old behavior.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.e, 4, dur: .half, dyn: .mp)
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 1)
#expect(abs(events[0].duration - 2.0) < 1e-9, "half note = 2 beats")
// No <tie> in XML for untied note.
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<tie"), "untied note must not emit <tie>; got:\n\(xml)")
}
// MARK: Encoder: tie XML emission
@Test func tiedPairEmitsTieStartOnFirstAndStopOnSecond() {
// A quarter tied to an eighth must emit <tie type="start"/> on the first note
// and <tie type="stop"/> on the second.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, tie: true)
Note(.c, 4, dur: .eighth)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<tie type=\"start\"/>"),
"first note of tied pair must emit <tie type=\"start\"/>; got:\n\(xml)")
#expect(xml.contains("<tie type=\"stop\"/>"),
"second note of tied pair must emit <tie type=\"stop\"/>; got:\n\(xml)")
#expect(xml.contains("<tied type=\"start\"/>"),
"first note of tied pair must emit <tied type=\"start\"/> in notations; got:\n\(xml)")
#expect(xml.contains("<tied type=\"stop\"/>"),
"second note of tied pair must emit <tied type=\"stop\"/> in notations; got:\n\(xml)")
}
@Test func pitchMismatchTieEmitsNoTieElements() {
// A tie==true note followed by a different pitch must NOT emit any <tie> elements.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, tie: true)
Note(.d, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<tie type=\"start\"/>"),
"pitch-mismatch tie must not emit <tie type=\"start\"/>; got:\n\(xml)")
#expect(!xml.contains("<tie type=\"stop\"/>"),
"pitch-mismatch tie must not emit <tie type=\"stop\"/>; got:\n\(xml)")
}
// MARK: Round-trip
@Test func tiedPairRoundTripsToOneEventWithSummedDuration() throws {
// Encode a tied quarter+eighth, parse back, flatten — must produce ONE event
// of 1.5 beats (same as the flatten test above).
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, tie: true)
Note(.c, 4, dur: .eighth)
}
}
let xmlData: Data = score.toMusicXMLData()
let roundTripped: Score = try Score.fromMusicXML(data: xmlData)
let events: [ScoreEvent] = roundTripped.parts[0].flatten()
#expect(events.count == 1,
"round-tripped tied pair must produce 1 event; got \(events.count)")
let expectedDur: Double = 1.5
#expect(abs(events[0].duration - expectedDur) < 1e-9,
"round-trip event duration must be 1.5 beats; got \(events[0].duration)")
#expect(events[0].pitch == Pitch.named(.c, 4), "round-trip pitch must be C4")
}
// MARK: No-regression: existing barline-split tie behavior unchanged
@Test func barlineSplitTieNotAffectedByAuthoredTieChange() throws {
// A whole note in 4/4 is fine; a 5-beat note must cross the barline and
// get barline-split with ties. Authored tie must not interfere.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
// whole note (4 beats) + quarter (1 beat) = 5 beats → 2 measures
Note(.f, 4, dur: .whole)
Note(.f, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// The 4/4 score has exactly 2 measures; no authored ties involved.
#expect(xml.contains("<measure number=\"2\">"),
"second measure must be present; got:\n\(xml)")
// No authored tie flags were set, so no authored tie XML should appear
// (barline-split ties are emitted by the existing mechanism; not counted here).
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 2, "two separate untied notes must produce 2 events; got \(events.count)")
}
// MARK: - Authored ties fix tests
@Test func tieAsLastElementEmitsNoTieXML() {
// A note with tie:true that is the only/last element has no matching successor.
// The annotateTieAuthored pass must clear tieAuthoredStart so no <tie> is emitted.
let score: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, tie: true)
}
}
let xml: String = score.toMusicXMLString()
// No <tie> element of any kind must appear — the dangling tie is suppressed.
#expect(!xml.contains("<tie"),
"dangling tie (last element) must not emit <tie>; got:\n\(xml)")
// The note still appears in the score.
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 1, "single tie:true note must produce 1 event; got \(events.count)")
}
@Test func authoredTieComposesWithBarlineSplit() {
// In 4/4, a half note (tie:true) followed by a dotted-half (3 beats) that
// crosses the barline. Layout:
// Bar 1: half C4 [tie:true] (beats 0-2) +
// half C4 (beats 2-4, first piece of the dotted-half)
// Bar 2: quarter C4 (beat 0-1, second piece of the dotted-half)
//
// Authored tie: A (half, tie:true) → B (dotted-half).
// Barline tie: B1 (half, bar 1) → B2 (quarter, bar 2).
//
// Expected tie elements in the XML (each piece):
// A: <tie type="start"/> (authored, leaves from last notehead of A)
// B1: <tie type="stop"/> (authored, arrives at first notehead of B)
// <tie type="start"/> (barline, leaves from last notehead of B1)
// B2: <tie type="stop"/> (barline, arrives at first notehead of B2)
//
// Total: 2 starts, 2 stops.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Note(.c, 4, dur: .half, tie: true)
Note(.c, 4, dur: .dotted(.half))
}
}
let xml: String = score.toMusicXMLString()
// Count start and stop tie elements — must be balanced (2 each).
let startCount: Int = xml.components(separatedBy: "<tie type=\"start\"/>").count - 1
let stopCount: Int = xml.components(separatedBy: "<tie type=\"stop\"/>").count - 1
#expect(startCount == stopCount,
"tie starts (\(startCount)) must equal tie stops (\(stopCount)); got:\n\(xml)")
#expect(startCount == 2,
"expected exactly 2 tie starts (1 authored + 1 barline); got \(startCount);\n\(xml)")
#expect(stopCount == 2,
"expected exactly 2 tie stops (1 authored + 1 barline); got \(stopCount);\n\(xml)")
// Second measure must be present (barline split happened).
#expect(xml.contains("<measure number=\"2\">"),
"barline split must produce measure 2; got:\n\(xml)")
// Flatten round-trip: the authored tie merges A + B into 1 event of 5 beats
// (half = 2 beats, dotted-half = 3 beats).
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 1,
"authored tied pair must flatten to 1 event; got \(events.count)")
let expectedDuration: Double = 5.0 // 2 + 3 beats
#expect(abs(events[0].duration - expectedDuration) < 1e-9,
"merged duration must be 5.0 beats; got \(events[0].duration)")
}
// MARK: - Chord ties
// MARK: Flatten merge
@Test func tiedChordPairFlattensToMergedEventsWithSummedDuration() {
// A whole-note C major chord tied to a half-note C major chord:
// each pitch should produce ONE event of 1.0 + 0.5 = 1.5 beats.
// Pitch count (3) events total — not 6.
let score: Score = Score(bpm: 120) {
Part("p") {
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .quarter, tie: true)
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .eighth)
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
// 3 pitches × 1 merged event each = 3 events total (not 6).
#expect(events.count == 3,
"tied chord pair must produce pitch-count events (not 2×); got \(events.count)")
let expectedDur: Double = 1.5 // quarter (1.0) + eighth (0.5)
for event: ScoreEvent in events {
#expect(abs(event.duration - expectedDur) < 1e-9,
"every pitch must have merged duration 1.5; got \(event.duration) for \(event.pitch)")
#expect(abs(event.beat - 0.0) < 1e-9,
"every pitch must start at beat 0; got \(event.beat)")
}
// All three pitches present.
let pitchSet: Set<Pitch> = Set(events.map { $0.pitch })
#expect(pitchSet.contains(.named(.c, 4)), "merged chord must include C4")
#expect(pitchSet.contains(.named(.e, 4)), "merged chord must include E4")
#expect(pitchSet.contains(.named(.g, 4)), "merged chord must include G4")
}
@Test func tiedChordPitchSetMismatchProducesUnmergedEvents() {
// Chord tie where the follower has a DIFFERENT pitch set → no merge.
// 2 chords × 3 pitches each = 6 events.
let score: Score = Score(bpm: 120) {
Part("p") {
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .quarter, tie: true)
Chord([(.c, 4), (.f, 4), (.a, 4)], dur: .quarter)
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 6,
"pitch-set mismatch chord tie must produce 6 events; got \(events.count)")
// First chord at beat 0.
let beat0: [ScoreEvent] = events.filter { abs($0.beat - 0.0) < 1e-9 }
let beat1: [ScoreEvent] = events.filter { abs($0.beat - 1.0) < 1e-9 }
#expect(beat0.count == 3, "first chord must have 3 pitches at beat 0; got \(beat0.count)")
#expect(beat1.count == 3, "second chord must have 3 pitches at beat 1; got \(beat1.count)")
}
@Test func threeChordTieChainFlattensToSummedDuration() {
// Three-chord tie chain: quarter + eighth + sixteenth = 1.75 beats per pitch.
let score: Score = Score(bpm: 120) {
Part("p") {
Chord([(.c, 4), (.e, 4)], dur: .quarter, tie: true)
Chord([(.c, 4), (.e, 4)], dur: .eighth, tie: true)
Chord([(.c, 4), (.e, 4)], dur: .sixteenth)
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 2,
"three-chord tie chain must collapse to pitch-count events; got \(events.count)")
let expectedDur: Double = 1.75 // 1.0 + 0.5 + 0.25
for event: ScoreEvent in events {
#expect(abs(event.duration - expectedDur) < 1e-9,
"chain-merged pitch must be 1.75 beats; got \(event.duration)")
}
}
@Test func fourChordChainTerminatesAtUntiedMember() {
// A.tie → B.tie → C(untied) → D: the chain must STOP at C; D must NOT
// merge in. Exercises per-run tie-flag re-evaluation in the chain loop.
let score: Score = Score(bpm: 120) {
Part("p") {
Chord([(.c, 4), (.e, 4)], dur: .quarter, tie: true)
Chord([(.c, 4), (.e, 4)], dur: .eighth, tie: true)
Chord([(.c, 4), (.e, 4)], dur: .sixteenth) // chain ends here
Chord([(.c, 4), (.e, 4)], dur: .eighth) // must remain separate
}
}
let events: [ScoreEvent] = score.parts[0].flatten()
// Merged A+B+C (1.75 beats) × 2 pitches + separate D (0.5 beats) × 2 = 4 events.
#expect(events.count == 4,
"chain must stop at untied C; D stays separate; got \(events.count)")
let mergedDur: Double = 1.75 // quarter + eighth + sixteenth
let separateDur: Double = 0.5 // eighth
let merged: Int = events.filter { abs($0.duration - mergedDur) < 1e-9 }.count
let separate: Int = events.filter { abs($0.duration - separateDur) < 1e-9 }.count
#expect(merged == 2, "merged A+B+C group must have 2 pitches; got \(merged)")
#expect(separate == 2, "separate D must have 2 pitches; got \(separate)")
}
// MARK: Encoder: tie XML emission per notehead
@Test func tiedChordEmitsTieStartOnEveryNotehead() {
// A tied whole-note chord (3 pitches) must emit <tie type="start"/> on
// ALL three noteheads (lead + 2 chord-mates), not just the lead.
let score: Score = Score(bpm: 120) {
Part("p") {
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .quarter, tie: true)
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .eighth)
}
}
let xml: String = score.toMusicXMLString()
let startCount: Int = xml.components(separatedBy: "<tie type=\"start\"/>").count - 1
let stopCount: Int = xml.components(separatedBy: "<tie type=\"stop\"/>").count - 1
// 3 noteheads in the first chord → 3 starts;
// 3 noteheads in the second chord → 3 stops.
#expect(startCount == 3,
"tied chord (3 pitches) must emit 3 <tie type=\"start\"/>; got \(startCount);\n\(xml)")
#expect(stopCount == 3,
"follower chord (3 pitches) must emit 3 <tie type=\"stop\"/>; got \(stopCount);\n\(xml)")
// Corresponding <tied> notations elements.
let tiedStartCount: Int = xml.components(separatedBy: "<tied type=\"start\"/>").count - 1
let tiedStopCount: Int = xml.components(separatedBy: "<tied type=\"stop\"/>").count - 1
#expect(tiedStartCount == 3,
"tied chord must emit 3 <tied type=\"start\"/>; got \(tiedStartCount);\n\(xml)")
#expect(tiedStopCount == 3,
"follower chord must emit 3 <tied type=\"stop\"/>; got \(tiedStopCount);\n\(xml)")
}
@Test func pitchSetMismatchChordTieEmitsNoTieElements() {
// A tie==true chord followed by a different-pitch-set chord must not
// emit any <tie> elements.
let score: Score = Score(bpm: 120) {
Part("p") {
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .quarter, tie: true)
Chord([(.c, 4), (.f, 4), (.a, 4)], dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<tie type=\"start\"/>"),
"pitch-set mismatch chord tie must not emit <tie type=\"start\"/>; got:\n\(xml)")
#expect(!xml.contains("<tie type=\"stop\"/>"),
"pitch-set mismatch chord tie must not emit <tie type=\"stop\"/>; got:\n\(xml)")
}
// MARK: Round-trip
@Test func tiedChordRoundTripsToMergedEvents() throws {
// Encode a tied chord pair, parse back, flatten — must produce pitch-count
// events of the summed duration (same as flatten-only test above).
let score: Score = Score(bpm: 120) {
Part("p") {
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .quarter, tie: true)
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .eighth)
}
}
let xmlData: Data = score.toMusicXMLData()
let roundTripped: Score = try Score.fromMusicXML(data: xmlData)
let events: [ScoreEvent] = roundTripped.parts[0].flatten()
// The parser merges tie-stop noteheads back into the prior chord,
// so the round-tripped score is one merged chord: 3 events.
#expect(events.count == 3,
"round-tripped tied chord must produce 3 events; got \(events.count)")
let expectedDur: Double = 1.5
for event: ScoreEvent in events {
#expect(abs(event.duration - expectedDur) < 1e-9,
"round-trip event must be 1.5 beats; got \(event.duration)")
}
let pitchSet: Set<Pitch> = Set(events.map { $0.pitch })
#expect(pitchSet.contains(.named(.c, 4)), "round-trip must include C4")
#expect(pitchSet.contains(.named(.e, 4)), "round-trip must include E4")
#expect(pitchSet.contains(.named(.g, 4)), "round-trip must include G4")
}
// MARK: No-regression: existing chord encoding unchanged
@Test func untiedChordEncodingUnchanged() {
// A chord without tie must produce exactly the same output as before chord-tie support.
let score: Score = Score(bpm: 120) {
Part("p") {
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .half)
}
}
let xml: String = score.toMusicXMLString()
// No tie elements whatsoever.
#expect(!xml.contains("<tie"), "untied chord must not emit <tie>; got:\n\(xml)")
// 2 <chord/> flags (lead is not flagged; 2nd and 3rd pitches are).
let chordFlagCount: Int = xml.components(separatedBy: "<chord/>").count - 1
#expect(chordFlagCount == 2,
"3-pitch chord must emit 2 <chord/> flags; got \(chordFlagCount);\n\(xml)")
// Events: 3 separate events (no merge because not tied).
let events: [ScoreEvent] = score.parts[0].flatten()
#expect(events.count == 3,
"untied chord must produce 3 separate events; got \(events.count)")
}
// MARK: - TempoChange
// MARK: TempoChange init preconditions
@Test func tempoChangeInitValidValues() {
// Normal construction must succeed.
let tc: TempoChange = TempoChange(measure: 3, bpm: 144.0)
#expect(tc.measure == 3)
#expect(tc.bpm == 144.0)
}
@Test func tempoChangeHashableAndSendable() {
// Two TempoChange instances with the same fields must be equal.
let a: TempoChange = TempoChange(measure: 5, bpm: 120.0)
let b: TempoChange = TempoChange(measure: 5, bpm: 120.0)
#expect(a == b)
let c: TempoChange = TempoChange(measure: 5, bpm: 100.0)
#expect(a != c)
let d: TempoChange = TempoChange(measure: 6, bpm: 120.0)
#expect(a != d)
}
@Test func tempoChangeDefaultEmptyOnScore() {
// Score.tempoChanges defaults to [] when omitted.
let score: Score = Score(bpm: 120) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
#expect(score.tempoChanges.isEmpty,
"Score.tempoChanges must default to [] when not provided")
}
@Test func tempoChangeStoredOnScore() {
// tempoChanges is accessible on the Score after construction.
let changes: [TempoChange] = [
TempoChange(measure: 3, bpm: 96.0),
TempoChange(measure: 7, bpm: 160.0)
]
let score: Score = Score(bpm: 120, tempoChanges: changes) {
Part("p") { Note(.c, 4, dur: .quarter) }
}
#expect(score.tempoChanges.count == 2)
#expect(score.tempoChanges[0].measure == 3)
#expect(score.tempoChanges[0].bpm == 96.0)
#expect(score.tempoChanges[1].measure == 7)
#expect(score.tempoChanges[1].bpm == 160.0)
}
// MARK: Encoder — tempo direction emission
@Test func encodeNoTempoChangesEmitsOneTempoPerPart() {
// A score with NO tempo changes must emit exactly ONE <metronome> block per
// part (the measure-1 block). This is the byte-identical regression guard.
let score: Score = Score(bpm: 120) {
Part("p1") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
}
Part("p2") {
Note(.g, 3, dur: .whole)
Note(.a, 3, dur: .whole)
Note(.b, 3, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
// Two parts × one <metronome> each = 2 occurrences.
let metronomeCount: Int = xml.components(separatedBy: "<metronome>").count - 1
#expect(metronomeCount == 2,
"2-part score with no tempo changes must emit exactly 2 <metronome> blocks; got \(metronomeCount)")
}
@Test func encodeTempoChangeEmitsMetronomeAtCorrectMeasure() {
// A TempoChange at measure 3 must emit a <metronome>/<per-minute> block
// inside measure 3 — in every part.
let score: Score = Score(
bpm: 120,
tempoChanges: [TempoChange(measure: 3, bpm: 144.0)]
) {
Part("lead") {
// 4 whole notes → 4 measures in 4/4
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
// The <per-minute> block for the change must contain 144.
#expect(xml.contains("<per-minute>144</per-minute>"),
"tempo change to 144 must emit <per-minute>144</per-minute>; got:\n\(xml)")
// The change must be INSIDE measure 3 (which follows measure 2's </measure>).
// Verify: the second occurrence of <per-minute> (index 1) comes after
// measure number="3".
let perMinuteRanges: [Range<String.Index>] = xml.ranges(of: "<per-minute>")
#expect(perMinuteRanges.count == 2,
"1-part score with 1 tempo change must emit 2 <per-minute> blocks; got \(perMinuteRanges.count)")
// The "measure number=\"3\"" text must precede the second <per-minute>.
if perMinuteRanges.count >= 2 {
let m3Range: Range<String.Index>? = xml.range(of: "number=\"3\"")
#expect(m3Range != nil, "measure number=\"3\" must appear in the XML")
if let m3Range: Range<String.Index> = m3Range {
#expect(m3Range.lowerBound < perMinuteRanges[1].lowerBound,
"the second <per-minute> must come AFTER measure number=\"3\"")
}
}
}
@Test func encodeTempoChangeEmitsInEveryPart() {
// The tempo change direction must appear in EVERY part (same measure index).
let score: Score = Score(
bpm: 120,
tempoChanges: [TempoChange(measure: 2, bpm: 90.0)]
) {
Part("p1") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
}
Part("p2") {
Note(.g, 3, dur: .whole)
Note(.a, 3, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
// 2 parts × 2 <metronome> blocks each = 4 total.
let metronomeCount: Int = xml.components(separatedBy: "<metronome>").count - 1
#expect(metronomeCount == 4,
"2-part score with 1 tempo change must emit 4 <metronome> blocks total; got \(metronomeCount)")
// Both blocks for the change must carry 90.
let perMinuteCount: Int = xml.components(separatedBy: "<per-minute>90</per-minute>").count - 1
#expect(perMinuteCount == 2,
"tempo change to 90 must appear in both parts (2 <per-minute>90 blocks); got \(perMinuteCount)")
}
@Test func encodeTempoChangeMeasureOneIsIgnored() {
// A TempoChange at measure 1 is superseded by Score.bpm (the encoder uses
// bpm for measure 1 always). The base tempo should still be 120, not 200.
// The output must still contain exactly 1 <metronome> block per part.
let score: Score = Score(
bpm: 120,
tempoChanges: [TempoChange(measure: 1, bpm: 200.0)]
) {
Part("p") { Note(.c, 4, dur: .whole) }
}
let xml: String = score.toMusicXMLString()
// Measure 1 tempo comes from bpm = 120; the TempoChange(measure: 1) is not
// emitted as an extra direction (there is only 1 measure total here anyway).
#expect(xml.contains("<per-minute>120</per-minute>"),
"measure-1 tempo must be Score.bpm=120; got:\n\(xml)")
// Only ONE <metronome> block (the measure-1 base tempo).
let metronomeCount: Int = xml.components(separatedBy: "<metronome>").count - 1
#expect(metronomeCount == 1,
"a TempoChange at measure 1 must not produce an extra <metronome>; got \(metronomeCount)")
}
@Test func encodeSoundTempoAttributeAtChangePoint() {
// The change direction must also include <sound tempo="X"/>.
let score: Score = Score(
bpm: 120,
tempoChanges: [TempoChange(measure: 2, bpm: 80.0)]
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<sound tempo=\"80\"/>"),
"tempo change direction must emit <sound tempo=\"80\"/>; got:\n\(xml)")
}
// MARK: Parser — reading tempo changes from measures >= 2
@Test func parseTempoChangeFromMetronome() throws {
// A document with <metronome><per-minute>144 in measure 3 must parse
// to tempoChanges == [TempoChange(measure: 3, bpm: 144)].
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<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>
<direction placement="above">
<direction-type>
<metronome>
<beat-unit>quarter</beat-unit>
<per-minute>120</per-minute>
</metronome>
</direction-type>
<sound tempo="120"/>
</direction>
<note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice></note>
</measure>
<measure number="2">
<note><pitch><step>D</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice></note>
</measure>
<measure number="3">
<direction placement="above">
<direction-type>
<metronome>
<beat-unit>quarter</beat-unit>
<per-minute>144</per-minute>
</metronome>
</direction-type>
<sound tempo="144"/>
</direction>
<note><pitch><step>E</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice></note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.bpm == 120.0, "measure-1 tempo must set Score.bpm")
#expect(score.tempoChanges.count == 1,
"one tempo change at measure 3; got \(score.tempoChanges)")
#expect(score.tempoChanges[0].measure == 3)
#expect(score.tempoChanges[0].bpm == 144.0)
}
@Test func parseTempoChangeFromSoundOnly() throws {
// A document where the tempo change uses only <sound tempo="X"/> (no
// <metronome>) must still parse the TempoChange correctly.
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<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>
<direction placement="above">
<direction-type><metronome><beat-unit>quarter</beat-unit><per-minute>100</per-minute></metronome></direction-type>
<sound tempo="100"/>
</direction>
<note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice></note>
</measure>
<measure number="2">
<direction><sound tempo="60"/></direction>
<note><pitch><step>D</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice></note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.bpm == 100.0)
#expect(score.tempoChanges.count == 1,
"sound-only mid-piece direction must yield one tempo change; got \(score.tempoChanges.count)")
#expect(score.tempoChanges[0].measure == 2)
#expect(score.tempoChanges[0].bpm == 60.0)
}
@Test func parseMeasureOneTempoNotInChanges() throws {
// The measure-1 tempo must set Score.bpm and NOT appear in tempoChanges.
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<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>
<direction placement="above">
<direction-type><metronome><beat-unit>quarter</beat-unit><per-minute>88</per-minute></metronome></direction-type>
<sound tempo="88"/>
</direction>
<note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice></note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.bpm == 88.0)
#expect(score.tempoChanges.isEmpty,
"measure-1 tempo must not appear in tempoChanges; got \(score.tempoChanges)")
}
@Test func parseTempoChangeSortedByMeasure() throws {
// Multiple tempo changes must be returned sorted ascending by measure number.
let xml: String = """
<?xml version="1.0" encoding="UTF-8"?>
<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>
<direction><direction-type><metronome><beat-unit>quarter</beat-unit><per-minute>120</per-minute></metronome></direction-type><sound tempo="120"/></direction>
<note><pitch><step>C</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice></note>
</measure>
<measure number="2">
<direction><direction-type><metronome><beat-unit>quarter</beat-unit><per-minute>80</per-minute></metronome></direction-type><sound tempo="80"/></direction>
<note><pitch><step>D</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice></note>
</measure>
<measure number="3">
<note><pitch><step>E</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice></note>
</measure>
<measure number="4">
<direction><direction-type><metronome><beat-unit>quarter</beat-unit><per-minute>160</per-minute></metronome></direction-type><sound tempo="160"/></direction>
<note><pitch><step>F</step><octave>4</octave></pitch><duration>4</duration><voice>1</voice></note>
</measure>
</part>
</score-partwise>
"""
let score: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(score.bpm == 120.0)
#expect(score.tempoChanges.count == 2,
"two tempo changes (measures 2 and 4); got \(score.tempoChanges)")
#expect(score.tempoChanges[0].measure == 2)
#expect(score.tempoChanges[0].bpm == 80.0)
#expect(score.tempoChanges[1].measure == 4)
#expect(score.tempoChanges[1].bpm == 160.0)
}
// MARK: Round-trip — TempoChange
@Test func roundTripTempoChange() throws {
// Score with a tempo change must round-trip with the same bpm and tempoChanges.
let original: Score = Score(
bpm: 120,
tempoChanges: [TempoChange(measure: 4, bpm: 90.0)]
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
}
}
let xmlData: Data = original.toMusicXMLData()
let recovered: Score = try Score.fromMusicXML(data: xmlData)
#expect(recovered.bpm == 120.0,
"base bpm must survive round-trip; got \(recovered.bpm)")
#expect(recovered.tempoChanges.count == 1,
"one tempo change must round-trip; got \(recovered.tempoChanges)")
#expect(recovered.tempoChanges[0].measure == 4)
#expect(abs(recovered.tempoChanges[0].bpm - 90.0) < 0.001,
"tempo change bpm must round-trip; got \(recovered.tempoChanges[0].bpm)")
}
@Test func roundTripMultipleTempoChanges() throws {
// Multiple tempo changes must all round-trip correctly.
let original: Score = Score(
bpm: 100,
tempoChanges: [
TempoChange(measure: 3, bpm: 132.0),
TempoChange(measure: 6, bpm: 72.0)
]
) {
Part("p") {
Note(.c, 4, dur: .whole)
Note(.d, 4, dur: .whole)
Note(.e, 4, dur: .whole)
Note(.f, 4, dur: .whole)
Note(.g, 4, dur: .whole)
Note(.a, 4, dur: .whole)
}
}
let xmlData: Data = original.toMusicXMLData()
let recovered: Score = try Score.fromMusicXML(data: xmlData)
#expect(recovered.bpm == 100.0)
#expect(recovered.tempoChanges.count == 2,
"two tempo changes must round-trip; got \(recovered.tempoChanges)")
#expect(recovered.tempoChanges[0].measure == 3)
#expect(abs(recovered.tempoChanges[0].bpm - 132.0) < 0.001)
#expect(recovered.tempoChanges[1].measure == 6)
#expect(abs(recovered.tempoChanges[1].bpm - 72.0) < 0.001)
}
// MARK: Flatten unchanged with and without tempo changes
@Test func flattenUnchangedWithTempoChanges() {
// flatten() must produce identical output regardless of tempoChanges.
let withoutChanges: Score = Score(bpm: 120) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .mf)
Note(.d, 4, dur: .eighth)
Note(.e, 4, dur: .half)
Rest(dur: .eighth)
}
}
let withChanges: Score = Score(
bpm: 120,
tempoChanges: [
TempoChange(measure: 1, bpm: 200.0),
TempoChange(measure: 2, bpm: 60.0)
]
) {
Part("p") {
Note(.c, 4, dur: .quarter, dyn: .mf)
Note(.d, 4, dur: .eighth)
Note(.e, 4, dur: .half)
Rest(dur: .eighth)
}
}
let eventsWithout: [ScoreEvent] = withoutChanges.parts[0].flatten()
let eventsWith: [ScoreEvent] = withChanges.parts[0].flatten()
#expect(eventsWithout.count == eventsWith.count,
"tempoChanges must not affect flatten() event count")
for (a, b): (ScoreEvent, ScoreEvent) in zip(eventsWithout, eventsWith) {
#expect(abs(a.beat - b.beat) < 1e-9,
"event beat must be identical regardless of tempoChanges")
#expect(abs(a.duration - b.duration) < 1e-9,
"event duration must be identical regardless of tempoChanges")
}
}
// MARK: - Grace notes
/// flatten() skips grace notes — event count and timings are identical
/// whether or not grace notes are present.
@Test func graceNoteFlattenSkip() {
let scoreWithGrace: Score = Score(bpm: 120) {
Part("lead") {
Grace(.d, 5)
Note(.c, 5, dur: .quarter, dyn: .mf)
Note(.e, 5, dur: .quarter, dyn: .mf)
Note(.g, 5, dur: .half, dyn: .mf)
}
}
let scoreWithout: Score = Score(bpm: 120) {
Part("lead") {
Note(.c, 5, dur: .quarter, dyn: .mf)
Note(.e, 5, dur: .quarter, dyn: .mf)
Note(.g, 5, dur: .half, dyn: .mf)
}
}
let eventsWithGrace: [ScoreEvent] = scoreWithGrace.parts[0].flatten()
let eventsWithout: [ScoreEvent] = scoreWithout.parts[0].flatten()
#expect(eventsWithGrace.count == eventsWithout.count,
"grace notes must not affect event count; got \(eventsWithGrace.count) vs \(eventsWithout.count)")
for (a, b): (ScoreEvent, ScoreEvent) in zip(eventsWithGrace, eventsWithout) {
#expect(abs(a.beat - b.beat) < 1e-9,
"event beat must be identical when grace notes are present")
#expect(abs(a.duration - b.duration) < 1e-9,
"event duration must be identical when grace notes are present")
}
}
/// Multiple consecutive grace notes before a main note — all skipped by flatten.
@Test func multipleGraceNotesFlattenSkip() {
let scoreWithGraces: Score = Score(bpm: 120) {
Part("lead") {
Grace(.b, 4)
Grace(.d, 5, slashed: false)
Note(.c, 5, dur: .quarter, dyn: .mf)
Note(.e, 5, dur: .half, dyn: .mf)
Rest(dur: .quarter)
}
}
let scoreWithout: Score = Score(bpm: 120) {
Part("lead") {
Note(.c, 5, dur: .quarter, dyn: .mf)
Note(.e, 5, dur: .half, dyn: .mf)
Rest(dur: .quarter)
}
}
let withGraces: [ScoreEvent] = scoreWithGraces.parts[0].flatten()
let without: [ScoreEvent] = scoreWithout.parts[0].flatten()
#expect(withGraces.count == without.count,
"multiple grace notes must not affect event count")
}
/// Grace note encoder: emits <grace slash="yes"/> with no <duration>;
/// slashed=false emits <grace/> (no slash attribute).
@Test func graceNoteEncoderSlashedTrue() {
let score: Score = Score(bpm: 120) {
Part("lead") {
Grace(.fSharp, 5, slashed: true)
Note(.g, 5, dur: .quarter, dyn: .mf)
Note(.c, 5, dur: .half, dyn: .mf)
Rest(dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Grace note XML must contain <grace slash="yes"/>
#expect(xml.contains("<grace slash=\"yes\"/>"),
"slashed grace note must emit <grace slash=\"yes\"/>; got:\n\(xml)")
// The grace note must NOT contain <duration>
// Check that <grace> note block has no <duration> child.
// The most robust check: the grace note block ends before any <duration>.
// We verify that the character sequence <grace slash="yes"/>\n...
// is NOT immediately followed by a <duration> (the following note is).
let graceIdx: String.Index? = xml.range(of: "<grace slash=\"yes\"/>")?.lowerBound
#expect(graceIdx != nil, "grace element must be present in XML")
if let idx: String.Index = graceIdx {
// Extract the <note>…</note> block containing this grace element.
let noteOpenRange: Range<String.Index>? = xml.range(
of: " <note>\n",
range: xml.startIndex..<idx
)
if let noteStart: String.Index = noteOpenRange?.lowerBound {
let noteCloseRange: Range<String.Index>? = xml.range(
of: " </note>",
range: noteStart..<xml.endIndex
)
if let noteEnd: String.Index = noteCloseRange?.upperBound {
let graceNoteBlock: String = String(xml[noteStart..<noteEnd])
#expect(!graceNoteBlock.contains("<duration>"),
"grace note block must NOT contain <duration>; got:\n\(graceNoteBlock)")
#expect(graceNoteBlock.contains("<type>eighth</type>"),
"grace note block must contain <type>eighth</type>; got:\n\(graceNoteBlock)")
}
}
}
}
/// Grace note encoder: slashed=false emits <grace/> (no slash attribute).
@Test func graceNoteEncoderSlashedFalse() {
let score: Score = Score(bpm: 120) {
Part("lead") {
Grace(.e, 5, slashed: false)
Note(.d, 5, dur: .quarter, dyn: .mf)
Note(.c, 5, dur: .half, dyn: .mf)
Rest(dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Must have <grace/> (no slash attribute).
#expect(xml.contains("<grace/>"),
"unslashed grace note must emit <grace/>; got:\n\(xml)")
// Must NOT have slash="yes".
#expect(!xml.contains("<grace slash=\"yes\"/>"),
"unslashed grace note must NOT emit slash=\"yes\"; got:\n\(xml)")
}
/// measureCount is not inflated by grace notes — a full measure of quarter
/// notes plus a leading grace still reports the correct measure count.
@Test func graceNoteDoesNotInflateMeasureCount() {
// 4 quarter notes = exactly one 4/4 measure.
// Adding a grace note must NOT push the content into a second measure.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Grace(.b, 4)
Note(.c, 5, dur: .quarter, dyn: .mf)
Note(.d, 5, dur: .quarter, dyn: .mf)
Note(.e, 5, dur: .quarter, dyn: .mf)
Note(.f, 5, dur: .quarter, dyn: .mf)
}
}
let xml: String = score.toMusicXMLString()
// Count <measure> elements — must be exactly 1.
let measureCount: Int = xml.components(separatedBy: "<measure ").count - 1
#expect(measureCount == 1,
"grace note must not inflate measure count; expected 1 got \(measureCount); xml:\n\(xml)")
}
/// Round-trip: Grace(.fSharp, 5) before a note encodes and parses back
/// with the grace element recovered (pitch + slashed). Event round-trip unchanged.
@Test func graceNoteRoundTrip() throws {
let original: Score = Score(bpm: 120) {
Part("lead") {
Grace(.fSharp, 5, slashed: true)
Note(.g, 5, dur: .quarter, dyn: .mf)
Note(.e, 5, dur: .quarter, dyn: .mp)
Note(.c, 5, dur: .half, dyn: .p)
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
// Event round-trip: grace produces no events.
let origEvents: [ScoreEvent] = original.allEvents
let rtEvents: [ScoreEvent] = recovered.allEvents
#expect(origEvents.count == rtEvents.count,
"grace round-trip must preserve event count; \(origEvents.count) → \(rtEvents.count)")
// Structural round-trip: the recovered part should contain a .grace element.
let recoveredElements: [ScoreElement] = recovered.parts[0].elements
let hasGrace: Bool = recoveredElements.contains {
if case .grace(let p, let slashed) = $0 {
return slashed == true && p == Pitch.named(NoteName(letter: .f, accidental: .sharp), 5)
}
return false
}
#expect(hasGrace,
"round-tripped part must contain .grace(.fSharp, 5, slashed: true); elements: \(recoveredElements)")
}
/// No-regression: a score WITHOUT grace notes encodes to byte-identical
/// output before and after the grace-note feature is present.
@Test func graceNoteDoesNotBreakAuthoredTie() {
// A grace note interleaved between a tie:true note and its continuation
// must NOT clear the authored tie — annotateTieAuthored skips graces.
let score: Score = Score(bpm: 120) {
Part("lead") {
Note(.c, 5, dur: .quarter, dyn: .mf, tie: true)
Grace(.d, 5)
Note(.c, 5, dur: .quarter, dyn: .mf)
}
}
let xml: String = score.toMusicXMLString()
let startCount: Int = xml.components(separatedBy: "<tie type=\"start\"/>").count - 1
let stopCount: Int = xml.components(separatedBy: "<tie type=\"stop\"/>").count - 1
#expect(startCount == 1,
"tie must survive an interleaved grace; got \(startCount) starts;\n\(xml)")
#expect(stopCount == 1,
"tie stop must land on the continuation note; got \(stopCount) stops;\n\(xml)")
}
@Test func graceNoteNoRegressionOnNonGraceScore() {
let score: Score = Score(bpm: 120) {
Part("lead") {
Note(.c, 5, dur: .quarter, dyn: .mf)
Note(.d, 5, dur: .quarter, dyn: .mp)
Note(.e, 5, dur: .half, dyn: .p)
}
}
let xml: String = score.toMusicXMLString()
// Must not contain any <grace> element.
#expect(!xml.contains("<grace"),
"non-grace score must not emit any <grace> element; got:\n\(xml)")
// Standard elements still present.
#expect(xml.contains("<pitch>"), "non-grace score must still emit <pitch>")
#expect(xml.contains("<duration>"), "non-grace score must still emit <duration>")
}
// MARK: - Transposing keys
// MARK: Transpose type
@Test func transposeInitDefaults() {
let t: Transpose = Transpose(chromatic: -2)
#expect(t.chromatic == -2)
#expect(t.diatonic == 0)
#expect(t.octaveChange == 0)
}
@Test func transposeInitAllParams() {
let t: Transpose = Transpose(chromatic: -7, diatonic: -4, octaveChange: -1)
#expect(t.chromatic == -7)
#expect(t.diatonic == -4)
#expect(t.octaveChange == -1)
}
@Test func transposeHashableAndSendable() {
let a: Transpose = Transpose(chromatic: -2, diatonic: -1)
let b: Transpose = Transpose.bFlat
#expect(a == b, "bFlat convenience must equal explicitly constructed value")
let c: Transpose = Transpose(chromatic: -3, diatonic: -2)
#expect(c != a, "different values must not be equal")
}
@Test func transposeNamedConvenienceBFlat() {
let t: Transpose = Transpose.bFlat
#expect(t.chromatic == -2)
#expect(t.diatonic == -1)
#expect(t.octaveChange == 0)
}
@Test func transposeNamedConvenienceA() {
let t: Transpose = Transpose.a
#expect(t.chromatic == -3)
#expect(t.diatonic == -2)
#expect(t.octaveChange == 0)
}
@Test func transposeNamedConvenienceEFlat() {
let t: Transpose = Transpose.eFlat
#expect(t.chromatic == -9)
#expect(t.diatonic == -5)
#expect(t.octaveChange == 0)
}
@Test func transposeNamedConvenienceFHorn() {
let t: Transpose = Transpose.fHorn
#expect(t.chromatic == -7)
#expect(t.diatonic == -4)
#expect(t.octaveChange == 0)
}
// MARK: Per-part key override — encoder
@Test func perPartKeyOverrideEncodesCorrectFifths() {
// Part 0: score key = G major (fifths=1). Part 1: A major override (fifths=3).
let score: Score = Score(bpm: 120, keySignature: .gMajor) {
Part("strings") {
Note(.g, 4, dur: .quarter)
}
Part("clarinet", clef: .treble, keySignature: .aMajor) {
Note(.a, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Part 1 (P1) should emit <fifths>1</fifths> (G major).
// Part 2 (P2) should emit <fifths>3</fifths> (A major override).
// Locate both <part> blocks and check their key blocks.
let p1Range: Range<String.Index>? = xml.range(of: "<part id=\"P1\">")
let p2Range: Range<String.Index>? = xml.range(of: "<part id=\"P2\">")
#expect(p1Range != nil, "P1 block must be present")
#expect(p2Range != nil, "P2 block must be present")
if let p1Start: String.Index = p1Range?.lowerBound,
let p2Start: String.Index = p2Range?.lowerBound
{
let p1Block: String = String(xml[p1Start..<p2Start])
let p2Block: String = String(xml[p2Start...])
#expect(p1Block.contains("<fifths>1</fifths>"),
"P1 must emit score key fifths=1 (G major); P1 block:\n\(p1Block)")
#expect(p2Block.contains("<fifths>3</fifths>"),
"P2 must emit override key fifths=3 (A major); P2 block:\n\(p2Block)")
#expect(!p1Block.contains("<fifths>3</fifths>"),
"P1 must NOT emit A major; P1 block:\n\(p1Block)")
}
}
@Test func noTransposePartEmitsScoreKey() {
// A part with no key override and no transpose should emit the score key.
let score: Score = Score(bpm: 120, keySignature: .gMajor) {
Part("melody") {
Note(.g, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<fifths>1</fifths>"),
"non-transposing part must emit score key fifths=1; xml:\n\(xml)")
#expect(!xml.contains("<transpose>"),
"non-transposing part must NOT emit <transpose>; xml:\n\(xml)")
}
// MARK: Transpose element — encoder
@Test func transposeElementEmittedAfterClef() {
// A B♭ clarinet part: key override A major + .bFlat transpose.
let score: Score = Score(bpm: 120, keySignature: .gMajor) {
Part("clarinet", clef: .treble, keySignature: .aMajor, transpose: .bFlat) {
Note(.a, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// <transpose> must appear after <clef> and before </attributes>.
let clefEnd: Range<String.Index>? = xml.range(of: "</clef>")
let transposeStart: Range<String.Index>? = xml.range(of: "<transpose>")
let attribEnd: Range<String.Index>? = xml.range(of: "</attributes>")
#expect(clefEnd != nil, "xml must contain </clef>")
#expect(transposeStart != nil, "xml must contain <transpose>")
#expect(attribEnd != nil, "xml must contain </attributes>")
if let ce: Range<String.Index> = clefEnd,
let ts: Range<String.Index> = transposeStart,
let ae: Range<String.Index> = attribEnd
{
#expect(ce.upperBound <= ts.lowerBound,
"</clef> must come before <transpose>")
#expect(ts.lowerBound <= ae.lowerBound,
"<transpose> must come before </attributes>")
}
// Verify the child values.
#expect(xml.contains("<diatonic>-1</diatonic>"),
"B♭ transpose must have diatonic -1; xml:\n\(xml)")
#expect(xml.contains("<chromatic>-2</chromatic>"),
"B♭ transpose must have chromatic -2; xml:\n\(xml)")
// octaveChange must be omitted (0).
#expect(!xml.contains("<octave-change>"),
"B♭ transpose must NOT emit octave-change (is 0); xml:\n\(xml)")
}
@Test func transposeWithNonZeroOctaveChange() {
// octaveChange: -1 must be emitted.
let score: Score = Score(bpm: 120, keySignature: .cMajor) {
Part("bass-clarinet", clef: .treble, transpose: Transpose(chromatic: -2, diatonic: -1, octaveChange: -1)) {
Note(.c, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(xml.contains("<octave-change>-1</octave-change>"),
"octaveChange -1 must be emitted; xml:\n\(xml)")
}
@Test func noTransposeNoTransposeElement() {
// Verifies the no-transpose guarantee at the XML level.
let score: Score = Score(bpm: 120, keySignature: .cMajor) {
Part("piano") {
Note(.c, 5, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
#expect(!xml.contains("<transpose>"),
"non-transposing part must emit no <transpose>; xml:\n\(xml)")
}
// MARK: Transpose element — parser
@Test func parserReadsTransposeBlock() throws {
// Build a score with transpose, encode, then decode.
let original: Score = Score(bpm: 120, keySignature: .gMajor) {
Part("clarinet", clef: .treble, keySignature: .aMajor, transpose: .bFlat) {
Note(.a, 5, dur: .quarter)
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(recovered.parts.count == 1)
let part: ScorePart = recovered.parts[0]
#expect(part.transpose?.chromatic == -2,
"parsed transpose chromatic must be -2; got \(String(describing: part.transpose))")
#expect(part.transpose?.diatonic == -1,
"parsed transpose diatonic must be -1; got \(String(describing: part.transpose))")
#expect(part.transpose?.octaveChange == 0,
"parsed transpose octaveChange must be 0; got \(String(describing: part.transpose))")
}
@Test func parserReadsPerPartKeyOverride() throws {
// Multi-part: part 1 = G major, part 2 = A major override.
let original: Score = Score(bpm: 120, keySignature: .gMajor) {
Part("strings") {
Note(.g, 4, dur: .quarter)
}
Part("clarinet", clef: .treble, keySignature: .aMajor, transpose: .bFlat) {
Note(.a, 5, dur: .quarter)
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
// Score key = first part's key = G major.
#expect(recovered.keySignature == .gMajor,
"score key must be G major; got \(recovered.keySignature)")
// Part 0 (strings): key matches score, so override must be nil.
#expect(recovered.parts[0].keySignature == nil,
"strings part override must be nil (matches score key); got \(String(describing: recovered.parts[0].keySignature))")
// Part 1 (clarinet): key differs from score, must be A major.
#expect(recovered.parts[1].keySignature == .aMajor,
"clarinet part override must be A major; got \(String(describing: recovered.parts[1].keySignature))")
// Transpose round-trip.
#expect(recovered.parts[1].transpose == Transpose.bFlat,
"clarinet transpose must round-trip as bFlat; got \(String(describing: recovered.parts[1].transpose))")
}
@Test func uniformKeyScoreAllOverridesNil() throws {
// All parts share the same key → all overrides nil after round-trip.
let original: Score = Score(bpm: 120, keySignature: .dMajor) {
Part("violin") { Note(.d, 5, dur: .quarter) }
Part("viola") { Note(.d, 4, dur: .quarter) }
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
#expect(recovered.keySignature == .dMajor)
for part: ScorePart in recovered.parts {
#expect(part.keySignature == nil,
"uniform-key part override must be nil; got \(String(describing: part.keySignature))")
}
}
// MARK: Round-trip
@Test func transposeRoundTrip() throws {
// Full round-trip: Score with transposing part → encode → decode → properties preserved.
let original: Score = Score(bpm: 120, keySignature: .gMajor) {
Part("strings") {
Note(.g, 4, dur: .quarter)
Note(.a, 4, dur: .quarter)
}
Part("clarinet", clef: .treble, keySignature: .aMajor, transpose: .bFlat) {
Note(.a, 5, dur: .quarter)
Note(.b, 5, dur: .quarter)
}
}
let xml: String = original.toMusicXMLString()
let recovered: Score = try Score.fromMusicXML(data: Data(xml.utf8))
// Score-level properties.
#expect(recovered.keySignature == .gMajor)
#expect(recovered.parts.count == 2)
// Part 0: no override, no transpose.
#expect(recovered.parts[0].keySignature == nil)
#expect(recovered.parts[0].transpose == nil)
// Part 1: override + transpose preserved.
#expect(recovered.parts[1].keySignature == .aMajor)
#expect(recovered.parts[1].transpose == Transpose.bFlat)
// Flatten event count: unchanged (transpose is notation-only).
let origEvents: [ScoreEvent] = original.allEvents
let rtEvents: [ScoreEvent] = recovered.allEvents
#expect(origEvents.count == rtEvents.count,
"transpose round-trip must preserve event count; \(origEvents.count) → \(rtEvents.count)")
}
@Test func transposeNoRegressionNonTransposing() {
// A score without any per-part key or transpose must produce byte-identical
// MusicXML before and after transposing-key support (no regression).
let score: Score = Score(bpm: 120, keySignature: .gMajor) {
Part("melody", clef: .treble) {
Note(.g, 4, dur: .quarter, dyn: .mf)
Note(.a, 4, dur: .quarter, dyn: .mf)
}
}
let xml: String = score.toMusicXMLString()
// No <transpose> element, no extra key blocks.
#expect(!xml.contains("<transpose>"),
"non-transposing score must not contain <transpose>; xml:\n\(xml)")
// The single <key> block uses the score key.
let fifthsCount: Int = xml.components(separatedBy: "<fifths>1</fifths>").count - 1
#expect(fifthsCount == 1,
"one-part score must contain exactly one <fifths>1</fifths>; got \(fifthsCount)")
}
// MARK: - Nested tuplet per-level bracket engraving
@Test func nestedTuplet5_4inside3_2EmitsInnerBracketWithLocalRatio() {
// 5:4 outer ⊃ 3:2 inner. Because this
// part contains nesting (partHasNestedTuplet == true), ALL bracket starts
// use the full explicit form with <tuplet-actual>/<tuplet-normal>/<tuplet-type>.
//
// Outer bracket (number=1): full form with local 5:4 and <tuplet-type>quarter</tuplet-type>.
// Inner bracket (number=2): full form with local 3:2 and <tuplet-type>quarter</tuplet-type>.
// Both STOP brackets remain bare self-closing.
//
// Outer nominal = 3 quarters + inner(3 quarters × 2/3) = 5 quarter-slots.
// Total sounding = 5 quarter-slots × 4/5 = 4 beats. Fits a 4/4 measure.
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Tuplet(5, inTimeOf: 4) {
Note(.c, 5, dur: .quarter, dyn: .mp)
Note(.d, 5, dur: .quarter, dyn: .mp)
Note(.e, 5, dur: .quarter, dyn: .mp)
Tuplet(3, inTimeOf: 2) {
Note(.f, 5, dur: .quarter, dyn: .mp)
Note(.g, 5, dur: .quarter, dyn: .mp)
Note(.gSharp, 5, dur: .quarter, dyn: .mp)
}
}
}
}
let xml: String = score.toMusicXMLString()
// 1. Outer bracket (number=1): partHasNestedTuplet → full form (not bare).
#expect(xml.contains("<tuplet type=\"start\" number=\"1\">"),
"outer bracket start must be full form in a nested part; got:\n\(xml)")
#expect(!xml.contains("<tuplet type=\"start\" number=\"1\"/>"),
"outer bracket start must NOT be bare self-closing in a nested part; got:\n\(xml)")
#expect(xml.contains("<tuplet-number>5</tuplet-number>"),
"outer bracket must contain <tuplet-number>5</tuplet-number>; got:\n\(xml)")
#expect(xml.contains("<tuplet-number>4</tuplet-number>"),
"outer bracket must contain <tuplet-number>4</tuplet-number>; got:\n\(xml)")
// <tuplet-type>quarter</tuplet-type> in both bracket starts.
#expect(xml.contains("<tuplet-type>quarter</tuplet-type>"),
"brackets must contain <tuplet-type>quarter</tuplet-type>; got:\n\(xml)")
#expect(xml.contains("<tuplet type=\"stop\" number=\"1\"/>"),
"outer bracket stop must be bare self-closing; got:\n\(xml)")
// 2. Inner bracket (number=2): local 3:2 and full form.
#expect(xml.contains("<tuplet type=\"start\" number=\"2\">"),
"inner bracket start must be full form (not self-closing); got:\n\(xml)")
#expect(xml.contains("<tuplet-actual>"),
"inner bracket must contain <tuplet-actual>; got:\n\(xml)")
#expect(xml.contains("<tuplet-number>3</tuplet-number>"),
"inner bracket must contain <tuplet-number>3</tuplet-number>; got:\n\(xml)")
#expect(xml.contains("<tuplet-normal>"),
"inner bracket must contain <tuplet-normal>; got:\n\(xml)")
#expect(xml.contains("<tuplet-number>2</tuplet-number>"),
"inner bracket must contain <tuplet-number>2</tuplet-number>; got:\n\(xml)")
#expect(xml.contains("<tuplet type=\"stop\" number=\"2\"/>"),
"inner bracket stop must be bare self-closing; got:\n\(xml)")
// 3. Outer notes carry cumulative time-modification 5:4.
#expect(xml.contains("<actual-notes>5</actual-notes>"),
"outer notes must carry <actual-notes>5</actual-notes>; got:\n\(xml)")
#expect(xml.contains("<normal-notes>4</normal-notes>"),
"outer notes must carry <normal-notes>4</normal-notes>; got:\n\(xml)")
// 4. Inner notes carry cumulative time-modification 15:8.
#expect(xml.contains("<actual-notes>15</actual-notes>"),
"inner notes must carry <actual-notes>15</actual-notes>; got:\n\(xml)")
#expect(xml.contains("<normal-notes>8</normal-notes>"),
"inner notes must carry <normal-notes>8</normal-notes>; got:\n\(xml)")
// 5. Ordering: outer bracket start appears before inner bracket start.
let outerStartRange: Range<String.Index>? = xml.range(
of: "<tuplet type=\"start\" number=\"1\">"
)
let innerStartRange: Range<String.Index>? = xml.range(
of: "<tuplet type=\"start\" number=\"2\">"
)
if let o: Range<String.Index> = outerStartRange,
let i: Range<String.Index> = innerStartRange {
#expect(o.lowerBound < i.lowerBound,
"outer bracket start must precede inner bracket start")
} else {
Issue.record("both bracket starts must be present; got:\n\(xml)")
}
// 6. Round-trip: flatten beats must be unchanged (4 beats total sounding).
let events: [ScoreEvent] = score.allEvents
let totalSounding: Double = events.map { $0.duration }.reduce(0.0, +)
#expect(abs(totalSounding - 4.0) < 0.001,
"6 notes at (3×4/5 outer + 3×8/15 inner) must sum to 4 beats; got \(totalSounding)")
#expect(events.count == 6,
"must have exactly 6 note events; got \(events.count)")
}
@Test func singleLevelTupletStillBare() {
// REGRESSION guard: a plain 3:2 triplet must still emit the bare
// self-closing <tuplet type="start" number="1"/> — byte-identical
// to the pre-nested-bracket output (local 3:2 == cumulative 3:2).
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Tuplet(3, inTimeOf: 2) {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
}
// Fill the remainder of the 4/4 bar.
Note(.f, 4, dur: .quarter)
}
}
let xml: String = score.toMusicXMLString()
// Bare self-closing start — no <tuplet-actual> child element.
#expect(xml.contains("<tuplet type=\"start\" number=\"1\"/>"),
"single-level triplet start must be bare self-closing; got:\n\(xml)")
#expect(!xml.contains("<tuplet-actual>"),
"single-level triplet must NOT emit <tuplet-actual>; got:\n\(xml)")
#expect(!xml.contains("<tuplet-normal>"),
"single-level triplet must NOT emit <tuplet-normal>; got:\n\(xml)")
// Stop is always bare.
#expect(xml.contains("<tuplet type=\"stop\" number=\"1\"/>"),
"single-level triplet stop must be bare self-closing; got:\n\(xml)")
}
@Test func nestedTupletFullFormIncludesTupletType() {
// Both bracket starts in a nested-tuplet part must include
// <tuplet-type>TYPE</tuplet-type> inside <tuplet-actual> and <tuplet-normal>.
// The TYPE is derived from typeInfo?.0 (the note's printed type name).
// For a 5:4 ⊃ 3:2 nested tuplet of quarter notes the type is "quarter".
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Tuplet(5, inTimeOf: 4) {
Note(.c, 5, dur: .quarter, dyn: .mf)
Note(.d, 5, dur: .quarter, dyn: .mf)
Note(.e, 5, dur: .quarter, dyn: .mf)
Tuplet(3, inTimeOf: 2) {
Note(.f, 5, dur: .quarter, dyn: .mf)
Note(.g, 5, dur: .quarter, dyn: .mf)
Note(.a, 5, dur: .quarter, dyn: .mf)
}
}
}
}
let xml: String = score.toMusicXMLString()
// Both bracket starts must carry <tuplet-type>quarter</tuplet-type>.
let tupletTypeCount: Int = xml.components(
separatedBy: "<tuplet-type>quarter</tuplet-type>"
).count - 1
// Each bracket start emits one <tuplet-type> in <tuplet-actual> and one
// in <tuplet-normal>, so there are at least 4 occurrences (2 brackets × 2).
#expect(tupletTypeCount >= 4,
"<tuplet-type>quarter</tuplet-type> must appear ≥4 times (2 brackets × actual+normal); got \(tupletTypeCount);\n\(xml)")
// Single-level part does NOT emit <tuplet-type>.
let singleScore: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("q") {
Tuplet(3, inTimeOf: 2) {
Note(.c, 4, dur: .quarter)
Note(.d, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
}
Note(.f, 4, dur: .quarter)
}
}
let singleXML: String = singleScore.toMusicXMLString()
#expect(!singleXML.contains("<tuplet-type>"),
"single-level part must NOT emit <tuplet-type>; got:\n\(singleXML)")
}
@Test func nestedTupletRoundTripEventCountPreserved() {
// Round-trip through MusicXML parse: parser is duration-driven and ignores
// bracket markup, so event count and sounding beats must be preserved.
let original: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("p") {
Tuplet(5, inTimeOf: 4) {
Note(.c, 5, dur: .quarter, dyn: .mp)
Note(.d, 5, dur: .quarter, dyn: .mp)
Note(.e, 5, dur: .quarter, dyn: .mp)
Tuplet(3, inTimeOf: 2) {
Note(.f, 5, dur: .quarter, dyn: .mp)
Note(.g, 5, dur: .quarter, dyn: .mp)
Note(.gSharp, 5, dur: .quarter, dyn: .mp)
}
}
// Fill remaining beat with a quarter rest.
Note(.c, 4, dur: .quarter)
}
}
let xmlData: Data = original.toMusicXMLData()
guard let recovered: Score = try? Score.fromMusicXML(data: xmlData) else {
Issue.record("MusicXML round-trip parse failed")
return
}
let origEvents: [ScoreEvent] = original.allEvents
let rtEvents: [ScoreEvent] = recovered.allEvents
#expect(origEvents.count == rtEvents.count,
"round-trip must preserve event count: \(origEvents.count) → \(rtEvents.count)")
}
}