SPB Git

Repository Public

MIDIMappingProfileTests.swift 11.2 KB 223 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX DJ9// File             : Packages/ORIXDJCore/Tests/ORIXMIDITests/MIDIMappingProfileTests.swift10// Description      : Profile tests: JSON round trip, tolerant decoding,11//                    validation, file import/export.12// Module           : ORIXMIDITests13// Repository       : https://git.spboucher.ai/orix-dj14// Created          : 2026-11-2115// Last Modified    : 2026-11-2116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation90import Testing91@testable import ORIXMIDI9293@Suite struct MIDIMappingProfileTests {94    private func sample() -> MIDIMappingProfile {95        MIDIMappingProfile(96            name: "Test Controller",97            controllerNameHint: "DDJ",98            mappings: [99                MIDIMapping(control: .note(channel: 0, note: 11), target: "deck.A.play", mode: .toggle),100                MIDIMapping(control: .cc(channel: 6, controller: 31), deviceUniqueID: -123456, target: "mixer.crossfader", mode: .absolute, minValue: 0.1, maxValue: 0.9, invert: true, softTakeover: true),101                MIDIMapping(control: .cc(channel: 0, controller: 33), target: "deck.A.jog", mode: .relative, relativeEncoding: .signedBit, sensitivity: 2.5),102                MIDIMapping(control: .pitchBend(channel: 1), target: "deck.B.tempo", mode: .absolute),103                MIDIMapping(control: .note(channel: 0, note: 12), target: "deck.A.cue", mode: .momentary),104                MIDIMapping(control: .note(channel: 0, note: 13), target: "deck.A.sync", mode: .trigger),105            ]106        )107    }108109    @Test func jsonRoundTrip() throws {110        let profile = sample()111        #expect(profile.validate().isEmpty)112        let data = try profile.jsonData()113        let decoded = try MIDIMappingProfile(jsonData: data)114        #expect(decoded == profile)115        // Stable output: encoding twice gives identical bytes.116        #expect(try decoded.jsonData() == data)117        let text = String(decoding: data, as: UTF8.self)118        #expect(text.contains("\"formatVersion\" : 1"))119        #expect(text.contains("mixer.crossfader"))120    }121122    @Test func messageAndDeviceCodableRoundTrip() throws {123        let messages: [MIDIMessage] = [124            .noteOn(channel: 1, note: 2, velocity: 3), .noteOff(channel: 1, note: 2, velocity: 0),125            .controlChange(channel: 4, controller: 5, value: 6), .pitchBend(channel: 7, value: 9000),126            .programChange(channel: 8, program: 9),127        ]128        let data = try JSONEncoder().encode(messages)129        #expect(try JSONDecoder().decode([MIDIMessage].self, from: data) == messages)130        let device = MIDIDeviceInfo(uniqueID: -5, name: "N", manufacturer: "M", model: "X", isOnline: false, isVirtual: true, kind: .destination)131        #expect(try JSONDecoder().decode(MIDIDeviceInfo.self, from: JSONEncoder().encode(device)) == device)132    }133134    @Test func tolerantDecodingOfHandWrittenJSON() throws {135        let json = """136        { "name": "Minimal",137          "mappings": [138            { "control": { "kind": "cc", "channel": 0, "number": 7 }, "target": "mixer.master", "mode": "absolute" },139            { "control": { "kind": "note", "channel": 1, "number": 60 }, "target": "deck.B.play", "mode": "toggle" },140            { "control": { "kind": "pitchBend", "channel": 2, "number": 99 }, "target": "deck.B.tempo", "mode": "absolute" }141          ] }142        """143        let profile = try MIDIMappingProfile(jsonData: Data(json.utf8))144        #expect(profile.formatVersion == 1)145        #expect(profile.controllerNameHint == "")146        #expect(profile.mappings.count == 3)147        #expect(profile.mappings[0].control == .cc(channel: 0, controller: 7))148        #expect(profile.mappings[0].maxValue == 1 && profile.mappings[0].minValue == 0)149        #expect(profile.mappings[0].sensitivity == 1 && !profile.mappings[0].softTakeover)150        #expect(profile.mappings[0].deviceUniqueID == nil)151        #expect(profile.validate().isEmpty)152    }153154    @Test func rejectsNewerFormatAndGarbage() {155        let newer = Data(#"{ "name": "Future", "formatVersion": 99, "mappings": [] }"#.utf8)156        #expect(throws: MIDIMappingProfileError.unsupportedFormatVersion(99)) {157            _ = try MIDIMappingProfile(jsonData: newer)158        }159        #expect(throws: (any Error).self) { _ = try MIDIMappingProfile(jsonData: Data("not json".utf8)) }160        #expect(throws: (any Error).self) {161            _ = try MIDIMappingProfile(jsonData: Data(#"{ "name": "x", "mappings": [ { "target": "t", "mode": "warp" } ] }"#.utf8))162        }163    }164165    @Test func validationReportsDuplicateControls() {166        var profile = sample()167        let first = profile.mappings[0]168        let duplicate = MIDIMapping(control: first.control, target: "deck.B.play", mode: .toggle)169        let third = MIDIMapping(control: first.control, target: "deck.C.play", mode: .trigger)170        // Same control but scoped to a device: a legitimate override, not a duplicate.171        let scoped = MIDIMapping(control: first.control, deviceUniqueID: 9, target: "deck.D.play", mode: .toggle)172        profile.mappings += [duplicate, third, scoped]173        expectEqual(profile.validate(), [174            .duplicateControl(control: first.control, deviceUniqueID: nil, mappingIDs: [first.id, duplicate.id, third.id])175        ])176    }177178    @Test func validationReportsEverythingElse() {179        let sharedID = UUID()180        let a = MIDIMapping(id: sharedID, control: .cc(channel: 0, controller: 1), target: "a", mode: .absolute)181        let b = MIDIMapping(id: sharedID, control: .cc(channel: 0, controller: 2), target: "b", mode: .absolute)182        let empty = MIDIMapping(control: .cc(channel: 0, controller: 3), target: "  ", mode: .absolute)183        let badControl = MIDIMapping(control: .cc(channel: 16, controller: 200), target: "c", mode: .absolute)184        let badRange = MIDIMapping(control: .cc(channel: 0, controller: 5), target: "d", mode: .absolute, minValue: -1, maxValue: .nan)185        let relativeNote = MIDIMapping(control: .note(channel: 0, note: 6), target: "e", mode: .relative, sensitivity: 0)186        let bendButton = MIDIMapping(control: .pitchBend(channel: 0), target: "f", mode: .toggle)187        let profile = MIDIMappingProfile(name: "bad", mappings: [a, b, empty, badControl, badRange, relativeNote, bendButton], formatVersion: 7)188        expectEqual(profile.validate(), [189            .unsupportedFormatVersion(7),190            .duplicateMappingID(sharedID),191            .emptyTarget(mappingID: empty.id),192            .invalidControl(mappingID: badControl.id),193            .invalidRange(mappingID: badRange.id),194            .incompatibleMode(mappingID: relativeNote.id),195            .invalidSensitivity(mappingID: relativeNote.id),196            .incompatibleMode(mappingID: bendButton.id),197        ])198    }199200    @Test func fileExportImport() throws {201        let directory = FileManager.default.temporaryDirectory202            .appendingPathComponent("orixmidi-tests-\(UUID().uuidString)", isDirectory: true)203        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)204        defer { try? FileManager.default.removeItem(at: directory) }205        let url = directory.appendingPathComponent("profile.\(MIDIMappingProfile.fileExtension)")206        let profile = sample()207        try profile.write(to: url)208        #expect(try MIDIMappingProfile(contentsOf: url) == profile)209        #expect(throws: (any Error).self) {210            _ = try MIDIMappingProfile(contentsOf: directory.appendingPathComponent("missing.orixmidi"))211        }212    }213214    @Test func controlIDFromMessage() {215        #expect(MIDIControlID(message: .noteOn(channel: 1, note: 2, velocity: 3)) == .note(channel: 1, note: 2))216        #expect(MIDIControlID(message: .noteOff(channel: 1, note: 2, velocity: 0)) == .note(channel: 1, note: 2))217        #expect(MIDIControlID(message: .controlChange(channel: 1, controller: 2, value: 3)) == .cc(channel: 1, controller: 2))218        #expect(MIDIControlID(message: .pitchBend(channel: 4, value: 3)) == .pitchBend(channel: 4))219        #expect(MIDIControlID(message: .programChange(channel: 1, program: 2)) == nil)220        #expect(MIDIControlID(kind: .pitchBend, channel: 1, number: 55).number == 0)221    }222}223
Files main
Menu

Theme