// MIDIMapCodableTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable import LyrebirdShoeGaze @MainActor @Suite("MIDIMap persistence") struct MIDIMapCodableTests { // Fixed ids so the round-trip comparison is deterministic. private static let boardID: UUID = UUID() private static let looperID: UUID = UUID() private static let volumeID: UUID = UUID() private func sampleMap() -> MIDIMap { MIDIMap( switches: [ MIDIMap.SwitchBinding(program: 3, channel: 0, action: .rigBypass, displayNameHint: "Rig"), MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardID: Self.boardID), displayNameHint: "Board 2"), MIDIMap.SwitchBinding(program: 5, action: .tunerToggle), MIDIMap.SwitchBinding(program: 6, action: .tapTempo), MIDIMap.SwitchBinding( program: 7, action: .pedalAction(pedalID: Self.looperID, kind: .looperRecordStop), displayNameHint: "Looper" ), ], ccs: [ MIDIMap.CCBinding( controller: 7, channel: 0, target: .pedalControl( pedalID: Self.volumeID, controlIndex: 0, pedalNameHint: "Volume", controlLabelHint: "Position" ) ), MIDIMap.CCBinding( controller: 11, channel: 0, target: .boardLevel(boardID: Self.boardID, boardLabelHint: "Board 1") ), ] ) } @Test func mapRoundTrips() throws { let map: MIDIMap = sampleMap() let data: Data = try JSONEncoder().encode(map) let decoded: MIDIMap = try JSONDecoder().decode(MIDIMap.self, from: data) #expect(decoded == map) } @Test func rigStateEmbedsAndRestoresMap() throws { let state: ShoeGazeState = ShoeGazeState(boards: [], midiMap: sampleMap()) let data: Data = try JSONEncoder().encode(state) let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data) #expect(decoded.midiMap == sampleMap()) } @Test func malformedMidiMapDropsBindingsNotTheRig() throws { // A midiMap in a shape this build can't read (e.g. an older binding schema) must NOT throw // and lose the whole rig — it drops just the (re-learnable) bindings. let json: String = #"{"version":1,"boards":[],"midiMap":{"switches":"not-an-array","ccs":42}}"# let data: Data = Data(json.utf8) let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data) #expect(decoded.midiMap == nil, "an unreadable midiMap should decode to nil, not throw") #expect(decoded.version == 1) } @Test func oldRigWithoutMapDecodesToNil() throws { // A rig saved before MIDI mapping existed has no `midiMap` key at all. let legacyJSON: String = #"{"version":1,"boards":[]}"# let data: Data = Data(legacyJSON.utf8) let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data) #expect(decoded.midiMap == nil, "legacy rig JSON should decode with a nil midiMap") } }