Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356import Foundationimport Testing
@testable import ParcelConfig
@Suite struct ConfigResourceTests { private static let tables = ["Parser", "Keybindings", "Schema", "Store"] private static let repositoryURL = URL(fileURLWithPath: #filePath) .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() private static let resourcesURL = repositoryURL.appending(path: "Sources/ParcelConfig/Resources")
@Test(arguments: tables) func compiledEnglishMatchesCatalog(table: String) throws { let catalog = try catalog(table: table) #expect(catalog.sourceLanguage == "en") let stringsURL = try #require( Bundle.module.url(forResource: table, withExtension: "strings", subdirectory: "en.lproj")) let expected = try catalog.strings.mapValues { try #require($0.localizations["en"]).stringUnit.value } #expect(try strings(at: stringsURL) == expected) }
@Test(arguments: tables) func moduleLookupResolvesEveryEnglishEntry(table: String) throws { let catalog = try catalog(table: table) let missing = "Missing localization: \(UUID().uuidString)" #expect(!catalog.strings.isEmpty) for (key, entry) in catalog.strings { let expected = try #require(entry.localizations["en"]).stringUnit.value let value = Bundle.module.localizedString(forKey: key, value: missing, table: table) #expect(value != missing, "Missing entry in \(table): \(key)") #expect(value == expected) } #expect(Bundle.module.localizedString(forKey: missing, value: missing, table: table) == missing) }
@Test func moduleLookupReportsMissingTable() { let missing = "Missing localization: \(UUID().uuidString)" let value = Bundle.module.localizedString( forKey: "A key chord cannot be empty.", value: missing, table: missing) #expect(value == missing) }
@Test func everySourceCatalogIsBundledAndTested() throws { let sourceFiles = try FileManager.default.contentsOfDirectory( at: Self.resourcesURL, includingPropertiesForKeys: nil) let sourceTables = Set( sourceFiles.filter { $0.pathExtension == "xcstrings" }.map { $0.deletingPathExtension().lastPathComponent }) let bundleURL = try #require(Bundle.module.resourceURL) let bundledFiles = try FileManager.default.contentsOfDirectory(at: bundleURL, includingPropertiesForKeys: nil) let bundledTables = Set( bundledFiles.filter { $0.pathExtension == "xcstrings" }.map { $0.deletingPathExtension().lastPathComponent } ) #expect(sourceTables == Set(Self.tables)) #expect(bundledTables == sourceTables) }
@Test func generatorWritesOutsideTheSourceTree() throws { try withResources { output in let before = try snapshot(Self.resourcesURL) let result = try runGenerator(resources: Self.resourcesURL, output: output) try #require(result.status == 0, "\(result.output)") #expect(try snapshot(Self.resourcesURL) == before) for table in Self.tables { let bundled = try #require( Bundle.module.url(forResource: table, withExtension: "strings", subdirectory: "en.lproj")) #expect(try strings(at: output.appending(path: "en.lproj/\(table).strings")) == strings(at: bundled)) } } }
@Test func generatorPreservesEscapingAndLanguagesAndIsRepeatable() throws { try withResources { resources in let english = "“C:\\Notes” says \"Hello\", %@.\n\t%lld <items> & more." let french = "Été : %@, %lld éléments." try writeCatalog(at: resources, table: "Example table", translations: ["en": english, "fr": french]) try writeCatalog(at: resources, table: "Other", translations: ["en": "Another table"]) let catalogData = try snapshot(resources) let first = try runGenerator(resources: resources) try #require(first.status == 0, "\(first.output)") #expect( try strings(at: resources.appending(path: "en.lproj/Example table.strings")) == ["notice.key": english]) #expect( try strings(at: resources.appending(path: "fr.lproj/Example table.strings")) == ["notice.key": french]) #expect( try strings(at: resources.appending(path: "en.lproj/Other.strings")) == ["notice.key": "Another table"]) let generated = try snapshot(resources) for (path, data) in catalogData { #expect(generated[path] == data) } let second = try runGenerator(resources: resources) #expect(second.status == 0, "\(second.output)") #expect(try snapshot(resources) == generated) let check = try runGenerator(arguments: ["--check"], resources: resources) #expect(check.status == 0, "\(check.output)") #expect(try snapshot(resources) == generated) } }
@Test func untranslatedKeysCompileIntoTheSourceLanguage() throws { try withResources { resources in let catalog = resources.appending(path: "Example.xcstrings") let source = Data(#"{"sourceLanguage":"en","strings":{"Source key":{}},"version":"1.0"}"#.utf8) try source.write(to: catalog) let result = try runGenerator(resources: resources) try #require(result.status == 0, "\(result.output)") #expect( try strings(at: resources.appending(path: "en.lproj/Example.strings")) == ["Source key": "Source key"]) #expect(try Data(contentsOf: catalog) == source) } }
@Test func generatorCanCompileOneLanguageForTheBuildPlugin() throws { try withResources { resources in try writeCatalog(at: resources, translations: ["en": "English", "fr": "Français"]) let result = try runGenerator(arguments: ["--language", "fr"], resources: resources) try #require(result.status == 0, "\(result.output)") #expect( try strings(at: resources.appending(path: "fr.lproj/Example.strings")) == ["notice.key": "Français"]) #expect(!FileManager.default.fileExists(atPath: resources.appending(path: "en.lproj").path)) } }
@Test(arguments: ResourceChange.allCases) func checkDetectsDriftWithoutWritingAndGenerationRepairsIt(change: ResourceChange) throws { try withResources { resources in try writeCatalog(at: resources) let generated = try runGenerator(resources: resources) try #require(generated.status == 0, "\(generated.output)") let unrelated = resources.appending(path: "en.lproj/keep.txt") try Data("Unrelated resource".utf8).write(to: unrelated) let changedURL = resources.appending(path: change.path) switch change { case .missing: try FileManager.default.removeItem(at: changedURL) case .changed, .obsoleteTable, .obsoletePlural, .obsoleteLanguage: try FileManager.default.createDirectory( at: changedURL.deletingLastPathComponent(), withIntermediateDirectories: true) try Data("Outdated output".utf8).write(to: changedURL) } let before = try snapshot(resources) let check = try runGenerator(arguments: ["--check"], resources: resources) #expect(check.status == 1) #expect(check.output.contains(change.path)) #expect(check.output.contains("generate-config-strings.sh")) #expect(try snapshot(resources) == before) let repaired = try runGenerator(resources: resources) #expect(repaired.status == 0, "\(repaired.output)") let recheck = try runGenerator(arguments: ["--check"], resources: resources) #expect(recheck.status == 0, "\(recheck.output)") #expect( try strings(at: resources.appending(path: "en.lproj/Example.strings")) == [ "notice.key": "A translated value" ]) #expect(try Data(contentsOf: unrelated) == Data("Unrelated resource".utf8)) } }
@Test func generatorRemovesOutputsForDeletedCatalogsAndLanguages() throws { try withResources { resources in try writeCatalog(at: resources, translations: ["en": "English", "fr": "Français"]) try writeCatalog(at: resources, table: "Deleted") let initial = try runGenerator(resources: resources) try #require(initial.status == 0, "\(initial.output)") try writeCatalog(at: resources, translations: ["en": "Updated English"]) try FileManager.default.removeItem(at: resources.appending(path: "Deleted.xcstrings")) let check = try runGenerator(arguments: ["--check"], resources: resources) #expect(check.status == 1) #expect(check.output.contains("fr.lproj/Example.strings")) #expect(check.output.contains("en.lproj/Deleted.strings")) let result = try runGenerator(resources: resources) #expect(result.status == 0, "\(result.output)") #expect(!FileManager.default.fileExists(atPath: resources.appending(path: "fr.lproj/Example.strings").path)) #expect(!FileManager.default.fileExists(atPath: resources.appending(path: "en.lproj/Deleted.strings").path)) #expect( try strings(at: resources.appending(path: "en.lproj/Example.strings")) == [ "notice.key": "Updated English" ]) } }
@Test(arguments: [false, true]) func malformedCatalogFailsBeforeChangingOutputs(check: Bool) throws { try withResources { resources in try writeCatalog(at: resources) let initial = try runGenerator(resources: resources) try #require(initial.status == 0, "\(initial.output)") try writeCatalog(at: resources, translations: ["en": "Changed value"]) try Data("{ invalid catalog".utf8).write(to: resources.appending(path: "ZBroken.xcstrings")) let before = try snapshot(resources) let result = try runGenerator(arguments: check ? ["--check"] : [], resources: resources) #expect(result.status != 0) #expect(!result.output.isEmpty) #expect(try snapshot(resources) == before) } }
@Test(arguments: [false, true]) func noCatalogsIsAnErrorAndPreservesExistingOutputs(check: Bool) throws { try withResources { resources in let language = resources.appending(path: "en.lproj") try FileManager.default.createDirectory(at: language, withIntermediateDirectories: true) try Data("Existing output".utf8).write(to: language.appending(path: "Example.strings")) let before = try snapshot(resources) let result = try runGenerator(arguments: check ? ["--check"] : [], resources: resources) #expect(result.status == 1) #expect(result.output.contains("No String Catalogs found")) #expect(try snapshot(resources) == before) } }
@Test func unknownGeneratorOptionIsAnError() throws { let result = try runGenerator(arguments: ["--unknown"]) #expect(result.status == 2) #expect(result.output.contains("Usage:")) }
@Test func generatorCompilesPluralVariations() throws { try withResources { resources in let source = #""" { "sourceLanguage": "en", "version": "1.0", "strings": { "%lld files": { "extractionState": "manual", "localizations": { "en": { "variations": { "plural": { "one": {"stringUnit": {"state": "translated", "value": "%lld file"}}, "other": {"stringUnit": {"state": "translated", "value": "%lld files"}} } } } } } } } """# try Data(source.utf8).write(to: resources.appending(path: "Counts.xcstrings")) let result = try runGenerator(resources: resources) try #require(result.status == 0, "\(result.output)") let pluralURL = resources.appending(path: "en.lproj/Counts.stringsdict") #expect(try !Data(contentsOf: pluralURL).isEmpty) let englishBundle = try #require(Bundle(url: resources.appending(path: "en.lproj"))) let format = englishBundle.localizedString(forKey: "%lld files", value: "Missing plural", table: "Counts") #expect(format != "Missing plural") #expect(String.localizedStringWithFormat(format, Int64(1)) == "1 file") #expect(String.localizedStringWithFormat(format, Int64(2)) == "2 files") let check = try runGenerator(arguments: ["--check"], resources: resources) #expect(check.status == 0, "\(check.output)") } }
@Test func diagnosticDescriptionUsesOneBasedPosition() { let diagnostic = ConfigDiagnostic(location: SourceLocation(line: 12, column: 9), message: "Check this value.") #expect(diagnostic.description == "line 12, column 9: Check this value.") #expect(diagnostic.severity == .error) #expect(diagnostic.relatedLocation == nil) }
enum ResourceChange: CaseIterable { case missing, changed, obsoleteTable, obsoletePlural, obsoleteLanguage
var path: String { switch self { case .missing, .changed: "en.lproj/Example.strings" case .obsoleteTable: "en.lproj/Removed.strings" case .obsoletePlural: "en.lproj/Example.stringsdict" case .obsoleteLanguage: "fr.lproj/Example.strings" } } }
private func catalog(table: String) throws -> Catalog { let url = try #require(Bundle.module.url(forResource: table, withExtension: "xcstrings")) return try JSONDecoder().decode(Catalog.self, from: Data(contentsOf: url)) }
private func strings(at url: URL) throws -> [String: String] { try PropertyListDecoder().decode([String: String].self, from: Data(contentsOf: url)) }
private func writeCatalog( at resources: URL, table: String = "Example", translations: [String: String] = ["en": "A translated value"] ) throws { let localizations = translations.mapValues { Catalog.Localization(stringUnit: Catalog.Unit(value: $0)) } let catalog = Catalog(strings: ["notice.key": Catalog.Entry(localizations: localizations)]) try JSONEncoder().encode(catalog).write(to: resources.appending(path: "\(table).xcstrings")) }
private func runGenerator(arguments: [String] = [], resources: URL? = nil, output: URL? = nil) throws -> ( status: Int32, output: String ) { let process = Process() process.executableURL = Self.repositoryURL.appending(path: "Scripts/generate-config-strings.sh") process.currentDirectoryURL = Self.repositoryURL.appending(path: "Tests") process.arguments = arguments + (resources.map { [$0.path, (output ?? $0).path] } ?? []) let pipe = Pipe() process.standardOutput = pipe process.standardError = pipe try process.run() let data = try pipe.fileHandleForReading.readToEnd() ?? Data() process.waitUntilExit() #expect(process.terminationReason == .exit) return (process.terminationStatus, try #require(String(data: data, encoding: .utf8))) }
private func withResources(_ body: (URL) throws -> Void) throws { let resources = Self.repositoryURL.appending(path: ".build/catalog-check/Resource test \(UUID().uuidString)") try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true) defer { do { try FileManager.default.removeItem(at: resources) } catch { Issue.record(error) } } try body(resources) }
private func snapshot(_ directory: URL) throws -> [String: Data] { var files: [String: Data] = [:] for url in try FileManager.default.contentsOfDirectory( at: directory, includingPropertiesForKeys: [.isDirectoryKey]) { if try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true { for (path, data) in try snapshot(url) { files["\(url.lastPathComponent)/\(path)"] = data } } else { files[url.lastPathComponent] = try Data(contentsOf: url) } } return files }
private struct Catalog: Codable { var sourceLanguage = "en" let strings: [String: Entry] var version = "1.0"
struct Entry: Codable { var extractionState = "manual" let localizations: [String: Localization] } struct Localization: Codable { let stringUnit: Unit } struct Unit: Codable { var state = "translated" let value: String } }}