Repository Public License
1// ORIX Convert — Packages/ConvertKit/Tests/ConvertKitTests/ParsingTests.swift2// Description: Argument parsing, option typing and secret handling of the command-line tool.3// Author: Simon-Pierre Boucher — contact@spboucher.ai4import Foundation5import Testing6import ConvertCore7import ConvertKit8@testable import ConvertCLI910@Suite struct ArgumentParsingTests {11 let spec = CommandSpec("demo", summary: "", usage: "demo <a> [b]", flags: ["json"], options: ["to"], repeated: ["option"], positionals: 1...2)1213 @Test func flagsOptionsAndPositionals() throws {14 let parsed = try ArgumentParser.parse(["a.png", "--to", "jpeg", "--json", "--option=quality=80", "--option", "x=1", "b.png"], spec: spec)15 #expect(parsed.positionals == ["a.png", "b.png"])16 #expect(parsed.value("to") == "jpeg")17 #expect(parsed.flag("json"))18 #expect(parsed.all("option") == ["quality=80", "x=1"])19 }2021 @Test func doubleDashEndsOptions() throws {22 let parsed = try ArgumentParser.parse(["--", "--to"], spec: spec)23 #expect(parsed.positionals == ["--to"])24 #expect(parsed.value("to") == nil)25 }2627 @Test func errors() {28 #expect(throws: UsageError.self) { try ArgumentParser.parse(["a", "--nope"], spec: spec) }29 #expect(throws: UsageError.self) { try ArgumentParser.parse(["a", "--to"], spec: spec) }30 #expect(throws: UsageError.self) { try ArgumentParser.parse(["a", "--to", "x", "--to", "y"], spec: spec) }31 #expect(throws: UsageError.self) { try ArgumentParser.parse(["a", "--json=1"], spec: spec) }32 #expect(throws: UsageError.self) { try ArgumentParser.parse([], spec: spec) }33 #expect(throws: UsageError.self) { try ArgumentParser.parse(["a", "b", "c"], spec: spec) }34 #expect(throws: UsageError.self) { try ArgumentParser.parse(["a", "-x"], spec: spec) }35 }3637 @Test func helpSkipsPositionalChecks() throws {38 #expect(try ArgumentParser.parse(["--help"], spec: spec).flag("help"))39 #expect(try ArgumentParser.parse(["-h"], spec: spec).flag("help"))40 }4142 @Test func numericValues() throws {43 let numbers = CommandSpec("n", summary: "", usage: "n", options: ["jobs"])44 #expect(try ArgumentParser.parse(["--jobs", "4"], spec: numbers).int("jobs", in: 1...64) == 4)45 #expect(throws: UsageError.self) { try ArgumentParser.parse(["--jobs", "0"], spec: numbers).int("jobs", in: 1...64) }46 #expect(throws: UsageError.self) { try ArgumentParser.parse(["--jobs", "many"], spec: numbers).int("jobs", in: 1...64) }47 }4849 @Test func formatNames() throws {50 #expect(try Shared.format("JPG", option: "--to") == .jpeg)51 #expect(try Shared.format(".tar.gz", option: "--to") == .tgz)52 #expect(try Shared.format("markdown", option: "--to") == .markdown)53 #expect(try Shared.format("md", option: "--to") == .markdown)54 #expect(throws: UsageError.self) { try Shared.format("nonsense", option: "--to") }55 }56}5758@Suite struct OptionParsingTests {59 let descriptors = [60 OptionDescriptor("quality", label: "Quality", kind: .integer(default: 80, range: 1...100, unit: nil)),61 OptionDescriptor("scale", label: "Scale", kind: .number(default: 1, range: 0.1...4, step: 0.1, unit: nil)),62 OptionDescriptor("strip", label: "Strip", kind: .toggle(default: false)),63 OptionDescriptor("mode", label: "Mode", kind: .choice(default: "a", choices: [.init("a", "A"), .init("b", "B")])),64 OptionDescriptor("title", label: "Title", kind: .text(default: "", placeholder: "")),65 ]6667 @Test func typesComeFromTheDescriptors() throws {68 let raws = [("quality", "55"), ("scale", "2"), ("strip", "yes"), ("mode", "b"), ("title", "12")].map { OptionParsing.Raw(key: $0.0, value: $0.1) }69 let options = try OptionParsing.typed(raws, descriptors: descriptors)70 #expect(options["quality"] == .int(55))71 #expect(options["scale"] == .double(2))72 #expect(options["strip"] == .bool(true))73 #expect(options["mode"] == .string("b"))74 #expect(options["title"] == .string("12"))75 }7677 @Test func rangesAndChoicesAreChecked() {78 #expect(throws: UsageError.self) { try OptionParsing.typed([.init(key: "quality", value: "101")], descriptors: descriptors) }79 #expect(throws: UsageError.self) { try OptionParsing.typed([.init(key: "quality", value: "high")], descriptors: descriptors) }80 #expect(throws: UsageError.self) { try OptionParsing.typed([.init(key: "mode", value: "c")], descriptors: descriptors) }81 #expect(throws: UsageError.self) { try OptionParsing.typed([.init(key: "strip", value: "maybe")], descriptors: descriptors) }82 }8384 @Test func unknownKeysAreInferredAndReported() throws {85 var unknown: [String] = []86 let options = try OptionParsing.typed([.init(key: "x.flag", value: "true"), .init(key: "x.n", value: "7"), .init(key: "x.f", value: "1.5"), .init(key: "x.s", value: "abc")],87 descriptors: descriptors) { unknown.append($0) }88 #expect(options["x.flag"] == .bool(true))89 #expect(options["x.n"] == .int(7))90 #expect(options["x.f"] == .double(1.5))91 #expect(options["x.s"] == .string("abc"))92 #expect(unknown == ["x.flag", "x.n", "x.f", "x.s"])93 }9495 @Test func secretsFromEnvironmentAndStandardInput() throws {96 let capture = Capture()97 capture.environment = ["PDF_PW": "s3cret-from-env"]98 capture.stdin = ["typed-secret"]99 let raws = try OptionParsing.resolve(["password=@env:PDF_PW", "output.password.user=@stdin", "quality=80"], io: capture.io)100 #expect(raws == [.init(key: "password", value: "s3cret-from-env"), .init(key: "output.password.user", value: "typed-secret"), .init(key: "quality", value: "80")])101 #expect(capture.err.isEmpty)102 }103104 @Test func missingSecretSourcesAreUsageErrors() {105 let capture = Capture()106 #expect(throws: UsageError.self) { try OptionParsing.resolve(["password=@env:NOT_SET_ANYWHERE"], io: capture.io) }107 #expect(throws: UsageError.self) { try OptionParsing.resolve(["password=@stdin"], io: capture.io) }108 #expect(throws: UsageError.self) { try OptionParsing.resolve(["novalue"], io: capture.io) }109 }110111 @Test func literalSecretWarnsWithoutEchoingIt() throws {112 let capture = Capture()113 let raws = try OptionParsing.resolve(["password=hunter2"], io: capture.io)114 #expect(raws.first?.value == "hunter2")115 #expect(capture.err.contains("@env:"))116 #expect(!capture.err.contains("hunter2"))117 }118119 @Test func aSecretIsNeverEchoedInAnError() {120 let secret = OptionDescriptor("password.level", label: "", kind: .integer(default: 1, range: 1...3, unit: nil))121 do {122 _ = try OptionParsing.typed([.init(key: "password.level", value: "topsecret")], descriptors: [secret])123 Issue.record("expected a usage error")124 } catch let error as UsageError {125 #expect(!error.message.contains("topsecret"))126 } catch { Issue.record("unexpected error \(error)") }127 }128129 @Test func atSignOnlyMattersForSecretKeys() throws {130 let raws = try OptionParsing.resolve(["title=@env:HOME", "password=@@literal"], io: Capture().io)131 #expect(raws[0].value == "@env:HOME")132 #expect(raws[1].value == "@literal")133 }134}135136@Suite struct ToolEnvironmentTests {137 @Test func aHelpersFolderWithToolsIsRecognised() throws {138 let scratch = Scratch()139 let helpers = scratch.url.appendingPathComponent("ORIX Convert.app/Contents/Helpers", isDirectory: true)140 try FileManager.default.createDirectory(at: helpers, withIntermediateDirectories: true)141 let executable = helpers.appendingPathComponent("orix-convert")142 #expect(ToolEnvironment.toolsDirectory(forExecutable: executable) == nil)143 try Data().write(to: helpers.appendingPathComponent("ffmpeg"))144 #expect(ToolEnvironment.toolsDirectory(forExecutable: executable)?.path == helpers.path)145 }146147 @Test func enginesAreAssembledOnce() {148 let engines = ORIXEngines.all()149 #expect(!engines.isEmpty)150 #expect(Set(engines.map { $0.id }).count == engines.count)151 #expect(ORIXEngines.wiredPackages.allSatisfy(ORIXEngines.knownPackages.contains))152 for required in ["EnginePDF", "EngineImage", "EngineVector", "EngineMedia", "EngineDocuments", "EngineData"] {153 #expect(ORIXEngines.wiredPackages.contains(required))154 }155 let registry = FormatRegistry(engines: engines)156 #expect(registry.diagnostics.isEmpty)157 #expect(ORIXEngines.heavyEngineIDs.isSubset(of: Set(engines.map { $0.id })))158 }159160 @Test func serviceUsesTheHeavyEngineRule() async {161 let scratch = Scratch()162 let service = ConversionService(configuration: .init(maxConcurrentJobs: 3, recordHistory: false, workRoot: scratch.workRoot))163 let configuration = await service.queue.currentConfiguration164 #expect(configuration.maxConcurrentJobs == 3)165 #expect(configuration.heavyEngineIDs == ORIXEngines.heavyEngineIDs)166 #expect(service.history == nil)167 #expect(service.historyError == nil)168 }169}170