SPB Git

Repository Public

LocalizationTests.swift 7.4 KB 118 lines swift

1import Foundation2import Testing3@testable import FeatureAudit45@Suite struct LocalizationTests {6    static let packageRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()78    struct Catalog: Decodable {9        struct Entry: Decodable { var localizations: [String: Localization] }10        struct Localization: Decodable { var stringUnit: Unit }11        struct Unit: Decodable { var state: String; var value: String }12        var sourceLanguage: String13        var strings: [String: Entry]14    }1516    static func catalog() throws -> Catalog {17        let url = packageRoot.appendingPathComponent("Sources/FeatureAudit/Resources/Localizable.xcstrings")18        return try JSONDecoder().decode(Catalog.self, from: Data(contentsOf: url))19    }2021    /// First string literal of every L("…") call in the sources.22    static func keysInSources() throws -> Set<String> {23        let dir = packageRoot.appendingPathComponent("Sources/FeatureAudit")24        let regex = try NSRegularExpression(pattern: #"\bL\(\s*"((?:[^"\\]|\\.)*)""#)25        var keys = Set<String>()26        let files = FileManager.default.enumerator(at: dir, includingPropertiesForKeys: nil)27        while let url = files?.nextObject() as? URL {28            guard url.pathExtension == "swift" else { continue }29            let text = try String(contentsOf: url, encoding: .utf8)30            let ns = text as NSString31            for m in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {32                keys.insert(ns.substring(with: m.range(at: 1)).replacingOccurrences(of: "\\\"", with: "\""))33            }34        }35        return keys36    }3738    /// Conversion types of the format specifiers, ordered by argument position.39    static func specifiers(_ s: String) -> [String] {40        let regex = try! NSRegularExpression(pattern: #"%(?:(\d+)\$)?(@|d|ld|lld|f|\.\d+f)"#)41        let ns = s as NSString42        var indexed = [(Int, String)]()43        for (i, m) in regex.matches(in: s, range: NSRange(location: 0, length: ns.length)).enumerated() {44            let position = m.range(at: 1).location == NSNotFound ? i + 1 : Int(ns.substring(with: m.range(at: 1))) ?? i + 145            indexed.append((position, ns.substring(with: m.range(at: 2))))46        }47        return indexed.sorted { $0.0 < $1.0 }.map(\.1)48    }4950    @Test func everyKeyUsedInTheSourcesHasACanadianFrenchTranslation() throws {51        let catalog = try Self.catalog()52        let used = try Self.keysInSources()53        #expect(used.count > 400)54        #expect(catalog.sourceLanguage == "en")55        let missing = used.filter { catalog.strings[$0]?.localizations["fr-CA"] == nil }.sorted()56        #expect(missing.isEmpty, "missing fr-CA: \(missing)")57    }5859    @Test func translationsAreCompleteAndKeepTheirArguments() throws {60        let catalog = try Self.catalog()61        for (key, entry) in catalog.strings {62            let fr = try #require(entry.localizations["fr-CA"]?.stringUnit, "\(key)")63            #expect(fr.state == "translated" && !fr.value.isEmpty, "\(key)")64            #expect(Self.specifiers(fr.value) == Self.specifiers(key), "\(key) → \(fr.value)")65            #expect(entry.localizations["en"]?.stringUnit.value == key)66        }67    }6869    @Test func engineTitlesAndDynamicKeysAreInTheCatalog() throws {70        let catalog = try Self.catalog()71        var dynamic = ["Invalid entry", "Invalid formula", "The formula could not be parsed."]72        dynamic += ["Error value", "Broken reference", "Circular reference", "Inconsistent formula", "Hardcoded value in a formula range", "Hardcoded constant in a formula",73                    "Reference to a blank cell", "Text that looks like a number used in a calculation", "Number stored as text", "Mixed data types in a table column",74                    "Formula returning text in a numeric column", "Duplicated calculation", "Volatile function", "Whole-column reference in a volatile formula",75                    "Long or deeply nested formula", "Slow formula", "Unused defined name", "Broken defined name", "External workbook reference",76                    "Merged cells inside a data range", "Hidden content"]77        dynamic += RuleEditorModel.RuleType.allCases.map(\.titleKey) + RulePresets.Preset.allCases.map(\.titleKey)78        dynamic += [RuleEditorModel.Problem.invalidRange, .missingValue, .missingSecondValue, .invalidFormula(""), .invalidRank, .missingText, .invalidThreshold].map(\.messageKey)79        dynamic += [ValidationEditorModel.Problem.missingValue, .missingSecondValue, .invalidValue(""), .emptyList, .invalidListRange, .missingFormula, .invalidFormula, .noRange].map(\.messageKey)80        dynamic += [NameRules.Problem.empty, .tooLong, .invalidStart, .invalidCharacter(" "), .looksLikeReference, .reserved, .duplicate, .tableConflict, .emptyReference, .invalidReference].map(\.messageKey)81        dynamic += ["arrows", "grey arrows", "traffic lights", "signs", "symbols (circled)", "symbols", "flags", "stars", "triangles", "ratings", "red to black", "quarters", "boxes"]82        dynamic += ["Model Auditor", "Dependency Graph", "Audit Findings", "Formula Intelligence", "Conditional Formatting", "Data Validation", "Table and Data"]83        for key in dynamic { #expect(catalog.strings[key]?.localizations["fr-CA"] != nil, "\(key)") }84    }8586    @Test func auditRuleTitlesMatchTheEngine() throws {87        let catalog = try Self.catalog()88        for rule in ["errorValue", "brokenReference", "circularReference", "inconsistentFormula", "hardcodedOverwrite", "hardcodedConstant", "blankReference",89                     "textNumberInArithmetic", "numberStoredAsText", "mixedTypesInTableColumn", "textResultInNumericColumn", "duplicatedCalculation", "volatileFunction",90                     "volatileWholeColumn", "complexFormula", "slowFormula", "unusedName", "brokenName", "externalReference", "mergedCellsInData", "hiddenContent"] {91            let title = try #require(AuditRuleTitles.title(rawValue: rule), "\(rule)")92            #expect(catalog.strings[title] != nil, "\(title)")93        }94        #expect(AuditRuleTitles.count == 21)95    }9697    @Test func bundleCarriesTheFrenchTable() throws {98        let bundle = AuditLocalization.bundle99        #expect(AuditLocalization.string("Run Audit") == NSLocalizedString("Run Audit", bundle: bundle, comment: ""))100        let lproj = try #require(bundle.localizations.first { $0.lowercased().hasPrefix("fr") }, "localizations: \(bundle.localizations)")101        let path = try #require(bundle.path(forResource: lproj, ofType: "lproj"))102        let fr = try #require(Bundle(path: path))103        #expect(fr.localizedString(forKey: "Run Audit", value: nil, table: nil) == "Lancer l’audit")104        #expect(String(format: fr.localizedString(forKey: "%d of %d rows shown", value: nil, table: nil), 4, 6) == "4 lignes affichées sur 6")105        #expect(String(format: fr.localizedString(forKey: "%@ applied to %@", value: nil, table: nil), "Top 10", "A1:A9") == "Top 10 appliqué à A1:A9")106    }107}108109@Suite struct LanguageLookupTests {110    @Test func languagesOfTheCatalog() throws {111        #expect(AuditLocalization.bundle(forLanguage: "de") == nil)112        let fr = try #require(AuditLocalization.bundle(forLanguage: "fr-CA"))113        #expect(fr.localizedString(forKey: "Run Audit", value: nil, table: nil) == "Lancer l’audit")114        #expect(AuditLocalization.bundle(forLanguage: "fr") != nil)115        #expect(!AuditLocalization.use(language: "de"))          // an unknown language leaves the active table alone116    }117}118
Files main
Menu

Theme