SPB Git

Repository Public License

TestSupport.swift 13.4 KB 301 lines swift

1// ORIX Secure2// File: Packages/ORIXMediaCleanup/Tests/ORIXMediaCleanupTests/TestSupport.swift3// Description: Test helpers: seeded random numbers, programmatic images and their transformations, item factories and an4//              in-memory media library.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import CoreGraphics9import CoreText10import Foundation11import ImageIO12import ORIXSecureModel13import UniformTypeIdentifiers14@testable import ORIXMediaCleanup1516/// SplitMix64: small, fast, reproducible.17struct SeededGenerator: RandomNumberGenerator {18    var state: UInt641920    init(seed: UInt64) { state = seed &+ 0x9E37_79B9_7F4A_7C15 }2122    mutating func next() -> UInt64 {23        state &+= 0x9E37_79B9_7F4A_7C1524        var z = state25        z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B926        z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB27        return z ^ (z >> 31)28    }2930    mutating func unit() -> CGFloat { CGFloat(next() >> 11) / CGFloat(1 << 53) }31}3233enum TestImages {34    static func context(width: Int, height: Int) -> CGContext {35        CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4,36                  space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!37    }3839    /// A reproducible scene: gradient background, shapes, lines, a word and mild noise.40    static func scene(seed: UInt64, width: Int = 256, height: Int = 192) -> CGImage {41        var rng = SeededGenerator(seed: seed)42        let ctx = context(width: width, height: height)43        let w = CGFloat(width), h = CGFloat(height)44        func color(alpha: CGFloat = 1) -> CGColor {45            CGColor(srgbRed: rng.unit(), green: rng.unit(), blue: rng.unit(), alpha: alpha)46        }47        let gradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB)!, colors: [color(), color()] as CFArray, locations: [0, 1])!48        ctx.drawLinearGradient(gradient, start: CGPoint(x: rng.unit() * w, y: 0), end: CGPoint(x: rng.unit() * w, y: h), options: [.drawsBeforeStartLocation, .drawsAfterEndLocation])49        let shapes = 6 + Int(rng.next() % 5)50        for _ in 0..<shapes {51            let rect = CGRect(x: rng.unit() * w * 0.8, y: rng.unit() * h * 0.8, width: w * (0.12 + rng.unit() * 0.4), height: h * (0.12 + rng.unit() * 0.4))52            ctx.setFillColor(color(alpha: 0.75 + rng.unit() * 0.25))53            switch rng.next() % 3 {54            case 0: ctx.fill(rect)55            case 1: ctx.fillEllipse(in: rect)56            default:57                ctx.beginPath()58                ctx.move(to: CGPoint(x: rect.minX, y: rect.minY))59                ctx.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))60                ctx.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))61                ctx.closePath()62                ctx.fillPath()63            }64        }65        for _ in 0..<(2 + Int(rng.next() % 3)) {66            ctx.setStrokeColor(color())67            ctx.setLineWidth(3 + rng.unit() * 8)68            ctx.move(to: CGPoint(x: rng.unit() * w, y: rng.unit() * h))69            ctx.addLine(to: CGPoint(x: rng.unit() * w, y: rng.unit() * h))70            ctx.strokePath()71        }72        let letters = Array("ABCDEFGHKMNPRSTXYZ")73        var word = ""74        for _ in 0..<4 { word.append(letters[Int(rng.next() % UInt64(letters.count))]) }75        let font = CTFontCreateWithName("Helvetica-Bold" as CFString, h * (0.2 + rng.unit() * 0.15), nil)76        let attributes = [kCTFontAttributeName: font, kCTForegroundColorAttributeName: color()] as CFDictionary77        let line = CTLineCreateWithAttributedString(CFAttributedStringCreate(nil, word as CFString, attributes)!)78        ctx.textPosition = CGPoint(x: rng.unit() * w * 0.4, y: rng.unit() * h * 0.7)79        CTLineDraw(line, ctx)80        // Mild sensor-like noise.81        let data = ctx.data!.assumingMemoryBound(to: UInt8.self)82        for index in 0..<(width * height) {83            let delta = Int(rng.next() % 9) - 484            for channel in 0..<3 {85                let value = Int(data[index * 4 + channel]) + delta86                data[index * 4 + channel] = UInt8(max(0, min(255, value)))87            }88        }89        return ctx.makeImage()!90    }9192    /// Pure seeded noise.93    static func noise(seed: UInt64, side: Int = 128) -> CGImage {94        var rng = SeededGenerator(seed: seed)95        let ctx = context(width: side, height: side)96        let data = ctx.data!.assumingMemoryBound(to: UInt8.self)97        for index in 0..<(side * side * 4) { data[index] = UInt8(truncatingIfNeeded: rng.next()) }98        return ctx.makeImage()!99    }100101    static func jpeg(_ image: CGImage, quality: Double) -> CGImage {102        let data = NSMutableData()103        let destination = CGImageDestinationCreateWithData(data, UTType.jpeg.identifier as CFString, 1, nil)!104        CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)105        CGImageDestinationFinalize(destination)106        let source = CGImageSourceCreateWithData(data, nil)!107        return CGImageSourceCreateImageAtIndex(source, 0, nil)!108    }109110    static func resized(_ image: CGImage, scale: CGFloat) -> CGImage {111        let width = max(1, Int(CGFloat(image.width) * scale)), height = max(1, Int(CGFloat(image.height) * scale))112        let ctx = context(width: width, height: height)113        ctx.interpolationQuality = .high114        ctx.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))115        return ctx.makeImage()!116    }117118    /// Removes `fraction` of the width and height on every side.119    static func cropped(_ image: CGImage, fraction: CGFloat) -> CGImage {120        let dx = CGFloat(image.width) * fraction, dy = CGFloat(image.height) * fraction121        return image.cropping(to: CGRect(x: dx, y: dy, width: CGFloat(image.width) - 2 * dx, height: CGFloat(image.height) - 2 * dy).integral)!122    }123124    /// Moves the content by `fraction` of the width; the uncovered band is filled with gray.125    static func shifted(_ image: CGImage, fraction: CGFloat) -> CGImage {126        let ctx = context(width: image.width, height: image.height)127        ctx.setFillColor(gray: 0.5, alpha: 1)128        ctx.fill(CGRect(x: 0, y: 0, width: image.width, height: image.height))129        ctx.draw(image, in: CGRect(x: CGFloat(image.width) * fraction, y: 0, width: CGFloat(image.width), height: CGFloat(image.height)))130        return ctx.makeImage()!131    }132133    static func mapPixels(_ image: CGImage, _ transform: (inout UInt8, inout UInt8, inout UInt8) -> Void) -> CGImage {134        let ctx = context(width: image.width, height: image.height)135        ctx.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))136        let data = ctx.data!.assumingMemoryBound(to: UInt8.self)137        for index in 0..<(image.width * image.height) {138            transform(&data[index * 4], &data[index * 4 + 1], &data[index * 4 + 2])139        }140        return ctx.makeImage()!141    }142143    static func brightened(_ image: CGImage, by delta: Int) -> CGImage {144        mapPixels(image) { r, g, b in145            r = UInt8(max(0, min(255, Int(r) + delta)))146            g = UInt8(max(0, min(255, Int(g) + delta)))147            b = UInt8(max(0, min(255, Int(b) + delta)))148        }149    }150151    /// Same structure, other colours: red and blue exchanged.152    static func colorSwapped(_ image: CGImage) -> CGImage {153        mapPixels(image) { r, _, b in swap(&r, &b) }154    }155156    static func fingerprint(_ image: CGImage) -> ImageFingerprint {157        ImageFingerprinter.fingerprint(of: image)!158    }159}160161enum Fixture {162    static let epoch = Date(timeIntervalSinceReferenceDate: 800_000_000)163164    static func date(_ seconds: TimeInterval) -> Date { epoch.addingTimeInterval(seconds) }165166    static let plainSignature = [UInt8](repeating: 120, count: ImageFingerprint.colorSignatureLength)167168    static func fingerprint(d: UInt64, p: UInt64? = nil, luma: UInt8 = 120, signature: [UInt8]? = nil) -> ImageFingerprint {169        ImageFingerprint(dHash: d, pHash: p ?? d, meanLuma: luma, colorSignature: signature ?? plainSignature)170    }171172    /// `hash` with `count` bits flipped, chosen reproducibly.173    static func flipping(_ hash: UInt64, bits count: Int, seed: UInt64) -> UInt64 {174        var rng = SeededGenerator(seed: seed)175        var positions = Set<UInt64>()176        while positions.count < count { positions.insert(rng.next() % 64) }177        var output = hash178        for position in positions { output ^= 1 << position }179        return output180    }181182    static func photo(183        _ id: String, at seconds: TimeInterval?, fingerprint: ImageFingerprint? = nil, width: Int = 4032, height: Int = 3024,184        size: Int64? = nil, hash: String? = nil, favorite: Bool = false, edited: Bool = false, screenshot: Bool = false,185        burst: String? = nil, kind: MediaKind = .photo186    ) -> MediaItem {187        MediaItem(188            id: id, kind: kind, isScreenshot: screenshot, isBurstMember: burst != nil, burstIdentifier: burst,189            isFavorite: favorite, isEdited: edited, creationDate: seconds.map(date), pixelWidth: width, pixelHeight: height,190            duration: 0, fingerprint: fingerprint, byteSize: size.map { .measured($0) } ?? MediaItem.sizeNotMeasured, contentHash: hash)191    }192193    static func video(_ id: String, at seconds: TimeInterval, duration: TimeInterval, width: Int = 1920, height: Int = 1080, size: Int64? = nil) -> MediaItem {194        MediaItem(195            id: id, kind: .video, creationDate: date(seconds), pixelWidth: width, pixelHeight: height, duration: duration,196            byteSize: size.map { .measured($0) } ?? MediaItem.sizeNotMeasured)197    }198199    static func groupIDs(_ groups: [CleanupGroup]) -> [[String]] {200        groups.map { $0.items.map { $0.id }.sorted() }.sorted { $0.lexicographicallyPrecedes($1) }201    }202}203204/// An in-memory library whose behaviour at deletion time is scripted.205actor FakeMediaLibrary: MediaLibrary {206    enum DeleteBehavior: Sendable {207        case deleteAll208        /// Reports success but leaves these identifiers in place.209        case deletePartially(keeping: Set<String>)210        case userCancels211        case fails(String)212    }213214    struct FetchFailure: Error {}215216    var items: [String: MediaItem]217    var measurements: [String: MediaMeasurement]218    var access: MediaLibraryAccess219    var behavior: DeleteBehavior220    /// With limited access only these identifiers are visible.221    var visibleWhenLimited: Set<String>?222    var scanDelayPerItem: Duration?223    var failVerification = false224    private(set) var deleteRequests: [[String]] = []225    private(set) var measureRequests: [[String]] = []226    private var fetchCount = 0227228    init(items: [MediaItem], measurements: [String: MediaMeasurement] = [:], access: MediaLibraryAccess = .authorized, behavior: DeleteBehavior = .deleteAll) {229        var map: [String: MediaItem] = [:]230        for item in items { map[item.id] = item }231        self.items = map232        self.measurements = measurements233        self.access = access234        self.behavior = behavior235    }236237    func setAccess(_ value: MediaLibraryAccess, visible: Set<String>? = nil) {238        access = value239        visibleWhenLimited = visible240    }241242    func setBehavior(_ value: DeleteBehavior) { behavior = value }243    func setScanDelay(_ value: Duration?) { scanDelayPerItem = value }244    func setFailVerification(_ value: Bool) { failVerification = value }245246    private var visible: [String: MediaItem] {247        guard access == .limited, let allowed = visibleWhenLimited else { return items }248        return items.filter { allowed.contains($0.key) }249    }250251    func accessLevel() async -> MediaLibraryAccess { access }252253    func requestAccess() async -> MediaLibraryAccess { access }254255    func scan(progress: (@Sendable (ScanProgress) -> Void)?) async throws -> LibraryScan {256        guard access.canRead else { throw MediaLibraryError.accessDenied(access) }257        let all = visible.values.sorted { $0.id < $1.id }258        var output: [MediaItem] = []259        for (index, item) in all.enumerated() {260            try Task.checkCancellation()261            if let delay = scanDelayPerItem { try await Task.sleep(for: delay) }262            output.append(item)263            progress?(ScanProgress(processed: index + 1, total: all.count))264        }265        return LibraryScan(items: output, statistics: ScanStatistics(assetsEnumerated: output.count, accessIsLimited: access.isLimited), access: access)266    }267268    func measure(ids: [String], progress: (@Sendable (MeasureProgress) -> Void)?) async throws -> [String: MediaMeasurement] {269        measureRequests.append(ids)270        var output: [String: MediaMeasurement] = [:]271        for id in ids where visible[id] != nil {272            output[id] = measurements[id] ?? .inCloudOnly273        }274        progress?(MeasureProgress(completed: ids.count, total: ids.count))275        return output276    }277278    func existingIdentifiers(among ids: [String]) async throws -> Set<String> {279        fetchCount += 1280        if failVerification && fetchCount > 1 { throw FetchFailure() }281        let current = visible282        return Set(ids.filter { current[$0] != nil })283    }284285    func delete(ids: [String]) async -> MediaDeletionOutcome {286        deleteRequests.append(ids)287        switch behavior {288        case .deleteAll:289            for id in ids { items[id] = nil }290            return .performed291        case .deletePartially(let keeping):292            for id in ids where !keeping.contains(id) { items[id] = nil }293            return .performed294        case .userCancels:295            return .cancelledByUser296        case .fails(let message):297            return .failed(message)298        }299    }300}301
Files main
Menu

Theme