Repository Public License
1// ORIX Convert — Packages/ORIXConvertCore/Tests/ConvertCoreTests/WorkflowTests.swift2// Description: Workflow conditions, validation against the registry, the runner end to end over the mock engine,3// the workflow library and run history.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import Testing7@testable import ConvertCore89private func convert(_ format: FormatID, op: String? = nil, _ options: [String: OptionValue] = [:]) -> WorkflowNode {10 .convert(destination: format, operation: op, options: ConversionOptions(options))11}1213@Suite struct WorkflowConditionTests {14 private func eval(_ c: WorkflowCondition, name: String = "Photo.JPG", format: FormatID? = .jpeg, size: Int64? = 2_000, inspection: FileInspection? = nil) -> Bool {15 c.evaluate(name: name, format: format, size: size, inspection: inspection)16 }1718 @Test func formatCategorySizeAndName() {19 #expect(eval(.formatIs(.jpeg)) && !eval(.formatIs(.png)) && !eval(.formatIs(.jpeg), format: nil))20 #expect(eval(.categoryIs(.image)) && !eval(.categoryIs(.video)))21 #expect(eval(.sizeAbove(1_999)) && !eval(.sizeAbove(2_000)) && eval(.sizeBelow(2_001)) && !eval(.sizeBelow(2_000)))22 #expect(!eval(.sizeAbove(1), size: nil) && !eval(.sizeBelow(1), size: nil), "unknown size satisfies nothing")23 #expect(eval(.nameMatches("*.jpg")) && eval(.nameMatches("photo.*")) && eval(.nameMatches("Ph?to.[jJ][pP][gG]")) && !eval(.nameMatches("*.png")))24 }2526 @Test func inspectionBasedComparisons() {27 var inspection = FileInspection(format: .jpeg)28 inspection.pixelWidth = 400029 inspection.pixelHeight = 300030 inspection.durationSeconds = 12.531 #expect(eval(.width(.greaterThan, 3999), inspection: inspection) && !eval(.width(.greaterThan, 4000), inspection: inspection))32 #expect(eval(.width(.greaterOrEqual, 4000), inspection: inspection) && eval(.height(.equal, 3000), inspection: inspection))33 #expect(eval(.height(.lessOrEqual, 3000), inspection: inspection) && eval(.duration(.lessThan, 13), inspection: inspection))34 #expect(!eval(.width(.lessThan, 99_999)), "an unreadable dimension makes the condition false")35 #expect(!eval(.duration(.greaterThan, 0), inspection: FileInspection(format: .jpeg)))36 #expect(WorkflowCondition.width(.equal, 1).needsInspection && WorkflowCondition.all([.formatIs(.png), .not(.duration(.equal, 1))]).needsInspection)37 #expect(!WorkflowCondition.any([.formatIs(.png), .sizeAbove(3)]).needsInspection)38 }3940 @Test func booleanCombinators() {41 #expect(eval(.not(.formatIs(.png))) && !eval(.not(.formatIs(.jpeg))))42 #expect(eval(.all([.formatIs(.jpeg), .sizeAbove(10)])) && !eval(.all([.formatIs(.jpeg), .sizeAbove(10_000)])) && eval(.all([])))43 #expect(eval(.any([.formatIs(.png), .sizeAbove(10)])) && !eval(.any([.formatIs(.png), .sizeAbove(10_000)])) && !eval(.any([])))44 }4546 @Test func workflowsAreCodable() throws {47 let workflow = Workflow(name: "All nodes", summary: "s", nodes: [48 .filter(.all([.categoryIs(.image), .not(.sizeBelow(10)), .any([.nameMatches("*.png"), .width(.greaterThan, 100)])])),49 .branch(condition: .formatIs(.png), then: [convert(.jpeg, ["quality": .double(0.8)])], otherwise: [convert(.pdf, op: "image.to-pdf")]),50 .rename(template: "{name}-{counter:3}"),51 .export(folder: URL(fileURLWithPath: "/tmp/out"), conflictPolicy: .skip),52 ], errorPolicy: .continueItem)53 let decoded = try JSONDecoder().decode(Workflow.self, from: JSONEncoder().encode(workflow))54 #expect(decoded == workflow)55 }56}5758@Suite struct WorkflowValidationTests {59 let registry = FormatRegistry(engines: [TextEngine(), HTMLEngine()])60 let out = URL(fileURLWithPath: "/tmp/orix-out")6162 private func validate(_ nodes: [WorkflowNode], inputs: Set<FormatID>? = nil) -> WorkflowValidation {63 WorkflowValidator.validate(Workflow(name: "w", nodes: nodes), registry: registry, inputFormats: inputs)64 }6566 @Test func aRealPathIsValid() {67 let v = validate([convert(.markdown), .export(folder: out, conflictPolicy: .rename)], inputs: [.txt])68 #expect(v.isValid && v.issues.isEmpty && v.exportedFormats == [.markdown] && !v.canExportUnconverted)69 }7071 @Test func chainedPathsCount() {72 #expect(validate([convert(.html), .export(folder: out, conflictPolicy: .rename)], inputs: [.txt]).isValid)73 }7475 @Test func reportsTheInvalidNodeAndWhy() {76 let v = validate([.rename(template: "{name}"), convert(.markdown), convert(.mp3), .export(folder: out, conflictPolicy: .rename)], inputs: [.txt])77 #expect(!v.isValid && v.errors.count == 1)78 #expect(v.errors[0].nodePath == "3" && v.errors[0].message == "No conversion to MP3 exists for: MARKDOWN.")79 }8081 @Test func explicitInputsMustAllHaveAPath() {82 let v = validate([convert(.markdown), .export(folder: out, conflictPolicy: .rename)], inputs: [.txt, .png, .mp3])83 #expect(v.errors.map(\.nodePath) == ["1"] && v.errors[0].message.contains("MP3, PNG") && !v.errors[0].message.contains("TXT"))84 }8586 @Test func filtersNarrowTheFormatsThatReachANode() {87 let filtered = validate([.filter(.formatIs(.txt)), convert(.markdown), .export(folder: out, conflictPolicy: .rename)], inputs: [.txt, .png, .mp3])88 #expect(filtered.isValid)89 let byCategory = validate([.filter(.categoryIs(.document)), convert(.markdown), .export(folder: out, conflictPolicy: .rename)], inputs: [.txt, .png])90 #expect(byCategory.isValid)91 let negated = validate([.filter(.not(.formatIs(.png))), convert(.markdown), .export(folder: out, conflictPolicy: .rename)], inputs: [.txt, .png])92 #expect(negated.isValid)93 let unreachable = validate([.filter(.formatIs(.gif)), convert(.markdown), .export(folder: out, conflictPolicy: .rename)], inputs: [.txt])94 #expect(unreachable.isValid && unreachable.issues.contains { $0.severity == .warning && $0.nodePath == "2" })95 }9697 @Test func branchesAreValidatedWithNestedPaths() {98 let v = validate([99 .branch(condition: .formatIs(.txt), then: [convert(.markdown)], otherwise: [.rename(template: " "), convert(.yaml)]),100 .export(folder: out, conflictPolicy: .rename),101 ], inputs: [.txt, .png])102 #expect(v.errors.map(\.nodePath) == ["1.otherwise.1", "1.otherwise.2"])103 #expect(v.errors[0].message == "The name template is empty." && v.errors[1].message.contains("PNG"))104 #expect(v.exportedFormats == [.markdown, .yaml])105 }106107 @Test func alreadyInDestinationFormatPassesThrough() {108 let v = validate([convert(.markdown), .export(folder: out, conflictPolicy: .rename)], inputs: [.txt, .markdown])109 #expect(v.isValid && v.canExportUnconverted, "a markdown input is exported as it came")110 }111112 @Test func withoutKnownInputsOnlyImpossibleNodesAreErrors() {113 #expect(validate([convert(.markdown), .export(folder: out, conflictPolicy: .rename)]).isValid, "some source format reaches markdown")114 let impossible = validate([convert(.mp3), .export(folder: out, conflictPolicy: .rename)])115 #expect(impossible.errors.map(\.nodePath) == ["1"])116 }117118 @Test func structuralProblems() {119 #expect(validate([]).errors.first?.message == "The workflow has no step.")120 let noExport = validate([convert(.markdown)], inputs: [.txt])121 #expect(noExport.isValid && noExport.issues.contains { $0.severity == .warning && $0.nodePath.isEmpty } && noExport.exportedFormats == [.markdown])122 let asking = validate([convert(.markdown), .export(folder: out, conflictPolicy: .askUser)], inputs: [.txt])123 #expect(asking.isValid && asking.issues.contains { $0.severity == .warning && $0.nodePath == "2" })124 let passthrough = validate([.export(folder: out, conflictPolicy: .rename)], inputs: [.txt])125 #expect(passthrough.canExportUnconverted && passthrough.exportedFormats == [.txt])126 }127128 @Test func operationsAreValidatedToo() {129 #expect(validate([convert(.folder, op: "text.explode"), .export(folder: out, conflictPolicy: .rename)], inputs: [.txt]).isValid)130 #expect(!validate([convert(.folder, op: "nope"), .export(folder: out, conflictPolicy: .rename)], inputs: [.txt]).isValid)131 }132}133134@Suite struct WorkflowRunnerTests {135 let bed = TestBed()136137 private var runner: WorkflowRunner { WorkflowRunner(queue: bed.queue, history: bed.history, workDirectories: bed.workDirectories) }138 private var out: URL { bed.output }139140 @Test func convertsRenamesAndExportsABatch() async throws {141 let workflow = Workflow(name: "Notes", nodes: [convert(.markdown), .rename(template: "{counter:2}-{name}"), .export(folder: out, conflictPolicy: .rename)])142 let inputs = [bed.source("a.txt", "alpha"), bed.source("b.txt", "beta")]143 let run = try await runner.run(workflow, inputs: inputs)144 #expect(run.items.map(\.status) == [.succeeded, .succeeded] && run.count(.succeeded) == 2)145 #expect(bed.temp.list("out") == ["01-a.md", "02-b.md"] && bed.temp.read("out/02-b.md") == "BETA")146 #expect(run.items[0].outputs.map(\.lastPathComponent) == ["01-a.md"] && run.items[0].jobIDs.count == 1)147 #expect(bed.temp.list("in") == ["a.txt", "b.txt"], "sources are untouched")148 #expect(bed.leftoverWorkDirectories.isEmpty, "intermediates are cleaned")149 }150151 @Test func chainsConversionsThroughWorkDirectoryIntermediates() async throws {152 let workflow = Workflow(name: "Two steps", nodes: [convert(.markdown, ["suffix": .string("!")]), convert(.html), .export(folder: out, conflictPolicy: .rename)])153 let run = try await runner.run(workflow, inputs: [bed.source("page.txt", "hi")])154 #expect(run.items[0].status == .succeeded && run.items[0].jobIDs.count == 2)155 #expect(bed.temp.list("out") == ["page.html"] && bed.temp.read("out/page.html").contains("<pre>HI!</pre>"))156 }157158 @Test func exportsAtSeveralPoints() async throws {159 let other = bed.temp.subdirectory("other")160 let workflow = Workflow(name: "Both", nodes: [161 .export(folder: other, conflictPolicy: .rename), // the original, copied162 convert(.markdown), .export(folder: out, conflictPolicy: .rename),163 convert(.html), .export(folder: out, conflictPolicy: .rename),164 ])165 let run = try await runner.run(workflow, inputs: [bed.source("n.txt", "x")])166 #expect(run.items[0].outputs.count == 3)167 #expect(bed.temp.list("other") == ["n.txt"] && bed.temp.list("out") == ["n.html", "n.md"])168 #expect(bed.temp.exists("in/n.txt"), "exporting the original copies it")169 }170171 @Test func filtersItemsByNameSizeAndInspection() async throws {172 let workflow = Workflow(name: "Filtered", nodes: [173 .filter(.all([.nameMatches("keep*"), .sizeAbove(3), .height(.greaterOrEqual, 2)])),174 convert(.markdown), .export(folder: out, conflictPolicy: .rename),175 ])176 let inputs = [bed.source("keep-two-lines.txt", "one\ntwo\n"), bed.source("keep-one-line.txt", "only one"), bed.source("drop.txt", "one\ntwo\n"), bed.source("keep-tiny.txt", "a\n")]177 let run = try await runner.run(workflow, inputs: inputs)178 #expect(run.items.map(\.status) == [.succeeded, .filtered, .filtered, .filtered])179 #expect(bed.temp.list("out") == ["keep-two-lines.md"] && run.count(.filtered) == 3)180 }181182 @Test func branchesThenContinues() async throws {183 let workflow = Workflow(name: "Branch", nodes: [184 .branch(condition: .nameMatches("big*"), then: [convert(.latex)], otherwise: [convert(.markdown)]),185 .rename(template: "{name}-done"),186 .export(folder: out, conflictPolicy: .rename),187 ])188 let run = try await runner.run(workflow, inputs: [bed.source("big.txt", "x"), bed.source("small.txt", "y")])189 #expect(run.items.allSatisfy { $0.status == .succeeded })190 #expect(bed.temp.list("out") == ["big-done.tex", "small-done.md"])191 #expect(run.items[0].warnings.map(\.code) == ["styles-lost"], "engine warnings reach the item result")192 }193194 @Test func conditionsAfterAConvertSeeTheConvertedFile() async throws {195 let workflow = Workflow(name: "After", nodes: [convert(.markdown), .filter(.formatIs(.markdown)), .filter(.nameMatches("*.md")), .export(folder: out, conflictPolicy: .rename)])196 let run = try await runner.run(workflow, inputs: [bed.source("a.txt", "x")])197 #expect(run.items[0].status == .succeeded && bed.temp.list("out") == ["a.md"])198 }199200 @Test func aFailingItemDoesNotStopTheBatch() async throws {201 let workflow = Workflow(name: "Fragile", nodes: [convert(.markdown), .export(folder: out, conflictPolicy: .rename)])202 let inputs = [bed.source("ok1.txt", "a"), bed.temp.write("in/picture.png", bytes: Fixtures.png), bed.temp.file("in/ghost.txt"), bed.source("ok2.txt", "b")]203 let run = try await runner.run(workflow, inputs: inputs)204 #expect(run.items.map(\.status) == [.succeeded, .failed, .failed, .succeeded])205 #expect(run.items[1].errors.first?.contains("PNG to MARKDOWN is not supported") == true)206 #expect(run.items[2].errors.first?.contains("no longer exists") == true)207 #expect(bed.temp.list("out") == ["ok1.md", "ok2.md"])208 }209210 @Test func stopItemPolicyEndsTheItemAtTheFailingNode() async throws {211 let workflow = Workflow(name: "Stop", nodes: [convert(.rtf), .export(folder: out, conflictPolicy: .rename)], errorPolicy: .stopItem)212 let run = try await runner.run(workflow, inputs: [bed.source("a.txt", "x")])213 #expect(run.items[0].status == .failed && run.items[0].errors == ["The file is damaged or not what its name says. mock failure"])214 #expect(bed.temp.list("out").isEmpty && run.items[0].jobIDs.count == 1)215 }216217 @Test func continueItemPolicySkipsTheFailingNode() async throws {218 let workflow = Workflow(name: "Continue", nodes: [convert(.rtf), .export(folder: out, conflictPolicy: .rename)], errorPolicy: .continueItem)219 let run = try await runner.run(workflow, inputs: [bed.source("a.txt", "x")])220 #expect(run.items[0].status == .succeededWithErrors && run.items[0].errors.count == 1 && run.items[0].jobIDs.count == 1)221 #expect(bed.temp.list("out") == ["a.txt"], "the following nodes ran on the unchanged file")222 }223224 @Test func exportConflictPolicies() async throws {225 bed.temp.write("out/a.md", "existing")226 func run(_ policy: ConflictPolicy) async throws -> WorkflowItemResult {227 let workflow = Workflow(name: "P", nodes: [convert(.markdown), .export(folder: out, conflictPolicy: policy)])228 return try await runner.run(workflow, inputs: [bed.source("a.txt", "new")]).items[0]229 }230 let skipped = try await run(.skip)231 #expect(skipped.status == .succeeded && skipped.outputs.isEmpty && bed.temp.read("out/a.md") == "existing")232 let asked = try await run(.askUser)233 #expect(asked.status == .failed && asked.errors.first?.contains("already exists") == true)234 let renamed = try await run(.rename)235 #expect(renamed.outputs.map(\.lastPathComponent) == ["a 2.md"])236 let replaced = try await run(.replace)237 #expect(replaced.outputs.map(\.lastPathComponent) == ["a.md"] && bed.temp.read("out/a.md") == "NEW")238 }239240 @Test func pathsWithoutExportUseTheDefaultFolder() async throws {241 let workflow = Workflow(name: "Implicit", nodes: [convert(.markdown)])242 let beside = try await runner.run(workflow, inputs: [bed.source("a.txt", "x")])243 #expect(beside.items[0].outputs.map(\.lastPathComponent) == ["a.md"] && bed.temp.exists("in/a.md"))244 let elsewhere = try await runner.run(workflow, inputs: [bed.source("b.txt", "x")], options: WorkflowRunOptions(defaultExportFolder: out))245 #expect(elsewhere.items[0].outputs.first?.path.hasSuffix("/out/b.md") == true)246 // Nothing converted, nothing renamed, same folder: nothing to write.247 let noop = try await runner.run(Workflow(name: "Noop", nodes: [.filter(.sizeAbove(0))]), inputs: [bed.source("c.txt", "x")])248 #expect(noop.items[0].status == .succeeded && noop.items[0].outputs.isEmpty && bed.temp.list("in").filter { $0.hasPrefix("c") } == ["c.txt"])249 }250251 @Test func neverWritesOverTheSource() async throws {252 let source = bed.temp.write("in/doc.md", "words\n")253 let workflow = Workflow(name: "Same place", nodes: [.export(folder: bed.input, conflictPolicy: .replace)])254 let run = try await runner.run(workflow, inputs: [source])255 #expect(run.items[0].status == .failed && bed.temp.read("in/doc.md") == "words\n")256 let renaming = Workflow(name: "Copy", nodes: [.export(folder: bed.input, conflictPolicy: .rename)])257 let copy = try await runner.run(renaming, inputs: [source])258 #expect(copy.items[0].outputs.map(\.lastPathComponent) == ["doc 2.md"])259 }260261 @Test func alreadyInDestinationFormatIsNotReconverted() async throws {262 let workflow = Workflow(name: "Normalize", nodes: [convert(.markdown), .export(folder: out, conflictPolicy: .rename)])263 let run = try await runner.run(workflow, inputs: [bed.temp.write("in/ready.md", "# Title\n\n**bold** text\n")])264 #expect(run.items[0].status == .succeeded && run.items[0].jobIDs.isEmpty && bed.temp.read("out/ready.md").hasPrefix("# Title"))265 }266267 @Test func multipleOutputsFlowThroughTheFollowingNodes() async throws {268 let workflow = Workflow(name: "Rows", nodes: [convert(.tsv), .rename(template: "row-{name}"), .export(folder: out, conflictPolicy: .rename)])269 let run = try await runner.run(workflow, inputs: [bed.source("t.txt", "a\nb\nc\n")])270 // Three files from one input: exported in one folder named after the (renamed) input.271 #expect(run.items[0].outputs.count == 3 && bed.temp.list("out") == ["row-t"] && bed.temp.list("out/row-t") == ["row-t-1.tsv", "row-t-2.tsv", "row-t-3.tsv"])272 }273274 @Test func folderOutputsAreExported() async throws {275 let workflow = Workflow(name: "Explode", nodes: [convert(.folder, op: "text.explode"), .export(folder: out, conflictPolicy: .rename)])276 let run = try await runner.run(workflow, inputs: [bed.source("lines.txt", "a\nb\n")])277 #expect(run.items[0].status == .succeeded && bed.temp.list("out/lines") == ["line-1.txt", "line-2.txt"])278 }279280 @Test func invalidWorkflowsAreRefusedBeforeAnythingRuns() async throws {281 let workflow = Workflow(name: "Bad", nodes: [convert(.markdown), convert(.mp3), .export(folder: out, conflictPolicy: .rename)])282 do {283 _ = try await runner.run(workflow, inputs: [bed.source("a.txt", "x")])284 Issue.record("expected the run to be refused")285 } catch WorkflowError.invalid(let validation) {286 #expect(validation.errors.map(\.nodePath) == ["2"])287 #expect(WorkflowError.invalid(validation).errorDescription?.contains("Step 2: No conversion to MP3") == true)288 }289 #expect(bed.probe.order.isEmpty && bed.temp.list("out").isEmpty)290 }291292 @Test func cancellationStopsOutstandingJobs() async throws {293 let slow = TestBed(maxConcurrent: 2, steps: 500, stepDelay: 0.02)294 let runner = WorkflowRunner(queue: slow.queue, history: slow.history, workDirectories: slow.workDirectories)295 let workflow = Workflow(name: "Slow", nodes: [convert(.yaml), .export(folder: slow.output, conflictPolicy: .rename)])296 let inputs = (0..<6).map { slow.source("f\($0).txt") }297 let task = Task { try await runner.run(workflow, inputs: inputs) }298 #expect(await eventually { slow.probe.order.count >= 2 })299 let started = Date()300 task.cancel()301 let run = try await task.value302 #expect(Date().timeIntervalSince(started) < 5, "did not wait for the 10 s conversions")303 #expect(run.items.allSatisfy { $0.status == .cancelled } && slow.temp.list("out").isEmpty)304 await slow.queue.waitUntilIdle()305 #expect(await slow.queue.snapshot().jobs.allSatisfy { $0.state == .cancelled })306 #expect(slow.leftoverWorkDirectories.isEmpty)307 }308309 @Test func itemCallbackAndConcurrencyBound() async throws {310 let seen = LockedBox<[String]>([])311 let workflow = Workflow(name: "CB", nodes: [convert(.markdown), .export(folder: out, conflictPolicy: .rename)])312 let inputs = (0..<9).map { bed.source("f\($0).txt", "x") }313 let run = try await runner.run(workflow, inputs: inputs, options: WorkflowRunOptions(maxConcurrentItems: 2)) { item in314 seen.mutate { $0.append(item.source.lastPathComponent) }315 }316 #expect(run.items.map(\.source) == inputs, "results are in input order")317 #expect(seen.value.sorted() == inputs.map(\.lastPathComponent).sorted())318 #expect(bed.probe.maximum <= 2)319 }320321 @Test func runsAreRecordedInTheHistoryStoreAndJobsAreNot() async throws {322 let workflow = Workflow(name: "Recorded", nodes: [.filter(.not(.nameMatches("skip*"))), convert(.markdown), .export(folder: out, conflictPolicy: .rename)])323 let run = try await runner.run(workflow, inputs: [bed.source("a.txt", "x"), bed.source("skip.txt", "x"), bed.temp.file("in/ghost.txt")])324 let records = try await bed.history.workflowRuns(workflowID: workflow.id)325 let record = try #require(records.first)326 #expect(records.count == 1 && record.id == run.runID && record.workflowName == "Recorded")327 #expect(record.itemCount == 3 && record.succeeded == 1 && record.filtered == 1 && record.failed == 1 && record.cancelled == 0)328 #expect(record.items.map(\.status) == ["succeeded", "filtered", "failed"] && record.items[0].outputPaths.first?.hasSuffix("/out/a.md") == true)329 #expect(try await bed.history.count() == 0, "intermediate jobs do not clutter the job history")330 _ = try await runner.run(workflow, inputs: [bed.source("b.txt", "x")], options: WorkflowRunOptions(recordRun: false))331 #expect(try await bed.history.workflowRuns().count == 1)332 }333}334335@Suite struct WorkflowLibraryTests {336 let temp = TempDir("library")337 private var url: URL { temp.file("support/workflows.json") }338 private let sample = Workflow(name: "Web", nodes: [convert(.markdown), .export(folder: URL(fileURLWithPath: "/tmp/o"), conflictPolicy: .rename)])339340 @Test func savesReplacesDeletesAndPersists() async throws {341 let library = WorkflowLibrary(fileURL: url)342 try await library.save(sample)343 var edited = sample344 edited.name = "Web v2"345 try await library.save(edited)346 #expect(await WorkflowLibrary(fileURL: url).all == [edited])347 #expect(await library.workflow(id: sample.id)?.name == "Web v2")348 let copy = try await library.duplicate(id: sample.id)349 let count = await library.all.count350 #expect(copy.id != sample.id && copy.name == "Web v2 copy" && count == 2)351 try await library.delete(id: sample.id)352 #expect(await WorkflowLibrary(fileURL: url).all == [copy])353 do {354 try await library.delete(id: sample.id)355 Issue.record("expected notFound")356 } catch WorkflowError.notFound {}357 }358359 @Test func exportsAndImports() async throws {360 let library = WorkflowLibrary(fileURL: url)361 try await library.save(sample)362 let data = try await library.exportData()363 let other = WorkflowLibrary(fileURL: temp.file("other.json"))364 let imported = try await other.importData(data)365 #expect(imported.count == 1 && imported[0].id != sample.id && imported[0].nodes == sample.nodes)366 #expect(try await library.exportData(ids: []).count < data.count)367 do {368 _ = try await other.importData(Data("[]".utf8))369 Issue.record("expected a storage error")370 } catch WorkflowError.storage {}371 }372373 @Test func corruptLibraryIsReported() async throws {374 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)375 try Data("nope".utf8).write(to: url)376 let library = WorkflowLibrary(fileURL: url)377 let loadError = await library.loadError, all = await library.all378 #expect(loadError != nil && all.isEmpty)379 }380}381