SPB Git

Repository Public

FileProviderTests.swift 6.3 KB 106 lines swift

1// SP Drive iOS2// File: Tests/FileProviderTests.swift3// Description: The File Provider extension exercised the way the Files app and other apps use it: through the file system of the domain,4//              with file coordination. Every effect is checked on the server through a second client.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import FileProvider9import Foundation10import Testing11@testable import SPDrive1213@Suite(.enabled(if: TestBackend.available, "disposable backend not configured"), .serialized)14@MainActor15struct FileProviderTests {16    /// Coordinated access, as any document-based app does.17    nonisolated static func coordinate<T: Sendable>(_ url: URL, write: Bool = false, options: NSFileCoordinator.WritingOptions = [], _ body: @escaping @Sendable (URL) throws -> T) async throws -> T {18        try await Task.detached {19            var coordError: NSError?20            var result: Result<T, Error> = .failure(CocoaError(.fileReadUnknown))21            let c = NSFileCoordinator()22            if write { c.coordinate(writingItemAt: url, options: options, error: &coordError) { u in result = Result { try body(u) } } }23            else { c.coordinate(readingItemAt: url, options: [], error: &coordError) { u in result = Result { try body(u) } } }24            if let coordError { throw coordError }25            return try result.get()26        }.value27    }2829    func signedInModel() async throws -> AppModel {30        let model = try #require(AppDelegate.current?.model)31        #expect(await TestBackend.eventually(40) { model.phase == .signedIn && model.store.rootID != nil })32        return model33    }3435    @Test func domainIsRegisteredAndServesTheDrive() async throws {36        let model = try await signedInModel()37        let api = TestBackend.api()38        let rootID = try await api.rootID()39        let ws = try await api.createFolder(parentID: rootID, name: "fp-\(UUID().uuidString.prefix(8))", onConflict: .rename)40        let original = Data("contenu d'origine".utf8)41        let seeded = try await TestBackend.upload(original, named: "note.txt", into: ws.id, api: api)4243        let domains = try await NSFileProviderManager.domains()44        let domain = try #require(domains.first, "the app registers its Files location when signed in")45        #expect(domain.displayName == "SP Drive")46        let manager = try #require(NSFileProviderManager(for: domain))47        try await manager.signalEnumerator(for: .workingSet)48        let root = try await manager.getUserVisibleURL(for: .rootContainer)49        let scoped = root.startAccessingSecurityScopedResource()50        defer { if scoped { root.stopAccessingSecurityScopedResource() } }51        let folder = root.appendingPathComponent(ws.name, isDirectory: true)5253        // 1. listing: the folder created on the server appears in the domain54        let listed = await TestBackend.eventually(60) {55            ((try? await Self.coordinate(root) { try FileManager.default.contentsOfDirectory(atPath: $0.path) }) ?? []).contains(ws.name)56        }57        #expect(listed, "the extension lists the Drive's root")58        let names = try await Self.coordinate(folder) { try FileManager.default.contentsOfDirectory(atPath: $0.path) }59        #expect(names.contains("note.txt"))6061        // 2. download on demand, verified62        let file = folder.appendingPathComponent("note.txt")63        let read = try await Self.coordinate(file) { try Data(contentsOf: $0) }64        #expect(read == original)6566        // 3. a document saved by another app into the folder reaches the Drive67        let created = folder.appendingPathComponent("créé dans Fichiers.txt")68        let createdData = Data("écrit par une autre app".utf8)69        try await Self.coordinate(created, write: true, options: .forReplacing) { try createdData.write(to: $0) }70        var createdOnServer: DriveItem?71        #expect(await TestBackend.eventually(60) {72            createdOnServer = (try? await TestBackend.children(of: ws.id, api: api))?.first { $0.name == "créé dans Fichiers.txt" }73            return createdOnServer != nil74        }, "createItem uploaded the new document")75        #expect(createdOnServer?.sha256 == IntegrityVerifier.sha256(createdData))7677        // 4. an edit of an existing document becomes a new version, the previous one stays in the history78        let edited = Data("modifié depuis une app compatible".utf8)79        try await Self.coordinate(file, write: true, options: .forMerging) { try edited.write(to: $0) }80        #expect(await TestBackend.eventually(60) { (try? await api.item(id: seeded.id, isFolder: false))?.sha256 == IntegrityVerifier.sha256(edited) }, "modifyItem uploaded the edit")81        let detail = try await api.fileDetail(id: seeded.id)82        #expect(detail.versions.count == 2)83        #expect(detail.versions.contains { $0.sha256 == IntegrityVerifier.sha256(original) })8485        // 5. the app's own mirror learns the change too (same server, separate databases)86        await model.engine.sync()87        #expect(model.store.item(seeded.id)?.sha256 == IntegrityVerifier.sha256(edited))8889        // 6. rename90        let renamed = folder.appendingPathComponent("note renommée.txt")91        try await Self.coordinate(file, write: true, options: .forMoving) { try FileManager.default.moveItem(at: $0, to: renamed) }92        #expect(await TestBackend.eventually(60) { (try? await api.item(id: seeded.id, isFolder: false))?.name == "note renommée.txt" }, "rename reached the server")9394        // 7. a change made elsewhere shows up in the domain95        _ = try await TestBackend.upload(Data("arrivé d'ailleurs".utf8), named: "depuis-un-autre-appareil.txt", into: ws.id, api: api)96        try await manager.signalEnumerator(for: .workingSet)97        #expect(await TestBackend.eventually(60) {98            ((try? await Self.coordinate(folder) { try FileManager.default.contentsOfDirectory(atPath: $0.path) }) ?? []).contains("depuis-un-autre-appareil.txt")99        }, "remote change enumerated")100101        // 8. deleting in Files sends the document to the Drive's trash: restorable, never destroyed outright102        try await Self.coordinate(renamed, write: true, options: .forDeleting) { try FileManager.default.removeItem(at: $0) }103        #expect(await TestBackend.eventually(60) { (try? await api.item(id: seeded.id, isFolder: false))?.isTrashed == true }, "deletion became a trash operation on the server")104    }105}106
Files main
Menu

Theme