Repository Public
1// SP Notes iOS2// File: Tests/InboxTests.swift3// Description: Inbox triage against the fake backend of the Core: file / archive / delete / turn into a task with the server's4// undo when online; offline the action is done on the device and queued (never lost), can still be undone, and5// reaches the server at the next sync. Also the list's sources and its wording.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Testing11import SPNotesCore12@testable import SPNotes1314/// The application model's local operations and a fake-backed repository over the SAME store: what the app has in production15/// (`AppModel` + `app.repositories`), with the fake server in place of the real one.16@MainActor17private final class InboxWorld {18 let fake = FakeBackend()19 let app: AppModel20 let device: FakeDevice21 var online = true22 let model: InboxModel2324 init() throws {25 app = try ShellFixtures.app()26 device = try FakeDevice(fake: fake, store: app.store)27 let box = OnlineBox()28 model = InboxModel(repository: device.repositories.inbox, local: .live(app), canReachServer: { box.online })29 self.box = box30 }3132 private let box: OnlineBox33 @MainActor final class OnlineBox { var online = true }3435 func setOffline(_ offline: Bool) {36 fake.setOffline(offline)37 // the network monitor still says "online" in a test: the model must cope with a server that does not answer38 box.online = true39 }40 /// Signed out or airplane mode known to the app: the server is not even asked.41 func setUnreachableKnown(_ value: Bool) { box.online = !value }4243 func capture(_ title: String) async -> String {44 let id = fake.webCreatePage(title: title, inbox: true)45 _ = await device.sync()46 return id47 }4849 func entry(_ id: String) throws -> InboxEntry { try #require(model.entries.first { $0.id == id }) }50 func shutdown() async { await device.engine.stop(); fake.shutdown() }51}5253@Suite("Boîte de réception", .serialized)54@MainActor55struct InboxModelTests {56 @Test func theListIsTheServersMergedWithTheDevice() async throws {57 let world = try InboxWorld()58 let first = await world.capture("Idée de cadeau")59 let second = await world.capture("Article à lire")60 // a capture made on the device (1.0 path), not on the server yet61 let local = try await world.app.createNote(title: "Capturée hors ligne")62 _ = try await world.app.store.setInbox(id: local, at: Date())63 // a capture the server lists that this device has not pulled yet64 let remoteOnly = world.fake.webCreatePage(title: "Pas encore synchronisée", inbox: true)6566 await world.model.load()67 #expect(world.model.origin == .server)68 #expect(Set(world.model.entries.map(\.id)) == [first, second, local, remoteOnly])69 #expect(try world.entry(local).isDeviceOnly && world.entry(local).isOnDevice)70 #expect(try !world.entry(remoteOnly).isOnDevice)71 #expect(try world.entry(first).isOnDevice && !world.entry(first).isDeviceOnly)7273 // offline: the last list (with its date) plus the device's pages74 world.setOffline(true)75 await world.model.load()76 if case .cache = world.model.origin {} else { Issue.record("expected the cached list, got \(world.model.origin)") }77 #expect(world.model.entries.count == 4)78 await world.shutdown()79 }8081 @Test func onlineEveryActionGoesToTheServerAndCanBeUndone() async throws {82 let world = try InboxWorld()83 // the fake does not model the undo journal nor the "task" action: scripted with the server's shapes84 world.fake.stub("POST", path: "^/api/inbox/undo$", json: #"{"ok":true,"already":false}"#)85 world.fake.stub("POST", path: "^/api/inbox/[0-9a-f-]{36}$") { request in86 String(data: request.body, encoding: .utf8)?.contains(#""task""#) == true ? .json(#"{"actionId":"act-task","summary":"Task created","created":{"taskId":"t1"}}"#) : nil87 }88 let filed = await world.capture("À classer")89 let archived = await world.capture("À archiver")90 let trashed = await world.capture("À supprimer")91 let converted = await world.capture("À faire")92 await world.model.load()93 #expect(world.model.entries.count == 4)9495 let fileOutcome = try #require(await world.model.perform(.file(section: "projects"), on: try world.entry(filed)))96 #expect(fileOutcome.message == "Classée dans Projets" && !fileOutcome.queued)97 #expect(world.fake.page(filed)?.section == "projects" && world.fake.page(filed)?.inboxAt == nil)98 guard case .server(let actionId)? = fileOutcome.undo else { Issue.record("no server undo"); return }99 #expect(!actionId.isEmpty)100 #expect(!world.model.entries.contains { $0.id == filed }, "the row leaves at once")101102 #expect(try #require(await world.model.perform(.archive, on: try world.entry(archived))).message == "Capture archivée")103 #expect(world.fake.page(archived)?.archived == true)104 #expect(await world.model.perform(.trash, on: try world.entry(trashed)) != nil)105 #expect(world.fake.page(trashed)?.deletedAt != nil)106 let taskOutcome = try #require(await world.model.perform(.task, on: try world.entry(converted)))107 #expect(taskOutcome.undo == .server(actionId: "act-task") && taskOutcome.message == "Convertie en tâche")108 #expect(try await world.app.store.queuedOps().isEmpty, "online nothing is queued: the server did it")109110 // undo goes to the server's journal with the action id111 #expect(await world.model.undo(.server(actionId: actionId)))112 #expect(world.fake.count("POST", "^/api/inbox/undo$") == 1)113 #expect(world.model.notice == nil)114 await world.shutdown()115 }116117 @Test func offlineTheActionIsKeptQueuedAndSentAtTheNextSync() async throws {118 let world = try InboxWorld()119 let filed = await world.capture("Classée hors ligne")120 let archived = await world.capture("Archivée hors ligne")121 let trashed = await world.capture("Supprimée hors ligne")122 await world.model.load()123 world.setOffline(true) // the server does not answer: `RepositoryError.offline`124125 let outcome = try #require(await world.model.perform(.file(section: "documents"), on: try world.entry(filed)))126 #expect(outcome.queued, "done on the device")127 #expect(outcome.message == "Classée dans Documents — sera envoyé au retour du réseau")128 if case .local? = outcome.undo {} else { Issue.record("an offline action must still be undoable") }129 let page = try #require(try await world.app.store.summary(id: filed))130 #expect(page.inboxAt == nil && page.section == "documents")131 #expect(try await world.app.store.queuedOps().contains { $0.kind == "triage" && $0.targetId == filed }, "the 1.0 queued triage carries it")132133 #expect(try #require(await world.model.perform(.archive, on: try world.entry(archived))).queued)134 #expect(try await world.app.store.summary(id: archived)?.archived == true)135 #expect(try #require(await world.model.perform(.trash, on: try world.entry(trashed))).queued)136 #expect(try await world.app.store.summary(id: trashed)?.deletedAt != nil)137 #expect(world.model.entries.isEmpty && world.model.notice == nil)138 // the server knows nothing yet139 #expect(world.fake.page(filed)?.inboxAt != nil && world.fake.page(archived)?.archived == false)140141 // the list rebuilt offline does not bring the triaged captures back142 await world.model.load()143 #expect(world.model.entries.isEmpty)144145 // network back: everything is delivered146 world.setOffline(false)147 #expect(await world.device.sync() == .completed)148 #expect(await world.device.sync() == .completed)149 #expect(world.fake.page(filed)?.inboxAt == nil && world.fake.page(filed)?.section == "documents")150 #expect(world.fake.page(archived)?.archived == true)151 #expect(world.fake.page(trashed)?.deletedAt != nil)152 #expect(try await world.app.store.queuedOps().isEmpty)153 await world.shutdown()154 }155156 @Test func anOfflineActionCanBeUndoneBeforeItLeaves() async throws {157 let world = try InboxWorld()158 let filed = await world.capture("Classée puis annulée")159 let archived = await world.capture("Archivée puis annulée")160 let trashed = await world.capture("Supprimée puis annulée")161 await world.model.load()162 world.setUnreachableKnown(true) // airplane mode known to the app: the server is not asked at all163 let before = world.fake.requests.count164165 for (id, triage) in [(filed, InboxTriage.file(section: "research")), (archived, .archive), (trashed, .trash)] {166 let outcome = try #require(await world.model.perform(triage, on: try world.entry(id)))167 #expect(outcome.queued)168 #expect(await world.model.undo(try #require(outcome.undo)))169 let page = try #require(try await world.app.store.summary(id: id))170 #expect(page.inboxAt != nil && page.section == "notes" && !page.archived && page.deletedAt == nil, "\(triage) undone")171 }172 #expect(world.fake.requests.count == before, "no request was attempted")173 #expect(try await world.app.store.queuedOps().filter { $0.kind == "triage" }.isEmpty, "the queued filing was withdrawn")174 #expect(Set(world.model.entries.map(\.id)) == [filed, archived, trashed], "they are back in the inbox")175176 // after the sync the server still has them in the inbox: nothing wrong was sent177 world.setUnreachableKnown(false)178 #expect(await world.device.sync() == .completed)179 #expect(await world.device.sync() == .completed)180 #expect(world.fake.page(filed)?.inboxAt != nil && world.fake.page(archived)?.archived == false && world.fake.page(trashed)?.deletedAt == nil)181 await world.shutdown()182 }183184 @Test func offlineConversionCreatesTheTaskInTheOutboxAndFilesTheCapture() async throws {185 let world = try InboxWorld()186 let id = await world.capture("Appeler le notaire")187 await world.model.load()188 world.setOffline(true)189 let outcome = try #require(await world.model.perform(.task, on: try world.entry(id)))190 #expect(outcome.queued && outcome.message.hasPrefix("Convertie en tâche"))191 let tasks = try await world.app.repositories.tasks.list(.open)192 #expect(tasks.map(\.title) == ["Appeler le notaire"] && tasks.first?.pageId == id)193 #expect(try await world.app.store.summary(id: id)?.inboxAt == nil)194 // undo removes the task and puts the capture back195 #expect(await world.model.undo(try #require(outcome.undo)))196 #expect(try await world.app.repositories.tasks.list(.all).isEmpty)197 #expect(try await world.app.store.summary(id: id)?.inboxAt != nil)198199 // done again and synced: the server gets the task (once) and the filing200 _ = try #require(await world.model.perform(.task, on: try world.entry(id)))201 world.setOffline(false)202 #expect(await world.device.sync() == .completed)203 #expect(await world.device.sync() == .completed)204 #expect(world.fake.allTasks.map(\.title) == ["Appeler le notaire"])205 #expect(world.fake.allTasks.first?.pageId == id)206 #expect(world.fake.page(id)?.inboxAt == nil)207 await world.shutdown()208 }209210 @Test func aCaptureThatIsNotOnTheDeviceCannotBeTriagedOffline() async throws {211 let world = try InboxWorld()212 let remoteOnly = world.fake.webCreatePage(title: "Seulement sur le serveur", inbox: true)213 await world.model.load()214 world.setOffline(true)215 #expect(await world.model.perform(.archive, on: try world.entry(remoteOnly)) == nil)216 #expect(world.model.notice?.contains("pas encore sur cet appareil") == true, "said plainly, nothing pretended")217 #expect(world.model.entries.contains { $0.id == remoteOnly }, "the row stays")218 await world.shutdown()219 }220221 @Test func aServerRefusalIsReportedAndTheListReloaded() async throws {222 let world = try InboxWorld()223 let id = await world.capture("Déjà triée ailleurs")224 await world.model.load()225 let entry = try world.entry(id)226 // triaged from the web in the meantime227 world.fake.webPatchMeta(id, ["archived": true])228 world.fake.inject(.status(409, code: "not_in_inbox"), method: "POST", path: "^/api/inbox/")229 #expect(await world.model.perform(.file(section: "notes"), on: entry) == nil)230 #expect(world.model.notice?.isEmpty == false)231 #expect(try await world.app.store.queuedOps().isEmpty, "a refusal is not an offline case: nothing is queued behind the server's back")232 await world.shutdown()233 }234235 @Test func wordingSaysWhereTheListComesFrom() {236 #expect(InboxText.summary(count: 0) == "Rien à trier.")237 #expect(InboxText.summary(count: 1) == "1 capture à trier")238 #expect(InboxText.summary(count: 4) == "4 captures à trier")239 #expect(InboxText.origin(.server, signedIn: true) == nil)240 #expect(InboxText.origin(.device, signedIn: true) == "Hors ligne : les captures de cet appareil")241 #expect(InboxText.origin(.device, signedIn: false) == "Les captures de cet appareil")242 #expect(InboxText.origin(.cache(Date(timeIntervalSinceNow: -7200)), signedIn: true)?.hasPrefix("Liste du serveur mise à jour") == true)243 #expect(InboxModel.message(.task, queued: false) == "Convertie en tâche")244 #expect(InboxModel.message(.trash, queued: true) == "Déplacée dans la corbeille — sera envoyé au retour du réseau")245 #expect(InboxText.kindLabel("audio")?.symbol == "waveform" && InboxText.kindLabel("note") == nil)246 #expect(InboxTriage.file(section: "research").serverAction == .keep(section: .research))247 #expect(InboxTriage.task.serverAction == .task())248 }249}250