import Foundation import Testing @testable import ParcelConfig @Suite("Configuration JSON Schema") struct ConfigJSONSchemaTests { @Test func schemaIsDraft202012() throws { #expect(try schema()["$schema"] == .string("https://json-schema.org/draft/2020-12/schema")) } @Test func schemaDescribesRootTable() throws { #expect(try schema()["type"] == .string("object")) } @Test func schemaExposesSupportedRootKeys() throws { let properties = try #require(schema()["properties"]?.object) #expect( Set(properties.keys) == [ "version", "general", "layout", "motion", "mouse", "hover-bar", "keybindings", "float-rules", "rules", "accessibility", "mode", "classification", "callbacks", "focus-modes", "memory", "appearance", ]) } @Test func schemaVersionIsOptionalButConstrainedToOne() throws { let root = try schema() #expect(root["required"] == nil) #expect(root["properties"]?["version"]?["const"] == .number(1)) #expect(root["properties"]?["version"]?["default"] == .number(1)) } @Test(arguments: ["general", "motion", "focus-modes", "mouse", "hover-bar"]) func schemaAllowsUnknownKeysForValidatorWarnings(table: String) throws { #expect(try schema()["additionalProperties"] == .bool(true)) #expect(try schema()["properties"]?[table]?["additionalProperties"] == .bool(true)) } @Test func schemaGeneralDefaultsMatchModel() throws { let general = try schema()["properties"]?["general"]?["properties"] #expect(general?["prefix"]?["default"] == .string(ParcelConfiguration.defaults.general.prefix.description)) #expect(general?["launch-at-login"]?["default"] == .bool(false)) #expect(general?["shortcuts-enabled"]?["default"] == .bool(true)) #expect(general?["when-display-full"]?["default"] == .string("swap")) #expect(general?["when-display-full"]?["enum"] == .array([.string("swap"), .string("stack")])) } @Test func schemaLayoutEnumMatchesModel() throws { let layout = try schema()["properties"]?["layout"]?["properties"]?["default"] #expect(layout?["enum"] == .array(ConfigLayout.allCases.map { .string($0.rawValue) })) #expect(layout?["default"] == .string(ParcelConfiguration.defaults.layout.global.defaultLayout.rawValue)) } @Test func schemaMousePropertiesMatchPublicConfiguration() throws { let mouse = try #require(schema()["properties"]?["mouse"]) #expect(mouse["type"] == .string("object")) #expect(mouse["required"] == nil) #expect(mouse["additionalProperties"] == .bool(true)) let properties = try #require(mouse["properties"]?.object) #expect( Set(properties.keys) == [ "enabled", "swap-modifiers", "stack-modifiers", "move-modifiers", "resize-modifiers", "edge-snapping", "drop-to-ratio", "focus-follows-mouse", "focus-delay", "typing-cooldown", ]) let defaults = ParcelConfiguration.defaults.mouse for (key, expected) in [ ("enabled", defaults.enabled), ("edge-snapping", defaults.edgeSnapping), ("drop-to-ratio", defaults.dropToRatio), ("focus-follows-mouse", defaults.focusFollowsMouse), ] { #expect(properties[key]?["type"] == .string("boolean")) #expect(properties[key]?["default"] == .bool(expected)) } #expect(mouse["description"]?.string?.contains("distinct nonempty") == true) #expect(mouse["description"]?.string?.contains("subset is allowed") == true) } @Test(arguments: ["swap-modifiers", "stack-modifiers", "move-modifiers", "resize-modifiers"]) func schemaMouseModifierSetsAreNonblankFormattedStrings(key: String) throws { let property = try #require(schema()["properties"]?["mouse"]?["properties"]?[key]) #expect(property["type"] == .string("string")) #expect(property["minLength"] == .number(1)) #expect(property["pattern"] == .string("\\S")) #expect(property["format"] == .string("parcel-mouse-modifiers")) let pattern = try NSRegularExpression(pattern: #require(property["pattern"]?.string)) #expect(pattern.firstMatch(in: " ", range: NSRange(location: 0, length: 3)) == nil) #expect(pattern.firstMatch(in: "cmd", range: NSRange(location: 0, length: 3)) != nil) let defaults = ParcelConfiguration.defaults.mouse let expected = try #require( [ "swap-modifiers": defaults.swapModifiers, "stack-modifiers": defaults.stackModifiers, "move-modifiers": defaults.moveModifiers, "resize-modifiers": defaults.resizeModifiers, ][key]) let defaultText = try #require(property["default"]?.string) #expect(defaultText == expected.description) #expect(try MouseModifiers(parsing: defaultText) == expected) } @Test func schemaMouseDefaultsRoundTripThroughTOML() throws { let properties = try #require(schema()["properties"]?["mouse"]?["properties"]) let swap = try #require(properties["swap-modifiers"]?["default"]?.string) let stack = try #require(properties["stack-modifiers"]?["default"]?.string) let move = try #require(properties["move-modifiers"]?["default"]?.string) let resize = try #require(properties["resize-modifiers"]?["default"]?.string) let focusDelay = try #require(properties["focus-delay"]?["default"]?.number) let typingCooldown = try #require(properties["typing-cooldown"]?["default"]?.number) #expect(focusDelay == ParcelConfiguration.defaults.mouse.focusDelay) #expect(typingCooldown == ParcelConfiguration.defaults.mouse.typingCooldown) let source = """ [mouse] enabled = \(properties["enabled"]?["default"] == .bool(true)) swap-modifiers = "\(swap)" stack-modifiers = "\(stack)" move-modifiers = "\(move)" resize-modifiers = "\(resize)" edge-snapping = \(properties["edge-snapping"]?["default"] == .bool(true)) drop-to-ratio = \(properties["drop-to-ratio"]?["default"] == .bool(true)) focus-follows-mouse = \(properties["focus-follows-mouse"]?["default"] == .bool(true)) focus-delay = \(focusDelay) typing-cooldown = \(typingCooldown) """ + "\n" let document = try TOMLDocument(parsing: source) let result = ConfigValidator.validate(document) #expect(result.diagnostics.isEmpty) #expect(result.configuration == .defaults) #expect(document.render() == source) #expect(ConfigValidator.validate(try TOMLDocument(parsing: document.render())) == result) let comment = try #require(schema()["$comment"]?.string) #expect(comment.contains("parcel-mouse-modifiers")) #expect(comment.contains("distinct resolved mouse modifier sets")) #expect(comment.contains("inherited defaults")) } @Test func schemaMotionKeysMatchThePublicConfiguration() throws { let motion = try #require(schema()["properties"]?["motion"]?["properties"]?.object) #expect( Set(motion.keys) == [ "enabled", "level", "speed", "transitions", "sound", "highlight", "focus-border", "menu-bar-icon", "drop-hints", "experimental-dimming", "highlight-width", ]) } @Test func schemaHighlightsMatchConfigurationAndExplainLegacyPrecedence() throws { let motion = try #require(schema()["properties"]?["motion"]?["properties"]) #expect(motion["highlight"]?["enum"] == .array(ConfigHighlight.allCases.map { .string($0.rawValue) })) #expect(motion["highlight"]?["default"] == .string("active")) #expect(motion["highlight-width"]?["type"] == .string("number")) #expect(motion["highlight-width"]?["minimum"] == .number(MotionConfiguration.highlightWidths.lowerBound)) #expect(motion["highlight-width"]?["maximum"] == .number(MotionConfiguration.highlightWidths.upperBound)) #expect(motion["highlight-width"]?["default"] == .number(2)) #expect(motion["focus-border"]?["deprecated"] == .bool(true)) #expect(motion["focus-border"]?["description"]?.string?.contains("explicit highlight takes precedence") == true) } @Test func schemaOnlyPublishesDashedSettingKeys() throws { func check(_ node: TestJSON) { switch node { case .object(let values): if let properties = values["properties"]?.object { #expect(properties.keys.allSatisfy { !$0.contains("_") }) } for value in values.values { check(value) } case .array(let values): for value in values { check(value) } default: break } } check(try schema()) } @Test func schemaAppearanceDefaultsRoundTripWithoutInventingColorOverrides() throws { let appearance = try #require(schema()["properties"]?["appearance"]) #expect(appearance["required"] == nil) #expect(appearance["additionalProperties"] == .bool(true)) let properties = try #require(appearance["properties"]?.object) #expect( Set(properties.keys) == Set( ["palette", "mode", "stack-controls", "border-opacity", "border-radius"] + AppearanceColorRole.allCases.map(\.rawValue))) #expect(properties["palette"]?["enum"] == .array(ConfigAppearancePalette.allCases.map { .string($0.rawValue) })) #expect(properties["mode"]?["enum"] == .array(ConfigAppearanceMode.allCases.map { .string($0.rawValue) })) #expect(properties["stack-controls"]?["enum"] == .array([.string("on-demand"), .string("persistent")])) #expect(properties["stack-controls"]?["default"] == .string("on-demand")) let palette = try #require(properties["palette"]?["default"]?.string) let mode = try #require(properties["mode"]?["default"]?.string) let stackControls = try #require(properties["stack-controls"]?["default"]?.string) let opacity = try #require(properties["border-opacity"]?["default"]?.number) #expect(properties["border-radius"]?["default"] == nil) #expect(properties["border-radius"]?["type"] == .string("number")) #expect(properties["border-radius"]?["minimum"] == .number(AppearanceConfiguration.borderRadii.lowerBound)) #expect(properties["border-radius"]?["maximum"] == .number(AppearanceConfiguration.borderRadii.upperBound)) #expect(properties["border-radius"]?["description"]?.string?.contains("native corner radius") == true) let source = "[appearance]\npalette = '\(palette)'\nmode = '\(mode)'\nborder-opacity = \(opacity)\n" + "stack-controls = '\(stackControls)'\n" let result = ConfigValidator.validate(try TOMLDocument(parsing: source)) #expect(result.diagnostics.isEmpty) #expect(result.configuration?.appearance == ParcelConfiguration.defaults.appearance) for role in AppearanceColorRole.allCases { #expect(properties[role.rawValue]?["default"] == nil) } } @Test(arguments: AppearanceColorRole.allCases) func schemaColorConstraintsAgreeWithStrictHexParsing(role: AppearanceColorRole) throws { let property = try #require(schema()["properties"]?["appearance"]?["properties"]?[role.rawValue]) #expect(property["type"] == .string("string")) let pattern = try #require(property["pattern"]?.string) let minimum = try #require(property["minLength"]?.number) let maximum = try #require(property["maxLength"]?.number) for hex in [ "#000000", "#ffffff", "#a1B2c3", "#123", "#12345678", "#G12345", "#123456", " #123456", "#123456 ", "#123456\n", "123456", "#+12345", ] { let length = Double(hex.unicodeScalars.count) let accepted = try matches(pattern, hex) && length >= minimum && length <= maximum #expect(accepted == (AppearanceHexColor(hex: hex) != nil)) } } @Test func schemaFocusModesMatchDefaultsAndValidation() throws { let modes = try #require(schema()["properties"]?["focus-modes"]?["properties"]?.object) #expect(Set(modes.keys) == ["no-peek-level", "no-peek-blur", "clean-space-color"]) #expect(modes["no-peek-level"]?["type"] == .string("number")) #expect(modes["no-peek-level"]?["minimum"] == .number(FocusModeConfiguration.noPeekLevels.lowerBound)) #expect(modes["no-peek-level"]?["maximum"] == .number(FocusModeConfiguration.noPeekLevels.upperBound)) #expect(modes["no-peek-level"]?["default"] == .number(ParcelConfiguration.defaults.focusModes.noPeekLevel)) #expect(modes["no-peek-blur"]?["type"] == .string("boolean")) #expect(modes["no-peek-blur"]?["default"] == .bool(ParcelConfiguration.defaults.focusModes.noPeekBlur)) #expect( modes["clean-space-color"]?["enum"] == .array(ConfigCleanSpaceColor.allCases.map { .string($0.rawValue) })) #expect(modes["clean-space-color"]?["default"] == .string("graphite")) } @Test func schemaFocusCommandsAreNoLongerReserved() throws { let bindings = try #require(schema()["properties"]?["keybindings"]) for command in [ConfigCommand.toggleFocus, .toggleNoPeek, .toggleCleanSpace] { let property = try #require(bindings["properties"]?[command.rawValue]) let chord = try #require(DefaultKeybindings.bindings()[command]) #expect(property["description"]?.string?.contains("Reserved") == false) #expect(property["default"] == .string(chord.description)) #expect(bindings["default"]?[command.rawValue] == .string(chord.description)) } } @Test func schemaMotionLevelEnumMatchesModel() throws { let level = try schema()["properties"]?["motion"]?["properties"]?["level"] #expect(level?["type"] == .string("string")) #expect(level?["enum"] == .array(ConfigMotionLevel.allCases.map { .string($0.rawValue) })) #expect(level?["default"] == .string(ParcelConfiguration.defaults.motion.level.rawValue)) } @Test func schemaMotionTransitionEnumMatchesModel() throws { let transitions = try schema()["properties"]?["motion"]?["properties"]?["transitions"] #expect(transitions?["type"] == .string("string")) #expect(transitions?["enum"] == .array(ConfigMotionTransition.allCases.map { .string($0.rawValue) })) #expect(transitions?["default"] == .string(ParcelConfiguration.defaults.motion.transitions.rawValue)) } @Test func schemaMenuBarIconEnumMatchesModel() throws { let icon = try schema()["properties"]?["motion"]?["properties"]?["menu-bar-icon"] #expect(icon?["type"] == .string("string")) #expect(icon?["enum"] == .array(ConfigMenuBarIcon.allCases.map { .string($0.rawValue) })) #expect(icon?["default"] == .string(ParcelConfiguration.defaults.motion.menuBarIcon.rawValue)) } @Test func schemaMotionBooleanAndSpeedDefaultsMatchModel() throws { let motion = try schema()["properties"]?["motion"]?["properties"] let defaults = ParcelConfiguration.defaults.motion for (key, expected) in [ ("enabled", defaults.enabled), ("focus-border", defaults.focusBorder), ("sound", defaults.sound), ("drop-hints", defaults.dropHints), ("experimental-dimming", defaults.experimentalDimming), ] { #expect(motion?[key]?["type"] == .string("boolean")) #expect(motion?[key]?["default"] == .bool(expected)) } #expect(motion?["speed"]?["type"] == .string("number")) #expect(motion?["speed"]?["default"] == .number(defaults.speed)) } @Test(arguments: ConfigValidationTests.numericFields) func schemaBoundsMatchValidation(_ field: ConfigValidationTests.NumericField) throws { var node: TestJSON? = try schema() for key in field.path.split(separator: ".") { node = node?["properties"]?[String(key)] } #expect(node?["minimum"] == Double(field.lower).map(TestJSON.number)) #expect(node?["maximum"] == Double(field.upper).map(TestJSON.number)) if field.path == "appearance.border-radius" { #expect(node?["default"] == nil) } else { #expect(node?["default"] != nil) } } @Test func schemaWindowCapDistinguishesRequestedAndEffectiveLimits() throws { let global = try #require(schema()["properties"]?["layout"]?["properties"]) let display = try #require(global["displays"]?["additionalProperties"]?["properties"]) for properties in [global, display] { let cap = try #require(properties["window-cap"]) #expect(cap["type"] == .string("integer")) #expect(cap["minimum"] == .number(0)) #expect(cap["maximum"] == .number(100)) #expect(cap["description"]?.string?.contains("0 means unlimited") == true) #expect(cap["description"]?.string?.contains("bypasses layout capability limits") == true) #expect(cap["description"]?.string?.contains("Positive caps are limited") == true) #expect(cap["description"]?.string?.contains("without changing the request") == true) #expect(cap["description"]?.string?.contains("when-full") == true) #expect(cap["description"]?.string?.contains("when_full") == false) } } @Test func schemaLayoutOnlyDescribesCanonicalKebabKeysWhilePreservingUnknownKeyWarnings() throws { let layout = try #require(schema()["properties"]?["layout"]) let properties = try #require(layout["properties"]?.object) let expected: Set = [ "default", "portrait-layout", "ratio", "gaps", "reserved", "window-cap", "when-full", ] #expect(Set(properties.keys) == expected.union(["displays"])) #expect(layout["additionalProperties"] == .bool(true)) let display = try #require(properties["displays"]?["additionalProperties"]) #expect(Set(try #require(display["properties"]?.object).keys) == expected) #expect(display["additionalProperties"] == .bool(true)) for table in [layout, display] { #expect(table["properties"]?["portrait_layout"] == nil) #expect(table["properties"]?["when_full"] == nil) #expect(table["properties"]?["default"]?["description"]?.string?.contains("portrait-layout") == true) } } @Test func schemaLayoutDefaultsRoundTripTogetherThroughCanonicalTOMLKeys() throws { let properties = try #require(schema()["properties"]?["layout"]?["properties"]) let layout = try #require(properties["default"]?["default"]?.string) let portrait = try #require(properties["portrait-layout"]?["default"]?.string) let behavior = try #require(properties["when-full"]?["default"]?.string) let cap = try #require(properties["window-cap"]?["default"]?.number) let source = """ [layout] default = "\(layout)" portrait-layout = "\(portrait)" when-full = "\(behavior)" window-cap = \(try #require(Int(exactly: cap))) [layout.displays."00000000-0000-0000-0000-000000000001"] """ let result = ConfigValidator.validate(try TOMLDocument(parsing: source)) #expect(result.diagnostics.isEmpty) let configuration = try #require(result.configuration) #expect(configuration.layout.global == ParcelConfiguration.defaults.layout.global) #expect(configuration.layout.displays.count == 1) #expect(configuration.layout.displays.values.allSatisfy { $0 == configuration.layout.global }) } @Test func schemaPortraitLayoutsExposeChoicesAndInheritedDefaults() throws { let global = try #require(schema()["properties"]?["layout"]?["properties"]) let display = try #require(global["displays"]?["additionalProperties"]?["properties"]) #expect(global["portrait-layout"]?["default"] == .string("rows")) #expect(display["portrait-layout"]?["default"] == nil) for properties in [global, display] { let portrait = try #require(properties["portrait-layout"]) #expect(portrait["enum"] == .array(ConfigLayout.allCases.map { .string($0.rawValue) })) #expect(portrait["description"]?.string?.contains("taller than they are wide") == true) } } @Test func schemaWindowCapIsInteger() throws { let cap = try schema()["properties"]?["layout"]?["properties"]?["window-cap"] #expect(cap?["type"] == .string("integer")) #expect(cap?["default"] == .number(3)) #expect(cap?["minimum"] == .number(0)) #expect(cap?["maximum"] == .number(100)) #expect(cap?["description"]?.string?.contains("0 means unlimited") == true) } @Test func schemaOverflowBehaviorMatchesModelAndDisplayInheritance() throws { let layout = try schema()["properties"]?["layout"]?["properties"] let behavior = try #require(layout?["when-full"]) #expect(behavior["type"] == .string("string")) #expect(behavior["enum"] == .array(ConfigWhenFull.allCases.map { .string($0.rawValue) })) #expect(behavior["default"] == .string("stack")) let override = try #require(layout?["displays"]?["additionalProperties"]?["properties"]?["when-full"]) #expect(override["type"] == behavior["type"]) #expect(override["enum"] == behavior["enum"]) #expect(override["default"] == nil) } @Test func schemaDescribesWindowRuleAndPointerCommands() throws { let commands: [ConfigCommand] = [ .makePrimary, .windowNext, .windowPrevious, .resetSizes, .unstack, .close, .toggleFullscreen, .alwaysFloat, .undoLastRule, .toggleBorders, .toggleHoverFocus, .undo, ] + (0...5).map { .setWindowCap($0) } let root = try schema() let bindings = root["properties"]?["keybindings"] for command in commands { let property = try #require(bindings?["properties"]?[command.rawValue]) #expect(property["description"]?.string?.isEmpty == false) let mode = root["properties"]?["mode"]?["additionalProperties"]?["properties"]?[command.rawValue] #expect(mode?["description"] == property["description"]) } for command in [ConfigCommand.alwaysFloat, .undoLastRule, .toggleHoverFocus] { let chord = try #require(DefaultKeybindings.bindings()[command]) #expect(bindings?["properties"]?[command.rawValue]?["default"] == .string(chord.description)) #expect(bindings?["default"]?[command.rawValue] == .string(chord.description)) } } @Test(arguments: [ConfigCommand.ratioHalf, .ratioThreeFifths, .ratioTwoThirds]) func schemaMainSizePresetsAreDescribedButUnbound(command: ConfigCommand) throws { let root = try schema() let property = try #require(root["properties"]?["keybindings"]?["properties"]?[command.rawValue]) #expect(property["description"]?.string?.contains("main tile size") == true) #expect(property["default"] == nil) #expect(root["properties"]?["keybindings"]?["default"]?[command.rawValue] == nil) let named = try #require(root["properties"]?["mode"]?["additionalProperties"]?["properties"]?[command.rawValue]) #expect(named["description"] == property["description"]) #expect(named["default"] == nil) } @Test(arguments: 1...5) func schemaCountPresetsDescribeEffectiveClampingWithoutRejectingRequests(count: Int) throws { let key = ConfigCommand.setWindowCap(count).rawValue let property = try #require(schema()["properties"]?["keybindings"]?["properties"]?[key]) let description = try #require(property["description"]?.string) #expect(description.contains("effective cap is limited")) #expect(description.contains("without changing the request")) #expect(!description.contains("rejected")) } @Test func schemaDisplayKeysAreUUIDs() throws { let displays = try schema()["properties"]?["layout"]?["properties"]?["displays"] let pattern = try #require(displays?["propertyNames"]?["pattern"]?.string) let regex = try NSRegularExpression(pattern: pattern) let id = "A1B2C3D4-1234-5678-9ABC-0123456789AB" #expect(regex.firstMatch(in: id, range: NSRange(id.startIndex..., in: id)) != nil) #expect(regex.firstMatch(in: "invalid", range: NSRange(location: 0, length: 7)) == nil) } @Test func schemaDisplayOverridesDoNotShadowInheritedDefaults() throws { let override = try schema()["properties"]?["layout"]?["properties"]?["displays"]?["additionalProperties"]?[ "properties"] #expect(override?["ratio"]?["default"] == nil) #expect(override?["gaps"]?["properties"]?["inner"]?["default"] == nil) #expect(override?["reserved"]?["properties"]?["top"]?["default"] == nil) #expect(override?["window-cap"]?["default"] == nil) #expect(override?["displays"] == nil) } @Test func schemaDisplayBoundsMatchGlobalBounds() throws { let global = try schema()["properties"]?["layout"]?["properties"] let override = global?["displays"]?["additionalProperties"]?["properties"] #expect(override?["ratio"]?["minimum"] == global?["ratio"]?["minimum"]) #expect(override?["ratio"]?["maximum"] == global?["ratio"]?["maximum"]) } @Test func schemaHasEveryCommand() throws { let bindings = try #require(schema()["properties"]?["keybindings"]?["properties"]?.object) #expect(bindings.count == 145) #expect(Set(bindings.keys) == Set(ConfigCommand.bindableCases.map(\.rawValue))) } @Test(arguments: ConfigCommand.bindableCases) func schemaBindingDefaultsComeFromDefaultTable(_ command: ConfigCommand) throws { let binding = try schema()["properties"]?["keybindings"]?["properties"]?[command.rawValue] let chord = DefaultKeybindings.bindings()[command] #expect(binding?["default"] == chord.map { .string($0.description) }) let variants = try #require(binding?["oneOf"]?.array) #expect(variants.contains { $0["const"] == .bool(false) }) #expect(variants.contains { $0["type"] == .string("string") && $0["format"] == .string("parcel-key-chord") }) } @Test func schemaNamedModesHaveAllCommandsWithoutInheritedDefaults() throws { let named = try #require(schema()["properties"]?["mode"]?["additionalProperties"]) let properties = try #require(named["properties"]?.object) #expect(Set(properties.keys) == Set(ConfigCommand.bindableCases.map(\.rawValue) + ["exit-mode"])) #expect(named["additionalProperties"] == .bool(false)) #expect(properties["exit-mode"]?["default"] == .string(DefaultKeybindings.modeExit.description)) for command in ConfigCommand.bindableCases { #expect(properties[command.rawValue]?["default"] == nil) } let keybindings = try #require(schema()["properties"]?["keybindings"]) #expect(schemaEntryPattern(named) == schemaEntryPattern(keybindings)) } @Test(arguments: ["resize", "Resize", "a-b", "resize_2", "123", "default-mode"]) func schemaAcceptsValidModeNamesAndEntries(name: String) throws { let root = try schema() let names = try #require(root["properties"]?["mode"]?["propertyNames"]?["pattern"]?.string) let keybindings = try #require(root["properties"]?["keybindings"]) let entries = try #require(schemaEntryPattern(keybindings)) #expect(try matches(names, name)) #expect(try matches(entries, "enter-mode \(name)")) } @Test(arguments: ["", "default", "Default", "DEFAULT", "with space", "a.b", "é", " resize", "resize\n"]) func schemaRejectsInvalidModeNamesAndEntries(name: String) throws { let root = try schema() let names = try #require(root["properties"]?["mode"]?["propertyNames"]?["pattern"]?.string) let keybindings = try #require(root["properties"]?["keybindings"]) let entries = try #require(schemaEntryPattern(keybindings)) #expect(try !matches(names, name)) #expect(try !matches(entries, "enter-mode \(name)")) } @Test(arguments: [ "enter-mode", "enter-mode ", "enter-mode resize", "enter-mode\tresize", "exit-mode", "exit-mode extra", ]) func schemaRejectsMalformedDefaultModeActions(key: String) throws { let patterns = try #require(schema()["properties"]?["keybindings"]?["propertyNames"]?["anyOf"]?.array) #expect(try !patterns.contains { try matches(#require($0["pattern"]?.string), key) }) } @Test(arguments: ["focus-left", "focsu-left", "unknown-command", "enter-mode resize"]) func schemaDefaultNamesPreserveOrdinaryUnknownKeyWarnings(key: String) throws { let patterns = try #require(schema()["properties"]?["keybindings"]?["propertyNames"]?["anyOf"]?.array) #expect(try patterns.contains { try matches(#require($0["pattern"]?.string), key) }) } @Test func schemaDescribesNewTreeAndSpaceCommands() throws { let commands: [ConfigCommand] = [ .layoutTree, .layoutBSP, .layoutAccordion, .splitHorizontal, .splitVertical, .joinLeft, .joinRight, .joinUp, .joinDown, .balance, .rotate, .mirrorHorizontal, .mirrorVertical, ] + ConfigCommand.bindableCases.filter(\.isSpaceCommand) let root = try schema() for command in commands { let property = try #require(root["properties"]?["keybindings"]?["properties"]?[command.rawValue]) #expect(property["description"]?.string?.isEmpty == false) let named = root["properties"]?["mode"]?["additionalProperties"]?["properties"]?[command.rawValue] #expect(named?["description"] == property["description"]) if command.isSpaceCommand { #expect(property["default"] == nil) } } } @Test func schemaFloatRuleRequiresOneMatcher() throws { let rule = try schema()["properties"]?["float-rules"]?["items"] #expect( rule?["anyOf"] == .array(["bundle-id", "title-regex", "role"].map { .object(["required": .array([.string($0)])]) })) } @Test func schemaFloatMatchersMustBeNonblankStrings() throws { let properties = try schema()["properties"]?["float-rules"]?["items"]?["properties"] for key in ["bundle-id", "title-regex", "role"] { #expect(properties?[key]?["type"] == .string("string")) #expect(properties?[key]?["minLength"] == .number(1)) #expect(properties?[key]?["pattern"] == .string("\\S")) } } @Test func schemaDocumentsNativeValidation() throws { let root = try schema() #expect(root["$comment"]?.string?.contains("duplicate resolved shortcuts") == true) #expect( root["properties"]?["float-rules"]?["items"]?["properties"]?["title-regex"]?["format"] == .string("parcel-title-regex")) #expect(root["properties"]?["general"]?["properties"]?["prefix"]?["format"] == .string("parcel-modifiers")) } @Test func schemaAccessibilityDefaultMatchesModel() throws { #expect( try schema()["properties"]?["accessibility"]?["properties"]?["announce-layout-changes"]?["default"] == .bool(false)) } @Test func schemaExportUsesStableSortedKeys() throws { let root = try #require(try schema().object) let writtenKeys = ConfigJSONSchema.string.split(separator: "\n") .filter { $0.hasPrefix(" \"") } .compactMap { $0.split(separator: "\"").dropFirst().first.map(String.init) } #expect(writtenKeys == root.keys.sorted()) #expect(ConfigJSONSchema.string.hasPrefix("{\n")) #expect(ConfigJSONSchema.string.hasSuffix("\n}")) } @Test func publishedSchemaMatchesGeneratedSchema() throws { let root = URL(fileURLWithPath: #filePath) .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() let published = try String(contentsOf: root.appendingPathComponent("docs/parcel.schema.json"), encoding: .utf8) #expect(published == ConfigJSONSchema.string + "\n") #expect( ConfigJSONSchema.publishedURL == "https://tangled.org/vinnymac.dev/parcel/raw/main/docs/parcel.schema.json") #expect(try schema()["$id"] == .string(ConfigJSONSchema.publishedURL)) } private func schemaEntryPattern(_ table: TestJSON) -> String? { table["patternProperties"]?.object?.keys.first } private func matches(_ pattern: String, _ text: String) throws -> Bool { try NSRegularExpression(pattern: pattern).firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) != nil } private func schema() throws -> TestJSON { try JSONDecoder().decode(TestJSON.self, from: Data(ConfigJSONSchema.string.utf8)) } } private indirect enum TestJSON: Decodable, Equatable { case object([String: TestJSON]) case array([TestJSON]) case string(String) case number(Double) case bool(Bool) case null init(from decoder: any Decoder) throws { let value = try decoder.singleValueContainer() if value.decodeNil() { self = .null return } do { self = .object(try value.decode([String: TestJSON].self)) return } catch DecodingError.typeMismatch {} do { self = .array(try value.decode([TestJSON].self)) return } catch DecodingError.typeMismatch {} do { self = .string(try value.decode(String.self)) return } catch DecodingError.typeMismatch {} do { self = .bool(try value.decode(Bool.self)) return } catch DecodingError.typeMismatch {} self = .number(try value.decode(Double.self)) } subscript(key: String) -> TestJSON? { guard case .object(let values) = self else { return nil } return values[key] } var object: [String: TestJSON]? { guard case .object(let values) = self else { return nil } return values } var array: [TestJSON]? { guard case .array(let values) = self else { return nil } return values } var string: String? { guard case .string(let value) = self else { return nil } return value } var number: Double? { guard case .number(let value) = self else { return nil } return value } }