Repository Public License
1// ORIX Convert — Packages/ORIXConvertCore/Tests/ConvertCoreTests/RegistryPlannerTests.swift2// Description: FormatRegistry indexing, availability and matrix export; capability resolution and planning rules.3// Author: Simon-Pierre Boucher — contact@spboucher.ai4import Foundation5import Testing6@testable import ConvertCore78private func path(_ s: FormatID, _ d: FormatID, _ engine: String, op: String? = nil, status: SupportStatus = .supported,9 fidelity: Fidelity = .lossless, preserves: Set<Preserved> = [], limitations: [String] = [], multi: Bool = false) -> ConversionPath {10 ConversionPath(s, d, engine: engine, operation: op, title: op.map { "Op \($0)" }, status: status, fidelity: fidelity, preserves: preserves,11 limitations: limitations, acceptsMultipleSources: multi)12}1314private func registry(_ engines: [StubEngine]) -> FormatRegistry { FormatRegistry(engines: engines) }1516/// One engine per path (`e1`, `e2`…): chains are only built across engines, so tests about chains need them apart.17private func perPath(_ engine: StubEngine) -> [StubEngine] {18 engine.paths.enumerated().map { index, p in19 let id = "\(engine.id)\(index + 1)"20 return StubEngine(id: id, paths: [ConversionPath(p.source, p.destination, engine: id, operation: p.operation, title: p.title, status: p.status, fidelity: p.fidelity,21 preserves: p.preserves, limitations: p.limitations, acceptsMultipleSources: p.acceptsMultipleSources,22 producesMultipleOutputs: p.producesMultipleOutputs, appliesToAnyFile: p.appliesToAnyFile)])23 }24}2526@Suite struct FormatRegistryTests {27 let image = StubEngine(id: "image", paths: [28 path(.png, .jpeg, "image", fidelity: .lossy, limitations: ["Transparency is flattened."]),29 path(.png, .tiff, "image", preserves: [.transparency, .metadata]),30 path(.jpeg, .png, "image"),31 path(.png, .pdf, "image", op: "image.to-pdf", multi: true),32 ])33 let office = StubEngine(id: "office", paths: [path(.docx, .pdf, "office", fidelity: .structural)], unavailableReason: "LibreOffice is not bundled.")3435 @Test func indexesPathsBySourceAndDestination() {36 let r = registry([image])37 #expect(r.paths.count == 4)38 #expect(r.paths(from: .png).count == 3)39 #expect(r.paths(to: .png).map(\.source) == [.jpeg])40 #expect(r.paths(from: .png, to: .jpeg).count == 1)41 #expect(r.paths(from: .png, operation: .some(nil)).map(\.destination) == [.jpeg, .tiff])42 #expect(r.paths(from: .png, operation: .some("image.to-pdf")).count == 1)43 #expect(r.paths(engine: "nobody").isEmpty)44 }4546 @Test func listsSourceAndDestinationFormats() {47 let r = registry([image])48 #expect(r.sourceFormats == [.jpeg, .png])49 #expect(r.destinationFormats == [.jpeg, .pdf, .png, .tiff])50 #expect(r.destinations(for: .png) == [.jpeg, .tiff])51 #expect(r.destinations(for: .png, includingOperations: true) == [.jpeg, .pdf, .tiff])52 #expect(r.operations(for: .png).map(\.operation) == ["image.to-pdf"])53 #expect(r.destinations(for: .mp3).isEmpty)54 }5556 @Test func unavailableEnginesAreExcludedAndReported() {57 let r = registry([image, office])58 #expect(r.paths(from: .docx).isEmpty)59 #expect(!r.sourceFormats.contains(.docx))60 #expect(r.unavailableEngines.map(\.id) == ["office"])61 #expect(r.unavailableEngines[0].reason == "LibreOffice is not bundled.")62 #expect(r.unavailablePaths(from: .docx).count == 1)63 #expect(r.availability(ofEngine: "office") == .unavailable(reason: "LibreOffice is not bundled."))64 #expect(r.availability(ofEngine: "image") == .available)65 #expect(r.availability(ofEngine: "ghost") == nil)66 #expect(r.engine(id: "office") != nil, "the engine itself stays registered")67 }6869 @Test func countsFormatsAndPairs() {70 let extra = StubEngine(id: "other", paths: [path(.png, .jpeg, "other", status: .experimental, fidelity: .lossy), path(.gif, .png, "other", status: .experimental)])71 let counts = registry([image, extra, office]).counts72 #expect(counts.formatsWithPath == 5) // png jpeg tiff pdf gif73 #expect(counts.distinctPairs == 5) // png>jpeg, png>tiff, jpeg>png, png>pdf, gif>png74 #expect(counts.verifiedPairs == 4) // gif>png is only experimental75 #expect(counts.conversionPairs == 4)76 #expect(counts.operations == 1)77 #expect(counts.availablePaths == 6 && counts.unavailablePaths == 1)78 #expect(counts.engines == 3 && counts.unavailableEngines == 1)79 }8081 @Test func diagnosesDuplicateEnginesAndForeignPaths() {82 let twin = StubEngine(id: "image", paths: [path(.gif, .png, "image")])83 let liar = StubEngine(id: "liar", paths: [path(.gif, .png, "someone-else"), path(.bmp, .png, "liar"), path(.bmp, .png, "liar")])84 let r = registry([image, twin, liar])85 #expect(r.engines.count == 2)86 #expect(r.paths(from: .gif).isEmpty)87 #expect(r.paths(from: .bmp).count == 1)88 #expect(r.diagnostics.count == 3)89 }9091 @Test func inspectorLookup() {92 let r = registry([image, office])93 #expect(r.inspector(for: .png)?.id == "image")94 #expect(r.inspector(for: .docx) == nil, "an unavailable engine does not inspect")95 #expect(r.inspector(for: .mp3) == nil)96 }9798 @Test func matrixRowsAndMarkdown() {99 let r = registry([image, office])100 let rows = r.matrix()101 #expect(rows.count == 5)102 #expect(rows.last?.status == "unavailable" && rows.last?.unavailableReason == "LibreOffice is not bundled.")103 let markdown = r.matrixMarkdown()104 let lines = markdown.split(separator: "\n")105 #expect(lines.count == 7)106 #expect(lines[0].hasPrefix("| Source | Destination | Operation | Engine | Status | Fidelity | Preserves | Limitations |"))107 #expect(markdown.contains("| png | jpeg | — | image | supported | lossy | — | Transparency is flattened. |"))108 #expect(markdown.contains("| png | tiff | — | image | supported | lossless | metadata, transparency | — |"))109 #expect(markdown.contains("| docx | pdf | — | office | unavailable | structural | — | Unavailable: LibreOffice is not bundled. |"))110 }111112 @Test func matrixMarkdownEscapesPipes() {113 let r = registry([StubEngine(id: "e", paths: [path(.png, .gif, "e", limitations: ["a | b"])])])114 #expect(r.matrixMarkdown().contains("a \\| b"))115 }116117 @Test func matrixJSONIsStableAndDecodable() throws {118 struct Export: Codable { let counts: RegistryCounts; let rows: [MatrixRow] }119 let r = registry([image, office])120 let data = try r.matrixJSON()121 let export = try JSONDecoder().decode(Export.self, from: data)122 #expect(export.rows == r.matrix())123 #expect(export.counts == r.counts)124 #expect(try r.matrixJSON() == data)125 }126127 @Test func emptyRegistry() {128 let r = FormatRegistry(engines: [])129 #expect(r.paths.isEmpty && r.sourceFormats.isEmpty && r.counts.formatsWithPath == 0)130 #expect(r.matrixMarkdown().split(separator: "\n").count == 2)131 }132}133134@Suite struct CapabilityResolverTests {135 let engine = StubEngine(id: "image", paths: [136 path(.png, .jpeg, "image", fidelity: .lossy),137 path(.png, .tiff, "image"),138 path(.png, .pdf, "image", fidelity: .structural),139 path(.png, .webp, "image", status: .experimental, fidelity: .lossy),140 path(.png, .txt, "image", fidelity: .partial),141 path(.png, .gif, "image", fidelity: .lossy),142 path(.png, .pdf, "image", op: "image.to-pdf", multi: true),143 path(.tiff, .heic, "image", fidelity: .lossy),144 ])145146 @Test func recommendedTargetsFollowTheDocumentedScore() {147 let caps = ConversionCapabilityResolver(registry: registry([engine])).capabilities(for: .png)148 // Same category (+100) and position in the image list: jpeg (55), webp (45), tiff (40), gif (25); then pdf, txt.149 #expect(caps.targets.map(\.destination) == [.jpeg, .tiff, .webp, .gif, .pdf, .txt])150 #expect(caps.recommended.map(\.destination) == [.jpeg, .tiff, .webp, .gif])151 #expect(caps.operations.map(\.operation) == ["image.to-pdf"])152 #expect(caps.isSupported)153 }154155 @Test func scoreComponents() {156 let lossy = path(.png, .jpeg, "e", fidelity: .lossy)157 #expect(ConversionCapabilityResolver.score(lossy, sourceCategory: .image) == 100 + 55 + 10 + 2)158 let experimental = path(.png, .jpeg, "e", status: .experimental, fidelity: .lossy)159 #expect(ConversionCapabilityResolver.score(experimental, sourceCategory: .image) == 100 + 55 + 2)160 let crossCategory = path(.png, .pdf, "e", fidelity: .structural)161 #expect(ConversionCapabilityResolver.score(crossCategory, sourceCategory: .image) == 35 + 10 + 3)162 let uncommon = path(.png, .txt, "e", fidelity: .partial)163 #expect(ConversionCapabilityResolver.score(uncommon, sourceCategory: .image) == 10 + 1)164 }165166 @Test func targetsExposeEngineAlternativesBestFirst() {167 let a = StubEngine(id: "a", paths: [path(.png, .jpeg, "a", status: .experimental, fidelity: .lossless)])168 let b = StubEngine(id: "b", paths: [path(.png, .jpeg, "b", fidelity: .lossy)])169 let c = StubEngine(id: "c", paths: [path(.png, .jpeg, "c", fidelity: .structural)])170 let target = ConversionCapabilityResolver(registry: registry([a, b, c])).capabilities(for: .png).targets[0]171 #expect(target.alternatives.map(\.engine) == ["c", "b", "a"])172 #expect(target.best.engine == "c")173 }174175 @Test func chainedDestinationsAreListedSeparately() {176 let caps = ConversionCapabilityResolver(registry: registry(perPath(engine))).capabilities(for: .png)177 #expect(caps.chainedDestinations == [.heic])178 }179180 @Test func unsupportedFormatHasNoTargets() {181 let caps = ConversionCapabilityResolver(registry: registry([engine])).capabilities(for: .mp3)182 #expect(!caps.isSupported && caps.targets.isEmpty && caps.recommended.isEmpty)183 }184}185186@Suite struct PlannerTests {187 @Test func directPathIsPreferredOverAChain() throws {188 let e = StubEngine(id: "e", paths: [path(.png, .jpeg, "e", fidelity: .lossy), path(.png, .tiff, "e"), path(.tiff, .jpeg, "e", fidelity: .lossy)])189 let plan = try ConversionPlanner(registry: registry([e])).plan(from: .png, to: .jpeg)190 #expect(plan.steps.count == 1 && !plan.isChained && plan.engines == ["e"])191 }192193 @Test func engineChoiceIsStatusThenFidelity() throws {194 let a = StubEngine(id: "a", paths: [path(.png, .jpeg, "a", status: .experimental, fidelity: .lossless)])195 let b = StubEngine(id: "b", paths: [path(.png, .jpeg, "b", fidelity: .lossy)])196 let c = StubEngine(id: "c", paths: [path(.png, .jpeg, "c", fidelity: .structural)])197 let planner = ConversionPlanner(registry: registry([a, b, c]))198 #expect(try planner.plan(from: .png, to: .jpeg).engines == ["c"])199 #expect(try planner.plan(from: .png, to: .jpeg, engine: "a").engines == ["a"])200 #expect(throws: ConversionError.unsupportedPath(source: .png, destination: .jpeg)) {201 try planner.plan(from: .png, to: .jpeg, engine: "zzz")202 }203 }204205 @Test func chainsThroughOneIntermediate() throws {206 let e = StubEngine(id: "e", paths: [207 path(.docx, .odt, "e", fidelity: .structural, preserves: [.textStyles, .images], limitations: ["Fonts may differ."]),208 path(.odt, .epub, "e", fidelity: .structural, preserves: [.images, .links], limitations: ["Page layout is not kept.", "Fonts may differ."]),209 ])210 let plan = try ConversionPlanner(registry: registry(perPath(e))).plan(from: .docx, to: .epub)211 #expect(plan.isChained && plan.intermediates == [.odt])212 #expect(plan.source == .docx && plan.destination == .epub)213 #expect(plan.limitations == ["Fonts may differ.", "Page layout is not kept."], "union without duplicates, in order")214 #expect(plan.preserves == [.images])215 }216217 @Test func chainedPlanCarriesTheWorstFidelityAndStatus() throws {218 let e = StubEngine(id: "e", paths: [path(.png, .tiff, "e", fidelity: .lossless), path(.tiff, .heic, "e", status: .experimental, fidelity: .lossy)])219 let plan = try ConversionPlanner(registry: registry(perPath(e))).plan(from: .png, to: .heic)220 #expect(plan.fidelity == .lossy && plan.status == .experimental)221 #expect(Fidelity.worst(.structural, .partial) == .partial && Fidelity.worst(.lossless, .lossless) == .lossless)222 }223224 @Test func neverChainsThroughALossyIntermediateWhenALosslessOneExists() throws {225 let e = StubEngine(id: "e", paths: [226 path(.png, .jpeg, "e", fidelity: .lossy), path(.jpeg, .avif, "e", fidelity: .lossless),227 path(.png, .tiff, "e", fidelity: .lossless), path(.tiff, .avif, "e", fidelity: .lossy),228 ])229 let planner = ConversionPlanner(registry: registry(perPath(e)))230 let chains = planner.chains(from: .png, to: .avif)231 #expect(chains.map(\.intermediates) == [[.tiff]], "the JPEG route is discarded, not merely ranked lower")232 #expect(try planner.plan(from: .png, to: .avif).intermediates == [.tiff])233 }234235 @Test func usesALossyIntermediateOnlyWhenNothingElseExists() throws {236 let e = StubEngine(id: "e", paths: [path(.png, .jpeg, "e", fidelity: .lossy), path(.jpeg, .avif, "e", fidelity: .lossy)])237 let plan = try ConversionPlanner(registry: registry(perPath(e))).plan(from: .png, to: .avif)238 #expect(plan.intermediates == [.jpeg] && plan.fidelity == .lossy)239 }240241 @Test func cheapestChainWinsThenAlphabeticalIntermediate() throws {242 let e = StubEngine(id: "e", paths: [243 path(.csv, .json, "e", fidelity: .structural), path(.json, .parquet, "e", fidelity: .structural), // cost 2244 path(.csv, .arrow, "e", fidelity: .lossless), path(.arrow, .parquet, "e", fidelity: .lossless), // cost 0245 path(.csv, .tsv, "e", fidelity: .lossless), path(.tsv, .parquet, "e", fidelity: .lossless), // cost 0246 ])247 let chains = ConversionPlanner(registry: registry(perPath(e))).chains(from: .csv, to: .parquet)248 #expect(chains.map(\.intermediates) == [[.arrow], [.tsv], [.json]])249 #expect(ConversionPlanner.stepCost(path(.a, .b, "e", status: .experimental, fidelity: .partial)) == 10)250 }251252 @Test func neverChainsAcrossOrThroughOperations() {253 let e = StubEngine(id: "e", paths: [254 path(.pdf, .png, "e", op: "pdf.render"), path(.png, .jpeg, "e", fidelity: .lossy),255 path(.docx, .pdf, "e", fidelity: .structural), path(.pdf, .pdf, "e", op: "pdf.compress"),256 ])257 let planner = ConversionPlanner(registry: registry(perPath(e)))258 #expect(throws: ConversionError.self) { try planner.plan(from: .pdf, to: .jpeg) }259 #expect(throws: ConversionError.self) { try planner.plan(from: .docx, to: .pdf, operation: "pdf.compress") }260 #expect(planner.chains(from: .pdf, to: .jpeg).isEmpty)261 }262263 @Test func neverChainsThroughFoldersMultiSourcePathsOrMoreThanTwoHops() {264 let e = StubEngine(id: "e", paths: [265 path(.zip, .folder, "e"), path(.folder, .tgz, "e"),266 path(.png, .pdf, "e", multi: true), path(.pdf, .docx, "e", fidelity: .structural),267 path(.a, .b, "e"), path(.b, .c, "e"), path(.c, .d, "e"),268 ])269 let planner = ConversionPlanner(registry: registry(perPath(e)))270 #expect(throws: ConversionError.self) { try planner.plan(from: .zip, to: .tgz) }271 #expect(throws: ConversionError.self) { try planner.plan(from: .png, to: .docx) }272 #expect(throws: ConversionError.self) { try planner.plan(from: .a, to: .d) }273 #expect((try? planner.plan(from: .a, to: .c)) != nil)274 }275276 @Test func chainingCanBeDisabledAndIsOffWhenAnEngineIsForced() {277 let e = StubEngine(id: "e", paths: [path(.png, .tiff, "e"), path(.tiff, .heic, "e", fidelity: .lossy)])278 let planner = ConversionPlanner(registry: registry(perPath(e)))279 #expect(throws: ConversionError.self) { try planner.plan(from: .png, to: .heic, allowChaining: false) }280 #expect(throws: ConversionError.self) { try planner.plan(from: .png, to: .heic, engine: "e") }281 }282283 @Test func missingComponentIsReportedAsSuch() {284 let office = StubEngine(id: "office", paths: [path(.docx, .pdf, "office", fidelity: .structural)], unavailableReason: "LibreOffice is not bundled.")285 let planner = ConversionPlanner(registry: registry([office]))286 #expect(throws: ConversionError.engineUnavailable("LibreOffice is not bundled.")) { try planner.plan(from: .docx, to: .pdf) }287 #expect(throws: ConversionError.unsupportedPath(source: .docx, destination: .png)) { try planner.plan(from: .docx, to: .png) }288 }289290 @Test func plansAreCodable() throws {291 let e = StubEngine(id: "e", paths: [path(.png, .tiff, "e"), path(.tiff, .heic, "e", fidelity: .lossy)])292 let plan = try ConversionPlanner(registry: registry(perPath(e))).plan(from: .png, to: .heic)293 let decoded = try JSONDecoder().decode(ConversionPlan.self, from: JSONEncoder().encode(plan))294 #expect(decoded == plan)295 }296}297298private extension FormatID {299 static let a: FormatID = "fmt-a", b: FormatID = "fmt-b", c: FormatID = "fmt-c", d: FormatID = "fmt-d"300}301