fenilsonani / menu-browser / Tests/ GlobalShortcutTests.swift

import AppKit

enum GlobalShortcutTests {
    static func run() -> Suite {
        let suite = Suite("GlobalShortcut")

        withTemporaryDefaults("com.fenilsonani.MenuBrowser.tests.shortcut") { defaults in
            // Nothing stored yet.
            suite.expect(
                GlobalShortcut.load(from: defaults) == .fallback,
                "falls back to \u{2318}\u{21E7}B when no shortcut is stored"
            )

            // The regression this whole type exists for: keycode 0x00 is `A`, and the
            // old `integer(forKey:) != 0` check treated it as "nothing stored".
            let aShortcut = GlobalShortcut(keyCode: 0x00, modifiers: [.command, .shift])
            aShortcut.save(to: defaults)
            let restored = GlobalShortcut.load(from: defaults)
            suite.expect(restored == aShortcut, "restores an A-based shortcut (keycode 0)")
            suite.expect(restored.displayString == "\u{21E7}\u{2318}A", "renders \u{21E7}\u{2318}A")

            // A non-zero keycode still round-trips.
            let bShortcut = GlobalShortcut(keyCode: 0x0B, modifiers: [.command, .option])
            bShortcut.save(to: defaults)
            suite.expect(
                GlobalShortcut.load(from: defaults) == bShortcut,
                "round-trips a non-zero keycode with different modifiers"
            )

            // Modifier-less shortcuts are corrupt: they'd swallow a bare keypress globally.
            defaults.set(0x00, forKey: GlobalShortcut.DefaultsKey.keyCode)
            defaults.set(0, forKey: GlobalShortcut.DefaultsKey.modifiers)
            suite.expect(
                GlobalShortcut.load(from: defaults) == .fallback,
                "falls back when stored modifiers are empty"
            )
        }

        // Every letter keycode must survive persistence, not just the ones that are non-zero.
        withTemporaryDefaults("com.fenilsonani.MenuBrowser.tests.shortcut2") { defaults in
            var brokenCodes: [UInt16] = []
            for code in UInt16(0)...UInt16(0x7E) {
                let shortcut = GlobalShortcut(keyCode: code, modifiers: [.command, .shift])
                shortcut.save(to: defaults)
                if GlobalShortcut.load(from: defaults) != shortcut { brokenCodes.append(code) }
            }
            suite.expect(brokenCodes.isEmpty, "every keycode 0x00...0x7E round-trips")
            if !brokenCodes.isEmpty {
                suite.fail("keycodes that failed to restore: \(brokenCodes)")
            }
        }

        return suite
    }
}