Repository Public License
1import Foundation2import NavigatorCore3import Testing4@testable import NavigatorFeatures5@testable import NavigatorUI67/// String Catalogs of the package, read from the sources (SwiftPM does not compile catalogs, so a lookup at8/// run time would only ever return the English key).9struct Catalogs {10 static let packageRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()1112 private var cache: [String: [String: [String: Any]]?] = [:]1314 static func sourceDirectory(of module: String) -> URL { packageRoot.appending(path: "Sources/\(module)") }1516 /// `strings` of the module's catalog, or `nil` when the module has none.17 mutating func strings(of module: String) -> [String: [String: Any]]? {18 if let known = cache[module] { return known }19 let url = Self.sourceDirectory(of: module).appending(path: "Resources/Localizable.xcstrings")20 let strings = (try? Data(contentsOf: url)).flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }?["strings"]21 as? [String: [String: Any]]22 cache[module] = .some(strings)23 return strings24 }2526 mutating func value(_ key: String, language: String, module: String) -> String? {27 let localizations = strings(of: module)?[key]?["localizations"] as? [String: [String: [String: String]]]28 return localizations?[language]?["stringUnit"]?["value"]29 }3031 /// Every `L("…")` and `T("…")` key used in the sources of a module.32 static func keysInSources(of module: String) throws -> Set<String> {33 let pattern = try NSRegularExpression(pattern: #"\b[LT]\("((?:[^"\\]|\\.)*)""#)34 var keys = Set<String>()35 let files = FileManager.default.enumerator(at: sourceDirectory(of: module), includingPropertiesForKeys: nil)36 while let file = files?.nextObject() as? URL {37 guard file.pathExtension == "swift" else { continue }38 let text = try String(contentsOf: file, encoding: .utf8)39 for match in pattern.matches(in: text, range: NSRange(text.startIndex..., in: text)) {40 if let range = Range(match.range(at: 1), in: text) { keys.insert(String(text[range])) }41 }42 }43 return keys44 }4546 static func placeholders(_ text: String) -> [String] {47 var found: [String] = []48 var index = text.startIndex49 while let percent = text[index...].firstIndex(of: "%") {50 let next = text.index(after: percent)51 if next < text.endIndex, "@d".contains(text[next]) { found.append(String(text[next])) }52 index = next53 }54 return found55 }56}5758/// What the app registers at launch: the shell plus every feature.59@MainActor60func makeFullRegistry() -> FeatureRegistry {61 let registry = FeatureRegistry()62 NavigatorFeatures.registerAll(in: registry)63 return registry64}6566@Suite("Registry of the app")67@MainActor68struct RegistryAuditTests {69 @Test func registrationReportsNoIssue() {70 let registry = makeFullRegistry()71 #expect(registry.issues.isEmpty, "\(registry.issues)")72 // Registering twice is the mistake the registry must catch.73 NavigatorFeatures.registerAll(in: registry)74 let contributed = registry.identifiersByKind.values.map(\.count).reduce(0, +) - FeatureRegistry().identifiersByKind.values.map(\.count).reduce(0, +)75 #expect(registry.issues.count == contributed, "every feature contribution registered twice is reported once")76 }7778 @Test func identifiersAreUniqueAndWellFormed() {79 let registry = makeFullRegistry()80 for (kind, ids) in registry.identifiersByKind.sorted(by: { $0.key < $1.key }) {81 let duplicates = Dictionary(grouping: ids, by: { $0 }).filter { $0.value.count > 1 }.keys.sorted()82 #expect(duplicates.isEmpty, "duplicate \(kind) identifiers: \(duplicates)")83 for id in ids {84 #expect(!id.isEmpty && id == id.trimmingCharacters(in: .whitespacesAndNewlines) && !id.contains(" "), "\(kind) “\(id)”")85 }86 }87 // `-ORIXShow <id>` resolves overlays first, then panels: one identifier must not name both.88 let overlays = Set(registry.overlays.map(\.id)), panels = Set(registry.panels.map(\.id.rawValue))89 #expect(overlays.isDisjoint(with: panels), "\(overlays.intersection(panels))")90 // Commands are namespaced: `<owner>.<action>`.91 for command in registry.commands {92 #expect(command.id.range(of: #"^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$"#, options: .regularExpression) != nil,93 "command id “\(command.id)” is not dotted lower-case")94 }95 // What refers to a command or a panel refers to one that exists.96 func check(_ action: ContributionAction, owner: String) {97 switch action {98 case .command(let id): #expect(registry.command(id) != nil, "\(owner) runs an unknown command “\(id)”")99 case .panel(let id): #expect(registry.panel(id) != nil, "\(owner) opens an unknown panel “\(id)”")100 case .overlay(let id): #expect(registry.overlay(id) != nil, "\(owner) presents an unknown overlay “\(id)”")101 case .perform, .popover: break102 }103 }104 for item in registry.toolbarItems {105 check(item.action, owner: "toolbar item \(item.id)")106 #expect(!item.placement.isEmpty, "toolbar item \(item.id) has no placement")107 }108 for item in registry.sidebarFooterItems { check(item.action, owner: "sidebar item \(item.id)") }109 }110111 @Test func noTwoCommandsShareADefaultShortcut() {112 let collisions = makeFullRegistry().shortcutCollisions113 #expect(collisions.isEmpty, "\(collisions.map { "\($0.shortcut): \($0.commandIDs.joined(separator: ", "))" })")114 }115116 @Test func shortcutsStayClearOfTheSystemAndOfTextEditing() {117 // Taken by the system or by every text field: a command must not claim them.118 let reserved: [CommandShortcut] = [119 CommandShortcut("q"), CommandShortcut("h"), CommandShortcut("m"), CommandShortcut("c"), CommandShortcut("v"),120 CommandShortcut("x"), CommandShortcut("z"), CommandShortcut("a"), CommandShortcut("z", modifiers: [.command, .shift]),121 CommandShortcut(.tab), CommandShortcut(.space), CommandShortcut("`"),122 ]123 for command in makeFullRegistry().commands {124 guard let shortcut = command.shortcut else { continue }125 #expect(!reserved.contains(shortcut), "\(command.id) claims \(shortcut), which belongs to the system")126 #expect(!shortcut.modifiers.isEmpty || shortcut.key == .escape, "\(command.id): a shortcut needs a modifier")127 }128 }129130 @Test func everyTitleExistsInEnglishAndCanadianFrench() {131 let registry = makeFullRegistry()132 var catalogs = Catalogs()133 func check(_ text: LocalizedText, _ what: String) {134 guard !text.isVerbatim else {135 Issue.record("\(what) has a verbatim title “\(text.key)”: registry titles must come from a String Catalog")136 return137 }138 #expect(catalogs.value(text.key, language: "en", module: text.module) == text.key,139 "\(what): English missing for “\(text.key)” in \(text.module)")140 let french = catalogs.value(text.key, language: "fr-CA", module: text.module)141 #expect(french?.isEmpty == false, "\(what): French (Canada) missing for “\(text.key)” in \(text.module)")142 }143 for command in registry.commands {144 check(command.title, "command \(command.id)")145 check(command.category.title, "category of \(command.id)")146 }147 for panel in registry.panels { check(panel.title, "panel \(panel.id)") }148 for item in registry.toolbarItems { check(item.label, "toolbar item \(item.id)") }149 for item in registry.sidebarFooterItems { check(item.label, "sidebar item \(item.id)") }150 for layout in registry.tabLayouts { check(layout.title, "tab layout \(layout.id)") }151 for section in registry.settingsSections { check(section.title, "settings section \(section.id)") }152 }153154 @Test(arguments: NavigatorFeatures.moduleNames)155 func featureCatalogCoversItsSources(module: String) throws {156 let keys = try Catalogs.keysInSources(of: module)157 var catalogs = Catalogs()158 guard let strings = catalogs.strings(of: module) else {159 #expect(keys.isEmpty, "\(module) uses \(keys.count) strings but has no Resources/Localizable.xcstrings")160 return161 }162 for key in keys.sorted() {163 #expect(catalogs.value(key, language: "en", module: module) == key, "\(module): English missing for “\(key)”")164 let french = catalogs.value(key, language: "fr-CA", module: module)165 #expect(french?.isEmpty == false, "\(module): French (Canada) missing for “\(key)”")166 #expect(Catalogs.placeholders(french ?? "") == Catalogs.placeholders(key), "\(module): placeholders differ for “\(key)”")167 }168 let unused = Set(strings.keys).subtracting(keys)169 #expect(unused.isEmpty, "\(module): catalog entries no code uses: \(unused.sorted())")170 }171172 @Test func featuresAddOnlyRenderersForLayoutsTheShellLacks() {173 let registry = makeFullRegistry()174 #expect(registry.supportedLayouts.starts(with: [.vertical, .horizontal, .compact]))175 #expect(Set(registry.tabLayouts.map(\.mode)).count == registry.tabLayouts.count)176 }177178 /// Not an assertion on a number that changes with every feature: the count is printed in the test log so179 /// that a release can quote it, and the shell's own share is checked.180 @Test func commandCountIsReported() {181 let registry = makeFullRegistry()182 let shell = FeatureRegistry().commands.count183 var perOwner: [String: Int] = [:]184 for command in registry.commands { perOwner[command.title.module, default: 0] += 1 }185 let summary = perOwner.sorted { $0.key < $1.key }.map { "\($0.key) \($0.value)" }.joined(separator: ", ")186 print("ORIX Navigator registers \(registry.commands.count) commands (\(summary)); \(registry.commands.filter { $0.shortcut != nil }.count) have a default shortcut; \(registry.panels.count) panels, \(registry.overlays.count) overlays, \(registry.toolbarItems.count) toolbar items, \(registry.settingsSections.count) settings sections, \(registry.tabLayouts.count) tab layouts.")187 #expect(perOwner["NavigatorUI"] == shell)188 #expect(registry.commands.count >= shell)189 }190}191