Files
ShoeGaze/Tests/LyrebirdShoeGazeTests/PresetTests.swift
T
2026-06-21 12:25:18 -07:00

302 lines
12 KiB
Swift

// PresetTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Preset save/load")
struct PresetTests {
// MARK: - Helpers
/// Builds a two-board test rig and returns the `ShoeGaze` manager plus its engine.
///
/// Board 1: Overdrive → Delay
/// Board 2: Reverb
///
/// - Returns: `(ShoeGaze, SynthesisEngine, URL)` where `URL` is the NRT output file
/// that must be deleted by the caller (via `defer`).
private func makeTwoBoardRig() throws -> (ShoeGaze, SynthesisEngine, URL) {
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 128
)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board1: PedalBoard = try sg.addBoard()
try board1.add(OverdrivePedal())
try board1.add(DelayPedal())
try sg.finalizeBoard(board1)
let board2: PedalBoard = try sg.addBoard()
try board2.add(ReverbPedal())
try sg.finalizeBoard(board2)
return (sg, engine, url)
}
// MARK: - In-memory round-trip
@Test func captureStateRoundTripEquality() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: url) }
// Tweak some parameters on board 1 pedals.
guard let overdrive: OverdrivePedal = sg.boards[0].pedals[0] as? OverdrivePedal else {
Issue.record("Expected OverdrivePedal at board 0 pedal 0")
return
}
overdrive.drive = 12.0
overdrive.bypass = 1.0
guard let delay: DelayPedal = sg.boards[0].pedals[1] as? DelayPedal else {
Issue.record("Expected DelayPedal at board 0 pedal 1")
return
}
delay.time = 0.75
delay.feedback = 3.0
// Capture once, JSON encode → decode, compare to a second capture.
let captured: ShoeGazeState = sg.captureState()
let encoder: JSONEncoder = JSONEncoder()
let data: Data = try encoder.encode(captured)
let decoder: JSONDecoder = JSONDecoder()
let decoded: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
#expect(decoded == captured, "Decoded ShoeGazeState must equal original")
#expect(decoded.version == presetFormatVersion)
#expect(decoded.boards.count == 2)
#expect(decoded.boards[0].pedals.count == 2)
#expect(decoded.boards[0].pedals[0].type == "Overdrive")
#expect(decoded.boards[0].pedals[0].bypass == 1.0)
// Verify the overdrive drive value made it through.
// drive is the first effectKnob (index 0 in knobValues).
let driveValue: Double = decoded.boards[0].pedals[0].knobValues[0]
#expect(abs(driveValue - 12.0) < 1e-9, "drive knob value should be 12.0, got \(driveValue)")
}
// MARK: - Save / Load via temp file
@Test func saveRigAndLoadRigRestoresKnobValues() throws {
let renderDuration: Double = 0.1
let (engine, audioURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: audioURL) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let overdrive: OverdrivePedal = OverdrivePedal()
try board.add(overdrive)
try sg.finalizeBoard(board)
// Set a known knob value.
let knownDriveValue: Double = 17.5
overdrive.drive = knownDriveValue
// Save to a temp file.
let presetURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: presetURL) }
try sg.saveRig(to: presetURL)
// Mutate the live knob.
overdrive.drive = 1.0
#expect(abs(overdrive.drive - 1.0) < 1e-9)
// Load the preset — this rebuilds the entire graph.
try sg.loadRig(from: presetURL)
// After load there should be one board with one overdrive pedal.
#expect(sg.boards.count == 1, "Expected 1 board after loadRig")
#expect(sg.boards[0].pedals.count == 1, "Expected 1 pedal after loadRig")
guard let restoredPedal: OverdrivePedal = sg.boards[0].pedals[0] as? OverdrivePedal else {
Issue.record("Expected OverdrivePedal after loadRig")
return
}
// drive is the first effectKnob → knobValues[0] was applied via applyState.
#expect(
abs(restoredPedal.drive - knownDriveValue) < 1e-9,
"drive should be \(knownDriveValue) after loadRig, got \(restoredPedal.drive)"
)
}
@Test func savedFileContainsValidJSON() throws {
let renderDuration: Double = 0.1
let (engine, audioURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: audioURL) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(FuzzPedal())
try sg.finalizeBoard(board)
let presetURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: presetURL) }
try sg.saveRig(to: presetURL)
// Verify the file is non-empty and parses as JSON.
let data: Data = try Data(contentsOf: presetURL)
#expect(!data.isEmpty, "Preset file should not be empty")
let json: Any = try JSONSerialization.jsonObject(with: data)
#expect(json is [String: Any], "Root JSON object should be a dictionary")
}
// MARK: - applyState lightweight recall
@Test func applyStateRecallsKnobValuesWithoutRebuild() throws {
let renderDuration: Double = 0.1
let (engine, audioURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: audioURL) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let compressor: CompressorPedal = CompressorPedal()
try board.add(compressor)
try sg.finalizeBoard(board)
// Set a known threshold.
let knownThreshold: Double = -20.0
compressor.threshold = knownThreshold
// Capture the state at this point.
let captured: ShoeGazeState = sg.captureState()
// Mutate the threshold.
compressor.threshold = -5.0
#expect(abs(compressor.threshold - (-5.0)) < 1e-9)
// Apply the captured state (lightweight recall — no graph rebuild).
sg.applyState(captured)
// threshold is the first effectKnob; applyState calls knob.node.update(value)
// which sets the UIParamNode. The UIParamNode.value should now reflect the restored value.
let thresholdKnobValue: Double = compressor.knobs[0].node.value
#expect(
abs(thresholdKnobValue - knownThreshold) < 1e-9,
"threshold knob should be \(knownThreshold) after applyState, got \(thresholdKnobValue)"
)
}
// MARK: - PedalRegistry
@Test func registryReturnsCorrectPedalTypes() {
let overdrive: Pedal? = PedalRegistry.makePedal(type: "Overdrive")
let delay: Pedal? = PedalRegistry.makePedal(type: "Delay")
let reverb: Pedal? = PedalRegistry.makePedal(type: "Reverb")
let modulation: Pedal? = PedalRegistry.makePedal(type: "Modulation")
let fuzz: Pedal? = PedalRegistry.makePedal(type: "Fuzz")
let tremolo: Pedal? = PedalRegistry.makePedal(type: "Tremolo")
let phaser: Pedal? = PedalRegistry.makePedal(type: "Phaser")
let compressor: Pedal? = PedalRegistry.makePedal(type: "Compressor")
let unknown: Pedal? = PedalRegistry.makePedal(type: "UnknownPedal")
#expect(overdrive is OverdrivePedal, "Overdrive should produce OverdrivePedal")
#expect(delay is DelayPedal, "Delay should produce DelayPedal")
#expect(reverb is ReverbPedal, "Reverb should produce ReverbPedal")
#expect(modulation is ModulationPedal, "Modulation should produce ModulationPedal")
#expect(fuzz is FuzzPedal, "Fuzz should produce FuzzPedal")
#expect(tremolo is TremoloPedal, "Tremolo should produce TremoloPedal")
#expect(phaser is PhaserPedal, "Phaser should produce PhaserPedal")
#expect(compressor is CompressorPedal, "Compressor should produce CompressorPedal")
#expect(unknown == nil, "Unknown type should return nil")
}
// MARK: - Version guard
@Test func loadRigThrowsOnUnsupportedVersion() throws {
// Craft a state whose version is one ahead of the current format.
let futureVersion: Int = presetFormatVersion + 1
let state: ShoeGazeState = ShoeGazeState(version: futureVersion, boards: [])
let renderDuration: Double = 0.1
let (engine, audioURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: audioURL) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let presetURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: presetURL) }
let encoder: JSONEncoder = JSONEncoder()
let data: Data = try encoder.encode(state)
try data.write(to: presetURL, options: .atomic)
do {
try sg.loadRig(from: presetURL)
Issue.record("Expected PresetError.unsupportedVersion to be thrown")
} catch let error as PresetError {
#expect(
error == .unsupportedVersion(futureVersion),
"Expected .unsupportedVersion(\(futureVersion)), got \(error)"
)
}
}
@Test func loadRigSkipsUnknownPedalTypes() throws {
// Craft a ShoeGazeState that contains an unknown pedal type between two known ones.
let state: ShoeGazeState = ShoeGazeState(boards: [
BoardState(
label: "Test Board",
pedals: [
PedalState(type: "Overdrive", knobValues: [4.0, 4000.0, 1.0, 1.0], bypass: 0.0),
PedalState(type: "GhostPedal", knobValues: [], bypass: 0.0),
PedalState(type: "Fuzz", knobValues: [0.05, 3500.0, 1.0, 1.0], bypass: 0.0),
]
)
])
let renderDuration: Double = 0.1
let (engine, audioURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: audioURL) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let presetURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: presetURL) }
// Encode the crafted state to disk and load it.
let encoder: JSONEncoder = JSONEncoder()
let data: Data = try encoder.encode(state)
try data.write(to: presetURL, options: .atomic)
try sg.loadRig(from: presetURL)
// The unknown "GhostPedal" should be skipped; only Overdrive and Fuzz load.
#expect(sg.boards.count == 1, "Expected 1 board after loadRig")
#expect(sg.boards[0].pedals.count == 2, "Expected 2 pedals (unknown type skipped)")
#expect(sg.boards[0].pedals[0].displayName == "Overdrive")
#expect(sg.boards[0].pedals[1].displayName == "Fuzz")
}
}