SPB Git

Repository Public

LocalizationIntentTests.swift 11.7 KB 196 lines swift

1import Foundation2import Testing3import PDFKit4import SheetCore5import SheetEngine6import SheetIO7import SheetUI8import SheetAutomation9@testable import FeatureAutomation1011@Suite struct LocalizationTests {12    /// fr-CA values of the string catalog as shipped in the sources.13    static let frenchValues: [String: String] = {14        let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()15            .appendingPathComponent("Sources/FeatureAutomation/Resources/Localizable.xcstrings")16        let root = (try? JSONSerialization.jsonObject(with: Data(contentsOf: url))) as? [String: Any]17        var out: [String: String] = [:]18        for (key, entry) in root?["strings"] as? [String: Any] ?? [:] {19            let fr = (((entry as? [String: Any])?["localizations"] as? [String: Any])?["fr-CA"] as? [String: Any])?["stringUnit"] as? [String: Any]20            if let value = fr?["value"] as? String { out[key] = value }21        }22        return out23    }()2425    static func french(_ key: String) -> String? { frenchValues[key] }2627    @Test func everyLiteralUsedInTheSourcesIsTranslated() throws {28        let sources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Sources/FeatureAutomation")29        let regex = try NSRegularExpression(pattern: #"(?:\bL\(|Text\(l: |PanelHeading\(|section\(|accessList\()"((?:[^"\\]|\\.)*)""#)30        var keys = Set<String>()31        for file in try FileManager.default.contentsOfDirectory(at: sources, includingPropertiesForKeys: nil) where file.pathExtension == "swift" {32            let text = try String(contentsOf: file, encoding: .utf8)33            for m in regex.matches(in: text, range: NSRange(text.startIndex..., in: text)) { keys.insert(String(text[Range(m.range(at: 1), in: text)!])) }34        }35        #expect(keys.count > 150)36        let missing = keys.filter { Self.french($0) == nil }.sorted()37        #expect(missing.isEmpty, "no fr-CA for: \(missing)")38    }3940    @Test func everyRunTimeKeyIsTranslated() {41        var keys = Set<String>()42        for kind in StepKind.allCases {43            keys.insert(kind.title)44            for field in kind.fields {45                keys.insert(field.label)46                if case .choice(let options) = field.kind { for o in options { keys.insert("choice." + o) } }47            }48        }49        for c in StepCategory.allCases { keys.insert(c.rawValue) }50        for k in WorkflowParameter.Kind.allCases { keys.insert("choice." + k.rawValue) }51        for t in WorkflowTemplates.all {52            keys.insert(t.name); keys.insert(t.summary)53            for p in t.parameters { keys.insert(p.label) }54        }55        let missing = keys.filter { Self.french($0) == nil }.sorted()56        #expect(missing.isEmpty, "no fr-CA for: \(missing)")57    }5859    @Test func formatSpecifiersSurviveTranslation() {60        #expect(Self.frenchValues.count > 300)61        for (key, fr) in Self.frenchValues {62            func specifiers(_ s: String) -> [String] {63                var out: [String] = []64                var chars = Array(s)[...]65                while let i = chars.firstIndex(of: "%") {66                    var j = chars.index(after: i)67                    while j < chars.endIndex, chars[j].isNumber || chars[j] == "$" { j = chars.index(after: j) }68                    if j < chars.endIndex, "@d".contains(chars[j]) { out.append(String(chars[j])) }69                    chars = chars[min(j, chars.endIndex)...].dropFirst(0)70                    if chars.startIndex == i { chars = chars.dropFirst() }71                }72                return out.sorted()73            }74            #expect(specifiers(key) == specifiers(fr), "\(key) → \(fr)")75        }76    }7778    @MainActor @Test func theBundleResolvesStrings() {79        #expect(FeatureAutomation.L("Run") == "Run" || FeatureAutomation.L("Run") == "Exécuter")80        #expect(FeatureAutomation.L("choice.asSet") != "choice.asSet")                 // the English value differs from the key81        #expect(FeatureAutomation.L("%d steps", 3).contains("3"))82        #expect(AutomationStrings.bundle.bundlePath.contains("FeatureAutomation"))83    }8485    @Test func frenchIsCompiledIntoTheBundle() throws {86        let path = try #require(AutomationStrings.bundle.path(forResource: "fr-CA", ofType: "lproj"))87        let fr = try #require(Bundle(path: path))88        #expect(NSLocalizedString("Run", bundle: fr, comment: "") == "Exécuter")89        #expect(NSLocalizedString("Create pivot table", bundle: fr, comment: "") == "Créer un tableau croisé")90        #expect(String(format: NSLocalizedString("Step %@: %@", bundle: fr, comment: ""), "2", "x") == "Étape 2 : x")91    }9293    @MainActor @Test func registrationAddsThePaneAndTheToolsCommand() {94        AutomationFeature.register()95        let pane = Workspace.shared.panes(.studio).first { $0.id == AutomationFeature.paneID }96        #expect(pane?.systemImage == "flowchart" && pane?.plainTitle == FeatureAutomation.L("Automation"))97        let action = Workspace.shared.actions(.tools).first { $0.id == "automation.studio" }98        #expect(action?.title == FeatureAutomation.L("Automation"))99        let session = Env.session()100        action?.perform(session)101        #expect(session.studioPane == AutomationFeature.paneID)102        #expect(AutomationFeature.model(for: session) === AutomationFeature.model(for: session))103    }104}105106/// The work behind the App Intents, exercised without the Shortcuts runtime.107@Suite struct IntentServiceTests {108    func fixture() throws -> (dir: URL, xlsx: URL) {109        ORIXEngine.bootstrap()110        let dir = try AutomationService.workingDirectory()111        let wb = Workbook(sheetNames: ["Data", "Summary"])112        let e = CalcEngine(workbook: wb)113        let parser = InputParser(locale: Locale(identifier: "en_US_POSIX"))114        for (r, row) in [["category", "amount"], ["Housing", "1200"], ["Food", "450.25"]].enumerated() { for (c, t) in row.enumerated() { try e.setInput(sheet: 0, row: r, col: c, t, parser: parser) } }115        e.setFormula(sheet: 1, row: 0, col: 0, "=SUM(Data!B:B)")116        e.recalculate()117        let url = dir.appendingPathComponent("book.xlsx")118        try WorkbookWriter.save(wb, to: url, format: .xlsx)119        return (dir, url)120    }121122    @Test func convertSpreadsheet() async throws {123        let (dir, xlsx) = try fixture()124        defer { try? FileManager.default.removeItem(at: dir) }125        let out = dir.appendingPathComponent("out")126        try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)127        let csv = try await AutomationService.convert(xlsx, to: "csv", sheet: "Data", in: out)128        #expect(try String(contentsOf: csv, encoding: .utf8) == "category,amount\nHousing,1200\nFood,450.25\n")129        let second = try await AutomationService.convert(xlsx, to: "tsv", sheet: "2", in: out)130        #expect(try String(contentsOf: second, encoding: .utf8) == "1650.25\n")131        let pdf = try await AutomationService.convert(xlsx, to: "pdf", in: out)132        #expect(PDFDocument(url: pdf)?.pageCount == 2 && PDFDocument(url: pdf)?.string?.contains("Housing") == true)133        let ods = try await AutomationService.convert(csv, to: "ods", in: out)134        #expect(try WorkbookReader.load(url: ods).workbook.sheets[0].value(2, 1) == .number(450.25))135        await #expect(throws: AutomationIntentError.self) { _ = try await AutomationService.convert(xlsx, to: "csv", sheet: "Nope", in: out) }136        await #expect(throws: AutomationIntentError.self) { _ = try await AutomationService.convert(xlsx, to: "numbers", in: out) }137        await #expect(throws: AutomationIntentError.self) { _ = try await AutomationService.convert(dir.appendingPathComponent("absent.xlsx"), to: "csv", in: out) }138    }139140    @Test func recalculateAndCellValue() throws {141        let (dir, xlsx) = try fixture()142        defer { try? FileManager.default.removeItem(at: dir) }143        // make the stored values stale144        let wb = try WorkbookReader.load(url: xlsx).workbook145        wb.sheets[0].cells.set(row: 1, col: 1, Cell(value: .number(2000)))146        try WorkbookWriter.save(wb, to: xlsx, format: .xlsx)147        #expect(try AutomationService.cellValue(xlsx, sheet: "Summary", cell: "A1") == "1650.25")148        let out = dir.appendingPathComponent("out")149        try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)150        let result = try AutomationService.recalculate(xlsx, in: out)151        #expect(result.formulas == 1 && result.errors == 0 && result.file.lastPathComponent == "book.xlsx")152        #expect(try AutomationService.cellValue(result.file, sheet: "Summary", cell: "$A$1") == "2450.25")153        #expect(try AutomationService.cellValue(result.file, sheet: nil, cell: "a2") == "Housing")154        #expect(try AutomationService.cellValue(result.file, sheet: "1", cell: "Z99") == "")155        #expect(throws: AutomationIntentError.self) { try AutomationService.cellValue(xlsx, sheet: nil, cell: "nope") }156    }157158    @Test func runWorkflowIsConfinedToItsWorkingFolder() async throws {159        _ = await Env.support160        let (dir, _) = try fixture()161        defer { try? FileManager.default.removeItem(at: dir) }162        let csv = dir.appendingPathComponent("input/sales.csv")163        try FileManager.default.createDirectory(at: csv.deletingLastPathComponent(), withIntermediateDirectories: true)164        try Data("category,amount\nA,1\nB,2\nA,3\n".utf8).write(to: csv)165        let flow = dir.appendingPathComponent("report.orixflow")166        try WorkflowStore.exportFile(WorkflowTemplates.csvReport, to: flow)167        let work = dir.appendingPathComponent("work")168        try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)169        let result = try await AutomationService.runWorkflow(flow, input: csv, in: work)170        #expect(result.run.status == .succeeded)171        // the template's default output is next to the input; here it is redirected into the working folder172        #expect(result.files.map(\.lastPathComponent) == ["sales-report.pdf"] && result.files[0].deletingLastPathComponent().path == WorkflowPaths.canonical(work).path)173        #expect(!FileManager.default.fileExists(atPath: dir.appendingPathComponent("input/sales-report.pdf").path))174175        // a workflow that tries to write elsewhere is refused before anything runs176        let outside = dir.appendingPathComponent("outside.csv").path177        let hostile = Workflow(name: "Hostile", parameters: [WorkflowParameter(name: "source", kind: .file)],178                               [.importFile(ImportFileSettings(path: "{{source}}")), .exportFile(ExportFileSettings(path: outside))])179        try WorkflowStore.exportFile(hostile, to: flow)180        await #expect(throws: AutomationIntentError.self) { _ = try await AutomationService.runWorkflow(flow, input: csv, in: work) }181        #expect(!FileManager.default.fileExists(atPath: outside))182        // no file parameter to receive the input183        try WorkflowStore.exportFile(Workflow(name: "No input", [.newWorkbook(NewWorkbookSettings())]), to: flow)184        await #expect(throws: AutomationIntentError.self) { _ = try await AutomationService.runWorkflow(flow, input: csv, in: work) }185        #expect(try await AutomationService.runWorkflow(flow, input: nil, in: work).files.isEmpty)186    }187188    @Test func intentsAreDeclared() {189        // compile-time presence of the four intents and of the shortcuts provider; discovery by Shortcuts190        // itself can only be verified in the built app191        #expect(ORIXSheetShortcuts.appShortcuts.count == 4)192        #expect(SpreadsheetFormatOption.allCases.map(\.rawValue) == ["xlsx", "csv", "tsv", "ods", "json", "pdf"])193        _ = ConvertSpreadsheetIntent(); _ = RecalculateWorkbookIntent(); _ = RunWorkflowIntent(); _ = GetCellValueIntent()194    }195}196
Files main
Menu

Theme