// The tiers a capture makes, proved against a GENERATED picture.//// Every fixture here is synthetic — a gradient with noise drawn into a// CGContext, and a two-frame film written by AVAssetWriter// ([nothing-real-ever-goes-in-cotton-s-public-tree]). Nothing in this tree is// ever a real photograph, and these cases would be worthless if it were: the// point is the SIZES and the ORDER, not what the picture is of.//// The other half of this is `writes_tests.rs` in `cotton-ffi`, which owns where// the renditions GO. This file owns whether they can be made at all.import AVFoundationimportCoreGraphicsimportFoundationimportImageIOimportUniformTypeIdentifiersimport XCTest@testable importCottonKitfinalclassMediaTiersTests: XCTestCase {// ── The fixtures ────────────────────────────────────────────────────────privatefunc temporaryRoot() throws -> URL {let root = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent("cotton-media-tiers-\(UUID().uuidString)")tryFileManager.default.createDirectory(at: root, withIntermediateDirectories: true) addTeardownBlock { try? FileManager.default.removeItem(at: root) }return root }/// A picture of nothing, at a size the test names.////// Deliberately BUSY — a gradient plus per-cell noise — because a flat/// colour compresses to almost nothing and would make every size assertion/// below pass for the wrong reason.privatefunc aPicture(_ width: Int, _ height: Int, in directory: URL) throws -> URL {let space = CGColorSpaceCreateDeviceRGB()guardlet context = CGContext( data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue )else {throw XCTSkip("this machine has no RGB bitmap context") }var generator = SystemRandomNumberGenerator()let cell = 4for y in stride(from: 0, to: height, by: cell) {for x in stride(from: 0, to: width, by: cell) { context.setFillColor( red: CGFloat(x) / CGFloat(width), green: CGFloat(y) / CGFloat(height), blue: CGFloat(UInt8.random(in: 0...255, using: &generator)) / 255, alpha: 1 ) context.fill(CGRect(x: x, y: y, width: cell, height: cell)) } }guardlet image = context.makeImage() else {throw XCTSkip("this machine could not make a CGImage") }let url = directory.appendingPathComponent("\(UUID().uuidString).png")guardlet destination = CGImageDestinationCreateWithURL( url as CFURL, UTType.png.identifier as CFString,1,nil )else {throw XCTSkip("this machine has no PNG encoder") } CGImageDestinationAddImage(destination, image, nil) XCTAssertTrue(CGImageDestinationFinalize(destination), "the fixture was not written")return url }/// Two frames of a film, written by AVAssetWriter.privatefunc aFilm(in directory: URL) asyncthrows -> URL {let url = directory.appendingPathComponent("\(UUID().uuidString).mov")let writer = try AVAssetWriter(outputURL: url, fileType: .mov)let input = AVAssetWriterInput( mediaType: .video, outputSettings: [ AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: 160, AVVideoHeightKey: 120, ] ) input.expectsMediaDataInRealTime = falselet adaptor = AVAssetWriterInputPixelBufferAdaptor( assetWriterInput: input, sourcePixelBufferAttributes: [ kCVPixelBufferPixelFormatTypeKey asString: kCVPixelFormatType_32ARGB ] ) writer.add(input) XCTAssertTrue(writer.startWriting(), "\(String(describing: writer.error))") writer.startSession(atSourceTime: .zero)for frame in0..<4 {var buffer: CVPixelBuffer?guardlet pool = adaptor.pixelBufferPool, CVPixelBufferPoolCreatePixelBuffer(nil, pool, &buffer) == kCVReturnSuccess,let bufferelse {throw XCTSkip("this machine has no pixel buffer pool") } CVPixelBufferLockBaseAddress(buffer, [])iflet base = CVPixelBufferGetBaseAddress(buffer) { memset(base, Int32(40 + frame * 50), CVPixelBufferGetDataSize(buffer)) } CVPixelBufferUnlockBaseAddress(buffer, [])while !input.isReadyForMoreMediaData {tryawaitTask.sleep(nanoseconds: 1_000_000) } XCTAssertTrue( adaptor.append( buffer, withPresentationTime: CMTime(value: CMTimeValue(frame), timescale: 10) ) ) } input.markAsFinished()await writer.finishWriting() XCTAssertEqual(writer.status, .completed, "\(String(describing: writer.error))")return url }// ── a_thumb_is_at_most_twenty_kilobytes ─────────────────────────────────// ── a_blur_is_at_most_a_kilobyte_of_base64 ──────────────────────────────// ── a_small_original_gets_no_display_rendition ──────────────────────────// ── a_film_gets_a_still_first ───────────────────────────────────────────// ── a_capture_still_lands_when_the_tiers_cannot_be_made ─────────────────func testACaptureStillLandsWhenTheTiersCannotBeMade() asyncthrows {let root = try temporaryRoot()let notAPicture = root.appendingPathComponent("broken.heic")tryData("this is not a picture".utf8).write(to: notAPicture)let tiers = awaitMediaTiers.make(for: notAPicture, film: false, in: root) XCTAssertTrue(tiers.isEmpty, "something was made out of bytes ImageIO cannot read")// AND THE CAPTURE GOES ANYWAY, carrying NOTHING rather than a path to a// file that was never written. The crate refuses a named path that is// not there — deliberately, because a caller that sent one believes it// did something — so the only honest way to say "I could not make this// one" is to send no key at all.let request = CaptureMediaRequest( path: notAPicture.path(percentEncoded: false), mime: "image/heic", kind: .photo, filename: "broken.heic", tiers: tiers )let encoded = try JSONEncoder().encode(request)let json = try XCTUnwrap( JSONSerialization.jsonObject(with: encoded) as? [String: Any] ) XCTAssertEqual(json["path"] as? String, notAPicture.path(percentEncoded: false)) XCTAssertEqual(json["kind"] as? String, "photo")for tier in ["thumbPath", "displayPath", "posterPath", "preview"] { XCTAssertNil(json[tier], "`\(tier)` was sent for a capture that made no renditions") } }}