Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Camera9// File : Tests/LibraryEditorExportTests.swift10// Description : App-level tests of the library, editor session, export11// jobs and metadata rows, on real files in a temporary12// in-memory library.13// Module : Tests14// Repository : https://git.spboucher.ai/orix-camera15// Project Website : https://www.orixlab.dev16// Created : 2026-11-2117// Last Modified : 2026-11-2118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : Proprietary, all rights reserved (see license file)84// License File : LICENSE85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import CoreGraphics93import CoreImage94import Foundation95import ImageIO96import ORIXImaging97import Testing98import UniformTypeIdentifiers99@testable import ORIXCamera100101enum LibraryFixture {102 static func library() throws -> MediaLibrary {103 let root = FileManager.default.temporaryDirectory.appendingPathComponent("orix-app-tests-" + UUID().uuidString, isDirectory: true)104 return try MediaLibrary(storage: try CaptureStorage(root: root), inMemory: true)105 }106107 /// A JPEG rendered from the synthetic scene, optionally carrying EXIF and GPS, indexed in the library.108 @discardableResult109 static func addPhoto(_ library: MediaLibrary, base: String, kind: MediaKind = .photo, withMetadata: Bool = true, date: Date = Date(), time: Double = 1) throws -> MediaItem {110 let scene = try #require(SyntheticScene(width: 400, height: 300))111 let frame = try #require(scene.render(time: time))112 let image = try #require(PixelBuffers.cgImage(from: frame))113 let data = NSMutableData()114 let destination = try #require(CGImageDestinationCreateWithData(data, UTType.jpeg.identifier as CFString, 1, nil))115 var properties: [CFString: Any] = [kCGImageDestinationLossyCompressionQuality: 0.92]116 if withMetadata {117 properties[kCGImagePropertyTIFFDictionary] = [kCGImagePropertyTIFFMake: "ORIX", kCGImagePropertyTIFFModel: "Test camera"]118 properties[kCGImagePropertyExifDictionary] = [kCGImagePropertyExifISOSpeedRatings: [125], kCGImagePropertyExifExposureTime: 1.0 / 250, kCGImagePropertyExifFNumber: 1.8,119 kCGImagePropertyExifLensModel: "Test lens"] as [CFString: Any]120 properties[kCGImagePropertyGPSDictionary] = [kCGImagePropertyGPSLatitude: 46.8139, kCGImagePropertyGPSLatitudeRef: "N", kCGImagePropertyGPSLongitude: 71.2082,121 kCGImagePropertyGPSLongitudeRef: "W"] as [CFString: Any]122 }123 CGImageDestinationAddImage(destination, image, properties as CFDictionary)124 #expect(CGImageDestinationFinalize(destination))125 let name = try library.storage.write(data as Data, base: base, ext: "jpg")126 library.storage.makeImageThumbnail(for: name)127 return library.add(MediaItem(createdAt: date, kind: kind, fileName: name, pixelWidth: 400, pixelHeight: 300, captureSummary: "wide 1× · ISO 125 · 1/250"))128 }129130 static func exportDirectory() -> URL {131 FileManager.default.temporaryDirectory.appendingPathComponent("orix-app-exports-" + UUID().uuidString, isDirectory: true)132 }133134 static func pixels(_ url: URL) throws -> (image: CGImage, bytes: [UInt8]) {135 let source = try #require(CGImageSourceCreateWithURL(url as CFURL, nil))136 let image = try #require(CGImageSourceCreateImageAtIndex(source, 0, nil))137 return (image, try #require(FloatImage.rgba8(image)))138 }139}140141@Suite struct EditorSessionTests {142 @Test func commitUndoRedoReset() {143 let session = EditorSession(recipe: nil)144 #expect(!session.hasChanges && !session.canUndo && session.isPristine)145 session.recipe.exposure = 0.4; session.recipe.exposure = 0.8 // a slider moving: no undo step yet146 #expect(!session.canUndo && session.hasChanges)147 session.commit()148 session.recipe.contrast = 0.3; session.commit()149 #expect(session.canUndo && !session.canRedo)150 session.undo()151 #expect(session.recipe.contrast == 0 && session.recipe.exposure == 0.8 && session.canRedo)152 session.undo()153 #expect(session.recipe.isIdentity && !session.canUndo)154 session.redo(); session.redo()155 #expect(session.recipe.contrast == 0.3)156 session.reset()157 #expect(session.isPristine && session.canUndo)158 session.undo()159 #expect(session.recipe.contrast == 0.3)160 }161162 @Test func openingAnEditedItemStartsFromItsRecipe() {163 var saved = EditRecipe(); saved.vignette = 0.5; saved.quarterTurns = 1164 let session = EditorSession(recipe: saved)165 #expect(session.recipe == saved && !session.hasChanges && !session.isPristine)166 session.reset()167 #expect(session.hasChanges && session.isPristine)168 }169170 @Test func presetsKeepGeometryAndRAWDevelopment() {171 let session = EditorSession(recipe: nil)172 session.sourceAspect = 4.0 / 3173 session.rotateClockwise()174 session.setCrop(CGRect(x: 0.1, y: 0.1, width: 0.5, height: 0.5)); session.commit()175 session.updateRAW { $0.exposure = 0.7 }; session.commit()176 let preset = EditPreset.all.first { $0.recipe.lookID != nil }!177 session.apply(preset)178 #expect(session.recipe.lookID == preset.recipe.lookID)179 #expect(session.recipe.quarterTurns == 1 && session.recipe.crop == CGRect(x: 0.1, y: 0.1, width: 0.5, height: 0.5) && session.recipe.raw?.exposure == 0.7)180 session.undo()181 #expect(session.recipe.lookID == nil && session.recipe.quarterTurns == 1)182 }183184 @Test func cropIsNormalizedAndFullFrameMeansNoCrop() {185 let session = EditorSession(recipe: nil)186 session.setCrop(CGRect(x: -0.3, y: 0.2, width: 0.6, height: 2))187 let crop = session.recipe.crop188 #expect(crop?.minX == 0 && crop?.maxY ?? 2 <= 1 && crop?.width == 0.6)189 session.setCrop(CGRect(x: 0, y: 0, width: 1, height: 1))190 #expect(session.recipe.crop == nil && session.cropRect == CropMath.unit)191 session.updateRAW { _ in }192 #expect(session.recipe.raw == nil)193 }194195 @Test func aspectPresetsFollowTheImageOrientation() {196 let session = EditorSession(recipe: nil)197 session.sourceAspect = 4.0 / 3198 session.setAspect(.square)199 let square = session.cropRect200 #expect(abs(Double(square.width / square.height) * session.imageAspect - 1) < 1e-9)201 session.rotateClockwise() // now a portrait picture202 #expect(abs(session.imageAspect - 0.75) < 1e-9)203 session.setAspect(.r16x9)204 let tall = session.cropRect205 #expect(abs(Double(tall.width / tall.height) * session.imageAspect - 9.0 / 16) < 1e-9)206 session.setAspect(.original)207 #expect(session.recipe.crop == nil)208 session.resetGeometry()209 #expect(!session.recipe.hasGeometry && session.cropAspect == .free)210 }211212 /// Rotation and flip must carry the crop rectangle with the picture: the cropped content stays the same.213 @Test func rotateAndFlipCarryTheCropWithThePicture() throws {214 // A marker image: red block at the top-left, green block at the bottom-right.215 let buffer = try #require(PixelBuffers.makeBGRA(width: 120, height: 80))216 PixelBuffers.fill(buffer) { x, y in (x < 30 && y < 20) ? (255, 0, 0) : ((x >= 90 && y >= 60) ? (0, 255, 0) : (30, 30, 30)) }217 let marker = try #require(PixelBuffers.cgImage(from: buffer))218 let source = CIImage(cgImage: marker)219 func redAndGreen(_ recipe: EditRecipe) throws -> (red: Int, green: Int) {220 let image = try #require(EditPipeline.render(recipe: recipe, source: source))221 let bytes = try #require(FloatImage.rgba8(image))222 var red = 0, green = 0223 for i in 0..<(image.width * image.height) {224 if bytes[i * 4] > 200 && bytes[i * 4 + 1] < 60 { red += 1 }225 if bytes[i * 4 + 1] > 200 && bytes[i * 4] < 60 { green += 1 }226 }227 return (red, green)228 }229 let session = EditorSession(recipe: nil)230 session.sourceAspect = 1.5231 session.setCrop(CGRect(x: 0, y: 0, width: 0.5, height: 0.5)); session.commit() // keeps the red block only232 let start = try redAndGreen(session.recipe)233 #expect(start.red > 500 && start.green == 0)234 for _ in 0..<4 {235 session.rotateClockwise()236 let turned = try redAndGreen(session.recipe)237 #expect(abs(turned.red - start.red) < 40 && turned.green == 0, "after \(session.recipe.quarterTurns) quarter turns")238 }239 session.flipHorizontally()240 let flipped = try redAndGreen(session.recipe)241 #expect(abs(flipped.red - start.red) < 40)242 session.rotateClockwise(); session.flipHorizontally() // flip on a rotated picture243 let mixed = try redAndGreen(session.recipe)244 #expect(abs(mixed.red - start.red) < 40 && mixed.green == 0)245 }246247 @Test func flipMirrorsTheDisplayedPictureAtAnyRotation() throws {248 let buffer = try #require(PixelBuffers.makeBGRA(width: 90, height: 60))249 PixelBuffers.fill(buffer) { x, y in (x < 20 && y < 15) ? (255, 0, 0) : (20, 20, 20) }250 let marker = try #require(PixelBuffers.cgImage(from: buffer))251 let source = CIImage(cgImage: marker)252 for turns in 0..<4 {253 let session = EditorSession(recipe: nil)254 for _ in 0..<turns { session.rotateClockwise() }255 let before = try #require(EditPipeline.render(recipe: session.recipe, source: source))256 session.flipHorizontally()257 let after = try #require(EditPipeline.render(recipe: session.recipe, source: source))258 #expect(before.width == after.width && before.height == after.height)259 let a = try #require(FloatImage.rgba8(before)), b = try #require(FloatImage.rgba8(after))260 var mismatches = 0261 for y in 0..<before.height { for x in 0..<before.width {262 let isRedBefore = a[(y * before.width + x) * 4] > 200, isRedAfter = b[(y * before.width + (before.width - 1 - x)) * 4] > 200263 if isRedBefore != isRedAfter { mismatches += 1 }264 } }265 #expect(mismatches < 12, "\(turns) quarter turns: \(mismatches) pixels differ from a left-right mirror")266 }267 }268}269270@Suite struct ExportFlowTests {271 @Test(arguments: ExportImageFormat.allCases) func everyFormatProducesARealFile(format: ExportImageFormat) async throws {272 let library = try LibraryFixture.library()273 let item = try LibraryFixture.addPhoto(library, base: "A")274 var settings = ExportSettings(); settings.imageFormat = format; settings.fileName = "shot"275 let urls = try await MediaExport.run([item.snapshot(storage: library.storage)], settings: settings, directory: LibraryFixture.exportDirectory())276 #expect(urls.count == 1 && urls[0].lastPathComponent == "shot.\(format.fileExtension)")277 let meta = try #require(MetadataInspector.readImage(url: urls[0]))278 #expect(meta.typeIdentifier == format.type.identifier && meta.pixelWidth == 400 && meta.pixelHeight == 300)279 }280281 @Test func metadataPoliciesAreApplied() async throws {282 let library = try LibraryFixture.library()283 let snapshot = try LibraryFixture.addPhoto(library, base: "A").snapshot(storage: library.storage)284 func export(_ policy: MetadataPolicy) async throws -> MediaMetadata {285 var settings = ExportSettings(); settings.metadata = policy286 let url = try await MediaExport.run([snapshot], settings: settings, directory: LibraryFixture.exportDirectory())[0]287 return try #require(MetadataInspector.readImage(url: url))288 }289 #expect(ExportSettings().metadata == .removeLocation)290 let kept = try await export(.keepAll)291 #expect(kept.hasLocation && kept.iso == 125 && kept.cameraModel == "Test camera")292 let noLocation = try await export(.removeLocation)293 #expect(!noLocation.hasLocation && noLocation.iso == 125 && noLocation.lensModel == "Test lens")294 let bare = try await export(.removeAll)295 #expect(!bare.hasLocation && bare.iso == nil && bare.cameraModel == nil)296 }297298 @Test func originalExportIsByteIdenticalEvenWhenEdited() async throws {299 let library = try LibraryFixture.library()300 let item = try LibraryFixture.addPhoto(library, base: "A")301 var recipe = EditRecipe(); recipe.monochrome = true302 library.setRecipe(recipe, for: item)303 var settings = ExportSettings(); settings.imageFormat = nil304 let url = try await MediaExport.run([item.snapshot(storage: library.storage)], settings: settings, directory: LibraryFixture.exportDirectory())[0]305 #expect(try Data(contentsOf: url) == Data(contentsOf: library.storage.url(for: item.fileName)))306 #expect(url.pathExtension == "jpg")307 // And the original in the library is still the colour file: editing wrote nothing to it.308 let original = try LibraryFixture.pixels(library.storage.url(for: item.fileName))309 #expect(abs(Int(original.bytes[0]) - Int(original.bytes[2])) > 5 || abs(Int(original.bytes[4000]) - Int(original.bytes[4002])) > 5)310 }311312 @Test func renderedExportsApplyTheRecipeAndTheSizeLimit() async throws {313 let library = try LibraryFixture.library()314 let item = try LibraryFixture.addPhoto(library, base: "A")315 var recipe = EditRecipe(); recipe.monochrome = true; recipe.quarterTurns = 1; recipe.crop = CGRect(x: 0, y: 0, width: 1, height: 0.5)316 library.setRecipe(recipe, for: item)317 var settings = ExportSettings(); settings.imageFormat = .png; settings.size = .hd318 let url = try await MediaExport.run([item.snapshot(storage: library.storage)], settings: settings, directory: LibraryFixture.exportDirectory())[0]319 let result = try LibraryFixture.pixels(url)320 // 400×300 rotated = 300×400, top half = 300×200 (under the 1080 limit, so not resized).321 #expect(result.image.width == 300 && result.image.height == 200)322 for i in stride(from: 0, to: result.bytes.count, by: 4 * 97) { #expect(abs(Int(result.bytes[i]) - Int(result.bytes[i + 1])) <= 2 && abs(Int(result.bytes[i + 1]) - Int(result.bytes[i + 2])) <= 2) }323 settings.size = .original; settings.imageFormat = .jpeg324 var small = settings; small.size = .hd325 let scene = try #require(SyntheticScene(width: 2400, height: 1600))326 let bigFrame = try #require(scene.render(time: 0))327 let big = try #require(PixelBuffers.cgImage(from: bigFrame))328 var options = ImageExportOptions(); options.fileName = "big"329 let temp = try ImageExporter.export(big, options: options, to: library.storage.incomingDirectory)330 let bigItem = library.add(MediaItem(kind: .photo, fileName: try library.storage.adopt(temp, base: "BIG"), pixelWidth: 2400, pixelHeight: 1600))331 let limited = try await MediaExport.run([bigItem.snapshot(storage: library.storage)], settings: small, directory: LibraryFixture.exportDirectory())[0]332 let meta = try #require(MetadataInspector.readImage(url: limited))333 #expect(meta.pixelWidth == 1080 && meta.pixelHeight == 720)334 }335336 @Test func multipleItemsKeepTheirOwnNamesAndReportProgress() async throws {337 let library = try LibraryFixture.library()338 let a = try LibraryFixture.addPhoto(library, base: "ORIX_A"), b = try LibraryFixture.addPhoto(library, base: "ORIX_B", time: 3)339 var settings = ExportSettings(); settings.fileName = "ignored"; settings.imageFormat = .heic; settings.colorSpace = .displayP3340 let counter = ProgressCounter()341 let urls = try await MediaExport.run([a, b].map { $0.snapshot(storage: library.storage) }, settings: settings, directory: LibraryFixture.exportDirectory()) { counter.record($0) }342 #expect(urls.map(\.lastPathComponent) == ["ORIX_A.heic", "ORIX_B.heic"])343 #expect(counter.values == [1, 2])344 #expect(MetadataInspector.readImage(url: urls[0])?.colorProfile?.contains("P3") == true)345 }346347 @Test func aMissingFileFailsWithAReadErrorInsteadOfAnEmptyExport() async throws {348 let library = try LibraryFixture.library()349 let item = try LibraryFixture.addPhoto(library, base: "A")350 let snapshot = item.snapshot(storage: library.storage)351 try FileManager.default.removeItem(at: snapshot.url)352 await #expect(throws: ExportError.cannotRead) { _ = try await MediaExport.run([snapshot], settings: ExportSettings(), directory: LibraryFixture.exportDirectory()) }353 }354355 @Test func metadataReportIsValidJSONOfTheFile() throws {356 let library = try LibraryFixture.library()357 let item = try LibraryFixture.addPhoto(library, base: "A")358 let metadata = try #require(MetadataInspector.readImage(url: library.storage.url(for: item.fileName)))359 let url = try MediaExport.metadataReport(metadata, name: "A", directory: LibraryFixture.exportDirectory())360 let json = try JSONSerialization.jsonObject(with: Data(contentsOf: url))361 let object = try #require(json as? [String: Any])362 #expect(url.lastPathComponent == "A-metadata.json" && object["iso"] as? Double == 125 && object["cameraModel"] as? String == "Test camera")363 }364}365366nonisolated final class ProgressCounter: @unchecked Sendable {367 private let lock = NSLock()368 private var recorded: [Int] = []369 func record(_ value: Int) { lock.lock(); recorded.append(value); lock.unlock() }370 var values: [Int] { lock.lock(); defer { lock.unlock() }; return recorded }371}372373@Suite struct MetadataRowTests {374 @Test func onlyPresentFieldsBecomeRows() throws {375 let library = try LibraryFixture.library()376 let rich = try LibraryFixture.addPhoto(library, base: "RICH").snapshot(storage: library.storage)377 let bare = try LibraryFixture.addPhoto(library, base: "BARE", withMetadata: false).snapshot(storage: library.storage)378 let richSections = MetadataRows.sections(item: rich, metadata: MetadataInspector.readImage(url: rich.url))379 let bareSections = MetadataRows.sections(item: bare, metadata: MetadataInspector.readImage(url: bare.url))380 func labels(_ sections: [MetadataSection]) -> Set<String> { Set(sections.flatMap { $0.rows.map(\.label) }) }381 #expect(labels(richSections).isSuperset(of: ["ISO", "Exposure time", "Aperture", "Lens", "Model", "Latitude", "Longitude", "Dimensions", "File size"]))382 #expect(labels(bareSections).isDisjoint(with: ["ISO", "Exposure time", "Aperture", "Lens", "Model", "Latitude", "Longitude", "Altitude", "Duration", "Codec"]))383 #expect(labels(bareSections).isSuperset(of: ["Kind", "Dimensions", "File size", "Capture settings"]))384 #expect(richSections.contains { $0.title == "Location" } && !bareSections.contains { $0.title == "Location" })385 #expect(!richSections.contains { $0.rows.isEmpty })386 let iso = richSections.flatMap(\.rows).first { $0.label == "ISO" }387 #expect(iso?.value == "125")388 // No file at all: only what the library knows.389 let none = MetadataRows.sections(item: rich, metadata: nil)390 #expect(none.count == 1 && none[0].title == "Capture")391 }392393 @Test func editsAndSyntheticSourcesAreStated() throws {394 let library = try LibraryFixture.library()395 let item = try LibraryFixture.addPhoto(library, base: "A")396 item.isSynthetic = true397 var recipe = EditRecipe(); recipe.exposure = 0.3398 library.setRecipe(recipe, for: item)399 let labels = MetadataRows.sections(item: item.snapshot(storage: library.storage), metadata: nil).flatMap { $0.rows.map(\.label) }400 #expect(labels.contains("Edits") && labels.contains("Source"))401 }402}403404@Suite struct LibraryModelTests {405 @Test func filterSearchSelectionAndDelete() throws {406 let library = try LibraryFixture.library()407 let t = Date(timeIntervalSince1970: 1_800_000_000)408 let a = try LibraryFixture.addPhoto(library, base: "A", date: t)409 let b = try LibraryFixture.addPhoto(library, base: "B", kind: .lightTrails, date: t.addingTimeInterval(60))410 let c = try LibraryFixture.addPhoto(library, base: "C", date: t.addingTimeInterval(120))411 let model = LibraryModel(library: library)412 #expect(model.items.map(\.id) == [c.id, b.id, a.id] && model.totalCount == 3 && model.totalBytes > 0)413 model.filter = .computational414 #expect(model.items.map(\.id) == [b.id])415 model.filter = .all; model.search = "trails"416 #expect(model.items.map(\.id) == [b.id])417 model.search = ""; model.sort = .oldest418 #expect(model.items.first?.id == a.id)419 model.isSelecting = true420 model.toggleSelection(a); model.toggleSelection(b); model.toggleSelection(a); model.toggleSelection(c)421 #expect(Set(model.selectedItems.map(\.id)) == [b.id, c.id])422 model.toggleFavoriteForSelection()423 #expect(b.isFavorite && c.isFavorite && !a.isFavorite)424 model.toggleFavoriteForSelection()425 #expect(!b.isFavorite && !c.isFavorite)426 let doomedFile = library.storage.url(for: b.fileName)427 model.delete(model.selectedItems)428 #expect(model.items.map(\.id) == [a.id] && model.selection.isEmpty && !FileManager.default.fileExists(atPath: doomedFile.path))429 model.isSelecting = false430 #expect(model.selection.isEmpty)431 }432433 @Test func albumsGroupWithoutOwningItems() throws {434 let library = try LibraryFixture.library()435 let a = try LibraryFixture.addPhoto(library, base: "A"), b = try LibraryFixture.addPhoto(library, base: "B")436 let model = LibraryModel(library: library)437 #expect(model.createAlbum(named: " ") == nil)438 let album = try #require(model.createAlbum(named: "Trip"))439 model.add([a, b], to: album)440 model.album = album441 #expect(model.items.count == 2 && model.albums.map(\.name) == ["Trip"])442 model.remove([a], from: album)443 #expect(model.items.map(\.id) == [b.id])444 model.delete(album)445 #expect(model.album == nil && model.albums.isEmpty && model.items.count == 2 && library.storage.exists(a.fileName))446 }447448 @Test func missingFilesAreReportedAndForgottenOnlyOnRequest() throws {449 let library = try LibraryFixture.library()450 let a = try LibraryFixture.addPhoto(library, base: "A")451 _ = try LibraryFixture.addPhoto(library, base: "B")452 try FileManager.default.removeItem(at: library.storage.url(for: a.fileName))453 let model = LibraryModel(library: library)454 #expect(model.missing.map(\.id) == [a.id] && model.totalCount == 2)455 model.forgetMissing()456 #expect(model.missing.isEmpty && model.totalCount == 1)457 }458459 @Test func thumbnailsReflectTheRecipeAndTheCacheKeyChangesWithIt() async throws {460 let library = try LibraryFixture.library()461 let item = try LibraryFixture.addPhoto(library, base: "A")462 let plain = item.snapshot(storage: library.storage)463 var recipe = EditRecipe(); recipe.monochrome = true464 library.setRecipe(recipe, for: item)465 let edited = item.snapshot(storage: library.storage)466 #expect(ThumbnailCache.key(plain) != ThumbnailCache.key(edited))467 let cache = ThumbnailCache()468 let plainImage = await cache.image(for: plain), editedImage = await cache.image(for: edited)469 let colour = try #require(plainImage?.cgImage), mono = try #require(editedImage?.cgImage)470 func spread(_ image: CGImage) -> Int {471 let bytes = FloatImage.rgba8(image)!472 var total = 0473 for i in stride(from: 0, to: bytes.count, by: 4) { total += Int(max(bytes[i], bytes[i + 1], bytes[i + 2])) - Int(min(bytes[i], bytes[i + 1], bytes[i + 2])) }474 return total / (bytes.count / 4)475 }476 #expect(spread(colour) > 10 && spread(mono) <= 2)477 #expect(cache.cached(edited) != nil)478 }479480 @Test func viewerRenderAppliesTheRecipeGeometry() throws {481 let library = try LibraryFixture.library()482 let item = try LibraryFixture.addPhoto(library, base: "A")483 var recipe = EditRecipe(); recipe.quarterTurns = 1484 library.setRecipe(recipe, for: item)485 let image = try #require(MediaRenderer.rendered(item.snapshot(storage: library.storage), maxDimension: 200))486 #expect(image.width == 150 && image.height == 200)487 #expect(MediaRenderer.rendered(ItemSnapshot(id: UUID(), kind: .video, url: URL(fileURLWithPath: "/nope.mov"), companionURL: nil, thumbnailURL: URL(fileURLWithPath: "/nope.jpg"),488 fileName: "nope.mov", recipe: nil, title: "", captureSummary: "", createdAt: Date(), pixelWidth: 0, pixelHeight: 0, duration: 0, byteSize: 0, isSynthetic: false),489 maxDimension: 100) == nil)490 }491}492