SPB Git

Repository Public License

PlanAndLibraryTests.swift 17.4 KB 345 lines swift

1// ORIX Secure2// File: Packages/ORIXMediaCleanup/Tests/ORIXMediaCleanupTests/PlanAndLibraryTests.swift3// Description: Selection, plan, executor against an in-memory library (complete, partial, cancelled, failed, limited access),4//              result and report wording, and the scan → measure → analyse pipeline.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXSecureModel10import Testing11@testable import ORIXMediaCleanup1213@Suite("Selection, plan, deletion and report")14struct PlanAndLibraryTests {15    static let look = Fixture.fingerprint(d: 0xABCD_EF01_2345_6789)1617    /// a/b/c byte-identical (a favourite), s1/s2 similar with one unknown size, plus a screenshot and a lone photo.18    static func libraryItems() -> [MediaItem] {19        [20            Fixture.photo("a", at: 0, size: 4000, hash: "same", favorite: true),21            Fixture.photo("b", at: 5000, size: 4000, hash: "same"),22            Fixture.photo("c", at: 9000, size: 4000, hash: "same"),23            Fixture.photo("s1", at: 20_000, fingerprint: look, size: 2500, hash: "u1"),24            Fixture.photo("s2", at: 20_030, fingerprint: look, hash: nil),25            Fixture.photo("shot", at: 30_000, size: 800, screenshot: true),26            Fixture.photo("lone", at: 40_000, fingerprint: Fixture.fingerprint(d: 1), size: 100),27        ]28    }2930    static func analysis() async throws -> CleanupAnalysis {31        try await CleanupAnalyzer().analyze(libraryItems())32    }3334    // MARK: Selection and plan3536    @Test("Only the extra copies of exact duplicates are proposed by default")37    func preselection() async throws {38        let analysis = try await Self.analysis()39        var selection = CleanupSelection.preselected(from: analysis)40        #expect(selection.itemIDs == ["b", "c"])41        selection.toggle("b")42        #expect(!selection.contains("b"))43        selection.toggle("b")44        selection.select("shot")45        selection.deselect("c")46        #expect(selection.itemIDs == ["b", "shot"])47        let similar = try #require(analysis.groups(in: .similar).first)48        selection.selectCandidates(of: similar)49        #expect(selection.contains("s2"))50        #expect(!selection.contains("s1"))51        selection.deselectAll(of: similar)52        #expect(!selection.contains("s2"))53        selection.removeAll()54        #expect(selection.isEmpty)55        #expect(CleanupSelection().count == 0)56    }5758    @Test("Plan: count, measured bytes, unknown sizes, warnings")59    func plan() async throws {60        let analysis = try await Self.analysis()61        let plan = CleanupPlan(selection: CleanupSelection(["b", "c", "s2", "ghost"]), analysis: analysis)62        #expect(plan.itemIDs == ["b", "c", "s2"])63        #expect(plan.count == 3)64        #expect(plan.unknownIDs == ["ghost"])65        #expect(plan.measuredBytes == 8000)66        #expect(plan.measuredCount == 2)67        #expect(plan.unknownSizeIDs == ["s2"])68        #expect(plan.size.value == nil)69        #expect(plan.summary.contains("3"))70        #expect(plan.keeperIDs.isEmpty)71        #expect(plan.fullySelectedGroupIDs.isEmpty)72        #expect(plan.recentlyDeletedNote.contains("Recently Deleted"))73        #expect(plan.warnings.count == 1)7475        let measured = CleanupPlan(selection: CleanupSelection(["b", "c"]), analysis: analysis)76        #expect(measured.size == .measured(8000))77        #expect(measured.warnings.isEmpty)7879        // Selecting every copy, including the favourite proposed to keep, is allowed but flagged.80        let everything = CleanupPlan(selection: CleanupSelection(["a", "b", "c"]), analysis: analysis)81        #expect(everything.keeperIDs == ["a"])82        #expect(everything.favoriteIDs == ["a"])83        #expect(everything.fullySelectedGroupIDs == ["exactDuplicates:same"])84        #expect(everything.warnings.count == 2)8586        let empty = CleanupPlan(selection: CleanupSelection(), analysis: analysis)87        #expect(empty.isEmpty)88        #expect(empty.size == .measured(0))89    }9091    // MARK: Executor9293    @Test("Complete deletion: exactly the selected identifiers, verified, nothing claimed as freed")94    func completeDeletion() async throws {95        let analysis = try await Self.analysis()96        let library = FakeMediaLibrary(items: Self.libraryItems())97        let plan = CleanupPlan(selection: .preselected(from: analysis), analysis: analysis)98        let result = await CleanupExecutor(library: library).execute(plan)99        #expect(result.outcome == .completed)100        #expect(result.requested == ["b", "c"])101        #expect(result.deleted == ["b", "c"])102        #expect(!result.cancelledByUser)103        #expect(result.failed.isEmpty)104        #expect(result.skipped.isEmpty)105        #expect(result.movedToRecentlyDeleted == .measured(8000))106        #expect(result.bytesFreedImmediately == 0)107        #expect(result.freedNow.contains("Recently Deleted"))108        #expect(result.freedNow.contains("30 days"))109        #expect(result.recentlyDeletedNote.contains("not reclaimed"))110        let requests = await library.deleteRequests111        #expect(requests == [["b", "c"]])112        let remaining = await library.items.keys.sorted()113        #expect(remaining == ["a", "lone", "s1", "s2", "shot"])114    }115116    @Test("Partial deletion is reported item by item")117    func partialDeletion() async throws {118        let analysis = try await Self.analysis()119        let library = FakeMediaLibrary(items: Self.libraryItems(), behavior: .deletePartially(keeping: ["c"]))120        let plan = CleanupPlan(selection: CleanupSelection(["b", "c", "s2"]), analysis: analysis)121        let result = await CleanupExecutor(library: library).execute(plan)122        #expect(result.outcome == .partial)123        #expect(result.deleted == ["b", "s2"])124        #expect(result.failed.map { $0.id } == ["c"])125        // s2 was never measured: the moved amount is unavailable, the measured part is kept.126        #expect(result.movedToRecentlyDeleted.value == nil)127        #expect(result.movedMeasuredBytes == 4000)128        #expect(result.movedUnmeasuredCount == 1)129        #expect(result.summary.contains("2"))130    }131132    @Test("User declines the system confirmation")133    func userCancelled() async throws {134        let analysis = try await Self.analysis()135        let library = FakeMediaLibrary(items: Self.libraryItems(), behavior: .userCancels)136        let plan = CleanupPlan(selection: CleanupSelection(["b", "c"]), analysis: analysis)137        let result = await CleanupExecutor(library: library).execute(plan)138        #expect(result.outcome == .cancelledByUser)139        #expect(result.cancelledByUser)140        #expect(result.cancelled == ["b", "c"])141        #expect(result.deleted.isEmpty)142        #expect(result.failed.isEmpty)143        #expect(result.movedToRecentlyDeleted == .measured(0))144        let count = await library.items.count145        #expect(count == 7)146    }147148    @Test("Library error")149    func deletionError() async throws {150        let analysis = try await Self.analysis()151        let library = FakeMediaLibrary(items: Self.libraryItems(), behavior: .fails("disk is busy"))152        let plan = CleanupPlan(selection: CleanupSelection(["b", "c"]), analysis: analysis)153        let result = await CleanupExecutor(library: library).execute(plan)154        #expect(result.outcome == .failed)155        #expect(result.deleted.isEmpty)156        #expect(result.failed == [CleanupFailure(id: "b", message: "disk is busy"), CleanupFailure(id: "c", message: "disk is busy")])157        let report = result.report()158        let bullets = report.sections.flatMap { $0.bullets }159        #expect(bullets.contains("b: disk is busy"))160    }161162    @Test("Verification failure never counts items as deleted")163    func verificationFailure() async throws {164        let analysis = try await Self.analysis()165        let library = FakeMediaLibrary(items: Self.libraryItems())166        await library.setFailVerification(true)167        let plan = CleanupPlan(selection: CleanupSelection(["b"]), analysis: analysis)168        let result = await CleanupExecutor(library: library).execute(plan)169        #expect(result.outcome == .failed)170        #expect(result.deleted.isEmpty)171        #expect(result.failed.count == 1)172    }173174    @Test("Limited access: invisible items are skipped, the result says access was limited")175    func limitedAccess() async throws {176        let analysis = try await Self.analysis()177        let library = FakeMediaLibrary(items: Self.libraryItems())178        await library.setAccess(.limited, visible: ["a", "b", "shot"])179        let plan = CleanupPlan(selection: CleanupSelection(["b", "c", "ghost"]), analysis: analysis)180        let result = await CleanupExecutor(library: library).execute(plan)181        #expect(result.outcome == .completed)182        #expect(result.accessWasLimited)183        #expect(result.deleted == ["b"])184        #expect(result.skipped == [CleanupSkip(id: "ghost", reason: .notInAnalysis), CleanupSkip(id: "c", reason: .notInLibrary)])185        let requests = await library.deleteRequests186        #expect(requests == [["b"]])187        let report = result.report()188        let limited = report.unavailable.contains { $0.contains("limited") }189        #expect(limited)190    }191192    @Test("No access and empty plans delete nothing", arguments: [MediaLibraryAccess.denied, .restricted, .notDetermined])193    func noAccess(_ access: MediaLibraryAccess) async throws {194        let analysis = try await Self.analysis()195        let library = FakeMediaLibrary(items: Self.libraryItems(), access: access)196        let result = await CleanupExecutor(library: library).execute(CleanupPlan(selection: CleanupSelection(["b"]), analysis: analysis))197        #expect(result.outcome == .noAccess)198        #expect(result.skipped == [CleanupSkip(id: "b", reason: .noAccess)])199        let nothing = await CleanupExecutor(library: library).execute(CleanupPlan(selection: CleanupSelection(), analysis: analysis))200        #expect(nothing.outcome == .nothingRequested)201        let requests = await library.deleteRequests202        #expect(requests.isEmpty)203        #expect(access.coverageNote != nil)204        #expect(!access.canRead)205    }206207    @Test("Access levels")208    func accessLevels() {209        #expect(MediaLibraryAccess.authorized.coverageNote == nil)210        #expect(MediaLibraryAccess.limited.isLimited)211        #expect(MediaLibraryAccess.limited.canRead)212        #expect(MediaLibraryAccess.limited.coverageNote?.contains("selected") == true)213        for access in MediaLibraryAccess.allCases { #expect(!access.title.isEmpty) }214    }215216    // MARK: Report217218    @Test("Report: cleanup kind, Recently Deleted statement, no freed-space amount")219    func report() async throws {220        let analysis = try await Self.analysis()221        let library = FakeMediaLibrary(items: Self.libraryItems())222        let plan = CleanupPlan(selection: CleanupSelection(["b", "c", "s2"]), analysis: analysis)223        let result = await CleanupExecutor(library: library).execute(plan)224        let report = result.report()225        #expect(report.kind == .cleanup)226        #expect(report.createdAt == result.finishedAt)227        let text = ([report.title, report.summary] + report.sections.flatMap { [$0.title] + $0.paragraphs + $0.bullets + $0.facts.flatMap { [$0.label, $0.value] } } + report.unavailable).joined(separator: "\n")228        #expect(text.contains(CleanupStatements.recentlyDeletedNote))229        #expect(text.contains(CleanupStatements.freedNow))230        #expect(text.contains("30 days"))231        #expect(text.contains("never deletes anything on its own"))232        let freed = try #require(report.sections.first?.facts.first { $0.label == "Space freed now" })233        #expect(freed.value == CleanupStatements.freedNow)234        let moved = try #require(report.sections.first?.facts.first { $0.label == "Moved to Recently Deleted (verified)" })235        #expect(moved.value == "3")236        let unmeasured = report.unavailable.contains { $0.contains("never measured") }237        #expect(unmeasured)238        let reclaimed = report.unavailable.contains { $0.contains("space actually reclaimed") }239        #expect(reclaimed)240241        let cancelled = CleanupResult(outcome: .cancelledByUser, requested: ["x"], cancelledByUser: true, cancelled: ["x"])242        let cancelledText = cancelled.report().sections.flatMap { $0.paragraphs }.joined(separator: " ")243        #expect(cancelledText.contains("nothing was deleted"))244        #expect(cancelledText.contains("Recently Deleted"))245        for outcome in CleanupResult.Outcome.allCases {246            let summary = CleanupResult(outcome: outcome, requested: []).summary247            #expect(!summary.isEmpty)248        }249        let data = try JSONEncoder().encode(result)250        let decoded = try JSONDecoder().decode(CleanupResult.self, from: data)251        #expect(decoded == result)252    }253254    // MARK: Pipeline255256    @Test("Pipeline: only candidates are measured; exact duplicates appear once hashes are known")257    func pipeline() async throws {258        let twin = Fixture.fingerprint(d: 0x1111_2222_3333_4444)259        let items = [260            Fixture.photo("p1", at: 100.1, fingerprint: twin),261            Fixture.photo("p2", at: 100.6, fingerprint: twin),262            Fixture.photo("q1", at: 5000, fingerprint: Self.look),263            Fixture.photo("q2", at: 5040, fingerprint: Self.look),264            Fixture.photo("alone", at: 90_000, fingerprint: Fixture.fingerprint(d: 77)),265            Fixture.video("film", at: 10, duration: 300),266        ]267        let measurements: [String: MediaMeasurement] = [268            "p1": MediaMeasurement(byteSize: .measured(3000), contentHash: "twin", isLocallyAvailable: .measured(true)),269            "p2": MediaMeasurement(byteSize: .measured(3000), contentHash: "twin", isLocallyAvailable: .measured(true)),270            "q1": MediaMeasurement(byteSize: .measured(2000), contentHash: "q1", isLocallyAvailable: .measured(true)),271            "film": MediaMeasurement(byteSize: .measured(450_000_000), contentHash: nil, isLocallyAvailable: .measured(true)),272            // q2 is absent: the fake answers "in iCloud".273        ]274        let library = FakeMediaLibrary(items: items, measurements: measurements)275        let output = try await CleanupPipeline(library: library).run()276        let requests = await library.measureRequests277        #expect(requests == [["p1", "p2", "q1", "q2", "film"]])278        #expect(output.measuredCandidateCount == 5)279        #expect(output.coverageNote == nil)280281        let exact = try #require(output.analysis.groups(in: .exactDuplicates).first)282        #expect(exact.items.map { $0.id } == ["p1", "p2"])283        #expect(exact.recoverable == .measured(3000))284        #expect(output.analysis.groups(in: .probableDuplicates).isEmpty)285286        let similar = try #require(output.analysis.groups(in: .similar).first)287        #expect(similar.items.map { $0.id } == ["q1", "q2"])288        let q2 = try #require(similar.items.first { $0.id == "q2" })289        #expect(q2.byteSize.unavailability?.kind == .failed)290        #expect(q2.byteSize.unavailability?.detail == "Original is in iCloud; not downloaded to measure")291        #expect(q2.isLocallyAvailable == .measured(false))292        #expect(similar.recoverable.value == nil)293294        #expect(output.analysis.groups(in: .largeVideos).first?.ordering == .byMeasuredSize)295        #expect(output.analysis.preselectedIDs == ["p2"])296    }297298    @Test("Pipeline: denied access throws, limited access is flagged")299    func pipelineAccess() async throws {300        let denied = FakeMediaLibrary(items: Self.libraryItems(), access: .denied)301        await #expect(throws: MediaLibraryError.accessDenied(.denied)) {302            _ = try await CleanupPipeline(library: denied).run()303        }304        let limited = FakeMediaLibrary(items: Self.libraryItems())305        await limited.setAccess(.limited, visible: ["a", "b", "shot"])306        let output = try await CleanupPipeline(library: limited).run()307        #expect(output.access == .limited)308        #expect(output.scan.accessIsLimited)309        #expect(output.coverageNote?.contains("selected") == true)310        #expect(output.analysis.statistics.itemsScanned == 3)311    }312313    @Test("Cancellation in the middle of a scan returns promptly")314    func scanCancellation() async throws {315        let library = FakeMediaLibrary(items: SyntheticLibrary.items(count: 2000, seed: 4))316        await library.setScanDelay(.milliseconds(2))317        let clock = ContinuousClock()318        let task = Task { try await CleanupPipeline(library: library).run() }319        try await Task.sleep(for: .milliseconds(60))320        let cancelledAt = clock.now321        task.cancel()322        let result = await task.result323        let waited = clock.now - cancelledAt324        switch result {325        case .success: Issue.record("the pipeline finished although it was cancelled")326        case .failure(let error): #expect(error is CancellationError)327        }328        print("CANCELLATION scan returned \(waited) after cancel")329        #expect(waited < .seconds(1))330    }331332    @Test("Measurements are applied without losing a known hash")333    func applyingMeasurement() {334        let item = Fixture.photo("a", at: 0, hash: "known")335        let measured = item.applying(MediaMeasurement(byteSize: .measured(12), contentHash: nil, isLocallyAvailable: .measured(true)))336        #expect(measured.byteSize == .measured(12))337        #expect(measured.contentHash == "known")338        let cloud = item.applying(.inCloudOnly)339        #expect(cloud.byteSize.value == nil)340        #expect(cloud.isLocallyAvailable == .measured(false))341        #expect(MediaItem(id: "x").byteSize.unavailability?.kind == .notRequested)342        #expect(MediaItem(id: "x", pixelWidth: -4, pixelHeight: 10).pixelCount == 0)343    }344}345
Files main
Menu

Theme