Repository Public
1// SP Drive iOS2// File: Tests/NextTests.swift3// Description: App-hosted tests of the 2.0 pieces that need UIKit: PDF annotation flattened and saved as a new version through the4// sync engine, the widgets' snapshot, and deep links.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import PDFKit10import PencilKit11import Testing12import UIKit13@testable import SPDrive1415@Suite(.enabled(if: TestBackend.available, "disposable backend not configured"), .serialized)16@MainActor17struct NextTests {18 func signedInModel() async throws -> AppModel {19 let model = try #require(AppDelegate.current?.model)20 #expect(await TestBackend.eventually(40) { model.phase == .signedIn && model.store.rootID != nil })21 return model22 }2324 /// Red channel dominance at a point given in page points from the top left.25 func isInk(_ document: PDFDocument, page index: Int, x: CGFloat, y: CGFloat) throws -> Bool {26 let page = try #require(document.page(at: index))27 let box = page.bounds(for: .mediaBox)28 let image = page.thumbnail(of: box.size, for: .mediaBox)29 let cg = try #require(image.cgImage)30 let sx = CGFloat(cg.width) / box.width, sy = CGFloat(cg.height) / box.height31 var pixel = [UInt8](repeating: 0, count: 4)32 let ctx = try #require(CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))33 ctx.draw(cg, in: CGRect(x: -x * sx, y: -(CGFloat(cg.height) - y * sy), width: CGFloat(cg.width), height: CGFloat(cg.height)))34 return pixel[0] > 150 && pixel[1] < 110 && pixel[2] < 11035 }3637 @Test func pencilStrokesAreFlattenedAndSavedAsANewVersion() async throws {38 let model = try await signedInModel()39 let api = TestBackend.api()40 let ws = try await api.createFolder(parentID: try await api.rootID(), name: "annot-\(UUID().uuidString.prefix(8))", onConflict: .rename)41 // a two-page searchable PDF (the scan pipeline on generated pages)42 let source = FileManager.default.temporaryDirectory.appendingPathComponent("annot-\(UUID().uuidString).pdf")43 try ScanPipeline.makePDF(pages: ScanFixtures.invoice(), to: source, options: .init(ocr: true))44 let seeded = try await TestBackend.upload(try Data(contentsOf: source), named: "facture.pdf", into: ws.id, api: api)45 await model.engine.sync()46 #expect(model.store.item(seeded.id)?.versionCount == 1)47 let local = try await model.engine.localCopy(of: seeded.id)4849 // one red stroke on page 1, in a blank area (page space, origin top left)50 let points = stride(from: 100.0, through: 300.0, by: 8).map { PKStrokePoint(location: CGPoint(x: $0, y: 240), timeOffset: 0, size: CGSize(width: 8, height: 8), opacity: 1, force: 1, azimuth: 0, altitude: .pi / 2) }51 let drawing = PKDrawing(strokes: [PKStroke(ink: PKInk(.pen, color: .red), path: PKStrokePath(controlPoints: points, creationDate: .now))])52 let out = FileManager.default.temporaryDirectory.appendingPathComponent("annotated-\(UUID().uuidString).pdf")53 #expect(try PDFInk.flatten(local, drawings: [0: PKDrawing(), 1: PKDrawing()], to: out) == false, "nothing drawn: nothing written")54 #expect(try PDFInk.flatten(local, drawings: [0: drawing], to: out))5556 let before = try #require(PDFDocument(url: local)), after = try #require(PDFDocument(url: out))57 #expect(after.pageCount == 2)58 #expect(try isInk(before, page: 0, x: 200, y: 240) == false)59 #expect(try isInk(after, page: 0, x: 200, y: 240), "the stroke is where it was drawn")60 #expect(try isInk(after, page: 0, x: 200, y: 400) == false)61 #expect(try isInk(after, page: 1, x: 200, y: 240) == false, "the other page is untouched")62 #expect(after.string?.contains("Facture 2026-1119") == true && after.string?.contains("Conditions de paiement") == true, "the text layer survives")63 #expect(after.page(at: 0)?.annotations.isEmpty == true, "burnt in: no editable annotation left behind")6465 // saved through the engine: a new version of the same file, based on the one that was opened66 try await model.engine.replaceContent(of: seeded.id, with: out)67 let sha = try IntegrityVerifier.sha256(of: out)68 #expect(await TestBackend.eventually(40) { (try? await api.fileDetail(id: seeded.id))?.item.sha256 == sha })69 let detail = try await api.fileDetail(id: seeded.id)70 #expect(detail.versions.count == 2 && detail.versions.contains { $0.sha256 == seeded.sha256 }, "the original stays in the history")71 #expect(await TestBackend.eventually(20) { model.store.item(seeded.id)?.versionCount == 2 && model.store.localState(seeded.id)?.dirty == false })72 #expect(model.store.conflicts().isEmpty)7374 // a change made elsewhere in the meantime is never overwritten by an annotation: it raises a conflict75 _ = try await DirectTransfer.upload(file: source, remote: api, store: nil, resumeKey: nil, scratch: source.appendingPathExtension("chunk")) { size in76 try await api.createUpload(parentID: ws.id, name: "facture.pdf", size: size, onConflict: .version, fileID: seeded.id, baseVersionID: nil)77 }78 let again = FileManager.default.temporaryDirectory.appendingPathComponent("annotated2-\(UUID().uuidString).pdf")79 #expect(try PDFInk.flatten(out, drawings: [1: drawing], to: again))80 try await model.engine.replaceContent(of: seeded.id, with: again) // the device has not synced: it still believes version 2 is current81 #expect(await TestBackend.eventually(40) { model.store.conflict(itemID: seeded.id) != nil })82 #expect(try await api.fileDetail(id: seeded.id).item.sha256 == IntegrityVerifier.sha256(of: source), "the Drive still holds the other device's version")83 let c = try #require(model.store.conflict(itemID: seeded.id))84 try await model.engine.resolve(c.id, choice: .keepBoth, deviceName: "Simulateur")85 #expect(await TestBackend.eventually(40) { (try? await TestBackend.children(of: ws.id, api: api).count) == 2 })86 }8788 @Test func widgetSnapshotCarriesWhatTheWidgetsShowAndNothingElse() async throws {89 let model = try await signedInModel()90 let api = TestBackend.api()91 let ws = try await api.createFolder(parentID: try await api.rootID(), name: "widget-\(UUID().uuidString.prefix(8))", onConflict: .rename)92 _ = try await TestBackend.upload(Data("pour le widget".utf8), named: "récent-widget.txt", into: ws.id, api: api)93 await model.engine.sync()94 try await model.engine.setStarred([ws.id], true)95 let dir = try #require(WidgetSnapshot.directory(group: AppGroup.identifier), "the group container is available to the app")9697 UserDefaults.standard.set(false, forKey: "lock.enabled")98 WidgetBridge.publish(store: model.store, files: model.files, quota: (1_000, 10_000), holds: ["x": .waitingForWiFi])99 let snap = try #require(WidgetSnapshot.read(from: dir))100 #expect(snap.signedIn && !snap.redacted)101 #expect(snap.recent.first?.name == "récent-widget.txt")102 #expect(snap.favoriteFolders.contains { $0.id == ws.id && $0.itemCount == 1 })103 #expect(snap.storage == .init(used: 1_000, limit: 10_000, offlineBytes: model.store.localUsage().offlineBytes))104 #expect(snap.transfers.hold == "waitingForWiFi")105 let raw = try String(contentsOf: dir.appendingPathComponent("snapshot.json"), encoding: .utf8)106 #expect(!raw.contains(TestBackend.token ?? "no-token"), "no credential in the group container")107 #expect(!raw.contains("sha256") && !raw.contains("http"))108109 // app lock on: names stay out of the widgets110 UserDefaults.standard.set(true, forKey: "lock.enabled")111 defer { UserDefaults.standard.set(false, forKey: "lock.enabled") }112 WidgetBridge.publish(store: model.store, files: model.files, quota: (1_000, 10_000), holds: [:])113 let locked = try #require(WidgetSnapshot.read(from: dir))114 #expect(locked.redacted && locked.recent.isEmpty && locked.favoriteFolders.isEmpty && locked.storage != nil)115 WidgetBridge.clear()116 #expect(WidgetSnapshot.read(from: dir) == .signedOut || WidgetSnapshot.read(from: dir)?.signedIn == false)117 try await model.engine.setStarred([ws.id], false)118 }119120 @Test func deepLinksAreParsedStrictly() {121 let id = "0b9c2f6e-1a53-4d7e-9c41-7a1f0e2b3c4d"122 #expect(AppRoute(url: URL(string: "spdrive://upload")!) == .upload)123 #expect(AppRoute(url: URL(string: "spdrive://scan")!) == .scan)124 #expect(AppRoute(url: URL(string: "spdrive://transfers")!) == .transfers)125 #expect(AppRoute(url: SPDriveLink.folder(id)) == .folder(id))126 #expect(AppRoute(url: SPDriveLink.file(id)) == .file(id))127 #expect(AppRoute(url: URL(string: "spdrive://folder/../../etc")!) == nil)128 #expect(AppRoute(url: URL(string: "spdrive://folder/'%20OR%201=1")!) == nil)129 #expect(AppRoute(url: URL(string: "spdrive://folder")!) == nil)130 #expect(AppRoute(url: URL(string: "spdrive://delete-everything")!) == nil)131 #expect(AppRoute(url: URL(string: "https://drive.spboucher.ai/upload")!) == nil)132 }133}134