Repository Public License
1// ORIX Convert — Packages/ConvertKit/Tests/ConvertKitTests/ConvertTests.swift2// Description: `convert` end to end on a small subset (real queue, engines, validation, safe writer): outputs, JSON3// report, conflict policies, exit codes, multi-source operations, chained plans, cancellation, workflows,4// and the executable itself under Ctrl-C.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import Foundation7import Testing8import ConvertCore9import ConvertKit10@testable import ConvertCLI1112@Suite(.serialized) struct ConvertTests {13 @Test func convertsABatchAndReportsIt() async throws {14 let scratch = Scratch()15 let a = try scratch.png("in/a.png", seed: 1), b = try scratch.png("in/b.png", seed: 2)16 let out = scratch.file("out")17 let result = try await convert([a.path, b.path, "--to", "jpeg", "--output-dir", out.path, "--option", "quality=70", "--json"], scratch: scratch)18 #expect(result.code == .success)19 let printed = try result.capture.decode(BatchReport.self)20 #expect(printed.summary.total == 2 && printed.summary.finished == 2 && printed.summary.failed == 0 && printed.summary.exitCode == 0)21 #expect(printed.jobs.map { $0.sourceFormat } == ["png", "png"])22 #expect(printed.jobs.allSatisfy { $0.engines == ["image"] && !$0.checks.isEmpty && $0.checks.allSatisfy { $0.passed } && $0.seconds != nil })23 #expect(printed.leftoverTemporaryItems.isEmpty && scratch.leftovers().isEmpty)24 for name in ["a.jpg", "b.jpg"] {25 #expect(FileTypeDetector.detect(out.appendingPathComponent(name)).format == .jpeg)26 }27 #expect(printed.summary.bytesAfter > 0 && printed.summary.bytesBefore > 0)28 }2930 @Test func textOutputShowsWarningsChecksAndSummary() async throws {31 let scratch = Scratch()32 let target = scratch.file("alpha.png")33 try Seeds.writeImage(try Seeds.image(width: 64, height: 64, seed: 3, alpha: true), to: target)34 let result = try await convert([target.path, "--to", "jpeg", "--output-dir", scratch.file("out").path, "--verbose"], scratch: scratch)35 #expect(result.code == .success)36 let text = result.capture.out37 #expect(text.contains("ok alpha.png"))38 #expect(text.contains("check passed output.format"))39 #expect(text.contains("warning [")) // transparency is flattened: the engine says so40 #expect(text.contains("Summary: 1 job(s) — 1 converted, 0 failed, 0 skipped"))41 }4243 @Test func conflictPolicies() async throws {44 let scratch = Scratch()45 let source = try scratch.png("in/photo.png")46 let out = scratch.file("out")47 let arguments = [source.path, "--to", "jpeg", "--output-dir", out.path]48 #expect(try await convert(arguments, scratch: scratch).code == .success)49 let original = try Data(contentsOf: out.appendingPathComponent("photo.jpg"))5051 let failed = try await convert(arguments + ["--on-conflict", "fail"], scratch: scratch)52 #expect(failed.code == .destinationExists)53 #expect(failed.report.jobs.first?.errorKind == "destinationExists")54 #expect(try Data(contentsOf: out.appendingPathComponent("photo.jpg")) == original)55 #expect(scratch.leftovers().isEmpty)5657 let skipped = try await convert(arguments + ["--on-conflict", "skip"], scratch: scratch)58 #expect(skipped.code == .success && skipped.report.summary.skipped == 1)59 #expect(try Data(contentsOf: out.appendingPathComponent("photo.jpg")) == original)6061 let renamed = try await convert(arguments, scratch: scratch) // default: rename62 #expect(renamed.code == .success)63 #expect(renamed.report.jobs.first?.outputs.first?.path.hasSuffix("photo 2.jpg") == true)64 #expect(renamed.report.jobs.first?.outputs.first?.outcome == "renamed")65 #expect(try Data(contentsOf: out.appendingPathComponent("photo.jpg")) == original)6667 let replaced = try await convert(arguments + ["--on-conflict", "replace", "--option", "quality=20"], scratch: scratch)68 #expect(replaced.code == .success && replaced.report.jobs.first?.outputs.first?.outcome == "replaced")69 #expect(try Data(contentsOf: out.appendingPathComponent("photo.jpg")) != original)70 #expect(try FileManager.default.contentsOfDirectory(atPath: out.path).sorted() == ["photo 2.jpg", "photo.jpg"])71 }7273 @Test func theSourceIsNeverReplaced() async throws {74 let scratch = Scratch()75 let source = try scratch.png("photo.png")76 let before = try Data(contentsOf: source)77 let result = try await convert([source.path, "--to", "png", "--on-conflict", "replace"], scratch: scratch)78 #expect(result.code == .destinationExists)79 #expect(try Data(contentsOf: source) == before)80 let renamed = try await convert([source.path, "--to", "png"], scratch: scratch)81 #expect(renamed.code == .success && FileManager.default.fileExists(atPath: scratch.file("photo 2.png").path))82 #expect(try Data(contentsOf: source) == before)83 }8485 @Test func exitCodesForBadInputs() async throws {86 let scratch = Scratch()87 let wav = scratch.file("tone.wav")88 try Seeds.writeWAV(to: wav, seconds: 0.2)89 let unsupported = try await convert([wav.path, "--to", "docx", "--output-dir", scratch.file("out").path], scratch: scratch)90 #expect(unsupported.code == .unsupported && unsupported.report.jobs.first?.errorKind == "unsupportedPath")91 let missing = try await convert([scratch.file("absent.png").path, "--to", "jpeg"], scratch: scratch)92 #expect(missing.code == .inputError)93 let empty = scratch.file("empty.png")94 try Data().write(to: empty)95 let garbage = scratch.file("garbage.png")96 try Data((0..<3000).map { UInt8(truncatingIfNeeded: $0 &* 131 &+ 7) }).write(to: garbage)97 let bad = try await convert([empty.path, garbage.path, "--to", "jpeg", "--output-dir", scratch.file("out").path], scratch: scratch)98 #expect(bad.code != .success && bad.report.summary.failed == 2)99 #expect(bad.report.jobs.allSatisfy { !($0.error ?? "").isEmpty && $0.outputs.isEmpty })100 // One good file among bad ones: the good one is delivered and the status says a conversion failed.101 let good = try scratch.png("good.png")102 let mixed = try await convert([good.path, garbage.path, "--to", "jpeg", "--output-dir", scratch.file("out").path], scratch: scratch)103 #expect(mixed.code == .conversionFailed && mixed.report.summary.finished == 1 && mixed.report.summary.failed == 1)104 #expect(scratch.leftovers().isEmpty)105 #expect(((try? FileManager.default.contentsOfDirectory(atPath: scratch.file("out").path)) ?? []) == ["good.jpg"])106 }107108 @Test func outputFileNameTemplateAndRecursion() async throws {109 let scratch = Scratch()110 let source = try scratch.png("tree/one.png", seed: 1)111 try scratch.png("tree/deep/two.png", seed: 2)112 try scratch.text("tree/.hidden.png", "not a picture")113 let exact = try await convert([source.path, "--to", "jpeg", "--output", scratch.file("named/result.jpg").path], scratch: scratch)114 #expect(exact.code == .success && FileManager.default.fileExists(atPath: scratch.file("named/result.jpg").path))115 await #expect(throws: UsageError.self) { try await convert([source.path, "--to", "jpeg", "--output", scratch.file("named/result.png").path], scratch: scratch) }116 let out = scratch.file("out")117 let recursive = try await convert([scratch.file("tree").path, "--recursive", "--to", "webp", "--output-dir", out.path, "--name-template", "{counter:2}-{name}-{width}x{height}"], scratch: scratch)118 #expect(recursive.code == .success && recursive.report.summary.total == 2)119 #expect(try FileManager.default.contentsOfDirectory(atPath: out.path).sorted() == ["01-two-96x64.webp", "02-one-96x64.webp"])120 }121122 @Test func optionValuesAreValidatedAgainstTheDescriptors() async throws {123 let scratch = Scratch()124 let source = try scratch.png("photo.png")125 await #expect(throws: UsageError.self) { try await convert([source.path, "--to", "jpeg", "--option", "quality=900"], scratch: scratch) }126 let capture = Capture()127 let result = try await convert([source.path, "--to", "jpeg", "--output-dir", scratch.file("o").path, "--option", "made.up=1"], scratch: scratch, capture: capture)128 #expect(result.code == .success && capture.err.contains("'made.up' is not a documented setting"))129 }130131 @Test func secretOptionsReachTheRequestButNotTheScreen() throws {132 let scratch = Scratch()133 let pdf = scratch.file("doc.pdf")134 try DevCommand.writePDF(to: pdf, pages: 1, scanned: false)135 let capture = Capture()136 capture.environment = ["ORIX_TEST_PW": "correct horse"]137 let parsed = try ArgumentParser.parse([pdf.path, "--to", "png", "--option", "password=@env:ORIX_TEST_PW", "--no-history"], spec: ConvertCommand.spec)138 let plan = try ConvertCommand.prepare(parsed, io: capture.io, registry: Shared.registry())139 #expect(plan.requests.first?.options.string("password") == "correct horse")140 #expect(plan.requests.first?.options.redactingSecrets().has("password") == false)141 #expect(plan.requests.first?.recordInHistory == false)142 #expect(!capture.err.contains("correct horse") && !capture.out.contains("correct horse"))143 }144145 @Test func mergeTakesSeveralSourcesInOneJob() async throws {146 let scratch = Scratch()147 let a = scratch.file("a.pdf"), b = scratch.file("b.pdf")148 try DevCommand.writePDF(to: a, pages: 2, scanned: false)149 try DevCommand.writePDF(to: b, pages: 3, scanned: false)150 let merged = scratch.file("merged.pdf")151 let result = try await convert([a.path, b.path, "--to", "pdf", "--operation", "pdf.merge", "--output", merged.path], scratch: scratch)152 #expect(result.code == .success && result.report.summary.total == 1 && result.report.jobs.first?.sources.count == 2)153 let inspected = await FileInspector(registry: Shared.registry()).inspect(merged)154 #expect(inspected.inspection.pageCount == 5)155 await #expect(throws: UsageError.self) { try await convert([a.path, b.path, "--to", "txt", "--combine"], scratch: scratch) }156 }157158 @Test func aChainedPlanRunsThroughBothEngines() async throws {159 let scratch = Scratch()160 let registry = Shared.registry()161 // SVG → HEIC has no direct path: the planner bridges it (vector engine, then image engine).162 let csv = try scratch.text("drawing.svg", Seeds.svg)163 let destination = FormatID.heic164 #expect(registry.paths(from: .svg, to: .heic).isEmpty)165 let result = try await convert([csv.path, "--to", destination.rawValue, "--output-dir", scratch.file("out").path], scratch: scratch)166 #expect(result.code == .success, "\(result.report.jobs.first?.error ?? "")")167 #expect(result.report.jobs.first?.chained == true && result.report.jobs.first?.engines.count == 2)168 #expect(result.report.jobs.first?.checks.contains { $0.name.hasPrefix("step1.") } == true)169 let refused = try await convert([csv.path, "--to", destination.rawValue, "--output-dir", scratch.file("out2").path, "--no-chain"], scratch: scratch)170 #expect(refused.code == .unsupported)171 }172173 @Test func interruptionCancelsAndLeavesNothingBehind() async throws {174 let scratch = Scratch()175 var arguments: [String] = []176 for index in 1...40 { arguments.append(try scratch.png("in/p\(index).png", seed: index, width: 1200, height: 900).path) }177 InterruptCenter.shared.reset()178 defer { InterruptCenter.shared.reset() }179 let result = try await convert(arguments + ["--to", "heic", "--output-dir", scratch.file("out").path, "--jobs", "2"], scratch: scratch) { _, _ in180 InterruptCenter.shared.trigger()181 }182 #expect(result.code == .interrupted)183 #expect(result.report.summary.interrupted && result.report.summary.cancelled > 0)184 #expect(result.report.summary.cancelled + result.report.summary.finished + result.report.summary.failed == 40)185 #expect(scratch.leftovers().isEmpty)186 let written = (try? FileManager.default.contentsOfDirectory(atPath: scratch.file("out").path)) ?? []187 #expect(!written.contains { $0.contains(".partial") })188 #expect(written.count == result.report.summary.finished)189 }190191 @Test func workflowRunConvertsAndExports() async throws {192 let scratch = Scratch()193 let big = try scratch.png("in/big.png", seed: 1, width: 400, height: 300), small = try scratch.png("in/small.png", seed: 2, width: 80, height: 60)194 let note = try scratch.text("in/note.txt", Seeds.text)195 let out = scratch.file("exported")196 let workflow = Workflow(name: "Test flow", nodes: [197 .filter(.categoryIs(.image)),198 .branch(condition: .width(.greaterThan, 200), then: [.convert(destination: .jpeg, operation: nil, options: ConversionOptions(["quality": .int(60)])), .rename(template: "{name}-large")],199 otherwise: [.convert(destination: .webp, operation: nil, options: ConversionOptions())]),200 .export(folder: out, conflictPolicy: .rename),201 ])202 let file = try scratch.text("flow.json", try Shared.json(workflow))203 let result = await run(["workflow", "run", file.path, big.path, small.path, note.path, "--json", "--no-history"])204 #expect(result.code == 0, "\(result.capture.err)")205 let output = try result.capture.decode(WorkflowCommand.RunOutput.self)206 #expect(output.succeeded == 2 && output.filtered == 1 && output.failed == 0)207 #expect(try FileManager.default.contentsOfDirectory(atPath: out.path).sorted() == ["big-large.jpg", "small.webp"])208 }209}210211@Suite struct ExecutableTests {212 static var executable: URL? {213 // The executable is built next to the test bundle (the test target depends on it).214 var candidates = Bundle.allBundles.map { $0.bundleURL.deletingLastPathComponent() } + [Bundle(for: Capture.self).bundleURL.deletingLastPathComponent()]215 var directory = URL(fileURLWithPath: #filePath)216 for _ in 0..<3 { directory = directory.deletingLastPathComponent() }217 candidates.append(directory.appendingPathComponent(".build/debug"))218 return candidates.map { $0.appendingPathComponent("orix-convert") }.first { FileManager.default.isExecutableFile(atPath: $0.path) }219 }220221 func launch(_ arguments: [String], environment: [String: String] = [:], stdin: String? = nil, interruptAfter: TimeInterval? = nil) throws -> (status: Int32, out: String, err: String) {222 let executable = try #require(Self.executable)223 let process = Process()224 process.executableURL = executable225 process.arguments = arguments226 var env = ["PATH": "/usr/bin:/bin", "HOME": NSHomeDirectory(), "TMPDIR": NSTemporaryDirectory()]227 for (key, value) in environment { env[key] = value }228 process.environment = env229 let out = Pipe(), err = Pipe(), input = Pipe()230 process.standardOutput = out; process.standardError = err; process.standardInput = input231 try process.run()232 if let stdin { input.fileHandleForWriting.write(Data(stdin.utf8)) }233 try? input.fileHandleForWriting.close()234 if let interruptAfter {235 DispatchQueue.global().asyncAfter(deadline: .now() + interruptAfter) { if process.isRunning { kill(process.processIdentifier, SIGINT) } }236 }237 let outData = out.fileHandleForReading.readDataToEndOfFile(), errData = err.fileHandleForReading.readDataToEndOfFile()238 process.waitUntilExit()239 return (process.terminationStatus, String(decoding: outData, as: UTF8.self), String(decoding: errData, as: UTF8.self))240 }241242 @Test func runsWithAMinimalEnvironment() throws {243 let version = try launch(["version"])244 #expect(version.status == 0 && version.out.contains("orix-convert"))245 #expect(try launch([]).status == 2)246 let doctor = try launch(["doctor"])247 #expect(doctor.status == 0, "\(doctor.out)")248 #expect(doctor.out.contains("No problem found"))249 }250251 @Test func controlCEndsWithStatus130AndAnEmptyTemporaryRoot() throws {252 let scratch = Scratch()253 var arguments = ["convert"]254 for index in 1...60 { arguments.append(try scratch.png("in/p\(index).png", seed: index, width: 1600, height: 1200).path) }255 let tmp = scratch.file("tmp")256 try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true)257 let result = try launch(arguments + ["--to", "heic", "--output-dir", scratch.file("out").path, "--jobs", "2", "--no-history"],258 environment: ["TMPDIR": tmp.path + "/"], interruptAfter: 1.0)259 #expect(result.status == 130, "status \(result.status)\n\(result.err)")260 #expect(result.out.contains("interrupted"))261 let root = tmp.appendingPathComponent("ai.spboucher.orix.convert/work")262 #expect(((try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? []).isEmpty)263 let written = (try? FileManager.default.contentsOfDirectory(atPath: scratch.file("out").path)) ?? []264 #expect(!written.contains { $0.contains(".partial") || $0.hasPrefix(".orix") })265 }266267 @Test func aPasswordFromStandardInputStaysOutOfTheArguments() throws {268 let scratch = Scratch()269 let pdf = scratch.file("doc.pdf")270 try DevCommand.writePDF(to: pdf, pages: 1, scanned: false)271 // The PDF is not protected: the engine ignores the password, and the run must not echo it anywhere.272 let result = try launch(["convert", pdf.path, "--to", "txt", "--output-dir", scratch.file("out").path, "--option", "password=@stdin", "--no-history", "--verbose"], stdin: "pa55-from-stdin\n")273 #expect(result.status == 0, "\(result.err)")274 #expect(!result.out.contains("pa55-from-stdin") && !result.err.contains("pa55-from-stdin"))275 let missing = try launch(["convert", pdf.path, "--to", "txt", "--option", "password=@env:ORIX_NOT_SET", "--no-history"])276 #expect(missing.status == 2)277 }278}279280@Suite(.serialized) struct SweepTests {281 @Test func theSweepRunsOneEngineEndToEndAndWritesItsReport() async throws {282 let scratch = Scratch()283 let result = await run(["matrix", "--verify", "--engine", "subtitle", "--work-dir", scratch.file("work").path, "--report-dir", scratch.file("report").path, "--jobs", "4"])284 #expect(result.code == 0, "\(result.capture.err)")285 let report = try JSONDecoder().decode(SweepReport.self, from: Data(contentsOf: scratch.file("report/e2e-matrix-partial.json")))286 let declared = Shared.registry().paths(engine: "subtitle").count287 #expect(report.totals.total == declared && report.totals.pass == declared && report.totals.fail == 0 && report.totals.skip == 0)288 #expect(report.results.allSatisfy { $0.checks > 0 && $0.seconds != nil })289 #expect(report.temporaryLeftovers.isEmpty)290 #expect(report.fixtures.contains { $0.format == "srt" && $0.origin == "seed" })291 #expect(report.fixtures.contains { $0.format == "vtt" && $0.origin == "subtitle:srt>vtt" })292 let markdown = try String(contentsOf: scratch.file("report/e2e-matrix-partial.md"), encoding: .utf8)293 #expect(markdown.contains("PARTIAL RUN") && markdown.contains("`subtitle:srt>vtt`"))294 // A second invocation resumes: nothing is run again.295 let again = await run(["matrix", "--verify", "--engine", "subtitle", "--work-dir", scratch.file("work").path, "--report-dir", scratch.file("report").path])296 #expect(again.code == 0 && again.capture.err.contains("Running 0 of \(declared) path(s)"))297 }298}299