Files
Lyrebird/Tests/LyrebirdTests/TheoryMusicXMLRoundTripTests.swift

77 lines
3.0 KiB
Swift

// TheoryMusicXMLRoundTripTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
/// Confirms spellings produced by theory-layer transposition survive a full
/// MusicXML encode → decode round-trip (the spelled letter + accidental are not
/// collapsed to an enharmonic equivalent).
@Suite("Theory → MusicXML round-trip — transposed spellings survive export")
struct TheoryMusicXMLRoundTripTests {
/// Build a single-part score from named pitches (quarter notes).
private func score(from pitches: [Pitch]) throws -> Score {
var notes: [(NoteName, Int)] = []
for pitch: Pitch in pitches {
guard case .named(let name, let octave) = pitch else {
throw ScaleError.nonNamedPitch(pitch)
}
notes.append((name, octave))
}
return Score(bpm: 120) {
Part("p") {
for note: (NoteName, Int) in notes {
Note(note.0, note.1, dur: .quarter)
}
}
}
}
private func roundTrip(_ score: Score) throws -> [NoteName] {
let xml: String = score.toMusicXMLString()
let decoded: Score = try Score.fromMusicXML(data: Data(xml.utf8))
let events: [ScoreEvent] = decoded.parts[0].flatten()
var names: [NoteName] = []
for event: ScoreEvent in events {
guard case .named(let name, _) = event.pitch else { continue }
names.append(name)
}
return names
}
@Test func chromaticTransposeSharpSpellingsSurvive() throws {
// C-D-A up a major third = E-F#-C# (sharps must survive, not become Gb etc).
let phrase: PitchCollection = PitchCollection(pitches: [
.named(.c, 4), .named(.d, 4), .named(.a, 4),
])
let up: PitchCollection = try phrase.transposedChromatic(by: .majorThird)
let names: [NoteName] = try roundTrip(try score(from: up.pitches))
#expect(names == [.e, .fSharp, .cSharp])
}
@Test func augmentedSecondBSharpSurvives() throws {
// A +aug2 = B# — the round-trip must NOT collapse it to C natural.
let up: Pitch = try Pitch.named(.a, 4).transposed(by: .augmentedSecond)
let names: [NoteName] = try roundTrip(try score(from: [up]))
#expect(names == [.bSharp])
#expect(names.first != .c)
}
@Test func flatModeMappingSurvives() throws {
// C major triad mapped to Eb major = Eb-G-Bb (flats must survive).
let cMajor: Scale = try Scale.major(.c)
let eFlatMajor: Scale = try Scale.major(.eFlat)
let triad: PitchCollection = PitchCollection(pitches: [
.named(.c, 4), .named(.e, 4), .named(.g, 4),
])
let mapped: PitchCollection = try triad.mapped(from: cMajor, to: eFlatMajor)
let names: [NoteName] = try roundTrip(try score(from: mapped.pitches))
#expect(names == [.eFlat, .g, .bFlat])
}
}