SPB Git

Repository Public

EditingTests.swift 11.9 KB 188 lines swift

1import Foundation2import Testing3import SheetAutomation4@testable import FeatureAutomation56@Suite struct EditingTests {7    func sample() -> Workflow {8        Workflow(name: "S", parameters: [WorkflowParameter(name: "src", kind: .file)], steps: [9            WorkflowItem(.openWorkbook(OpenWorkbookSettings(path: "{{src}}"))),10            WorkflowItem(.forEachFile(ForEachFileSettings(folder: "{{src.folder}}", steps: [11                WorkflowItem(.recalculate(RecalculateSettings())),12                WorkflowItem(.exportFile(ExportFileSettings(path: "{{src.basename}}-{{input.basename}}.csv"))),13            ]))),14            WorkflowItem(.saveWorkbook(SaveWorkbookSettings(path: "out.orixsheet"))),15        ])16    }17    func kinds(_ wf: Workflow) -> [String] { wf.flattened.map { "\($0.path.map(String.init).joined(separator: ".")):\($0.item.step.kind.rawValue)" } }1819    @Test func lookup() {20        let wf = sample()21        #expect(WorkflowEditing.item(wf, at: [1, 1])?.step.kind == .exportFile)22        #expect(WorkflowEditing.item(wf, at: [1, 2]) == nil && WorkflowEditing.item(wf, at: [0, 0]) == nil && WorkflowEditing.item(wf, at: []) == nil)23        #expect(WorkflowEditing.items(wf, in: [1])?.count == 2 && WorkflowEditing.items(wf, in: [0]) == nil)24        #expect(WorkflowEditing.path(of: wf.steps[2].id, in: wf) == [2])25    }2627    @Test func insertAddRemoveDuplicate() {28        var wf = sample()29        #expect(WorkflowEditing.add(.validate, to: &wf, after: nil) == [3])30        #expect(WorkflowEditing.add(.sort, to: &wf, after: [0]) == [1])31        #expect(WorkflowEditing.add(.setCell, to: &wf, after: [2, 0]) == [2, 1])32        #expect(kinds(wf) == ["0:openWorkbook", "1:sort", "2:forEachFile", "2.0:recalculate", "2.1:setCell", "2.2:exportFile", "3:saveWorkbook", "4:validate"])33        // a batch never nests: asked inside one, it lands after it34        #expect(WorkflowEditing.add(.forEachFile, to: &wf, after: [2, 1]) == [3])35        #expect(WorkflowEditing.insert(.make(.forEachFile), into: &wf, at: [2, 0]) == nil)36        #expect(WorkflowEditing.insert(.make(.addSheet), into: &wf, at: [99]) == [6])37        let before = wf38        #expect(WorkflowEditing.remove(from: &wf, at: [2, 1])?.step.kind == .setCell)39        #expect(WorkflowEditing.remove(from: &wf, at: [9]) == nil)40        #expect(wf.flattened.count == before.flattened.count - 1)41        let copy = WorkflowEditing.duplicate(in: &wf, at: [2])42        #expect(copy == [3])43        #expect(wf.steps[3].step == wf.steps[2].step || {44            // nested steps get fresh identifiers, so compare by kind45            if case .forEachFile(let a) = wf.steps[2].step, case .forEachFile(let b) = wf.steps[3].step { return a.steps.map(\.step) == b.steps.map(\.step) && a.steps.map(\.id) != b.steps.map(\.id) }46            return false47        }())48        #expect(wf.steps[3].id != wf.steps[2].id)49    }5051    @Test func moveByKeyboard() {52        var wf = sample()53        #expect(WorkflowEditing.move(in: &wf, at: [0], by: -1) == nil)54        #expect(WorkflowEditing.move(in: &wf, at: [0], by: 1) == [1])55        #expect(kinds(wf).prefix(2) == ["0:forEachFile", "0.0:recalculate"])56        #expect(WorkflowEditing.move(in: &wf, at: [0, 1], by: -1) == [0, 0])57        #expect(WorkflowEditing.move(in: &wf, at: [0, 1], by: 1) == nil)58        #expect(kinds(wf) == ["0:forEachFile", "0.0:exportFile", "0.1:recalculate", "1:openWorkbook", "2:saveWorkbook"])59    }6061    @Test func moveByDragAndDrop() {62        var wf = sample()63        let open = wf.steps[0].id, batch = wf.steps[1].id, save = wf.steps[2].id64        let recalc = WorkflowEditing.item(wf, at: [1, 0])!.id65        // down within the same list: "before the step now at index 3" = the end66        #expect(WorkflowEditing.move(open, in: &wf, before: [3]) == [2])67        #expect(kinds(wf).map { $0.split(separator: ":")[1] } == ["forEachFile", "recalculate", "exportFile", "saveWorkbook", "openWorkbook"])68        #expect(WorkflowEditing.move(save, in: &wf, before: [0]) == [0])69        // into the batch (whose index shifts when an earlier sibling leaves)70        #expect(WorkflowEditing.move(save, in: &wf, before: [1, 1]) == [0, 1])71        #expect(kinds(wf) == ["0:forEachFile", "0.0:recalculate", "0.1:saveWorkbook", "0.2:exportFile", "1:openWorkbook"])72        // out of the batch73        #expect(WorkflowEditing.move(recalc, in: &wf, before: [1]) == [1])74        #expect(kinds(wf) == ["0:forEachFile", "0.0:saveWorkbook", "0.1:exportFile", "1:recalculate", "2:openWorkbook"])75        // a batch cannot enter itself, nor an unknown place76        let snapshot = wf77        #expect(WorkflowEditing.move(batch, in: &wf, before: [0, 0]) == nil)78        #expect(WorkflowEditing.move(open, in: &wf, before: [2, 0]) == nil)79        #expect(WorkflowEditing.move(UUID(), in: &wf, before: [0]) == nil)80        #expect(wf == snapshot)81        #expect(Set(wf.flattened.map(\.item.id)).count == 5)82    }8384    @Test func updateKeepsNestedStepsAndPolicies() {85        var wf = sample()86        var changed = ForEachFileSettings(folder: "elsewhere", pattern: "*.tsv", isolated: false, steps: [])87        changed.steps = []88        WorkflowEditing.update(.forEachFile(changed), in: &wf, at: [1])89        guard case .forEachFile(let s) = wf.steps[1].step else { Issue.record("not a batch"); return }90        #expect(s.folder == "elsewhere" && s.pattern == "*.tsv" && !s.isolated && s.steps.count == 2)91        WorkflowEditing.setPolicy(.continue, in: &wf, at: [1, 0])92        #expect(WorkflowEditing.item(wf, at: [1, 0])?.onError == .continue)93        WorkflowEditing.setPolicy(nil, in: &wf, at: [1, 0])94        #expect(WorkflowEditing.item(wf, at: [1, 0])?.onError == nil)95    }9697    @Test func renameParameterRewritesReferences() {98        var wf = sample()99        wf.parameters.append(WorkflowParameter(name: "out", defaultValue: "{{src.folder}}/x"))100        #expect(WorkflowEditing.renameParameter("src", to: "source", in: &wf))101        #expect(wf.parameters.map(\.name) == ["source", "out"] && wf.parameters[1].defaultValue == "{{source.folder}}/x")102        #expect(wf.flattened.map(\.item.step.summary).joined().contains("{{src") == false)103        guard case .forEachFile(let s) = wf.steps[1].step, case .exportFile(let e) = s.steps[1].step else { Issue.record("shape"); return }104        #expect(s.folder == "{{source.folder}}" && e.path == "{{source.basename}}-{{input.basename}}.csv")105        #expect(!WorkflowEditing.renameParameter("source", to: "out", in: &wf))           // taken106        #expect(!WorkflowEditing.renameParameter("source", to: "input", in: &wf))         // built-in107        #expect(!WorkflowEditing.renameParameter("source", to: "2x", in: &wf))108        #expect(WorkflowEditing.freshParameterName("out", in: wf) == "out2" && WorkflowEditing.freshParameterName("date", in: wf) == "date2")109    }110}111112@Suite struct ScheduleTests {113    @Test func calendarIntervals() {114        var spec = ScheduleSpec()115        spec.hour = 6; spec.minute = 30116        #expect(spec.calendarIntervals == [["Hour": 6, "Minute": 30]])117        spec.kind = .weekdays; spec.weekdays = [0, 5, 1]118        #expect(spec.calendarIntervals.map { $0["Weekday"]! } == [1, 5, 0])       // Monday first, Sunday last119        spec.kind = .monthly; spec.day = 31120        #expect(spec.calendarIntervals == [["Day": 28, "Hour": 6, "Minute": 30]])121        spec.hour = 99; spec.minute = -5122        #expect(spec.calendarIntervals == [["Day": 28, "Hour": 23, "Minute": 0]])123        let weekdays = ScheduleSpec(calendarIntervals: [["Weekday": 2, "Hour": 7, "Minute": 15], ["Weekday": 4, "Hour": 7, "Minute": 15]])124        #expect(weekdays?.kind == .weekdays && weekdays?.weekdays == [2, 4] && weekdays?.hour == 7 && weekdays?.minute == 15)125        #expect(ScheduleSpec(calendarIntervals: [["Day": 3, "Hour": 1, "Minute": 0]])?.kind == .monthly)126        #expect(ScheduleSpec(calendarIntervals: []) == nil)127    }128129    @Test func commandLineQuoting() {130        let args = WorkflowSchedule.arguments(tool: URL(fileURLWithPath: "/Applications/ORIX Sheet.app/Contents/MacOS/orix-sheet"),131                                              workflowFile: URL(fileURLWithPath: "/Users/me/Library/Application Support/ORIX Sheet/Workflows/a.orixflow"),132                                              parameters: ["source": "/data/it's here.csv", "empty": "", "n": "3"], workbook: URL(fileURLWithPath: "/data/book.xlsx"),133                                              baseDirectory: URL(fileURLWithPath: "/data"))134        #expect(args == ["/Applications/ORIX Sheet.app/Contents/MacOS/orix-sheet", "run", "/Users/me/Library/Application Support/ORIX Sheet/Workflows/a.orixflow",135                         "--param", "n=3", "--param", "source=/data/it's here.csv", "--workbook", "/data/book.xlsx", "--base-dir", "/data"])136        let line = WorkflowSchedule.commandLine(args)137        #expect(line.hasPrefix("'/Applications/ORIX Sheet.app/Contents/MacOS/orix-sheet' run '/Users/me/Library/Application Support/"))138        #expect(line.contains("--param n=3 --param 'source=/data/it'\\''s here.csv' --workbook /data/book.xlsx --base-dir /data"))139        // the shell reads the line back as the same arguments140        let p = Process()141        p.executableURL = URL(fileURLWithPath: "/bin/sh")142        p.arguments = ["-c", "printf '%s\\n' " + line]143        let pipe = Pipe()144        p.standardOutput = pipe145        try? p.run()146        let out = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)147        p.waitUntilExit()148        #expect(out.split(separator: "\n").map(String.init) == args)149    }150151    @Test func plistIsValidAndReadBack() throws {152        let dir = FileManager.default.temporaryDirectory.appendingPathComponent("orix-schedule-\(UUID().uuidString)", isDirectory: true)153        defer { try? FileManager.default.removeItem(at: dir) }154        let id = UUID()155        var spec = ScheduleSpec()156        spec.kind = .weekdays; spec.weekdays = [1, 3, 5]; spec.hour = 6; spec.minute = 45157        let args = ["/Applications/ORIX Sheet.app/Contents/MacOS/orix-sheet", "run", "/tmp/a b.orixflow", "--param", "x=<&>\"é"]158        let url = try WorkflowSchedule.write(workflowID: id, arguments: args, spec: spec, directory: dir.appendingPathComponent("LaunchAgents"), logDirectory: dir.appendingPathComponent("Logs"))159        #expect(url.lastPathComponent == "ai.spboucher.orix.sheet.workflow.\(id.uuidString).plist")160161        let lint = Process()162        lint.executableURL = URL(fileURLWithPath: "/usr/bin/plutil")163        lint.arguments = ["-lint", url.path]164        let pipe = Pipe()165        lint.standardOutput = pipe; lint.standardError = pipe166        try lint.run()167        let output = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)168        lint.waitUntilExit()169        #expect(lint.terminationStatus == 0 && output.contains("OK"), "\(output)")170171        let dict = try #require(try PropertyListSerialization.propertyList(from: Data(contentsOf: url), format: nil) as? [String: Any])172        #expect(dict["Label"] as? String == WorkflowSchedule.label(id))173        #expect(dict["ProgramArguments"] as? [String] == args)174        #expect(dict["RunAtLoad"] as? Bool == false)175        #expect((dict["StartCalendarInterval"] as? [[String: Int]])?.count == 3)176        #expect((dict["StandardErrorPath"] as? String)?.hasSuffix("Logs/workflow-\(id.uuidString).log") == true)177        #expect(dict["KeepAlive"] == nil && dict["WatchPaths"] == nil)178179        try Data("not a plist".utf8).write(to: dir.appendingPathComponent("LaunchAgents/ai.spboucher.orix.sheet.workflow.junk.plist"))180        try Data("x".utf8).write(to: dir.appendingPathComponent("LaunchAgents/com.other.agent.plist"))181        let installed = WorkflowSchedule.installed(directory: dir.appendingPathComponent("LaunchAgents"))182        #expect(installed.count == 1 && installed[0].workflowID == id && installed[0].spec == spec && installed[0].arguments == args)183        #expect(WorkflowSchedule.installed(directory: dir.appendingPathComponent("Nowhere")).isEmpty)184        // outside an app bundle there is no bundled tool: the install button stays disabled185        #expect(WorkflowSchedule.bundledTool() == nil)186    }187}188
Files main
Menu

Theme