Repository Public
1// SP Notes iOS2// File: Tests/CaptureTests.swift3// Description: The capture model: each kind lands in the inbox with its kind, offline first and exactly once on the server (fake4// backend), shared items become captures, the ledger that keeps a capture in the local inbox, and Quick Capture5// without its view (modes, kinds, drafts, signature motion under Reduce Motion).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import SwiftUI11import Testing12import SPNotesCore13import SPNotesDesign14@testable import SPNotes1516/// App models for the capture and voice tests: local only, or signed in against a fake backend.17@MainActor18enum CaptureTestSupport {19 static func localModel() throws -> (AppModel, URL) {20 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-capture-\(UUID().uuidString)", isDirectory: true)21 return (try AppModel(configuration: AppConfiguration(api: .production(appVersion: "2.0.0"), dataDirectory: directory, inMemoryStore: true)), directory)22 }2324 /// A signed-in model whose requests are answered by `fake`.25 static func model(on fake: FakeBackend) throws -> AppModel {26 AppModel.testSessionConfiguration = { FakeBackend.sessionConfiguration() }27 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-capture-\(UUID().uuidString)", isDirectory: true)28 var api = APIConfiguration(baseURL: fake.baseURL, userAgent: "tests")29 api.requestTimeout = 530 let app = try AppModel(configuration: AppConfiguration(api: api, dataDirectory: directory, inMemoryStore: true, injectedToken: fake.issueToken()))31 #expect(app.session == .signedIn)32 return app33 }3435 static func document(_ app: AppModel, _ id: String) async throws -> NoteDocument {36 try NoteDocument(json: try #require(try await app.store.page(id: id)).content)37 }3839 static func pngFile(named name: String = "photo.png") throws -> URL {40 // the smallest PNG: 1 × 1, transparent41 let data = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==")!42 return try MediaTemp.write(data, named: name)43 }44}4546@MainActor47@Suite("Capture — modèle")48struct CaptureModelTests {49 @Test func everyKindLandsInTheInboxWithItsKind() async throws {50 let (app, _) = try CaptureTestSupport.localModel()51 let kinds = [CaptureKindName.note, CaptureKindName.tasks, CaptureKindName.link, CaptureKindName.photo, CaptureKindName.file,52 CaptureKindName.audio, CaptureKindName.screenshot, CaptureKindName.selection, CaptureKindName.document]53 var ids: [String: String] = [:]54 for kind in kinds {55 let draft = CaptureDraft(kind: kind, text: "Capture \(kind)", url: kind == CaptureKindName.link ? "https://example.com/a" : nil)56 ids[kind] = try await app.capture(draft)57 }58 let inbox = try await app.store.summaries(list: .inbox)59 #expect(Set(inbox.map(\.id)) == Set(ids.values))60 for (kind, id) in ids {61 let page = try #require(try await app.store.page(id: id))62 #expect(page.captureKind == kind)63 #expect(page.inboxAt != nil)64 #expect(page.section == "notes" && page.parentId == nil)65 #expect(page.needsCreate, "written locally, waiting for the synchronisation")66 #expect(await app.captureKind(of: id) == kind)67 #expect(try NoteDocument(json: page.content).schemaViolations().isEmpty)68 }69 #expect(try await app.store.counts().inbox == kinds.count)70 }7172 @Test func theContentFollowsTheKind() async throws {73 let (app, _) = try CaptureTestSupport.localModel()7475 let note = try await app.capture(CaptureDraft(kind: CaptureKindName.note, text: "Appeler la banque demain\nDemander la prolongation du taux"))76 let notePage = try #require(try await app.store.page(id: note))77 #expect(notePage.title == "Appeler la banque demain")78 #expect(notePage.plainText.contains("Demander la prolongation du taux"))7980 let link = try await app.capture(CaptureDraft(kind: CaptureKindName.link, text: "À lire ce soir.", url: "https://www.example.com/article?id=3"))81 let linkPage = try #require(try await app.store.page(id: link))82 #expect(linkPage.title == "example.com")83 #expect(String(decoding: linkPage.content, as: UTF8.self).contains(#""href":"https://www.example.com/article?id=3""#))84 #expect(linkPage.plainText.contains("À lire ce soir."))8586 // a link capture finds the address in the text when no url is given87 let pasted = try await app.capture(CaptureDraft(kind: CaptureKindName.link, text: "Voir https://spboucher.ai/research pour la suite"))88 let pastedPage = try #require(try await app.store.page(id: pasted))89 #expect(String(decoding: pastedPage.content, as: UTF8.self).contains(#""href":"https://spboucher.ai/research""#))9091 let tasks = try await app.capture(CaptureDraft(kind: CaptureKindName.tasks, text: "Pain\n- [ ] Lait\n* Œufs"), title: "Épicerie")92 let taskDocument = try await CaptureTestSupport.document(app, tasks.pageId)93 #expect(taskDocument.taskItems().total == 3 && taskDocument.taskItems().checked == 0)94 #expect(try #require(try await app.store.page(id: tasks.pageId)).title == "Épicerie")9596 let idea = try await app.capture(CaptureDraft(kind: CaptureKindName.note, text: "Un atlas des loyers"), title: nil, icon: CaptureKinds.ideaIcon)97 #expect(try #require(try await app.store.page(id: idea.pageId)).icon == "💡")9899 let long = String(repeating: "mot ", count: 60)100 let longId = try await app.capture(CaptureDraft(kind: CaptureKindName.note, text: long))101 let longTitle = try #require(try await app.store.page(id: longId)).title102 #expect(longTitle.count <= 81 && longTitle.hasSuffix("…"))103 }104105 @Test func nothingToCaptureAndBadLinksAreRefusedWithoutCreatingAnything() async throws {106 let (app, _) = try CaptureTestSupport.localModel()107 await #expect(throws: CaptureError.empty) { try await app.capture(CaptureDraft(kind: CaptureKindName.note, text: " \n ")) }108 await #expect(throws: CaptureError.invalidLink) { try await app.capture(CaptureDraft(kind: CaptureKindName.link, text: "pas un lien", url: "ftp://example.com")) }109 await #expect(throws: CaptureError.invalidLink) { try await app.capture(CaptureDraft(kind: CaptureKindName.link, url: "javascript:alert(1)")) }110 #expect(try await app.store.pageCount() == 0)111 #expect(CaptureKinds.httpURL("https://example.com/x y") == nil)112 #expect(CaptureKinds.httpURL(" HTTPS://Example.com ") != nil)113 #expect(CaptureKinds.firstLink(in: "Regarde (https://example.com/a), c’est bien") == "https://example.com/a")114 }115116 @Test func filesAreAttachedAndAFailingFileNeverUndoesTheCapture() async throws {117 let (app, _) = try CaptureTestSupport.localModel()118 let photo = try CaptureTestSupport.pngFile()119 let missing = FileManager.default.temporaryDirectory.appendingPathComponent("absent-\(UUID().uuidString).pdf")120 let files = [CaptureFile(url: photo), CaptureFile(url: missing)]121 #expect(CaptureKinds.kind(forFiles: [CaptureFile(url: photo)]) == CaptureKindName.photo)122 #expect(CaptureKinds.kind(forFiles: files) == CaptureKindName.file)123 let outcome = try await app.capture(CaptureDraft(kind: CaptureKindName.photo), title: nil, files: files)124 #expect(outcome.failedFiles == 1 && outcome.created)125 let page = try #require(try await app.store.page(id: outcome.pageId))126 #expect(page.captureKind == CaptureKindName.photo && page.inboxAt != nil)127 #expect(page.title.hasPrefix("Photo · ") || page.title == "photo.png")128 let document = try NoteDocument(json: page.content)129 #expect(document.lines.first?.type == NodeType.image, "a capture made of a picture starts with the picture")130 #expect(try await app.store.attachments(pageId: outcome.pageId).count == 1)131 }132133 @Test func aClientChosenIdMakesTheCaptureIdempotent() async throws {134 let (app, _) = try CaptureTestSupport.localModel()135 let id = UUID().uuidString136 let first = try await app.capture(CaptureDraft(kind: CaptureKindName.note, text: "Une fois"), title: nil, id: id)137 let second = try await app.capture(CaptureDraft(kind: CaptureKindName.note, text: "Une fois"), title: nil, id: id.lowercased())138 #expect(first.created && !second.created)139 #expect(first.pageId == id.lowercased() && second.pageId == first.pageId)140 #expect(try await app.store.pageCount() == 1)141 }142}143144@MainActor145@Suite("Capture — hors ligne puis synchronisation (faux serveur)", .serialized)146struct CaptureSyncTests {147 @Test func anOfflineCaptureReachesTheServerExactlyOnceAndStaysInTheInbox() async throws {148 let fake = FakeBackend()149 defer { fake.shutdown() }150 let app = try CaptureTestSupport.model(on: fake)151 fake.setOffline(true)152153 let id = try await app.capture(CaptureDraft(kind: CaptureKindName.note, text: "Capturé sans réseau"))154 #expect(await app.syncAndWait() != .completed)155 #expect(fake.allPages.isEmpty)156 let offline = try #require(try await app.store.page(id: id))157 #expect(offline.inboxAt != nil && offline.captureKind == CaptureKindName.note && offline.needsCreate)158159 fake.setOffline(false)160 #expect(await app.syncAndWait() == .completed)161 #expect(fake.allPages.map(\.id) == [id], "created under its client-chosen id")162 #expect(fake.count("POST", "^/api/capture") == 0, "one creation path: the capture route is never called on top of the page creation")163164 // a lost answer and a second cycle create nothing more165 #expect(await app.syncAndWait() == .completed)166 #expect(await app.syncAndWait() == .completed)167 #expect(fake.allPages.count == 1)168 #expect(fake.page(id)?.title == "Capturé sans réseau")169170 // it is an inbox capture on the server too (the page creation carries inboxAt and captureKind), and stays one here171 #expect(fake.page(id)?.inboxAt != nil)172 let synced = try #require(try await app.store.page(id: id))173 #expect(!synced.needsCreate)174 #expect(synced.inboxAt != nil && synced.captureKind == CaptureKindName.note)175 #expect(try await app.store.summaries(list: .inbox).map(\.id) == [id])176 #expect(await app.syncAndWait() == .completed)177 #expect(try #require(try await app.store.page(id: id)).inboxAt != nil)178 #expect(fake.allPages.count == 1)179 }180181 @Test func aLostCreationAnswerDoesNotDuplicateTheCapture() async throws {182 let fake = FakeBackend()183 defer { fake.shutdown() }184 let app = try CaptureTestSupport.model(on: fake)185 fake.inject(.dropResponse, method: "POST", path: "^/api/pages$")186 let id = try await app.capture(CaptureDraft(kind: CaptureKindName.link, url: "https://example.com/unique"))187 _ = await app.syncAndWait()188 #expect(await app.syncAndWait() == .completed)189 #expect(fake.allPages.map(\.id) == [id])190 }191192 @Test func aFiledCaptureDoesNotComeBack() async throws {193 let fake = FakeBackend()194 defer { fake.shutdown() }195 let app = try CaptureTestSupport.model(on: fake)196 let id = try await app.capture(CaptureDraft(kind: CaptureKindName.note, text: "À classer"))197 #expect(await app.syncAndWait() == .completed)198 #expect(try await app.store.summaries(list: .inbox).map(\.id) == [id])199200 try await app.fileInboxItem(id, section: "projects")201 _ = await app.syncAndWait()202 let filed = try #require(try await app.store.page(id: id))203 #expect(filed.inboxAt == nil && filed.section == "projects")204 #expect(fake.allPages.count == 1)205 }206}207208@MainActor209@Suite("Capture — éléments partagés")210struct SharedCaptureTests {211 @Test func sharedItemsBecomeInboxCapturesWithTheirKindAndNeverTwice() async throws {212 let (app, directory) = try CaptureTestSupport.localModel()213 let inbox = SharedInbox(container: directory)214 let photo = try CaptureTestSupport.pngFile(named: "capture.png")215 let sources = FileManager.default.temporaryDirectory.appendingPathComponent("share-\(UUID().uuidString)", isDirectory: true)216 try FileManager.default.createDirectory(at: sources, withIntermediateDirectories: true)217 let pdf = sources.appendingPathComponent("Bail.pdf")218 try Data("%PDF-1.4 faux".utf8).write(to: pdf)219220 let text = SharedItem(createdAt: Date(timeIntervalSince1970: 1_000), text: "Une phrase partagée.")221 let link = SharedItem(createdAt: Date(timeIntervalSince1970: 2_000), title: "Article", text: "À lire", url: "https://example.com/article")222 let image = SharedItem(createdAt: Date(timeIntervalSince1970: 3_000))223 let file = SharedItem(createdAt: Date(timeIntervalSince1970: 4_000), title: "Bail signé")224 try inbox.save(text, files: [])225 try inbox.save(link, files: [])226 try inbox.save(image, files: [(name: "capture.png", source: photo)])227 try inbox.save(file, files: [(name: "Bail.pdf", source: pdf)])228229 await app.importSharedItems()230 #expect(app.banner == nil)231 #expect(inbox.pending().isEmpty)232 let captured = try await app.store.summaries(list: .inbox)233 #expect(captured.count == 4, "every shared item is in the inbox")234 // the page takes the id of the hand-off item235 let expected = [text.id: CaptureKindName.note, link.id: CaptureKindName.link, image.id: CaptureKindName.photo, file.id: CaptureKindName.file]236 for (id, kind) in expected {237 let page = try #require(try await app.store.page(id: id))238 #expect(page.captureKind == kind, "\(kind)")239 #expect(page.inboxAt?.timeIntervalSince1970 ?? 0 < 5_000, "captured when it was shared")240 }241 #expect(try #require(try await app.store.page(id: text.id)).title == "Une phrase partagée.")242 #expect(try #require(try await app.store.page(id: link.id)).title == "Article")243 #expect(try await app.store.attachments(pageId: file.id).map(\.filename) == ["Bail.pdf"])244245 // An interrupted removal: the item is still in the folder although its page exists. Nothing is created again.246 try inbox.save(link, files: [])247 try inbox.save(file, files: [(name: "Bail.pdf", source: pdf)])248 await app.importSharedItems()249 #expect(inbox.pending().isEmpty)250 #expect(try await app.store.pageCount() == 4)251 #expect(try await app.store.attachments(pageId: file.id).count == 1)252 await app.importSharedItems()253 #expect(try await app.store.pageCount() == 4)254 }255}256257@MainActor258@Suite("Capture rapide — modèle de la feuille")259struct QuickCaptureModelTests {260 private func defaults() -> UserDefaults { UserDefaults(suiteName: "capture-tests-\(UUID().uuidString)")! }261 private func model(_ mode: CaptureMode = .text, defaults: UserDefaults? = nil) -> QuickCaptureModel {262 QuickCaptureModel(mode: mode, recorder: VoiceRecorderModel(recorder: FakeRecorder(), authorizer: FakeMicrophone(.granted), sampling: nil),263 dictation: DictationModel(engine: FakeDictation(), silenceTimeout: nil), drafts: CaptureDraftStore(defaults: defaults ?? self.defaults()))264 }265266 @Test func routesNameTheModes() {267 #expect(CaptureMode(route: "audio") == .audio)268 #expect(CaptureMode(route: "Dictée") == .dictation)269 #expect(CaptureMode(route: "document") == .scan)270 #expect(CaptureMode(route: "note") == .text)271 #expect(CaptureMode(route: "inconnu") == nil && CaptureMode(route: nil) == nil)272 #expect(Set(CaptureMode.allCases.map(\.rawValue)) == ["text", "idea", "link", "photo", "scan", "audio", "dictation", "file"])273 }274275 @Test func eachModeSavesTheRightKind() throws {276 let model = model()277 #expect(!model.canSave)278 model.text = "Bonjour"279 #expect(model.canSave && model.kind == CaptureKindName.note)280 model.text = "https://example.com/seul"281 #expect(model.kind == CaptureKindName.link && model.draft.url == "https://example.com/seul", "a text that is only an address is a link")282 model.select(.idea); model.text = "Une idée"283 #expect(model.kind == CaptureKindName.note && model.icon == "💡")284 model.select(.link); model.link = "exemple"285 #expect(!model.canSave)286 model.link = "Regarde https://example.com/a pour demain"287 model.linkFieldChanged()288 #expect(model.link == "https://example.com/a" && model.text.contains("Regarde") && model.canSave && model.kind == CaptureKindName.link)289 model.select(.photo)290 #expect(!model.canSave)291 model.add(files: [try CaptureTestSupport.pngFile()])292 #expect(model.canSave && model.kind == CaptureKindName.photo && model.holdsUnsavedMedia)293 model.select(.scan)294 #expect(model.kind == CaptureKindName.document)295 model.select(.file)296 #expect(model.kind == CaptureKindName.photo, "a picture picked as a file is still a photo")297 model.select(.audio)298 #expect(model.kind == CaptureKindName.audio && !model.canSave)299 }300301 @Test func aTextCaptureIsSavedIntoTheInboxAndTheSheetIsReadyAgain() async throws {302 let (app, _) = try CaptureTestSupport.localModel()303 let store = defaults()304 let model = model(defaults: store)305 model.title = "Idée de titre"; model.text = "Le corps de la note"306 model.keepDraft()307 #expect(CaptureDraftStore(defaults: store).load()?.title == "Idée de titre")308 let id = try #require(await model.save(app: app))309 #expect(model.savedPageId == id && model.saveCount == 1 && model.title.isEmpty && model.text.isEmpty)310 #expect(CaptureDraftStore(defaults: store).load() == nil, "the draft goes once the capture exists")311 let page = try #require(try await app.store.page(id: id))312 #expect(page.title == "Idée de titre" && page.plainText.contains("Le corps de la note") && page.inboxAt != nil && page.captureKind == CaptureKindName.note)313 model.startAnother()314 #expect(model.savedPageId == nil)315 }316317 @Test func aDraftSurvivesAnAccidentalDismissal() {318 let store = defaults()319 let first = model(.idea, defaults: store)320 first.title = "Pas fini"; first.text = "à suivre"321 first.keepDraft()322 let second = model(defaults: store)323 #expect(second.restoredDraft && second.title == "Pas fini" && second.text == "à suivre" && second.mode == .idea)324 // an explicit mode wins over the draft's, the text stays325 let third = model(.dictation, defaults: store)326 #expect(third.mode == .dictation && third.text == "à suivre")327 second.discardAll()328 #expect(CaptureDraftStore(defaults: store).load() == nil)329 #expect(!model(defaults: store).restoredDraft)330 }331332 @Test func aFailedSaveKeepsEverything() async throws {333 let (app, _) = try CaptureTestSupport.localModel()334 let model = model(.link)335 model.link = "https://example.com/a"; model.title = "Titre"336 await app.store.close()337 #expect(await model.save(app: app) == nil)338 #expect(model.error != nil && model.link == "https://example.com/a" && model.title == "Titre" && model.savedPageId == nil)339 }340341 @Test func theSignatureMotionDegradesToAFadeUnderReduceMotion() {342 #expect(CaptureMotion.appearance(reduceMotion: false) == .scaleIn)343 #expect(CaptureMotion.appearance(reduceMotion: true) == .fade)344 #expect(CaptureMotion.appearDuration(reduceMotion: false) < 0.2, "sub-200 ms")345 #expect(CaptureMotion.appearDuration(reduceMotion: true) <= NVMotion.reducedMaxDuration)346 #expect(CaptureMotion.pulseExpands(reduceMotion: false) && !CaptureMotion.pulseExpands(reduceMotion: true))347 #expect(CaptureMotion.appearAnimation(reduceMotion: true) == NVMotion.animation(.fast, reduceMotion: true))348 #expect(CaptureMotion.appearAnimation(reduceMotion: true) != CaptureMotion.appearAnimation(reduceMotion: false))349 }350}351