SPB Git

Repository Public License

CleanupTests.swift 32.0 KB 485 lines swift

1// ORIX Clean — Packages/ORIXCleanCore/Tests/ORIXCleanCoreTests/CleanupTests.swift2// Description: Safety policy, deletion engine, catalog, downloads, trash, applications, history, reports and workflows.3// Author: Simon-Pierre Boucher — contact@spboucher.ai4import Darwin5import Foundation6import Testing7@testable import ORIXCleanCore89@Suite struct SafetyPolicyTests {10    let policy = SafetyPolicy(home: "/Users/tester")1112    @Test func protectedLocationsAreDenied() {13        for p in ["/", "/System", "/System/Library/CoreServices", "/usr/bin/zip", "/bin", "/Library", "/Library/Preferences", "/Applications",14                  "/Users", "/Users/tester", "/Users/other", "/Users/tester/Documents", "/Users/tester/Desktop", "/Users/tester/Library",15                  "/Users/tester/Library/Caches", "/Users/tester/Library/Application Support", "/Users/tester/Library/Keychains/login.keychain-db",16                  "/Volumes", "/Volumes/Backup", "/private/var/db/receipts", "/etc/hosts", "/var/root", "/System/Applications/Mail.app",17                  "/Applications/Safari.app/Contents/MacOS/Safari", "/Users/tester/Pictures/Photos Library.photoslibrary/database/Photos.sqlite",18                  "/System/Volumes/Data/Users/tester/Documents", "relative/path", "/Users/tester/Documents/../Library", "/Users/tester/.Trash",19                  "/private/tmp", "/tmp", "/Volumes/Backup/.Trashes", "/Volumes/Backup/.Trashes/501", "/private/var/folders/ab/cdef/T",20                  "/var/folders/ab/cdef", "/Users/tester/.ssh", "/Users/tester/.ssh/id_ed25519", "/Users/tester/.gnupg/pubring.kbx", "/Users/tester/.aws/credentials"] {21            #expect(policy.evaluate(p) != .allowed, "\(p) must be protected")22        }23    }2425    @Test func ordinaryItemsAreAllowed() {26        for p in ["/Users/tester/Downloads/installer.dmg", "/Users/tester/Library/Caches/com.vendor.app", "/Users/tester/Documents/old/report.pdf",27                  "/Applications/Vendor.app", "/Users/tester/Library/Developer/Xcode/DerivedData/App-abc", "/Users/tester/.npm/_cacache",28                  "/Users/tester/project", "/Users/tester/.Trash/old.zip", "/Volumes/Backup/folder/file.bin", "/private/tmp/scratch",29                  "/private/var/folders/ab/cdef/T/item", "/Users/tester/Pictures/Photos Library.photoslibrary", "/Volumes/Backup/.Trashes/501/x"] {30            #expect(policy.evaluate(p) == .allowed, "\(p) should be allowed")31        }32    }33}3435@Suite struct DeletionTests {36    func engine(_ s: Sandbox, failing: Set<String> = [], error: NSError? = nil) -> DeletionEngine {37        var t = FakeTrasher(bin: s.dir("bin"))38        t.failing = failing39        if let error { t.error = error }40        return DeletionEngine(policy: SafetyPolicy(home: s.path("home")), trasher: t)41    }4243    @Test func nothingIsRemovedWithoutAuthorization() {44        let s = Sandbox()45        let a = s.file("a.bin", size: 1000), b = s.file("b.bin", size: 2000)46        let confirmed = CleanupPlan(items: [item(a)])47        let auth = CleanupAuthorization(confirming: confirmed, highRiskAcknowledged: false)48        let r = engine(s).execute(plan: CleanupPlan(items: [item(a), item(b)]), authorization: auth)49        #expect(r.count(.movedToTrash) == 1 && r.count(.skipped) == 1)50        #expect(!FileManager.default.fileExists(atPath: a))51        #expect(FileManager.default.fileExists(atPath: b))52    }5354    @Test func highRiskNeedsExplicitAcknowledgement() {55        let s = Sandbox()56        let a = s.file("a.bin", size: 1000)57        let plan = CleanupPlan(items: [item(a, risk: .high)])58        let r1 = engine(s).execute(plan: plan, authorization: CleanupAuthorization(confirming: plan, highRiskAcknowledged: false))59        #expect(r1.count(.skipped) == 1 && FileManager.default.fileExists(atPath: a))60        let r2 = engine(s).execute(plan: plan, authorization: CleanupAuthorization(confirming: plan, highRiskAcknowledged: true))61        #expect(r2.count(.movedToTrash) == 1)62    }6364    @Test func moveToTheRealTrashAndRestore() throws {65        let s = Sandbox()66        let a = s.file("folder/keepsake.bin", size: 123_456, seed: 4)67        let digest = DuplicateFinder.fullHash(path: a)68        let plan = CleanupPlan(items: [item(s.path("folder"))])69        let real = DeletionEngine(policy: SafetyPolicy())70        let r = real.execute(plan: plan, authorization: CleanupAuthorization(confirming: plan, highRiskAcknowledged: false))71        #expect(r.count(.movedToTrash) == 1)72        #expect(!FileManager.default.fileExists(atPath: a))73        let rec = try #require(r.records.first)74        let trashPath = try #require(rec.trashPath)75        #expect(FileManager.default.fileExists(atPath: trashPath))76        #expect(real.restore(rec) == .restored)77        #expect(DuplicateFinder.fullHash(path: a) == digest)78        #expect(real.restore(rec) == .notInTrash)79    }8081    @Test func restoreRefusesToOverwrite() throws {82        let s = Sandbox()83        let a = s.file("a.bin", size: 100)84        let e = engine(s)85        let plan = CleanupPlan(items: [item(a)])86        let r = e.execute(plan: plan, authorization: CleanupAuthorization(confirming: plan, highRiskAcknowledged: false))87        s.file("a.bin", size: 5)88        #expect(e.restore(r.records[0]) == .destinationOccupied)89    }9091    @Test func revalidationSkipsVanishedReplacedAndChangedItems() {92        let s = Sandbox()93        let gone = s.file("gone.bin", size: 100), changed = s.file("changed.bin", size: 100), replaced = s.file("replaced.bin", size: 100)94        let plan = CleanupPlan(items: [item(gone), item(changed), item(replaced)])95        try? FileManager.default.removeItem(atPath: gone)96        FileManager.default.createFile(atPath: s.path("tmp"), contents: Data(count: 100))97        try? FileManager.default.removeItem(atPath: replaced)98        try? FileManager.default.moveItem(atPath: s.path("tmp"), toPath: replaced)99        let h = FileHandle(forWritingAtPath: changed)!; h.seekToEndOfFile(); h.write(Data(count: 7)); try? h.close()100        let r = engine(s).execute(plan: plan, authorization: CleanupAuthorization(confirming: plan, highRiskAcknowledged: false))101        #expect(r.count(.skipped) == 3 && r.count(.movedToTrash) == 0)102        #expect(FileManager.default.fileExists(atPath: changed) && FileManager.default.fileExists(atPath: replaced))103    }104105    @Test func duplicatesAreVerifiedAgainstTheKeptCopy() {106        let s = Sandbox()107        let keep = s.file("keep.bin", size: 50_000, seed: 1), dup = s.file("dup.bin", size: 50_000, seed: 1)108        let drift = s.file("drift.bin", size: 50_000, seed: 1), orphan = s.file("orphan.bin", size: 50_000, seed: 1)109        let linked = s.path("linked.bin"); link(keep, linked)110        let items = [item(dup, category: .duplicate, verify: keep), item(drift, category: .duplicate, verify: keep),111                     item(orphan, category: .duplicate, verify: s.path("missing.bin")), item(linked, category: .duplicate, verify: keep)]112        // Same size, different content after the scan.113        let fd = open(drift, O_WRONLY); var b: UInt8 = 0x42; pwrite(fd, &b, 1, 25_000); close(fd)114        let plan = CleanupPlan(items: items)115        let r = engine(s).execute(plan: plan, authorization: CleanupAuthorization(confirming: plan, highRiskAcknowledged: false))116        let status = Dictionary(uniqueKeysWithValues: r.records.map { (($0.path as NSString).lastPathComponent, $0.status) })117        #expect(status["dup.bin"] == .movedToTrash)118        #expect(status["drift.bin"] == .skipped && status["orphan.bin"] == .skipped && status["linked.bin"] == .skipped)119        #expect(FileManager.default.fileExists(atPath: keep))120    }121122    @Test func aGroupIsNeverEmptied() {123        let s = Sandbox()124        let a = s.file("a.bin", size: 9000, seed: 1), b = s.file("b.bin", size: 9000, seed: 1)125        let plan = CleanupPlan(items: [item(a, category: .duplicate, verify: b), item(b, category: .duplicate, verify: a)])126        let r = engine(s).execute(plan: plan, authorization: CleanupAuthorization(confirming: plan, highRiskAcknowledged: false))127        #expect(r.count(.movedToTrash) == 0)128        #expect(FileManager.default.fileExists(atPath: a) && FileManager.default.fileExists(atPath: b))129    }130131    @Test func partialFailureIsReportedPerItem() {132        let s = Sandbox()133        let ok = s.file("ok.bin", size: 100), denied = s.file("denied.bin", size: 100), noTrash = s.file("notrash.bin", size: 100)134        let plan = CleanupPlan(items: [item(ok), item(denied), item(noTrash)])135        let r = engine(s, failing: [denied]).execute(plan: plan, authorization: CleanupAuthorization(confirming: plan, highRiskAcknowledged: false))136        #expect(r.count(.movedToTrash) == 2 && r.count(.failed) == 1)137        #expect(r.records.count == 3)138        let unsupported = NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError)139        let plan2 = CleanupPlan(items: [item(denied)])140        let r2 = engine(s, failing: [denied], error: unsupported).execute(plan: plan2, authorization: CleanupAuthorization(confirming: plan2, highRiskAcknowledged: false))141        // No Trash on the volume: the item is left in place, never silently deleted for good.142        #expect(r2.count(.requiresManualAction) == 1 && FileManager.default.fileExists(atPath: denied))143    }144145    @Test func protectedPathsRunningAppsPermanentModeAndCancellation() {146        let s = Sandbox()147        let home = s.dir("home")148        let docs = s.dir("home/Documents")149        let cache = s.file("home/Library/Caches/com.x.app/data", size: 500)150        let e = engine(s)151        let whole = CleanupPlan(items: [item(home)])152        #expect(e.execute(plan: whole, authorization: CleanupAuthorization(confirming: whole, highRiskAcknowledged: true)).count(.skipped) == 1)153        let plan = CleanupPlan(items: [item(docs), item(s.path("home/Library")), item((cache as NSString).deletingLastPathComponent, close: ["com.x.app"])])154        let auth = CleanupAuthorization(confirming: plan, highRiskAcknowledged: true)155        let r = e.execute(plan: plan, authorization: auth, runningBundleIDs: ["com.x.app"])156        #expect(r.count(.skipped) == 2 && r.count(.requiresManualAction) == 0)157        let busy = CleanupPlan(items: [item((cache as NSString).deletingLastPathComponent, close: ["com.x.app"])])158        #expect(e.execute(plan: busy, authorization: CleanupAuthorization(confirming: busy, highRiskAcknowledged: true), runningBundleIDs: ["com.x.app"]).count(.requiresManualAction) == 1)159        #expect(FileManager.default.fileExists(atPath: docs) && FileManager.default.fileExists(atPath: cache))160        // Permanent deletion is refused outside the Trash category.161        let p2 = CleanupPlan(items: [item((cache as NSString).deletingLastPathComponent)])162        let r2 = e.execute(plan: p2, authorization: CleanupAuthorization(confirming: p2, highRiskAcknowledged: true), mode: .permanent)163        #expect(r2.count(.skipped) == 1 && FileManager.default.fileExists(atPath: cache))164        let outside = CleanupPlan(items: [item(s.file("t.bin", size: 10), category: .trash)])165        #expect(e.execute(plan: outside, authorization: CleanupAuthorization(confirming: outside, highRiskAcknowledged: true), mode: .permanent).count(.skipped) == 1)166        let p3 = CleanupPlan(items: [item(s.file("home/.Trash/t.bin", size: 10), category: .trash)])167        let r3 = e.execute(plan: p3, authorization: CleanupAuthorization(confirming: p3, highRiskAcknowledged: true), mode: .permanent)168        #expect(r3.count(.permanentlyDeleted) == 1)169        let cancelled = engine(s); cancelled.cancel()170        let p4 = CleanupPlan(items: [item(s.file("c.bin", size: 10))])171        let r4 = cancelled.execute(plan: p4, authorization: CleanupAuthorization(confirming: p4, highRiskAcknowledged: true))172        #expect(r4.cancelled && r4.count(.skipped) == 1 && FileManager.default.fileExists(atPath: s.path("c.bin")))173    }174175    @Test func readOnlyVolumeFailsCleanlyAndFullVolumeStillTrashes() throws {176        guard let ro = TestVolume(readOnlyAfter: { FileManager.default.createFile(atPath: $0 + "/frozen.bin", contents: Data(count: 4096)) }) else {177            Issue.record("hdiutil unavailable"); return178        }179        let frozen = ro.mountPoint + "/frozen.bin"180        let plan = CleanupPlan(items: [item(frozen)])181        let real = DeletionEngine(policy: SafetyPolicy())182        let r = real.execute(plan: plan, authorization: CleanupAuthorization(confirming: plan, highRiskAcknowledged: false))183        #expect(r.count(.movedToTrash) == 0)184        #expect(r.count(.failed) + r.count(.requiresManualAction) == 1)185        #expect(FileManager.default.fileExists(atPath: frozen))186187        guard let full = TestVolume(sizeMB: 12) else { Issue.record("hdiutil unavailable"); return }188        let victim = full.mountPoint + "/victim.bin"189        FileManager.default.createFile(atPath: victim, contents: Data(count: 200_000))190        // Fill the volume.191        let fd = open(full.mountPoint + "/filler.bin", O_CREAT | O_WRONLY, 0o644)192        let block = [UInt8](repeating: 0xAB, count: 1 << 20)193        while write(fd, block, block.count) == block.count {}194        close(fd)195        let p2 = CleanupPlan(items: [item(victim)])196        let r2 = real.execute(plan: p2, authorization: CleanupAuthorization(confirming: p2, highRiskAcknowledged: false))197        // Moving to the Trash is a rename on the same volume: it works with no free space, and frees nothing by itself.198        #expect(r2.count(.movedToTrash) == 1)199        #expect(r2.records.first?.trashPath?.contains("-mnt/.Trashes/") == true)200        let trash = TrashAnalyzer.locations(home: "/nonexistent", volumes: [Volumes.info(for: URL(fileURLWithPath: full.mountPoint))!])201        #expect(trash.first?.items.count == 1)202        #expect(trash.first?.logical == 200_000)203    }204205    @Test func planDeduplicatesNestedItems() {206        let s = Sandbox()207        s.file("d/a.bin", size: 5000); s.file("d/sub/b.bin", size: 7000)208        let plan = CleanupPlan(items: [item(s.path("d/sub/b.bin")), item(s.path("d")), item(s.path("d")), item(s.path("d/a.bin"))])209        #expect(plan.items.count == 1)210        #expect(plan.logicalSize == 12_000 && plan.fileCount == 2)211        #expect(plan.recoverable.maximum == plan.allocatedSize)212    }213}214215@Suite struct CatalogTests {216    func home() -> Sandbox {217        let s = Sandbox("home")218        s.file("Library/Caches/com.vendor.editor/blob", size: 300_000)219        s.file("Library/Caches/com.apple.Safari/blob", size: 300_000)220        s.file("Library/Caches/CloudKit/blob", size: 300_000)221        s.file("Library/Caches/tiny/blob", size: 100)222        s.file("Library/Caches/Google/Chrome/Default/Cache/data", size: 400_000)223        s.file("Library/Caches/Homebrew/downloads/pkg.tar.gz", size: 500_000)224        s.file("Library/Logs/Vendor/app.log", size: 200_000)225        s.file("Library/Developer/Xcode/DerivedData/App-aaaa/Build/x.o", size: 800_000)226        s.file("Library/Developer/Xcode/DerivedData/Lib-bbbb/Build/y.o", size: 700_000)227        s.file("Library/Developer/Xcode/Archives/2020-01-01/App.xcarchive/Info.plist", size: 900_000)228        s.file(".npm/_cacache/content/z", size: 600_000)229        return s230    }231232    @Test func cachesSectionListsOnlyDocumentedSafeLocations() {233        let s = home()234        let items = CleanupCatalog.discover(.caches, home: s.root, appNames: ["com.vendor.editor": "Editor"])235        let names = Set(items.map { $0.path.replacingOccurrences(of: s.root + "/", with: "") })236        #expect(names.contains("Library/Caches/com.vendor.editor"))237        #expect(names.contains("Library/Caches/Google/Chrome"))238        #expect(names.contains("Library/Logs/Vendor"))239        #expect(!names.contains { $0.contains("com.apple.") || $0.contains("CloudKit") || $0.contains("tiny") || $0.contains("Homebrew") })240        let editor = items.first { $0.path.hasSuffix("com.vendor.editor") }!241        #expect(editor.owner == "Editor" && editor.closeFirst == ["com.vendor.editor"] && editor.risk == .low)242        #expect(editor.measurement.logical == 300_000 && !editor.reason.isEmpty && !editor.consequence.isEmpty)243        let chrome = items.first { $0.path.hasSuffix("Google/Chrome") }!244        #expect(chrome.category == .browserCache && chrome.closeFirst == ["com.google.Chrome"])245        let policy = SafetyPolicy(home: s.root)246        #expect(items.allSatisfy { policy.evaluate($0.path) == .allowed })247    }248249    @Test func developerSectionSplitsPerProjectAndMarksArchivesForReview() {250        let s = home()251        let items = CleanupCatalog.discover(.developer, home: s.root)252        let derived = items.filter { $0.path.contains("DerivedData/") }253        #expect(derived.count == 2 && derived.allSatisfy { $0.risk == .low && $0.closeFirst == ["com.apple.dt.Xcode"] && $0.regeneration != nil })254        #expect(items.first { $0.path.contains("Archives/") }?.risk == .review)255        #expect(items.contains { $0.path.hasSuffix(".npm/_cacache") && $0.owner == "npm" })256        #expect(items.contains { $0.path.hasSuffix("Library/Caches/Homebrew") })257        let policy = SafetyPolicy(home: s.root)258        #expect(items.allSatisfy { policy.evaluate($0.path) == .allowed })259    }260261    @Test func everyRuleIsDocumented() {262        for rule in CleanupCatalog.rules(.caches) + CleanupCatalog.rules(.developer) {263            #expect(!rule.reason.isEmpty && !rule.consequence.isEmpty && rule.regeneration != nil, "\(rule.id)")264        }265        #expect(Set((CleanupCatalog.rules(.caches) + CleanupCatalog.rules(.developer)).map(\.id)).count == CleanupCatalog.rules(.caches).count + CleanupCatalog.rules(.developer).count)266    }267268    @Test func buildArtifactsNeedTheirManifest() throws {269        let s = Sandbox()270        s.text("web/package.json", "{}"); s.file("web/node_modules/lib/index.js", size: 300_000)271        s.file("stray/node_modules/lib/index.js", size: 300_000)272        s.text("pkg/Package.swift", "//"); s.file("pkg/.build/debug/x.o", size: 300_000)273        s.file("docs/target/notes.bin", size: 300_000)274        let items = CleanupCatalog.buildArtifacts(in: try s.scan().tree, minimumSize: 1000)275        #expect(Set(items.map { $0.path.replacingOccurrences(of: s.root + "/", with: "") }) == ["web/node_modules", "pkg/.build"])276        #expect(items.allSatisfy { $0.risk == .review })277    }278279    @Test func downloadsAreClassified() throws {280        let s = Sandbox()281        s.file("Downloads/App.dmg", size: 90_000); s.file("Downloads/Setup.pkg", size: 80_000)282        s.file("Downloads/photos.zip", size: 70_000); s.file("Downloads/photos/1.jpg", size: 10_000)283        s.file("Downloads/movie.mp4.crdownload", size: 60_000); s.file("Downloads/notes.txt", size: 100)284        s.text("Downloads/.hidden", "x")285        let entries = try DownloadsAnalyzer.analyze(folder: s.path("Downloads"))286        let kinds = Dictionary(uniqueKeysWithValues: entries.map { ($0.name, $0.kind) })287        #expect(kinds == ["App.dmg": .diskImage, "Setup.pkg": .installer, "photos.zip": .archive, "photos": .other,288                          "movie.mp4.crdownload": .partial, "notes.txt": .other])289        #expect(entries.first { $0.name == "photos.zip" }?.extractedSibling == "photos")290        let ci = entries.first { $0.name == "photos.zip" }!.cleanupItem()291        #expect(ci.risk == .review && ci.category == .archive && ci.reason.contains("photos"))292    }293294    @Test func trashInventory() {295        let s = Sandbox()296        s.file(".Trash/old.zip", size: 40_000); s.file(".Trash/folder/a.bin", size: 60_000)297        let t = TrashAnalyzer.locations(home: s.root, volumes: [])298        #expect(t.count == 1 && t[0].accessible && t[0].items.count == 2)299        #expect(t[0].logical == 100_000 && t[0].fileCount == 2)300        #expect(t[0].items[0].cleanupItem.category == .trash)301        chmod(s.path(".Trash"), 0)302        #expect(TrashAnalyzer.locations(home: s.root, volumes: []).first?.accessible == false)303        chmod(s.path(".Trash"), 0o700)304    }305}306307@Suite struct ApplicationTests {308    func makeApp(_ s: Sandbox, _ name: String, id: String) -> String {309        let plist: [String: Any] = ["CFBundleIdentifier": id, "CFBundleName": name, "CFBundleShortVersionString": "2.1", "CFBundleVersion": "42",310                                    "CFBundleExecutable": name, "CFBundlePackageType": "APPL"]311        let dir = s.dir("Applications/\(name).app/Contents")312        try! PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0).write(to: URL(fileURLWithPath: dir + "/Info.plist"))313        s.file("Applications/\(name).app/Contents/MacOS/\(name)", size: 150_000)314        return s.path("Applications/\(name).app")315    }316317    @Test func discoveryAssociatedFilesAndUninstallPlan() throws {318        let s = Sandbox()319        _ = makeApp(s, "Sketcher", id: "com.vendor.sketcher")320        s.file("Library/Application Support/com.vendor.sketcher/db.sqlite", size: 70_000)321        s.file("Library/Application Support/Sketcher/assets.bin", size: 60_000)322        s.file("Library/Application Support/Sketcher Pro/other.bin", size: 60_000)323        s.file("Library/Caches/com.vendor.sketcher/c", size: 50_000)324        s.file("Library/Caches/com.vendor.sketcher.helper/c", size: 20_000)325        s.text("Library/Preferences/com.vendor.sketcher.plist", "p")326        s.text("Library/Preferences/com.vendor.sketcherx.plist", "p")327        s.file("Library/Saved Application State/com.vendor.sketcher.savedState/w", size: 1000)328        s.file("Documents/Drawing.sketch", size: 1000)329        let apps = AppInventory.discover(directories: [s.path("Applications")])330        #expect(apps.count == 1)331        let app = AppInventory.measure(apps[0])332        #expect(app.name == "Sketcher" && app.bundleID == "com.vendor.sketcher" && app.version == "2.1" && app.build == "42" && !app.isSystem)333        #expect(app.measurement?.logical ?? 0 > 150_000)334        #expect(app.signature?.kind == .unsigned)335        let files = AppInventory.associatedFiles(for: app, home: s.root)336        let byName = Dictionary(uniqueKeysWithValues: files.map { ($0.path.replacingOccurrences(of: s.root + "/Library/", with: ""), $0.confidence) })337        #expect(byName == ["Application Support/com.vendor.sketcher": .identifier, "Application Support/Sketcher": .nameMatch,338                           "Caches/com.vendor.sketcher": .identifier, "Caches/com.vendor.sketcher.helper": .identifier,339                           "Preferences/com.vendor.sketcher.plist": .identifier, "Saved Application State/com.vendor.sketcher.savedState": .identifier])340        let items = AppInventory.uninstallItems(app: app, files: files)341        #expect(items.count == 7)342        #expect(items.first?.category == .application)343        #expect(items.first { $0.path.hasSuffix("Support/Sketcher") }?.risk == .high)344        #expect(!items.contains { $0.path.contains("Documents") })345        #expect(items.allSatisfy { $0.closeFirst == ["com.vendor.sketcher"] })346    }347348    @Test func systemApplicationsAreNeverOffered() {349        let mail = AppInventory.read("/System/Applications/Mail.app")350        #expect(mail?.isSystem == true)351        #expect(AppInventory.uninstallItems(app: mail!, files: []).isEmpty)352        let sig = AppInventory.signature(of: "/System/Applications/Mail.app")353        #expect(sig.kind == .apple && sig.valid)354    }355356    @Test func leftoversAreInferredConservatively() {357        let s = Sandbox()358        let app = AppInventory.read(makeApp(s, "Sketcher", id: "com.vendor.sketcher"))!359        s.file("Library/Application Support/com.gone.oldapp/data", size: 90_000)360        s.file("Library/Caches/com.vendor.sketcher/c", size: 90_000)361        s.file("Library/Caches/com.vendor.shared/c", size: 90_000)362        s.file("Library/Caches/com.apple.something/c", size: 90_000)363        s.file("Library/Caches/org.registered.tool/c", size: 90_000)364        s.file("Library/Application Support/Plain Name/c", size: 90_000)365        s.file("Library/Preferences/com.gone.oldapp.plist", size: 30_000)366        let found = LeftoverFinder.find(installed: [app], home: s.root, resolver: { $0 == "org.registered.tool" })367        #expect(Set(found.map(\.identifier)) == ["com.gone.oldapp"])368        #expect(found.count == 2)369        #expect(found[0].cleanupItem.risk == .review && found[0].cleanupItem.confidenceNote != nil)370    }371}372373@Suite struct HistoryAndReportTests {374    func volume(_ available: Int64) -> VolumeInfo {375        VolumeInfo(path: "/", name: "Macintosh HD", uuid: "UUID-1", format: "apfs", total: 1_000_000_000_000, available: available,376                   availableForImportantUsage: available, isInternal: true, isRemovable: false, isReadOnly: false, isStartup: true, isNetwork: false)377    }378379    @Test func historyStoreRoundTrip() throws {380        let s = Sandbox()381        let store = try HistoryStore(path: s.path("db/history.sqlite"))382        #expect(store.monitoringStart() == nil)383        let t0 = Date(timeIntervalSince1970: 1_800_000_000)384        for d in 0 ..< 10 { store.record(volume: volume(500_000_000_000 - Int64(d) * 2_000_000_000), at: t0.addingTimeInterval(Double(d) * 86400)) }385        store.record(volume: volume(500_000_000_000 - 18_000_000_000), at: t0.addingTimeInterval(9 * 86400 + 60))386        let samples = store.volumeSamples(volumeID: "UUID-1", since: nil)387        #expect(samples.count == 10)388        #expect(store.monitoringStart() == t0)389        let slope = try #require(Trend.bytesPerDay(samples))390        #expect(abs(slope - 2_000_000_000) < 1_000_000)391        #expect(Trend.bytesPerDay(Array(samples.prefix(2))) == nil)392        store.watch("/a"); store.watch("/a"); store.watch("/b"); store.unwatch("/b")393        #expect(store.watched() == ["/a"])394        var m = Measurement(); m.logical = 5; m.allocated = 4096; m.files = 1395        store.record(folder: "/a", measurement: m, at: t0)396        #expect(store.folderSamples(path: "/a").first?.allocated == 4096)397        let rec = DeletionRecord(path: "/x", status: .movedToTrash, detail: "d", trashPath: "/t", logicalSize: 1, allocatedSize: 2, category: .appCache)398        let report = DeletionReport(id: UUID(), started: t0, finished: t0, mode: .moveToTrash, records: [rec], cancelled: false, freeBefore: 1, freeAfter: 2)399        store.save(report)400        #expect(store.operations() == [report])401        store.saveDocument(Workflow(id: "w1", name: "Mine", steps: [.collectCaches, .review, .moveToTrash]), kind: "workflow", id: "w1")402        #expect(store.documents(Workflow.self, kind: "workflow").first?.name == "Mine")403        // Reopen: data persisted.404        #expect(try HistoryStore(path: s.path("db/history.sqlite")).volumeSamples(volumeID: "UUID-1", since: t0.addingTimeInterval(5 * 86400)).count == 5)405        store.eraseAll()406        #expect(store.monitoringStart() == nil && store.operations().isEmpty)407    }408409    @Test func recommendationsComeOnlyFromEvidence() {410        var f = Findings()411        #expect(RecommendationEngine.evaluate(f).isEmpty)412        f.volumes = [volume(50_000_000_000)]413        let low = RecommendationEngine.evaluate(f)414        #expect(low.count == 1 && low[0].id.hasPrefix("low-space") && low[0].evidence.contains("5"))415        f.volumes = [volume(500_000_000_000)]416        var m = Measurement(); m.allocated = 4_000_000_000; m.logical = 4_000_000_000; m.isDirectory = true417        f.developer = (0 ..< 2).map { CleanupItem(path: "/Users/t/Library/Developer/Xcode/DerivedData/P\($0)", category: .developer, risk: .low, reason: "r", consequence: "c", measurement: m) }418        f.caches = []419        let recs = RecommendationEngine.evaluate(f)420        #expect(recs.map(\.id) == ["deriveddata"])421        #expect(recs[0].measuredSize == 8_000_000_000 && recs[0].paths.count == 2)422        let t0 = Date(timeIntervalSince1970: 1_800_000_000)423        f.history = ["UUID-1": (0 ..< 8).map { VolumeSample(date: t0.addingTimeInterval(Double($0) * 86400), volumeID: "UUID-1", name: "M", total: 1_000_000_000_000, available: 500_000_000_000 - Int64($0) * 20_000_000_000) }]424        #expect(RecommendationEngine.evaluate(f).contains { $0.id == "growth-UUID-1" })425    }426427    @Test func reportRenderers() throws {428        let s = Sandbox()429        s.file("r/big.bin", size: 400_000); s.file("r/a|b,\"q\".txt", size: 1000); s.text("r/=cmd.txt", "x")430        let result = try s.scan("r")431        var sections = ReportBuilder.overview(result: result, volume: Volumes.containing(s.root))432        sections += ReportBuilder.duplicates(DuplicateFinder().run(tree: result.tree))433        sections.append(ReportSection(title: "Formula", headers: ["Path"], rows: [["=HYPERLINK(\"x\")"], ["+1"], ["normal"]]))434        let report = Report(title: "Storage overview", scope: s.path("r"),435                            limitations: ReportBuilder.limitations(issues: result.issues, fullDiskAccess: false, sharingMeasured: true), sections: sections, appVersion: "1.0.0")436        let md = String(decoding: report.render(.markdown), as: UTF8.self)437        #expect(md.hasPrefix("# Storage overview") && md.contains("big.bin") && md.contains("a\\|b") && md.contains("Full Disk Access"))438        let csv = String(decoding: report.render(.csv), as: UTF8.self)439        #expect(csv.contains("\"'=HYPERLINK(\"\"x\"\")\"") && csv.contains("\"'+1\"") && csv.contains("\"normal\""))440        #expect(csv.contains("a|b,\"\"q\"\".txt"))441        let json = try JSONSerialization.jsonObject(with: report.render(.json)) as? [String: Any]442        #expect(json?["title"] as? String == "Storage overview" && (json?["sections"] as? [Any])?.count == sections.count)443        let pdf = report.render(.pdf)444        #expect(pdf.prefix(5) == Data("%PDF-".utf8) && pdf.count > 3000)445        let rec = DeletionRecord(path: "/x", status: .failed, detail: "Permission denied", trashPath: nil, logicalSize: 1, allocatedSize: 4096, category: .appCache)446        let del = DeletionReport(id: UUID(), started: Date(), finished: Date(), mode: .moveToTrash, records: [rec], cancelled: false, freeBefore: 10, freeAfter: 10)447        let cleanup = ReportBuilder.cleanupResults(del)448        #expect(cleanup[0].rows[0][1] == DeletionStatus.failed.title && cleanup[0].note?.contains("Trash") == true)449    }450}451452struct AutoReviewer: WorkflowReviewer {453    var approve: Bool454    func review(_ plan: CleanupPlan) async -> (plan: CleanupPlan, authorization: CleanupAuthorization)? {455        approve ? (plan, CleanupAuthorization(confirming: plan, highRiskAcknowledged: false)) : nil456    }457}458459@Suite struct WorkflowTests {460    @Test func validationForbidsRemovalWithoutReview() {461        #expect(throws: WorkflowError.removalWithoutReview) { try Workflow(name: "bad", steps: [.collectCaches, .moveToTrash]).validate() }462        #expect(throws: WorkflowError.removalWithoutReview) { try Workflow(name: "bad", steps: [.collectCaches, .review, .collectDeveloperData, .moveToTrash]).validate() }463        #expect(throws: WorkflowError.removalWithoutReview) { try Workflow(name: "bad", steps: [.collectCaches, .review, .moveToTrash, .moveToTrash]).validate() }464        #expect(throws: WorkflowError.duplicatesWithoutScan) { try Workflow(name: "bad", steps: [.findDuplicates(minimumSizeMB: 1)]).validate() }465        #expect(throws: WorkflowError.empty) { try Workflow(name: "bad", steps: []).validate() }466        for w in Workflow.builtIns { #expect(throws: Never.self) { try w.validate() } }467    }468469    @Test func duplicateWorkflowKeepsOneCopyAndStopsWhenReviewIsDeclined() async throws {470        let s = Sandbox()471        s.file("home/Downloads/a.bin", size: 2_000_000, seed: 1); s.file("home/Downloads/a (1).bin", size: 2_000_000, seed: 1)472        s.file("home/Downloads/a (2).bin", size: 2_000_000, seed: 1); s.file("home/Downloads/b.bin", size: 2_000_000, seed: 2)473        let w = Workflow(name: "dups", steps: [.scanFolder(path: s.path("home/Downloads")), .findDuplicates(minimumSizeMB: 1), .review, .moveToTrash, .report])474        let declined = try await WorkflowRunner(policy: SafetyPolicy(home: s.path("home")), trasher: FakeTrasher(bin: s.dir("bin")), home: s.path("home"))475            .run(w, reviewer: AutoReviewer(approve: false))476        #expect(declined.cancelled && declined.report == nil)477        #expect(try FileManager.default.contentsOfDirectory(atPath: s.path("home/Downloads")).count == 4)478        let done = try await WorkflowRunner(policy: SafetyPolicy(home: s.path("home")), trasher: FakeTrasher(bin: s.dir("bin")), home: s.path("home"))479            .run(w, reviewer: AutoReviewer(approve: true))480        #expect(done.report?.count(.movedToTrash) == 2 && done.wantsReport && !done.cancelled)481        #expect(Set(try FileManager.default.contentsOfDirectory(atPath: s.path("home/Downloads"))) == ["a (1).bin", "b.bin"])482        #expect(done.events.count == 5)483    }484}485
Files main
Menu

Theme