Repository Public License
1import Foundation2import Testing3@testable import NavigatorUI45@Suite("String catalog")6struct LocalizationTests {7 static let packageRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()89 /// Every `L("…")` and `T("…")` key used in the sources.10 static func keysInSources() throws -> Set<String> {11 let sources = packageRoot.appending(path: "Sources/NavigatorUI")12 let pattern = try NSRegularExpression(pattern: #"\b[LT]\("((?:[^"\\]|\\.)*)""#)13 var keys = Set<String>()14 let files = FileManager.default.enumerator(at: sources, includingPropertiesForKeys: nil)15 while let file = files?.nextObject() as? URL {16 guard file.pathExtension == "swift" else { continue }17 let text = try String(contentsOf: file, encoding: .utf8)18 for match in pattern.matches(in: text, range: NSRange(text.startIndex..., in: text)) {19 if let range = Range(match.range(at: 1), in: text) { keys.insert(String(text[range])) }20 }21 }22 return keys23 }2425 @Test func everyUserFacingStringHasEnglishAndCanadianFrench() throws {26 let catalogURL = Self.packageRoot.appending(path: "Sources/NavigatorUI/Resources/Localizable.xcstrings")27 let catalog = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: catalogURL)) as? [String: Any])28 let strings = try #require(catalog["strings"] as? [String: [String: Any]])29 let keys = try Self.keysInSources()30 #expect(keys.count > 300)31 func value(_ key: String, _ language: String) -> String? {32 let localizations = strings[key]?["localizations"] as? [String: [String: [String: String]]]33 return localizations?[language]?["stringUnit"]?["value"]34 }35 func placeholders(_ text: String) -> [String] {36 var found: [String] = []37 var index = text.startIndex38 while let percent = text[index...].firstIndex(of: "%") {39 let next = text.index(after: percent)40 if next < text.endIndex, "@d".contains(text[next]) { found.append(String(text[next])) }41 index = next42 }43 return found44 }45 for key in keys.sorted() {46 #expect(value(key, "en") == key, "English missing for: \(key)")47 let french = value(key, "fr-CA")48 #expect(french?.isEmpty == false, "French (Canada) missing for: \(key)")49 #expect(placeholders(french ?? "") == placeholders(key), "Placeholders differ for: \(key)")50 }51 let unused = Set(strings.keys).subtracting(keys)52 #expect(unused.isEmpty, "Catalog entries no code uses: \(unused.sorted())")53 }5455 @Test func formatArgumentsAreApplied() {56 #expect(L("Search with %@", "Kagi") == "Search with Kagi")57 #expect(L("Step %d of %d", 2, 4) == "Step 2 of 4")58 }59}60