SPB Git

Repository Public License

SafetyTests.swift 24.9 KB 354 lines swift

1// ORIX Convert — Packages/EngineImage/Tests/EngineImageTests/SafetyTests.swift2// Description: Untrusted input (truncated, malformed, absurd headers), pixel limits, cancellation, concurrency,3//              preflight, validation of tampered output, the own codecs and the Quality Lab API.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import ConvertCore6import CoreGraphics7import Foundation8import ImageIO9import Testing10@testable import EngineImage1112@Suite("Untrusted input and limits")13struct SafetyTests {14    @Test("Truncated files are refused with a clear error", arguments: [FormatID.png, .jpeg, .gif, .tiff, .webp, .bmp, .heic, .avif, .ppm, .pgm, .pbm, .exr, .hdr, .tga, .psd, .jp2, .apng, .icns, .dng])15    func truncated(format: FormatID) async throws {16        let data = try Data(contentsOf: try await Fixtures.url(for: format))17        for fraction in [0.5, 0.15] {18            let cut = try Fixtures.write(data.prefix(Int(Double(data.count) * fraction)), name: "cut.\(format.rawValue)")19            do {20                let run = try await convert(cut, from: format, to: .png)21                Issue.record("\(format) truncated to \(Int(fraction * 100)) % was converted (\(run.output.facts["width"] ?? "?")×\(run.output.facts["height"] ?? "?")) instead of being refused")22            } catch let error as ConversionError {23                switch error {24                case .malformedInput, .unreadableInput: break25                default: Issue.record("unexpected error for truncated \(format): \(error)")26                }27                #expect(error.errorDescription?.isEmpty == false)28            }29        }30    }3132    @Test("Garbage, empty and mislabelled files do not crash")33    func garbage() async throws {34        var noise = Data(count: 4096)35        var state: UInt32 = 736        for i in 0..<noise.count { state = state &* 1664525 &+ 1013904223; noise[i] = UInt8(state >> 24) }37        let cases: [(String, Data)] = [("noise.png", noise), ("empty.jpg", Data()), ("text.gif", Data("this is not an image".utf8)),38                                       ("header-only.png", Data([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])),39                                       ("bad.ppm", Data("P6\n-5 10\n255\n".utf8)), ("bad2.ppm", Data("P6\n10 10\n70000\n".utf8)), ("bad3.pgm", Data("P2\n4 4\n255\n1 2 3".utf8)),40                                       ("riff.webp", Data("RIFF\u{10}\u{0}\u{0}\u{0}WEBPVP8 ".utf8))]41        for (name, data) in cases {42            let url = try Fixtures.write(data, name: name)43            await #expect(throws: ConversionError.self, "\(name)") { _ = try await convert(url, from: .png, to: .jpeg) }44            await #expect(throws: ConversionError.self, "\(name)") { _ = try await engine.inspect(url, format: .png) }45        }46        let missing = Fixtures.directory.appendingPathComponent("does-not-exist.png")47        await #expect(throws: ConversionError.self) { _ = try await convert(missing, from: .png, to: .jpeg) }48        // A real JPEG named .png is converted from what it really is.49        let jpeg = try Data(contentsOf: try await Fixtures.url(for: .jpeg))50        let mislabelled = try Fixtures.write(jpeg, name: "really-a-jpeg.png")51        let run = try await convert(mislabelled, from: .png, to: .bmp)52        #expect(run.failedChecks.isEmpty && run.inspection.fields.contains { $0.key == "Type identifier" && $0.value == "public.jpeg" })53    }5455    @Test("Headers declaring giant images are refused before any pixel is allocated")56    func giantHeaders() async throws {57        // PNG whose IHDR declares 60000 × 60000 (3.6 gigapixels) followed by almost no data.58        func chunk(_ type: String, _ payload: [UInt8]) -> [UInt8] {59            let body = Array(type.utf8) + payload60            let crc = crc32Checksum(body)61            let length = UInt32(payload.count)62            return [UInt8(length >> 24), UInt8((length >> 16) & 255), UInt8((length >> 8) & 255), UInt8(length & 255)] + body63                + [UInt8(crc >> 24), UInt8((crc >> 16) & 255), UInt8((crc >> 8) & 255), UInt8(crc & 255)]64        }65        let dimension: [UInt8] = [0x00, 0x00, 0xEA, 0x60]66        let bomb = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] + chunk("IHDR", dimension + dimension + [8, 6, 0, 0, 0])67            + chunk("IDAT", [0x78, 0x9C, 0x63, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01]) + chunk("IEND", [])68        let png = try Fixtures.write(Data(bomb), name: "bomb.png")69        let started = Date()70        do {71            _ = try await convert(png, from: .png, to: .jpeg)72            Issue.record("the 3.6-gigapixel PNG was converted")73        } catch let error as ConversionError {74            guard case .limitExceeded = error else { Issue.record("expected limitExceeded, got \(error)"); return }75        }76        let pnm = try Fixtures.write(Data("P6\n100000 100000\n255\n".utf8) + Data(count: 64), name: "bomb.ppm")77        do { _ = try await convert(pnm, from: .ppm, to: .png); Issue.record("the 10-gigapixel PPM was converted") } catch let error as ConversionError {78            guard case .limitExceeded = error else { Issue.record("expected limitExceeded, got \(error)"); return }79        }80        // Within the limit but with less data than declared: the length is not trusted.81        let short = try Fixtures.write(Data("P6\n4000 4000\n255\n".utf8) + Data(count: 1000), name: "short.ppm")82        do { _ = try await convert(short, from: .ppm, to: .png); Issue.record("truncated PPM converted") } catch let error as ConversionError {83            guard case .malformedInput = error else { Issue.record("expected malformedInput, got \(error)"); return }84        }85        #expect(Date().timeIntervalSince(started) < 5)86        await #expect(throws: ConversionError.self) { _ = try await engine.inspect(png, format: .png) }87        var declared = FileInspection(format: .png)88        declared.pixelWidth = 60000; declared.pixelHeight = 6000089        #expect(engine.preflight(ConversionRequest(source: png, sourceFormat: .png, destinationFormat: .jpeg), inspection: declared).contains { $0.code == "pixel-limit" })90    }9192    @Test("The pixel limit is enforced, and a subsampled decode serves smaller outputs of oversized sources")93    func pixelLimit() async throws {94        let smooth = Synth.image(4000, 3000) { x, y in (Double(x) / 3999, Double(y) / 2999, 0.5 + 0.5 * sin(Double(x + y) / 400), 1) }95        let source = try await makeFile("big.jpg") { try Synth.encode("public.jpeg", [smooth], properties: [kCGImageDestinationLossyCompressionQuality: 0.8]) }96        do { _ = try await convert(source, from: .jpeg, to: .png, ["limit.megapixels": .int(2)]); Issue.record("12 MP converted under a 2 MP limit") } catch let error as ConversionError {97            guard case .limitExceeded(let message) = error else { Issue.record("expected limitExceeded, got \(error)"); return }98            #expect(message.contains("12.0"))99        }100        let small = try await convert(source, from: .jpeg, to: .png, ["limit.megapixels": .int(2), "resize.mode": .string("long-edge"), "resize.long-edge": .int(500)])101        #expect(try small.image().width == 500 && small.image().height == 375)102        #expect(small.output.facts["decode.subsample"] == "1/4" && small.codes.contains("subsampled-decode") && small.failedChecks.isEmpty)103        // Under the limit and below the "very large" threshold, the full image is decoded (linear-light resize).104        let normal = try await convert(source, from: .jpeg, to: .png, ["resize.mode": .string("long-edge"), "resize.long-edge": .int(500)])105        #expect(normal.output.facts["decode.subsample"] == nil)106        // Both routes agree closely on a smooth picture.107        let agreement = try PixelCompare.compare(try small.image(), try normal.image())108        #expect((agreement.psnr ?? 99) > 35, "PSNR \(agreement.psnr ?? -1)")109        // Animations count every frame.110        let apng = try await Fixtures.url(for: .apng)       // 4 × 48 × 32 = 6144 pixels111        await #expect(throws: ConversionError.self) { _ = try await convert(apng, from: .apng, to: .gif, ["limit.megapixels": .int(1), "resize.mode": .string("percent"), "resize.percent": .double(3000)]) }112    }113114    @Test("Format dimension limits: WebP 16383 px is refused with advice, and accepted after a resize")115    func formatLimits() async throws {116        let wide = Synth.image(16400, 4)117        let source = try await makeFile("wide.png") { try Synth.encode("public.png", [wide]) }118        let inspection = try await engine.inspect(source, format: .png)119        let request = ConversionRequest(source: source, sourceFormat: .png, destinationFormat: .webp)120        #expect(engine.preflight(request, inspection: inspection).contains { $0.code == "dimension-limit" && $0.message.contains("16383") })121        do { _ = try await convert(source, from: .png, to: .webp); Issue.record("16400 px WebP written") } catch let error as ConversionError {122            guard case .limitExceeded = error else { Issue.record("expected limitExceeded, got \(error)"); return }123        }124        let resized = try await convert(source, from: .png, to: .webp, ["resize.mode": .string("long-edge"), "resize.long-edge": .int(4100)])125        #expect(resized.failedChecks.isEmpty && resized.output.facts["width"] == "4100")126        var synthetic = FileInspection(format: .png)127        synthetic.pixelWidth = 20000; synthetic.pixelHeight = 20000; synthetic.hasAlpha = true; synthetic.bitDepth = 16128        let codes = Set(engine.preflight(ConversionRequest(source: source, sourceFormat: .png, destinationFormat: .jpeg), inspection: synthetic).map(\.code))129        #expect(codes.isSuperset(of: ["alpha-flattened", "bit-depth-reduced"]))130        #expect(engine.preflight(ConversionRequest(source: source, sourceFormat: .png, destinationFormat: .ico), inspection: synthetic).contains { $0.code == "icon-resampled" })131        #expect(engine.preflight(ConversionRequest(source: source, sourceFormat: .png, destinationFormat: .gif), inspection: nil).contains { $0.code == "gif-palette" })132        let bad = ConversionRequest(source: source, sourceFormat: .png, destinationFormat: .jpeg, options: ConversionOptions(["quality": .int(500)]))133        #expect(engine.preflight(bad, inspection: synthetic).contains { $0.code == "invalid-option" })134    }135136    @Test("Cancellation stops a conversion, before it starts and while it runs")137    func cancellation() async throws {138        let frames = (0..<40).map { Synth.image(480, 360, alpha: true, seed: $0) }139        let source = try await makeFile("long.tiff") { try Synth.encode("public.tiff", frames) }140        let request = ConversionRequest(source: source, sourceFormat: .tiff, destinationFormat: .tiff,141                                        options: ConversionOptions(["resize.mode": .string("percent"), "resize.percent": .double(150), "resize.upscale": .bool(true)]))142        let work = try workDirectory()143        let early = Task { try await engine.convert(request, context: ConversionContext(workDirectory: work)) }144        early.cancel()145        await #expect(throws: CancellationError.self) { _ = try await early.value }146147        final class Counter: @unchecked Sendable { let lock = NSLock(); var n = 0; func bump() { lock.lock(); n += 1; lock.unlock() }; var value: Int { lock.lock(); defer { lock.unlock() }; return n } }148        let counter = Counter()149        let running = Task { try await engine.convert(request, context: ConversionContext(workDirectory: work, progress: { _ in counter.bump() })) }150        while counter.value < 4 { try await Task.sleep(nanoseconds: 2_000_000) }       // a few frames are done151        running.cancel()152        await #expect(throws: CancellationError.self) { _ = try await running.value }153        #expect(counter.value < 40)154        #expect((try FileManager.default.contentsOfDirectory(atPath: work.path)).isEmpty, "no partial output is left behind")155156        // libwebp is interrupted through its progress hook.157        let big = try PixelData(cgImage: Synth.noisy(1600, 1200))158        let flag = CancellationFlag()159        flag.cancel()160        #expect(throws: CancellationError.self) { _ = try WebPCodec.encodeStill(big, settings: WebPCodec.Settings(quality: 80, lossless: false, method: 6), flag: flag) }161    }162163    @Test("Many conversions run concurrently and each result is correct")164    func concurrency() async throws {165        let formats: [FormatID] = [.png, .jpeg, .heic, .webp, .tiff, .gif, .bmp, .avif]166        var sources: [FormatID: URL] = [:]167        for format in formats { sources[format] = try await Fixtures.url(for: format) }168        let jobs = (0..<48).map { (formats[$0 % formats.count], formats[($0 / formats.count + $0) % formats.count], 10 + $0 % 30) }169        let results = try await withThrowingTaskGroup(of: (Int, Int, Bool).self) { group -> [(Int, Int, Bool)] in170            for (from, to, edge) in jobs {171                let url = try #require(sources[from])172                group.addTask {173                    let run = try await convert(url, from: from, to: to, ["resize.mode": .string("long-edge"), "resize.long-edge": .int(edge)])174                    return (edge, max(Int(run.output.facts["width"] ?? "") ?? 0, Int(run.output.facts["height"] ?? "") ?? 0), run.failedChecks.isEmpty)175                }176            }177            var all: [(Int, Int, Bool)] = []178            for try await item in group { all.append(item) }179            return all180        }181        #expect(results.count == 48)182        for (asked, got, valid) in results { #expect(asked == got && valid) }183    }184185    @Test("Validation catches an output that is not what the conversion reported")186    func tamperedOutput() async throws {187        let source = try await Fixtures.url(for: .png)188        let request = ConversionRequest(source: source, sourceFormat: .png, destinationFormat: .png)189        let inspection = try await engine.inspect(source, format: .png)190        let work = try workDirectory()191        let output = try await engine.convert(request, context: ConversionContext(workDirectory: work))192        #expect(try await engine.validate(output, request: request, source: inspection).allSatisfy(\.passed))193        let url = try #require(output.files.first)194        #expect(url.deletingLastPathComponent().standardizedFileURL == work.standardizedFileURL)195        // Same size, one pixel changed: only the pixel digest can notice.196        var pixels = try PixelData(cgImage: try Synth.decode(url))197        pixels.bytes[40] ^= 0x01198        try Synth.encode("public.png", [try pixels.makeCGImage()]).write(to: url)199        let subtle = try await engine.validate(output, request: request, source: inspection)200        #expect(subtle.contains { $0.name == "pixels" && !$0.passed } && subtle.contains { $0.name == "dimensions" && $0.passed })201        try Synth.encode("public.png", [Synth.image(10, 10)]).write(to: url)202        let wrongSize = try await engine.validate(output, request: request, source: inspection)203        #expect(wrongSize.contains { $0.name == "dimensions" && !$0.passed })204        try Data("not an image".utf8).write(to: url)205        let broken = try await engine.validate(output, request: request, source: inspection)206        #expect(broken.contains { $0.name == "decodes" && !$0.passed })207    }208209    @Test("Unsupported requests are refused: unknown path, svg, pdf")210    func unsupported() async throws {211        let source = try await Fixtures.url(for: .png)212        for (from, to) in [(FormatID.png, FormatID.pdf), (.svg, .png), (.png, .jxl), (.png, .dng), (.jxl, .png)] {213            await #expect(throws: ConversionError.self) {214                _ = try await engine.convert(ConversionRequest(source: source, sourceFormat: from, destinationFormat: to), context: ConversionContext(workDirectory: try workDirectory()))215            }216        }217        await #expect(throws: ConversionError.self) {218            _ = try await engine.convert(ConversionRequest(source: source, sourceFormat: .png, destinationFormat: .png, operation: "image.nonexistent"), context: ConversionContext(workDirectory: try workDirectory()))219        }220        #expect(engine.availability() == .available)221        #expect(makeEngines().count == 1 && makeEngines().first?.id == "image")222    }223224    @Test("Option descriptors are well formed and their defaults are accepted")225    func descriptors() throws {226        let pattern = try Regex("^[a-z0-9]+([.-][a-z0-9]+)*$")227        for path in engine.paths {228            let options = engine.options(for: path)229            #expect(!options.isEmpty)230            #expect(Set(options.map(\.id)).count == options.count, "\(path.id)")231            var defaults: [String: OptionValue] = [:]232            for option in options {233                #expect(option.id.wholeMatch(of: pattern) != nil, "\(option.id)")234                #expect(!option.label.isEmpty && !option.group.isEmpty)235                defaults[option.id] = option.defaultValue236            }237            let destination = try #require(ImageFormats.spec(path.destination))238            _ = try ImageSettings(options: ConversionOptions(defaults), destination: destination, operation: path.operation)239            #expect(options.contains { $0.id == "quality" } == destination.quality)240            #expect(options.contains { $0.id == "metadata" } == destination.metadata)241            #expect(!path.limitations.contains { $0.isEmpty })242        }243    }244245    @Test("A real Photoshop file shipped with macOS converts (skipped when absent)")246    func systemPSD() async throws {247        let candidates = ["/System/Library/Frameworks/MapKit.framework/Versions/A/Resources/DarkAquaMasks-Artwork/Controls/Push Button/PushButton_PushButton_Regular.psd",248                          "/System/Library/Frameworks/AddressBook.framework/Versions/A/Resources/ContactsAppearance-Artwork/Controls/Pop Up Button/PopUpButton_ArrowsOnly_Regular.psd"]249        guard let path = candidates.first(where: { FileManager.default.isReadableFile(atPath: $0) }) else { print("NOTE: no system PSD found; real-PSD test skipped"); return }250        let run = try await convert(URL(fileURLWithPath: path), from: .psd, to: .png)251        #expect(run.failedChecks.isEmpty)252        print("NOTE: real PSD \(URL(fileURLWithPath: path).lastPathComponent) → PNG \(run.output.facts["width"] ?? "?")×\(run.output.facts["height"] ?? "?"), \(run.output.facts["verify.pixels"] ?? "?")")253    }254}255256@Suite("Own codecs and Quality Lab API")257struct CodecTests {258    @Test("Netpbm: P1–P6 round-trip, 8 and 16 bit, comments and odd maximum values")259    func netpbm() throws {260        let colour8 = try PixelData(cgImage: Synth.image(37, 23))261        let colour16 = try PixelData(cgImage: Synth.image(37, 23, bits: 16))262        for (pixels, kinds) in [(colour8, [PNMCodec.Kind.pixmap, .graymap, .bitmap]), (colour16, [.pixmap, .graymap])] {263            for kind in kinds {264                for plain in [false, true] {265                    let encoded = try PNMCodec.encode(pixels, kind: kind, plain: plain, checkCancellation: {})266                    let header = try PNMCodec.parseHeader(encoded.data)267                    #expect(header.width == 37 && header.height == 23 && header.isPlain == plain)268                    let decoded = try PNMCodec.decode(encoded.data, maxPixels: 1 << 20, checkCancellation: {})269                    #expect(try PixelCompare.compare(try encoded.reference.makeCGImage(), decoded).identical, "kind \(kind) plain \(plain) depth \(pixels.depth)")270                    if kind == .pixmap { #expect(try PixelCompare.compare(try pixels.makeCGImage(), decoded).identical) }271                }272            }273        }274        let commented = Data("P2 # gray\n# another comment\n3 1 # size\n15\n0 7\n15\n".utf8)275        let image = try PNMCodec.decode(commented, maxPixels: 100, checkCancellation: {})276        #expect(try [0, 1, 2].map { try Synth.pixel(image, $0, 0)[0] } == [0, 119, 255])277        let packed = Data("P1\n4 2\n0110\n1 0 0 1\n".utf8)278        let bitmap = try PNMCodec.decode(packed, maxPixels: 100, checkCancellation: {})279        #expect(try (0..<4).map { try Synth.pixel(bitmap, $0, 0)[0] } == [255, 0, 0, 255])280        #expect(throws: ConversionError.self) { _ = try PNMCodec.decode(Data("P5\n10 10\n255\n".utf8) + Data(count: 99), maxPixels: 1000, checkCancellation: {}) }281        #expect(throws: ConversionError.self) { _ = try PNMCodec.decode(Data("P5\n10 10\n255\n".utf8) + Data(count: 100), maxPixels: 50, checkCancellation: {}) }282    }283284    @Test("Radiance RGBE writer: ImageIO reads back the values within the precision of the format")285    func radiance() throws {286        for (w, h) in [(64, 16), (5, 3), (300, 2)] {      // RLE scanlines, flat scanlines (width < 8), long runs287            let source = Synth.image(w, h, bits: 32, space: Synth.linear) { x, y in288                x % 50 < 25 ? (2.5, 0.5, 0.125, 1) : (8 * Double(x) / Double(w), 0.01 * Double(y + 1), 1.0 / 3, 1)289            }290            let data = try RadianceCodec.encode(try PixelData(cgImage: source, depth: .float), checkCancellation: {})291            let decoded = try Synth.decode(data)292            #expect(decoded.width == w && decoded.height == h)293            for (x, y) in [(0, 0), (w - 1, h - 1), (w / 2, h / 2), (min(w - 1, 30), 0)] {294                let a = try Synth.floatPixel(source, x, y), b = try Synth.floatPixel(decoded, x, y)295                let top = max(a[0], a[1], a[2])296                for c in 0..<3 { #expect(abs(a[c] - b[c]) <= top / 128, "(\(x),\(y)) channel \(c): \(a[c]) vs \(b[c])") }297            }298        }299    }300301    @Test("PNG recompression keeps the file valid and the pixels identical")302    func pngRecompress() throws {303        let image = Synth.image(300, 200, alpha: true)304        let png = try Synth.encode("public.png", [image])305        let smaller = try #require(PNGOptimizer.recompress(png) {})306        #expect(smaller.count < png.count)307        #expect(try PixelCompare.compare(image, try Synth.decode(smaller)).identical)308        #expect(PNGOptimizer.recompress(Data("not a png".utf8)) {} == nil)309        #expect(PNGOptimizer.recompress(png.prefix(png.count / 2)) {} == nil)310        let animated = try Synth.encode("public.png", Fixtures.animationFrames())311        #expect(PNGOptimizer.recompress(animated) {} == nil)       // animations are left alone312    }313314    @Test("Pixel comparison: identical, known PSNR, transparent-only differences, size mismatch")315    func comparison() throws {316        let a = Synth.solid(50, 40, 100.0 / 255, 100.0 / 255, 100.0 / 255)317        let b = Synth.solid(50, 40, 110.0 / 255, 110.0 / 255, 110.0 / 255)318        let same = try ImageComparison.compare(a, a)319        #expect(same.identical && same.psnr == nil && same.differingPixels == 0)320        let different = try ImageComparison.compare(a, b)321        #expect(!different.identical && different.differingPixels == 2000 && different.differingFraction == 1)322        #expect(abs((different.psnr ?? 0) - 28.1308) < 0.001)       // 10·log10(255² / 10²)323        #expect(abs(different.maxDifference - 10.0 / 255) < 1e-9)324        let clearRed = Synth.image(8, 8, alpha: true) { _, _ in (1, 0, 0, 0) }325        let clearBlue = Synth.image(8, 8, alpha: true) { _, _ in (0, 0, 1, 0) }326        let hidden = try ImageComparison.compare(clearRed, clearBlue, matchingColorSpaces: false)327        #expect(!hidden.identical && hidden.identicalWhereVisible)328        #expect(throws: ConversionError.self) { _ = try ImageComparison.compare(a, Synth.solid(51, 40, 0, 0, 0)) }329        // The same colour expressed in two colour spaces compares as equal once the spaces are matched.330        let srgbRed = Synth.solid(8, 8, 1, 0, 0), p3Red = Synth.solid(8, 8, 234.0 / 255, 51.0 / 255, 35.0 / 255, space: Synth.p3)331        #expect((try ImageComparison.compare(srgbRed, p3Red, matchingColorSpaces: true)).maxDifference < 0.01)332        #expect((try ImageComparison.compare(srgbRed, p3Red, matchingColorSpaces: false)).maxDifference > 0.1)333    }334335    @Test("Bounded previews for every readable fixture, upright and no larger than asked")336    func previews() async throws {337        for spec in ImageFormats.all where ImageFormats.isReadable(spec) && spec.id != .jxl {338            let url = try await Fixtures.url(for: spec.id)339            let preview = try await offPoolThrowing { try ImagePreview.decode(url: url, maxPixelSize: 40) }340            #expect(max(preview.width, preview.height) <= 40 && min(preview.width, preview.height) > 0, "\(spec.id)")341        }342        let rotated = try await makeFile("o6-preview.jpg") { try Synth.encode("public.jpeg", [Synth.image(600, 400)], properties: [kCGImagePropertyOrientation: 6]) }343        let preview = try await offPoolThrowing { try ImagePreview.decode(url: rotated, maxPixelSize: 300) }344        #expect(preview.width == 200 && preview.height == 300)345        let second = try await offPoolThrowing { try ImagePreview.decode(url: try Fixtures.write(try Fixtures.data(for: .apng), name: "p.apng"), maxPixelSize: 64, frame: 2) }346        #expect(second.width == 48)347        let source = try await Fixtures.url(for: .png)348        let jpeg = try await convert(source, from: .png, to: .jpeg, ["background.color": .string("#000000")])349        let difference = try await offPoolThrowing { try ImageComparison.compare(fileA: jpeg.url, fileB: jpeg.url) }350        #expect(difference.identical)351        #expect(throws: ConversionError.self) { _ = try ImagePreview.decode(url: URL(fileURLWithPath: "/nonexistent.png")) }352    }353}354
Files main
Menu

Theme