import Foundation import Testing @testable import ParcelConfig @Suite("Configuration validation") struct ConfigValidationTests { private let displayID = "A1B2C3D4-1234-5678-9ABC-0123456789AB" @Test(arguments: ["", "version = 1"]) func emptyDocumentAndExplicitVersionOneUseDefaults(source: String) throws { let result = try validate(source) #expect(result.configuration == .defaults) #expect(result.diagnostics.isEmpty) let value = try #require(result.configuration) #expect(value == .defaults) } @Test(arguments: ConfigWhenDisplayFull.allCases) func fullDisplayPolicyAndMasterShortcutsParseIndependently(_ policy: ConfigWhenDisplayFull) throws { #expect(ParcelConfiguration.defaults.general.whenDisplayFull == .swap) #expect(ParcelConfiguration.defaults.general.shortcutsEnabled) let value = try configuration( "[general]\nwhen-display-full = '\(policy.rawValue)'\nshortcuts-enabled = false\n") #expect(value.general.whenDisplayFull == policy) #expect(!value.general.shortcutsEnabled) #expect(value.keybindings == DefaultKeybindings.bindings()) } @Test(arguments: ["when-display-full = 'float'", "when-display-full = false", "shortcuts-enabled = 'false'"]) func invalidGeneralShortcutAndDisplayPoliciesAreRejected(_ assignment: String) throws { #expect(try validate("[general]\n\(assignment)").configuration == nil) } @Test func explicitOldTreeChordWinsNewAutomaticTilingDefault() throws { let result = try validate("[keybindings]\nlayout-tree = 'ctrl-alt-t'\n") let value = try #require(result.configuration) #expect(value.keybindings[.layoutTree] == KeyChord(modifiers: [.ctrl, .alt], key: .t)) #expect(value.keybindings[.toggleAutomaticTiling] == nil) #expect(result.diagnostics.count == 1) #expect(result.diagnostics.first?.severity == .warning) #expect( result.diagnostics.first?.message.contains("Unbound because keybindings.layout-tree uses this key") == true) } @Test func explicitModeEntryWinsInheritedDefault() throws { let result = try validate("[keybindings]\n\"enter-mode resize\" = 'ctrl-alt-t'\n[mode.resize]\n") let value = try #require(result.configuration) #expect(value.keybindings[.toggleAutomaticTiling] == nil) #expect(value.defaultModeEntries["resize"] == KeyChord(modifiers: [.ctrl, .alt], key: .t)) #expect(value.inheritedShortcutDisplacements.first?.binding == .enterMode("resize")) #expect(result.diagnostics.first?.severity == .warning) } @Test func defaultGeneralAndAccessibilitySettings() { #expect(ParcelConfiguration.defaults.general.prefix == [.ctrl, .alt]) #expect(!ParcelConfiguration.defaults.general.launchAtLogin) #expect(!ParcelConfiguration.defaults.accessibility.announceLayoutChanges) } @Test func defaultLayoutAndCollections() { let layout = ParcelConfiguration.defaults.layout.global #expect(layout.defaultLayout == .grid) #expect(layout.portraitLayout == .rows) #expect(layout.ratio == 0.5) #expect(layout.windowCap == 3) #expect(layout.whenFull == .stack) #expect(layout.gaps == LayoutGaps(inner: 8, outer: 8)) #expect(layout.reserved == ReservedEdges(top: 0, right: 0, bottom: 0, left: 0)) #expect(ParcelConfiguration.defaults.layout.displays.isEmpty) #expect(ParcelConfiguration.defaults.floatRules.isEmpty) } @Test func defaultMotion() { #expect( ParcelConfiguration.defaults.motion == MotionConfiguration( enabled: true, level: .playful, speed: 1, transitions: .glide, focusBorder: true, sound: false, menuBarIcon: .minimap)) } @Test func defaultsIncludeOnlyBoundCommandsAndNoDuplicateChords() { let bindings = ParcelConfiguration.defaults.keybindings #expect(bindings == DefaultKeybindings.bindings()) #expect(Set(bindings.keys).isSubset(of: Set(ConfigCommand.allCases))) #expect(bindings[.snapLeftHalf] != nil) #expect(bindings[.snapCenter] == nil) #expect(Set(bindings.values).count == bindings.count) } @Test func customInitializerGeneratesPrefixDefaults() { let value = ParcelConfiguration(general: GeneralConfiguration(prefix: .fn)) #expect(value.keybindings == DefaultKeybindings.bindings(prefix: .fn)) } @Test func customInitializerCanRemoveEveryBinding() { #expect(ParcelConfiguration(keybindings: [:]).keybindings.isEmpty) } @Test(arguments: ["0", "2", "-1", "9223372036854775807", "1.0", "true", "\"1\"", "[]", "{}"]) func invalidVersions(_ value: String) throws { let result = try validate("version = \(value)") #expect(result.configuration == nil) let error = try #require(result.diagnostics.first) #expect(error.severity == .error) #expect(error.location.line == 1) #expect(error.location.column == 11) #expect(error.message.contains("version = 1")) } @Test func launchAtLoginCanBeEnabled() throws { #expect(try configuration("[general]\nlaunch-at-login = true").general.launchAtLogin) } @Test func prefixReplacesOnlyGeneratedDefaults() throws { let value = try configuration("[general]\nprefix = \"cmd-fn\"") #expect(value.general.prefix == [.cmd, .fn]) #expect(value.keybindings == DefaultKeybindings.bindings(prefix: [.cmd, .fn])) } @Test func emptyPrefixIsSupported() throws { let value = try configuration("[general]\nprefix = \"\"") #expect(value.general.prefix.isEmpty) #expect(value.keybindings == DefaultKeybindings.bindings(prefix: [])) } @Test func hyperPrefixIsSupported() throws { let value = try configuration("[general]\nprefix = \"hyper\"") #expect(value.general.prefix == .hyper) #expect(value.keybindings[.windowControls] == KeyChord(modifiers: .hyper, key: .f19)) #expect(value.keybindings[.stackPrevious] == KeyChord(modifiers: .hyper, key: .backslash)) } @Test func windowCountBindingsUseQuotedArgumentsAndCanBeRemappedOrDisabled() throws { let value = try configuration( """ [keybindings] "set-window-cap 1" = "fn-1" "set-window-cap 2" = false """) #expect(value.keybindings[.setWindowCap(1)] == (try KeyChord(parsing: "fn-1"))) #expect(value.keybindings[.setWindowCap(2)] == nil) #expect(value.keybindings[.setWindowCap(3)] == DefaultKeybindings.bindings()[.setWindowCap(3)]) } @Test func prefixAliasesAreNormalized() throws { #expect(try configuration("[general]\nprefix = \"CONTROL-OPTION\"").general.prefix == [.ctrl, .alt]) } @Test(arguments: ["\"ctrl-mystery\"", "\"ctrl-ctrl\"", "\"ctrl-a\"", "42", "true"]) func invalidPrefixes(_ value: String) throws { let result = try validate("[general]\nprefix = \(value)") #expect(result.configuration == nil) #expect(result.diagnostics.contains { $0.message.contains("prefix = \"ctrl-alt\"") }) } @Test func explicitShortcutIsAbsoluteAfterPrefixChange() throws { let value = try configuration("[general]\nprefix = \"fn\"\n[keybindings]\nfocus-left = \"cmd-f20\"") #expect(value.keybindings[.focusLeft] == (try KeyChord(parsing: "cmd-f20"))) #expect(value.keybindings[.focusRight] == DefaultKeybindings.bindings(prefix: .fn)[.focusRight]) } @Test(arguments: ConfigLayout.allCases) func everyLayoutIsAccepted(_ layout: ConfigLayout) throws { #expect(try configuration("[layout]\ndefault = \"\(layout.rawValue)\"").layout.global.defaultLayout == layout) } @Test(arguments: ConfigLayout.allCases) func everyPortraitLayoutIsAcceptedGloballyAndPerDisplay(_ layout: ConfigLayout) throws { let value = try configuration( "[layout]\nportrait-layout = \"\(layout.rawValue)\"\n[layout.displays.\"\(displayID)\"]") let id = try #require(UUID(uuidString: displayID)) #expect(value.layout.global.portraitLayout == layout) #expect(value.layout.values(for: id).portraitLayout == layout) let override = try configuration( "[layout.displays.\"\(displayID)\"]\nportrait-layout = \"\(layout.rawValue)\"") #expect(override.layout.values(for: id).portraitLayout == layout) #expect(override.layout.global.portraitLayout == .rows) } @Test(arguments: ["\"spiral\"", "\"Rows\"", "7", "false", "[]"]) func invalidPortraitLayoutsAreRejectedWithSourceLocations(_ value: String) throws { for table in ["layout", "layout.displays.\"\(displayID)\""] { let result = try validate("[\(table)]\nportrait-layout = \(value)") #expect(result.configuration == nil) let diagnostic = try #require(result.diagnostics.first) #expect(diagnostic.severity == .error) #expect(diagnostic.location.line == 2) #expect(diagnostic.location.column == 19) #expect(diagnostic.message.contains("portrait-layout")) } } @Test(arguments: [0, 100]) func portraitAndOverflowEditsPreserveCommentsAndExplicitCapInheritance(count: Int) throws { let source = """ # café [layout] default = "side" portrait-layout = "rows" # upright when-full = "stack" # overflow window-cap = \(count) # requested [layout.displays."\(displayID)"] portrait-layout = "tree" """ let id = try #require(UUID(uuidString: displayID)) var document = try TOMLDocument(parsing: source) try document.setValue(.string("columns"), forKey: ["layout", "portrait-layout"]) try document.setValue(.string("float"), forKey: ["layout", "when-full"]) #expect( document.render() == source.replacingOccurrences(of: "\"rows\"", with: "\"columns\"") .replacingOccurrences(of: "\"stack\"", with: "\"float\"")) let value = try configuration(document.render()) #expect( value.layout.global == LayoutValues(defaultLayout: .side, portraitLayout: .columns, windowCap: count, whenFull: .float)) #expect( value.layout.values(for: id) == LayoutValues(defaultLayout: .side, portraitLayout: .tree, windowCap: count, whenFull: .float)) try document.setValue(.integer(Int64(100 - count)), forKey: ["layout", "displays", displayID, "window-cap"]) try document.setValue(.string("grid"), forKey: ["layout", "displays", displayID, "portrait-layout"]) let updated = try configuration(document.render()) #expect(updated.layout.global == value.layout.global) #expect( updated.layout.values(for: id) == LayoutValues(defaultLayout: .side, portraitLayout: .grid, windowCap: 100 - count, whenFull: .float)) #expect(document.render().contains("window-cap = \(count) # requested")) #expect(!document.render().contains("portrait_layout")) #expect(!document.render().contains("when_full")) } @Test func orientationAndOverflowKebabKeysSupportInlineAndDottedTables() throws { let expected = LayoutValues(defaultLayout: .side, portraitLayout: .columns, windowCap: 0, whenFull: .float) for source in [ "layout = { default = 'side', portrait-layout = 'columns', window-cap = 0, when-full = 'float' }", "layout.default = 'side'\nlayout.portrait-layout = 'columns'\nlayout.window-cap = 0\nlayout.when-full = 'float'", ] { let value = try configuration(source) #expect(value.layout.global == expected) } for source in [ "layout.displays.\"\(displayID)\" = { default = 'side', portrait-layout = 'columns', window-cap = 0, when-full = 'float' }", "layout.displays.\"\(displayID)\".default = 'side'\nlayout.displays.\"\(displayID)\".portrait-layout = 'columns'\nlayout.displays.\"\(displayID)\".window-cap = 0\nlayout.displays.\"\(displayID)\".when-full = 'float'", ] { let value = try configuration(source) #expect(value.layout.global == LayoutValues()) #expect(value.layout.values(for: try #require(UUID(uuidString: displayID))) == expected) } } @Test func unknownLayoutIsRejectedWithExample() throws { let result = try validate("[layout]\ndefault = \"spiral\"") #expect(result.configuration == nil) #expect(result.diagnostics.first?.message.contains("\"grid\", \"columns\", \"rows\", \"side\"") == true) } @Test func layoutNamesAreCaseSensitive() throws { #expect(try validate("[layout]\ndefault = \"Grid\"").configuration == nil) } @Test func ratioCanBeCustomized() throws { #expect(try configuration("[layout]\nratio = 0.7").layout.global.ratio == 0.7) } @Test func gapsCanBeFractional() throws { let value = try configuration("[layout.gaps]\ninner = 2.5\nouter = 12") #expect(value.layout.global.gaps == LayoutGaps(inner: 2.5, outer: 12)) } @Test func reservedEdgesCanBeCustomized() throws { let value = try configuration("[layout.reserved]\ntop = 1\nright = 2.5\nbottom = 3\nleft = 4.5") #expect(value.layout.global.reserved == ReservedEdges(top: 1, right: 2.5, bottom: 3, left: 4.5)) } @Test func windowCapCanBeCustomized() throws { #expect(try configuration("[layout]\nwindow-cap = 12").layout.global.windowCap == 12) } @Test func fractionalWindowCapIsRejected() throws { #expect(try validate("[layout]\nwindow-cap = 12.5").configuration == nil) } @Test func omittedOverflowBehaviorDefaultsToStackWithThreeWindows() throws { for source in ["", "[layout]", "[layout.displays.\"\(displayID)\"]"] { let value = try configuration(source) let id = try #require(UUID(uuidString: displayID)) #expect(value.layout.global.whenFull == .stack) #expect(value.layout.global.windowCap == 3) #expect(value.layout.values(for: id).whenFull == .stack) #expect(value.layout.values(for: id).windowCap == 3) } #expect(LayoutValues(windowCap: 0).windowCap == 0) } @Test(arguments: ConfigWhenFull.allCases) func overflowBehaviorAcceptsGlobalAndDisplayValues(behavior: ConfigWhenFull) throws { let global = try configuration("[layout]\nwhen-full = \"\(behavior.rawValue)\"") #expect(global.layout.global.whenFull == behavior) let id = try #require(UUID(uuidString: displayID)) let display = try configuration("[layout.displays.\"\(displayID)\"]\nwhen-full = \"\(behavior.rawValue)\"") #expect(display.layout.displays[id]?.whenFull == behavior) #expect(display.layout.global.whenFull == .stack) } @Test(arguments: ["\"Stack\"", "\"FLOAT\"", "\"unknown\"", "\"\"", "true", "false", "1", "[]", "{}"]) func invalidOverflowBehaviorReportsGlobalAndDisplayValueLocations(value: String) throws { for path in ["layout", "layout.displays.\"\(displayID)\""] { let document = try TOMLDocument(parsing: "[\(path)]\n when-full = \(value)") let result = ConfigValidator.validate(document) #expect(result.configuration == nil) let error = try #require(result.diagnostics.first) #expect(error.severity == .error) #expect(error.location.line == 2) #expect(error.location.column == 15) #expect(error.message.contains("\(path).when-full")) #expect(error.message.contains("For example:")) #expect(result.diagnostics.count == 1) } } @Test func displayOverflowBehaviorInheritsGlobalButCanOverrideIndependently() throws { let id = try #require(UUID(uuidString: displayID)) let otherID = UUID() let value = try configuration( """ [layout] when-full = "float" window-cap = 0 [layout.displays."\(displayID)"] ratio = 0.7 [layout.displays."\(otherID.uuidString)"] when-full = "stack" window-cap = 2 """ ) #expect(value.layout.global == LayoutValues(windowCap: 0, whenFull: .float)) #expect(value.layout.values(for: id) == LayoutValues(ratio: 0.7, windowCap: 0, whenFull: .float)) #expect(value.layout.values(for: otherID) == LayoutValues(windowCap: 2, whenFull: .stack)) #expect(value.layout.values(for: UUID()) == value.layout.global) } @Test func overflowBehaviorSupportsInlineAndDottedKeys() throws { for source in [ "layout = { when-full = 'float', window-cap = 0 }", "layout.when-full = 'float'\nlayout.window-cap = 0", ] { #expect(try configuration(source).layout.global == LayoutValues(windowCap: 0, whenFull: .float)) } } @Test func overflowBehaviorRoundTripPreservesFormattingAndInheritance() throws { let source = "# café\r\n[layout]\r\nwhen-full = 'stack' # overflow\r\nwindow-cap = 0 # unlimited\r\n[layout.displays.'\(displayID)']\r\nratio = 0.7\r\n" var document = try TOMLDocument(parsing: source) try document.setValue(.string("float"), forKey: ["layout", "when-full"]) #expect(document.render() == source.replacingOccurrences(of: "'stack'", with: "\"float\"")) let value = try configuration(document.render()) let id = try #require(UUID(uuidString: displayID)) #expect(value.layout.global.whenFull == .float) #expect(value.layout.global.windowCap == 0) #expect(value.layout.values(for: id).whenFull == .float) try document.setValue(.string("stack"), forKey: ["layout", "displays", displayID, "when-full"]) #expect(try configuration(document.render()).layout.values(for: id).whenFull == .stack) #expect(try configuration(document.render()).layout.global.whenFull == .float) } @Test(arguments: ConfigLayout.allCases, 0...100) func requestedCapsStayUnclampedAcrossLayoutsAndDisplayInheritance(layout: ConfigLayout, count: Int) throws { let id = try #require(UUID(uuidString: displayID)) let overrideID = try #require(UUID(uuidString: "00000000-0000-0000-0000-000000000001")) for behavior in ConfigWhenFull.allCases { let value = try configuration( """ [layout] default = "\(layout.rawValue)" portrait-layout = "\(layout.rawValue)" window-cap = \(count) when-full = "\(behavior.rawValue)" [layout.displays."\(displayID)"] [layout.displays."\(overrideID.uuidString)"] default = "tree" portrait-layout = "columns" window-cap = \(100 - count) """) let expected = LayoutValues( defaultLayout: layout, portraitLayout: layout, windowCap: count, whenFull: behavior) #expect(value.layout.global == expected) #expect(value.layout.values(for: id) == expected) #expect( value.layout.values(for: overrideID) == LayoutValues( defaultLayout: .tree, portraitLayout: .columns, windowCap: 100 - count, whenFull: behavior)) } } @Test(arguments: [0, 1, 3, 100]) func displayWindowCapPreservesInclusiveRangeAndUnlimited(count: Int) throws { let id = try #require(UUID(uuidString: displayID)) let value = try configuration("[layout.displays.\"\(displayID)\"]\nwindow-cap = \(count)") #expect(value.layout.values(for: id).windowCap == count) #expect(value.layout.global.windowCap == 3) } @Test( arguments: ConfigLayout.allCases, ["-1", "101", "9223372036854775807", "0.0", "nan", "inf", "false", "\"0\"", "[]", "{}"]) func adaptiveLayoutsRejectInvalidRequestedCapsAtGlobalAndDisplayValueLocations( layout: ConfigLayout, value: String ) throws { for path in ["layout", "layout.displays.\"\(displayID)\""] { let document = try TOMLDocument( parsing: "[\(path)]\ndefault = '\(layout.rawValue)'\nportrait-layout = '\(layout.rawValue)'\nwhen-full = 'float'\n window-cap = \(value)" ) let result = ConfigValidator.validate(document) #expect(result.configuration == nil) #expect(result.diagnostics.count == 1) let diagnostic = try #require(result.diagnostics.first) #expect(diagnostic.location.line == 5) #expect(diagnostic.location.column == 16) #expect(diagnostic.severity == .error) #expect(diagnostic.message.contains("\(path).window-cap")) } } @Test(arguments: numericFields) func numericBoundsAreInclusive(_ field: NumericField) throws { #expect(try validate("\(field.path) = \(field.lower)").configuration != nil) #expect(try validate("\(field.path) = \(field.upper)").configuration != nil) } @Test(arguments: numericFields) func numericOutOfRangeValuesAreRejected(_ field: NumericField) throws { for value in [field.below, field.above] { let result = try validate("\(field.path) = \(value)") #expect(result.configuration == nil) let error = try #require(result.diagnostics.first) #expect(error.message.contains(field.path)) #expect(error.message.contains("For example:")) #expect(error.location.column == field.path.count + 4) } } @Test(arguments: numericFields) func numericFieldsRejectStrings(_ field: NumericField) throws { #expect(try validate("\(field.path) = \"2\"").configuration == nil) } @Test(arguments: ["nan", "+nan", "-nan", "inf", "+inf", "-inf"]) func nonFiniteNumbersAreRejected(_ number: String) throws { let result = try validate("motion.speed = \(number)") #expect(result.configuration == nil) #expect(result.diagnostics.first?.message.contains("finite number") == true) } @Test func omittedDisplayValuesInheritGlobalValues() throws { let value = try configuration( """ [layout] default = "side" ratio = 0.65 window-cap = 9 [layout.gaps] inner = 11 outer = 13 [layout.reserved] top = 17 [layout.displays."\(displayID)"] """ ) let id = try #require(UUID(uuidString: displayID)) #expect(value.layout.displays[id] == value.layout.global) } @Test func displayOverrideDoesNotChangeGlobalValues() throws { let value = try configuration( "[layout.displays.\"\(displayID)\"]\nratio = 0.8\ndefault = \"rows\"\nwindow-cap = 2") let id = try #require(UUID(uuidString: displayID)) #expect(value.layout.displays[id]?.ratio == 0.8) #expect(value.layout.displays[id]?.defaultLayout == .rows) #expect(value.layout.displays[id]?.windowCap == 2) #expect(value.layout.global == LayoutValues()) } @Test func displayGapsInheritIndividually() throws { let value = try configuration( "[layout.gaps]\ninner = 12\nouter = 18\n[layout.displays.\"\(displayID)\".gaps]\ninner = 3") let id = try #require(UUID(uuidString: displayID)) #expect(value.layout.displays[id]?.gaps == LayoutGaps(inner: 3, outer: 18)) } @Test func displayReservedEdgesInheritIndividually() throws { let value = try configuration( "[layout.reserved]\ntop = 10\nright = 20\nbottom = 30\nleft = 40\n[layout.displays.\"\(displayID)\".reserved]\nleft = 5" ) let id = try #require(UUID(uuidString: displayID)) #expect(value.layout.displays[id]?.reserved == ReservedEdges(top: 10, right: 20, bottom: 30, left: 5)) } @Test func unknownDisplayUsesGlobalValues() throws { let value = try configuration("[layout]\nratio = 0.75") let id = try #require(UUID(uuidString: displayID)) #expect(value.layout.values(for: id) == value.layout.global) } @Test func configuredDisplayUsesOverride() throws { let value = try configuration("[layout.displays.\"\(displayID)\"]\nratio = 0.75") let id = try #require(UUID(uuidString: displayID)) #expect(value.layout.values(for: id).ratio == 0.75) } @Test func lowercaseDisplayUUIDIsAccepted() throws { let value = try configuration("[layout.displays.\"\(displayID.lowercased())\"]\nratio = 0.75") #expect(value.layout.displays.count == 1) } @Test func duplicateUUIDCasingIsRejected() throws { let result = try validate("[layout.displays.\"\(displayID)\"]\n[layout.displays.\"\(displayID.lowercased())\"]") #expect(result.configuration == nil) #expect(result.diagnostics.contains { $0.message.contains("configured twice") && $0.relatedLocation != nil }) } @Test(arguments: ["display-one", "123", "A1B2C3D4123456789ABC0123456789AB", "ZZZZZZZZ-1234-5678-9ABC-0123456789AB"]) func malformedDisplayUUIDsAreRejected(_ id: String) throws { let result = try validate("[layout.displays.\"\(id)\"]\nratio = 0.75") #expect(result.configuration == nil) #expect(result.diagnostics.first?.message.contains("UUID") == true) } @Test func displayValueMustBeATable() throws { #expect(try validate("layout.displays.\"\(displayID)\" = 3").configuration == nil) } @Test func displayValuesUseSameLimits() throws { #expect(try validate("[layout.displays.\"\(displayID)\"]\nratio = 0.99").configuration == nil) } @Test func nestedDisplayOverridesAreUnknown() throws { let result = try validate("[layout.displays.\"\(displayID)\".displays]") #expect(result.configuration != nil) #expect(result.diagnostics.first?.severity == .warning) } @Test func motionCanBeDisabled() throws { #expect(try configuration("[motion]\nenabled = false").motion.enabled == false) } @Test func integerMotionSpeedIsAccepted() throws { #expect(try configuration("[motion]\nspeed = 2").motion.speed == 2) } @Test(arguments: ConfigMotionLevel.allCases) func everyMotionLevelIsAccepted(_ level: ConfigMotionLevel) throws { #expect(try configuration("[motion]\nlevel = \"\(level.rawValue)\"").motion.level == level) } @Test(arguments: ConfigMotionTransition.allCases) func everyMotionTransitionIsAccepted(_ transition: ConfigMotionTransition) throws { #expect( try configuration("[motion]\ntransitions = \"\(transition.rawValue)\"").motion.transitions == transition) } @Test(arguments: ConfigMenuBarIcon.allCases) func everyMenuBarIconIsAccepted(_ icon: ConfigMenuBarIcon) throws { #expect(try configuration("[motion]\nmenu-bar-icon = \"\(icon.rawValue)\"").motion.menuBarIcon == icon) } @Test( arguments: ["level", "transitions", "menu-bar-icon"], ["\"maximum\"", "\"Playful\"", "false", "1", "[]", "{}"]) func invalidMotionChoicesAreRejectedWithValueLocations(key: String, value: String) throws { let document = try TOMLDocument(parsing: "[motion]\n\(key) = \(value)") let result = ConfigValidator.validate(document) #expect(result.configuration == nil) let diagnostic = try #require(result.diagnostics.first) #expect(diagnostic.severity == .error) #expect(diagnostic.location == document.root["motion"]?[key]?.range.start) #expect(diagnostic.message.contains("motion.\(key)")) #expect(diagnostic.message.contains("For example:")) } @Test func allMotionSettingsCanBeCustomizedIndependently() throws { let motion = try configuration( """ [motion] enabled = false level = "extra" speed = 1.5 transitions = "ghost" focus-border = false sound = true menu-bar-icon = "logo" """ ).motion #expect( motion == MotionConfiguration( enabled: false, level: .extra, speed: 1.5, transitions: .ghost, focusBorder: false, sound: true, menuBarIcon: .logo)) } @Test func omittedMotionSettingsUseDefaults() throws { #expect(try configuration("[motion]").motion == MotionConfiguration()) #expect(try configuration("[motion]\nsound = true").motion == MotionConfiguration(sound: true)) #expect(try configuration("[motion]\nfocus-border = false").motion == MotionConfiguration(focusBorder: false)) } @Test(arguments: ["whimsy", "focus-bordr", "menu-bar-icn"]) func unknownMotionKeysWarnRatherThanChangeDefaults(key: String) throws { let result = try validate("[motion]\n\(key) = \"extra\"") #expect(result.configuration?.motion == MotionConfiguration()) #expect(result.diagnostics.count == 1) #expect(result.diagnostics.first?.severity == .warning) #expect(result.diagnostics.first?.message.contains("motion.\(key)") == true) } @Test func announcementCanBeEnabled() throws { #expect( try configuration("[accessibility]\nannounce-layout-changes = true").accessibility.announceLayoutChanges) } @Test(arguments: [ "general.launch-at-login", "motion.enabled", "motion.focus-border", "motion.sound", "mouse.enabled", "mouse.edge-snapping", "mouse.drop-to-ratio", "mouse.focus-follows-mouse", "hover-bar.enabled", "accessibility.announce-layout-changes", ]) func booleansRejectStrings(_ path: String) throws { #expect(try validate("\(path) = \"true\"").configuration == nil) } @Test(arguments: [ "general", "layout", "layout.gaps", "layout.reserved", "layout.displays", "motion", "keybindings", "accessibility", "mouse", "hover-bar", ]) func sectionsMustBeTables(_ path: String) throws { let result = try validate("\(path) = []") #expect(result.configuration == nil) #expect(result.diagnostics.contains { $0.message.contains("Expected a table") }) } } @Suite("Mouse configuration") struct MouseConfigurationTests { @Test func defaultsEnableDistinctCommandGestures() { let defaults = MouseConfiguration() #expect(defaults.enabled) #expect(defaults.swapModifiers == .command) #expect(defaults.stackModifiers == [.option, .command]) #expect(ParcelConfiguration.defaults.mouse == defaults) #expect(ParcelConfiguration().mouse == defaults) } @Test func initializerAndMutablePropertiesAreIndependent() { let custom = MouseConfiguration(enabled: false, swapModifiers: [.control, .shift], stackModifiers: .option) #expect(!custom.enabled) #expect(custom.swapModifiers == [.control, .shift]) #expect(custom.stackModifiers == .option) var configuration = ParcelConfiguration(mouse: custom) #expect(configuration.mouse == custom) #expect(configuration != .defaults) configuration.mouse.enabled = true #expect(configuration.mouse == MouseConfiguration(swapModifiers: [.control, .shift], stackModifiers: .option)) configuration.mouse.swapModifiers = .command #expect(configuration.mouse == MouseConfiguration(stackModifiers: .option)) configuration.mouse.stackModifiers = [.option, .command] #expect(configuration == .defaults) } @Test func omittedFieldsUseDefaultsAndEnabledCanBeDisabled() throws { #expect(try configuration("").mouse == MouseConfiguration()) #expect(try configuration("[mouse]").mouse == MouseConfiguration()) #expect(try configuration("[mouse]\nenabled = false").mouse == MouseConfiguration(enabled: false)) #expect( try configuration("[mouse]\nswap-modifiers = \"ctrl\"").mouse == MouseConfiguration(swapModifiers: .control) ) #expect( try configuration("[mouse]\nstack-modifiers = \"shift\"").mouse == MouseConfiguration(stackModifiers: .shift)) } @Test func allFieldsAcceptCustomSettings() throws { let mouse = try configuration( "[mouse]\nenabled = false\nswap-modifiers = \"CONTROL-SHIFT\"\nstack-modifiers = \"OPT\"" ).mouse #expect( mouse == MouseConfiguration(enabled: false, swapModifiers: [.control, .shift], stackModifiers: .option)) } @Test func chordAliasesNormalizeAndPrefixDoesNotAffectMouse() throws { let result = try configuration( "[general]\nprefix = \"fn\"\n[mouse]\nswap-modifiers = \"command\"\nstack-modifiers = \" CMD - OPTION \"" ) #expect(result.mouse == MouseConfiguration()) #expect(result.general.prefix == .fn) } @Test func inlineTablesAndDottedKeysAreSupported() throws { let expected = MouseConfiguration(enabled: false, swapModifiers: .shift, stackModifiers: [.control, .option]) #expect( try configuration("mouse = { enabled = false, swap-modifiers = 'shift', stack-modifiers = 'alt-ctrl' }") .mouse == expected) #expect( try configuration( "mouse.enabled = false\nmouse.swap-modifiers = 'shift'\nmouse.stack-modifiers = 'ctrl-alt'" ).mouse == expected) } @Test(arguments: UInt8(1)..<16, UInt8(1)..<16) func onlyEqualNonemptySetsAreAmbiguous(swapRawValue: UInt8, stackRawValue: UInt8) throws { let swap = MouseModifiers(rawValue: swapRawValue) let stack = MouseModifiers(rawValue: stackRawValue) let unused = (UInt8(1)..<16).map(MouseModifiers.init(rawValue:)).filter { $0 != swap && $0 != stack } let move = unused[0] let resize = unused[1] let result = try validate( "[mouse]\nswap-modifiers = \"\(swap)\"\nstack-modifiers = \"\(stack)\"\nmove-modifiers = \"\(move)\"\nresize-modifiers = \"\(resize)\"" ) if swap == stack { #expect(result.configuration == nil) #expect(result.diagnostics.count == 1) #expect(result.diagnostics.first?.severity == .error) } else { #expect(result.diagnostics.isEmpty) #expect( result.configuration?.mouse == MouseConfiguration( swapModifiers: swap, stackModifiers: stack, moveModifiers: move, resizeModifiers: resize)) } } @Test(arguments: [true, false]) func equalAliasesReportLaterAndRelatedValueLocations(reverse: Bool) throws { let swap = " swap-modifiers = \"COMMAND-OPTION\"" let stack = " stack-modifiers = \"alt-cmd\"" let source = "# café\n[mouse]\n" + (reverse ? "\(stack)\n\(swap)" : "\(swap)\n\(stack)") let document = try TOMLDocument(parsing: source) let result = ConfigValidator.validate(document) #expect(result.configuration == nil) #expect(result.diagnostics.count == 1) let diagnostic = try #require(result.diagnostics.first) let laterKey = reverse ? "swap-modifiers" : "stack-modifiers" let earlierKey = reverse ? "stack-modifiers" : "swap-modifiers" #expect(diagnostic.location == document.root["mouse"]?[laterKey]?.range.start) #expect(diagnostic.relatedLocation == document.root["mouse"]?[earlierKey]?.range.start) #expect(diagnostic.location.line == 4) #expect(diagnostic.relatedLocation?.line == 3) #expect(diagnostic.message.contains("mouse.swap-modifiers")) #expect(diagnostic.message.contains("mouse.stack-modifiers")) #expect(diagnostic.message.contains("alt-cmd")) #expect(diagnostic.message.contains("unambiguous")) } @Test(arguments: [ ("swap-modifiers", "command-alt", "stack-modifiers"), ("stack-modifiers", "CMD", "swap-modifiers"), ]) func equalityWithInheritedDefaultsIsIdentified(key: String, value: String, inheritedKey: String) throws { let document = try TOMLDocument(parsing: "[mouse]\n\(key) = \"\(value)\"") let result = ConfigValidator.validate(document) #expect(result.configuration == nil) #expect(result.diagnostics.count == 1) let diagnostic = try #require(result.diagnostics.first) #expect(diagnostic.location == document.root["mouse"]?[key]?.range.start) #expect(diagnostic.relatedLocation == nil) #expect(diagnostic.message.contains("inherited default")) #expect(diagnostic.message.contains("mouse.\(key)")) #expect(diagnostic.message.contains("mouse.\(inheritedKey)")) } @Test( arguments: ["swap-modifiers", "stack-modifiers"], ["", " ", "cmd-", "cmd-command", "alt-opt", "hyper-cmd", "fn", "cmd-a", "mystery"]) func invalidSetsRejectAtValueLocation(key: String, text: String) throws { let document = try TOMLDocument(parsing: "[mouse]\n \(key) = \"\(text)\"") let result = ConfigValidator.validate(document) #expect(result.configuration == nil) #expect(result.diagnostics.count == 1) let diagnostic = try #require(result.diagnostics.first) #expect(diagnostic.severity == .error) #expect(diagnostic.location == document.root["mouse"]?[key]?.range.start) #expect(diagnostic.location.line == 2) #expect(diagnostic.location.column == key.count + 6) #expect(diagnostic.relatedLocation == nil) #expect(diagnostic.message.contains("mouse.\(key)")) #expect(diagnostic.message.contains("For example:")) let fallback = key == "swap-modifiers" ? "cmd" : "alt-cmd" #expect(diagnostic.message.contains("\(key) = \"\(fallback)\"")) } @Test(arguments: ["swap-modifiers", "stack-modifiers"], ["true", "false", "1", "1.5", "[]", "{}"]) func modifierSetsRequireQuotedStrings(key: String, value: String) throws { let document = try TOMLDocument(parsing: "[mouse]\n\(key) = \(value)") let result = ConfigValidator.validate(document) #expect(result.configuration == nil) #expect(result.diagnostics.count == 1) let diagnostic = try #require(result.diagnostics.first) #expect(diagnostic.location == document.root["mouse"]?[key]?.range.start) #expect(diagnostic.message.contains("Expected a quoted string")) #expect(diagnostic.message.contains("mouse.\(key)")) } @Test(arguments: ["\"true\"", "1", "1.0", "[]", "{}"]) func enabledRequiresBoolean(value: String) throws { let document = try TOMLDocument(parsing: "[mouse]\nenabled = \(value)") let result = ConfigValidator.validate(document) #expect(result.configuration == nil) #expect(result.diagnostics.count == 1) #expect(result.diagnostics.first?.location == document.root["mouse"]?["enabled"]?.range.start) #expect(result.diagnostics.first?.message.contains("mouse.enabled") == true) #expect(result.diagnostics.first?.message.contains("true or false") == true) } @Test(arguments: ["true", "1", "\"cmd\"", "[]"]) func mouseSectionRequiresTable(value: String) throws { let document = try TOMLDocument(parsing: "mouse = \(value)") let result = ConfigValidator.validate(document) #expect(result.configuration == nil) #expect(result.diagnostics.count == 1) #expect(result.diagnostics.first?.location == document.root["mouse"]?.range.start) #expect(result.diagnostics.first?.message.contains("Expected a table for “mouse”") == true) } @Test(arguments: [ "swap-modfiers", "stack-modfiers", "move-modfiers", "resize-modfiers", "edge-snaping", "drop-to-rato", "focus-follows-mous", "focus-delai", "typing-cooldon", "enabld", ]) func unknownKeysWarnWithKeyLocationAndSuggestion(key: String) throws { let document = try TOMLDocument(parsing: "[mouse]\n \(key) = false") let result = ConfigValidator.validate(document) #expect(result.configuration?.mouse == MouseConfiguration()) #expect(result.diagnostics.count == 1) let diagnostic = try #require(result.diagnostics.first) #expect(diagnostic.severity == .warning) #expect(diagnostic.location == document.root["mouse"]?[key]?.keyRange?.start) #expect(diagnostic.message.contains("Did you mean")) } @Test func disabledGesturesStillValidateAndCollectIndependentErrors() throws { let result = try validate("[mouse]\nenabled = false\nswap-modifiers = \"\"\nstack-modifiers = \"fn\"") #expect(result.configuration == nil) #expect(result.diagnostics.count == 2) #expect(result.diagnostics.map(\.location.line) == [3, 4]) #expect(result.diagnostics.allSatisfy { $0.severity == .error }) #expect( try validate("[mouse]\nenabled = false\nswap-modifiers = \"cmd\"\nstack-modifiers = \"cmd\"").configuration == nil) } @Test func invalidModifierDoesNotCreateSpuriousDefaultConflict() throws { let result = try validate("[mouse]\nswap-modifiers = \"cmd-cmd\"\nstack-modifiers = \"cmd\"") #expect(result.configuration == nil) #expect(result.diagnostics.count == 1) #expect(result.diagnostics.first?.location.line == 2) } @Test func documentedDefaultMouseTableRoundTrips() throws { let root = URL(fileURLWithPath: #filePath) .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() let documentation = try String( contentsOf: root.appending(path: "Sources/ParcelConfig/ParcelConfig.docc/ParcelConfig.md"), encoding: .utf8) let blockStart = try #require(documentation.range(of: "```toml\n")) let blockEnd = try #require(documentation[blockStart.upperBound...].range(of: "\n```")) let document = try TOMLDocument(parsing: String(documentation[blockStart.upperBound.. ConfigValidationResult { ConfigValidator.validate(try TOMLDocument(parsing: source)) } private func configuration(_ source: String) throws -> ParcelConfiguration { let result = try validate(source) #expect(result.diagnostics.isEmpty) return try #require(result.configuration) } } extension ConfigValidationTests { @Test(arguments: [ ("bundle-id = \"com.example.app\"", FloatRule(bundleID: "com.example.app")), ("title-regex = \"^Preferences$\"", FloatRule(titleRegex: "^Preferences$")), ("role = \"AXDialog\"", FloatRule(role: "AXDialog")), ]) func floatRuleCanMatchEachField(_ assignment: String, _ expected: FloatRule) throws { #expect(try configuration("[[float-rules]]\n\(assignment)").floatRules == [expected]) } @Test func floatRuleCanCombineMatchers() throws { let value = try configuration( "[[float-rules]]\nbundle-id = \"com.example.app\"\ntitle-regex = \"Prefs.*\"\nrole = \"AXDialog\"") #expect(value.floatRules == [FloatRule(bundleID: "com.example.app", titleRegex: "Prefs.*", role: "AXDialog")]) } @Test func multipleFloatRulesPreserveOrder() throws { let value = try configuration( "[[float-rules]]\nrole = \"AXDialog\"\n[[float-rules]]\nbundle-id = \"com.example.app\"") #expect(value.floatRules == [FloatRule(role: "AXDialog"), FloatRule(bundleID: "com.example.app")]) } @Test func emptyFloatRulesArrayIsAccepted() throws { #expect(try configuration("float-rules = []").floatRules.isEmpty) } @Test func inlineFloatRuleTablesAreAccepted() throws { #expect(try configuration("float-rules = [{ role = \"AXDialog\" }]").floatRules.count == 1) } @Test func floatRulesMustBeAnArray() throws { #expect(try validate("[float-rules]\nrole = \"AXDialog\"").configuration == nil) } @Test func floatRuleElementsMustBeTables() throws { #expect(try validate("float-rules = [1]").configuration == nil) } @Test func floatRuleRequiresMatcher() throws { let result = try validate("[[float-rules]]") #expect(result.configuration == nil) #expect(result.diagnostics.contains { $0.message.contains("at least one matcher") }) } @Test func unknownMatcherDoesNotCountAsMatcher() throws { let result = try validate("[[float-rules]]\nbundle = \"com.example.app\"") #expect(result.configuration == nil) #expect(result.diagnostics.contains { $0.severity == .warning }) #expect(result.diagnostics.contains { $0.severity == .error }) } @Test(arguments: ["bundle-id", "title-regex", "role"]) func emptyMatchersAreRejected(_ key: String) throws { #expect(try validate("[[float-rules]]\n\(key) = \"\"").configuration == nil) #expect(try validate("[[float-rules]]\n\(key) = \" \"").configuration == nil) } @Test(arguments: ["bundle-id", "title-regex", "role"]) func matcherTypesAreChecked(_ key: String) throws { #expect(try validate("[[float-rules]]\n\(key) = 12").configuration == nil) } @Test func invalidRegexReportsValueLocation() throws { let document = try TOMLDocument(parsing: "[[float-rules]]\ntitle-regex = \"[\"") let result = ConfigValidator.validate(document) #expect(result.configuration == nil) let error = try #require(result.diagnostics.first) #expect(error.message.contains("regular expression")) #expect(error.location.line == 2) #expect(error.location.column == 15) } @Test func validRegexDoesNotTrimMeaningfulWhitespace() throws { #expect(try configuration("[[float-rules]]\ntitle-regex = \" a \"").floatRules.first?.titleRegex == " a ") } @Test func explicitBindingOverridesDefault() throws { #expect( try configuration("[keybindings]\nfocus-left = \"cmd-f20\"").keybindings[.focusLeft] == (try KeyChord(parsing: "cmd-f20"))) } @Test func falseRemovesBinding() throws { let value = try configuration("[keybindings]\nfocus-left = false") #expect(value.keybindings[.focusLeft] == nil) #expect(value.keybindings.count == DefaultKeybindings.bindings().count - 1) } @Test(arguments: ConfigCommand.allCases) func everyCommandCanBeRemoved(_ command: ConfigCommand) throws { #expect(try configuration("[keybindings]\n\"\(command.rawValue)\" = false").keybindings[command] == nil) } @Test(arguments: ConfigCommand.bindableCases) func everyCommandCanBeOverridden(_ command: ConfigCommand) throws { #expect( try configuration("[keybindings]\n\"\(command.rawValue)\" = \"cmd-f20\"").keybindings[command] == (try KeyChord(parsing: "cmd-f20"))) } @Test func allBindingsCanBeRemoved() throws { let text = "[keybindings]\n" + ConfigCommand.allCases.map { "\"\($0.rawValue)\" = false" }.joined(separator: "\n") #expect(try configuration(text).keybindings.isEmpty) } @Test(arguments: ["true", "1", "[]", "{}", "\"\"", "\"cmd\"", "\"cmd-notakey\""]) func invalidBindingValuesAreRejected(_ value: String) throws { let result = try validate("[keybindings]\nfocus-left = \(value)") #expect(result.configuration == nil) #expect(result.diagnostics.contains { $0.message.contains("For example:") }) } @Test func nativeBindingErrorsIncludeAValidQuotedAssignment() throws { let result = try validate("[keybindings]\n\"window-to-space 2 --follow\" = true") #expect(result.configuration == nil) #expect(result.diagnostics.first?.message.contains("\"window-to-space 2 --follow\" = false") == true) } @Test func duplicateExplicitBindingsIncludeBothValueLocations() throws { let document = try TOMLDocument(parsing: "[keybindings]\nfocus-left = \"cmd-f20\"\nfocus-right = \"cmd-f20\"") let result = ConfigValidator.validate(document) #expect(result.configuration == nil) let error = try #require(result.diagnostics.first) #expect(error.location == document.root["keybindings"]?["focus-right"]?.range.start) #expect(error.relatedLocation == document.root["keybindings"]?["focus-left"]?.range.start) #expect(error.message.contains("focus-left")) #expect(error.message.contains("focus-right")) #expect(error.message.contains("= false")) #expect(error.description.contains("line 3, column 15")) #expect(error.description.contains("line 2, column 14")) } @Test func aliasesResolveBeforeDuplicateCheck() throws { let result = try validate("[keybindings]\nfocus-left = \"CTRL-OPT-ESC\"\nfocus-right = \"alt-ctrl-escape\"") #expect(result.configuration == nil) #expect(result.diagnostics.count == 1) #expect(result.diagnostics.first?.relatedLocation != nil) } @Test func shiftedPunctuationResolvesBeforeDuplicateCheck() throws { let result = try validate("[keybindings]\nfocus-left = \"cmd-!\"\nfocus-right = \"cmd-shift-1\"") #expect(result.configuration == nil) #expect(result.diagnostics.count == 1) } @Test func explicitShortcutDisplacesInheritedDefaultWithWarning() throws { let chord = try #require(DefaultKeybindings.bindings()[.focusRight]) let document = try TOMLDocument(parsing: "[keybindings]\nfocus-left = \"\(chord.description)\"") let result = ConfigValidator.validate(document) let configuration = try #require(result.configuration) #expect(configuration.keybindings[.focusLeft] == chord) #expect(configuration.keybindings[.focusRight] == nil) #expect( configuration.inheritedShortcutDisplacements == [ InheritedShortcutDisplacement(command: .focusRight, chord: chord, binding: .command(.focusLeft)) ]) let warning = try #require(result.diagnostics.first) #expect(warning.severity == .warning) #expect(warning.message.contains("Unbound because keybindings.focus-left uses this key")) #expect(warning.message.contains("focus-right")) #expect(warning.location == document.root["keybindings"]?["focus-left"]?.range.start) #expect(warning.relatedLocation == document.root.range.start) } @Test func inheritedConflictPointsToChangedPrefix() throws { let chord = try #require(DefaultKeybindings.bindings(prefix: .fn)[.focusRight]) let document = try TOMLDocument( parsing: "[general]\nprefix = \"fn\"\n[keybindings]\nfocus-left = \"\(chord.description)\"") let result = ConfigValidator.validate(document) let error = try #require(result.diagnostics.first) #expect(error.relatedLocation == document.root["general"]?["prefix"]?.range.start) #expect(result.configuration != nil) #expect(error.severity == .warning) #expect(error.message.contains("Unbound because")) } @Test func disablingInheritedBindingResolvesConflict() throws { let chord = try #require(DefaultKeybindings.bindings()[.focusRight]) #expect( try validate("[keybindings]\nfocus-left = \"\(chord.description)\"\nfocus-right = false").configuration != nil) } @Test func overridingInheritedBindingResolvesConflict() throws { let chord = try #require(DefaultKeybindings.bindings()[.focusRight]) #expect( try validate("[keybindings]\nfocus-left = \"\(chord.description)\"\nfocus-right = \"cmd-f20\"") .configuration != nil) } @Test func threeDuplicateBindingsReportEachAdditionalBinding() throws { let result = try validate( "[keybindings]\nfocus-left = \"cmd-f20\"\nfocus-right = \"cmd-f20\"\nfocus-up = \"cmd-f20\"") #expect(result.diagnostics.count == 2) #expect(result.diagnostics.allSatisfy { $0.relatedLocation?.line == 2 }) } @Test func unknownRootKeyWarnsWithoutRejecting() throws { let result = try validate("future-feature = true") #expect(result.configuration == .defaults) #expect(result.diagnostics.first?.severity == .warning) } @Test func obsoleteKeyWarnsAtKeyRangeAndRetainsConfiguration() throws { let document = try TOMLDocument(parsing: "[general]\nprefix = 'fn'\n launch_at_login = true") let result = ConfigValidator.validate(document) #expect(result.configuration == (try configuration("[general]\nprefix = 'fn'"))) #expect(result.configuration?.general.launchAtLogin == false) #expect(result.configuration?.general.prefix == .fn) #expect(result.diagnostics.count == 1) let diagnostic = try #require(result.diagnostics.first) #expect(diagnostic.severity == .warning) #expect(diagnostic.location == document.root["general"]?["launch_at_login"]?.keyRange?.start) #expect(diagnostic.location.line == 3) #expect(diagnostic.location.column == 3) #expect(diagnostic.message.contains("Unknown key “general.launch_at_login”")) #expect(diagnostic.message.contains("Did you mean “general.launch-at-login”")) } @Test func nearbyUnknownKeyGetsSuggestion() throws { let result = try validate("[general]\nlaunch-at-logn = true") #expect(result.diagnostics.first?.message.contains("general.launch-at-login") == true) #expect(result.diagnostics.first?.message.contains("Did you mean") == true) } @Test func underscoreSpellingWarnsWithDashedKeySuggestion() throws { let document = try TOMLDocument(parsing: "[layout]\nratio = 0.6\nwindow_cap = 2") let result = ConfigValidator.validate(document) #expect(result.configuration == (try configuration("[layout]\nratio = 0.6"))) #expect(result.configuration?.layout.global.windowCap == 3) #expect(result.configuration?.layout.global.ratio == 0.6) #expect(result.diagnostics.count == 1) let diagnostic = try #require(result.diagnostics.first) #expect(diagnostic.severity == .warning) #expect(diagnostic.location == document.root["layout"]?["window_cap"]?.keyRange?.start) #expect(diagnostic.location.line == 3) #expect(diagnostic.location.column == 1) #expect(diagnostic.message.contains("Unknown key “layout.window_cap”")) #expect(diagnostic.message.contains("Did you mean “layout.window-cap”")) } @Test(arguments: [false, true]) func underscoreWarningsDoNotHideInvalidCanonicalValues(obsoleteFirst: Bool) throws { let obsolete = " window_cap = 2" let canonical = " window-cap = '2'" let source = "[layout]\n" + (obsoleteFirst ? obsolete + "\n" + canonical : canonical + "\n" + obsolete) let document = try TOMLDocument(parsing: source) let result = ConfigValidator.validate(document) #expect(result.configuration == nil) #expect(result.diagnostics.count == 2) #expect(result.diagnostics.map(\.severity) == (obsoleteFirst ? [.warning, .error] : [.error, .warning])) let warning = try #require(result.diagnostics.first { $0.severity == .warning }) #expect(warning.location == document.root["layout"]?["window_cap"]?.keyRange?.start) #expect(warning.message.contains("Did you mean “layout.window-cap”")) let error = try #require(result.diagnostics.first { $0.severity == .error }) #expect(error.location == document.root["layout"]?["window-cap"]?.range.start) #expect(error.message.contains("layout.window-cap")) #expect(error.message.contains("whole number")) } @Test func transposedLettersGetSuggestion() throws { let result = try validate("[layuot]") #expect(result.diagnostics.first?.message.contains("Did you mean “layout”") == true) } @Test func distantUnknownKeyDoesNotGetUnhelpfulSuggestion() throws { let result = try validate("something-entirely-different = true") #expect(result.diagnostics.first?.message.contains("Did you mean") == false) } @Test func unknownCommandGetsSuggestion() throws { let result = try validate("[keybindings]\nfocsu-left = false") #expect(result.configuration != nil) #expect(result.diagnostics.first?.message.contains("keybindings.focus-left") == true) } @Test(arguments: [ "layout.gaps.iner", "layout.reserved.tpo", "motion.speeed", "accessibility.announce-layout-change", ]) func nestedUnknownKeysWarn(_ path: String) throws { let result = try validate("\(path) = 1") #expect(result.configuration != nil) #expect(result.diagnostics.first?.severity == .warning) #expect(result.diagnostics.first?.message.contains("Did you mean") == true) } @Test( arguments: [("mouse", "focus-delay", "focus_delay"), ("hover-bar", "delay", "delai")], [false, true]) func mouseAndHoverWarningsDoNotHideInvalidCanonicalValues(setting: (String, String, String), unknownFirst: Bool) throws { let (table, key, unknownKey) = setting let unknown = " \(unknownKey) = 0.8" let canonical = " \(key) = 'slow'" let source = "[\(table)]\n" + (unknownFirst ? unknown + "\n" + canonical : canonical + "\n" + unknown) let document = try TOMLDocument(parsing: source) let result = ConfigValidator.validate(document) #expect(result.configuration == nil) #expect(result.diagnostics.count == 2) #expect(result.diagnostics.map(\.severity) == (unknownFirst ? [.warning, .error] : [.error, .warning])) let warning = try #require(result.diagnostics.first { $0.severity == .warning }) #expect(warning.location == document.root[table]?[unknownKey]?.keyRange?.start) #expect(warning.message.contains("Unknown key “\(table).\(unknownKey)”")) #expect(warning.message.contains("Did you mean “\(table).\(key)”")) let error = try #require(result.diagnostics.first { $0.severity == .error }) #expect(error.location == document.root[table]?[key]?.range.start) #expect(error.message.contains("Expected a number")) #expect(error.message.contains("\(table).\(key)")) } @Test(arguments: ["mouse", "hover-bar"]) func distantUnknownMouseAndHoverKeysWarnAndPreserveDefaults(table: String) throws { let document = try TOMLDocument(parsing: "[\(table)]\n future-pointer-setting = []") let result = ConfigValidator.validate(document) #expect(result.configuration == .defaults) #expect(result.diagnostics.count == 1) let warning = try #require(result.diagnostics.first) #expect(warning.severity == .warning) #expect(warning.location == document.root[table]?["future-pointer-setting"]?.keyRange?.start) #expect(warning.message.contains("Unknown key “\(table).future-pointer-setting”")) #expect(warning.message.contains("this setting is ignored")) #expect(!warning.message.contains("Did you mean")) } @Test func knownWrongTypeUsesValueRange() throws { let document = try TOMLDocument(parsing: "[motion]\n speed = \"fast\"") let result = ConfigValidator.validate(document) #expect(result.diagnostics.first?.location == document.root["motion"]?["speed"]?.range.start) #expect(result.diagnostics.first?.location.column == 11) } @Test func multipleErrorsAreCollectedAndSorted() throws { let result = try validate("version = 2\n[layout]\nratio = 4\n[motion]\nenabled = \"yes\"") #expect(result.configuration == nil) #expect(result.diagnostics.count == 3) #expect(result.diagnostics.map(\.location.line) == [1, 3, 5]) } @Test func warningsDoNotHideErrors() throws { let result = try validate("mystery = true\nversion = 2") #expect(result.configuration == nil) #expect(result.diagnostics.map(\.severity) == [.warning, .error]) } @Test func validationIsDeterministic() throws { let document = try TOMLDocument(parsing: "[layout]\nz = true\nx = 4\nratio = 7") #expect(ConfigValidator.validate(document) == ConfigValidator.validate(document)) } private func validate(_ source: String) throws -> ConfigValidationResult { ConfigValidator.validate(try TOMLDocument(parsing: source)) } private func configuration(_ source: String) throws -> ParcelConfiguration { let result = try validate(source) #expect(result.diagnostics.isEmpty) return try #require(result.configuration) } struct NumericField: Sendable { let path: String let lower: String let upper: String let below: String let above: String } static let numericFields: [NumericField] = [ NumericField(path: "layout.ratio", lower: "0.1", upper: "0.9", below: "0.099", above: "0.901"), NumericField(path: "layout.gaps.inner", lower: "0", upper: "256", below: "-0.1", above: "256.1"), NumericField(path: "layout.gaps.outer", lower: "0", upper: "256", below: "-0.1", above: "256.1"), NumericField(path: "layout.reserved.top", lower: "0", upper: "4096", below: "-0.1", above: "4096.1"), NumericField(path: "layout.reserved.right", lower: "0", upper: "4096", below: "-0.1", above: "4096.1"), NumericField(path: "layout.reserved.bottom", lower: "0", upper: "4096", below: "-0.1", above: "4096.1"), NumericField(path: "layout.reserved.left", lower: "0", upper: "4096", below: "-0.1", above: "4096.1"), NumericField(path: "layout.window-cap", lower: "0", upper: "100", below: "-1", above: "101"), NumericField(path: "motion.speed", lower: "0.1", upper: "4", below: "0.099", above: "4.001"), NumericField(path: "appearance.border-opacity", lower: "0", upper: "1", below: "-0.001", above: "1.001"), NumericField(path: "appearance.border-radius", lower: "0", upper: "40", below: "-0.001", above: "40.001"), NumericField(path: "mouse.focus-delay", lower: "0.1", upper: "3", below: "0.099", above: "3.001"), NumericField(path: "mouse.typing-cooldown", lower: "0", upper: "10", below: "-0.001", above: "10.001"), NumericField(path: "hover-bar.delay", lower: "0.1", upper: "3", below: "0.099", above: "3.001"), ] }