SPB Git

Repository Public

TasksLiveTests.swift 9.1 KB 139 lines swift

1// SP Notes iOS2// File: Tests/TasksLiveTests.swift3// Description: The offline scenario of the global task list, through the application model and the real INTEGRATION server (never4//              production): tasks are created, edited and completed without a network, the app is killed and relaunched offline5//              — everything is there —, the network returns — the server lists each task once —, a task is completed "on the6//              web" (the API, another session) — the device pulls it.7//              Runs only with TEST_RUNNER_SPNOTES_LIVE_URL and TEST_RUNNER_SPNOTES_LIVE_TOKEN (see Scripts/test-live.sh).8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation12import Testing13import SPNotesCore14@testable import SPNotes1516private let liveURL = ProcessInfo.processInfo.environment["SPNOTES_LIVE_URL"].flatMap(URL.init(string:))17private let liveToken = ProcessInfo.processInfo.environment["SPNOTES_LIVE_TOKEN"]1819@MainActor20@Suite("Tâches hors ligne (serveur d’intégration)", .enabled(if: liveURL != nil && liveToken != nil && liveURL?.host?.hasSuffix("spboucher.ai") == false), .serialized)21struct TasksLiveTests {22    private func configuration(directory: URL, online: Bool) -> AppConfiguration {23        // "Airplane mode" = a server address nothing listens on: every request fails at the transport level, like without a network.24        let url = online ? liveURL! : URL(string: "http://127.0.0.1:9")!25        var api = APIConfiguration(baseURL: url, userAgent: APIConfiguration.userAgent(appVersion: "2.0.0"))26        api.requestTimeout = online ? 30 : 227        return AppConfiguration(api: api, dataDirectory: directory, inMemoryStore: false, injectedToken: liveToken)28    }2930    /// Core 2.0 final + web 3.0: a capture made offline is an inbox capture on the SERVER after the sync (no device-local ledger).31    @Test func aCaptureMadeOfflineIsInTheServerInboxAfterTheSync() async throws {32        let stamp = String(UUID().uuidString.prefix(8))33        let device = FileManager.default.temporaryDirectory.appendingPathComponent("spn-capture-\(stamp)", isDirectory: true)34        let other = FileManager.default.temporaryDirectory.appendingPathComponent("spn-capture-B-\(stamp)", isDirectory: true)35        defer { try? FileManager.default.removeItem(at: device); try? FileManager.default.removeItem(at: other) }36        var app = try AppModel(configuration: configuration(directory: device, online: false))37        let id = try await app.capture(CaptureDraft(kind: CaptureKindName.link, text: "Capture \(stamp)", url: "https://example.com/\(stamp)"))38        #expect(await app.syncAndWait() == .offline)39        await app.store.close()40        app = try AppModel(configuration: configuration(directory: device, online: true))41        #expect(await app.syncAndWait() == .completed)42        #expect(await app.syncAndWait() == .completed)43        // the server's own inbox lists it, with its kind; and it is created once44        let inbox = try await app.api.inbox()45        #expect(inbox.filter { $0.id == id }.count == 1, "listed once by GET /api/inbox")46        let remote = try await app.api.page(id: id)47        #expect(remote.page.inboxAt != nil)48        #expect(remote.page.captureKind == CaptureKindName.link)49        // the device still has it in its inbox after the feed echo, and a second device receives it as a capture50        let local = try #require(try await app.store.page(id: id))51        #expect(local.inboxAt != nil && local.captureKind == CaptureKindName.link && !local.needsCreate)52        let second = try AppModel(configuration: configuration(directory: other, online: true))53        #expect(await second.syncAndWait() == .completed)54        let received = try #require(try await second.store.page(id: id))55        #expect(received.inboxAt != nil && received.captureKind == CaptureKindName.link)56        // tidy: file it away so the scratch inbox does not grow with every run57        try await app.trash(id)58        _ = await app.syncAndWait()59        await app.store.close(); await second.store.close()60    }6162    @Test func tasksCreatedOfflineReachTheServerOnceAndAWebCompletionIsPulled() async throws {63        let stamp = String(UUID().uuidString.prefix(8))64        let deviceA = FileManager.default.temporaryDirectory.appendingPathComponent("spn-tasks-A-\(stamp)", isDirectory: true)65        let deviceB = FileManager.default.temporaryDirectory.appendingPathComponent("spn-tasks-B-\(stamp)", isDirectory: true)66        defer { try? FileManager.default.removeItem(at: deviceA); try? FileManager.default.removeItem(at: deviceB) }6768        // the server must be a 3.x one with tasks: otherwise this scenario does not apply (said, not faked)69        var app = try AppModel(configuration: configuration(directory: deviceA, online: true))70        #expect(await app.syncAndWait() == .completed)71        let features = try #require(await app.repositories.features(), "the integration server did not answer /api/meta")72        try #require(features.has(ServerFeature.tasksV2), "the integration server does not offer tasks-v2")73        await app.store.close()7475        // 1. airplane mode: create, edit, complete, delete76        app = try AppModel(configuration: configuration(directory: deviceA, online: false))77        var tasks = TasksModel(app: app)78        await tasks.load()79        let day = TaskDue.day(TaskDue.today(), adding: 2)80        let plain = try #require(await tasks.add(title: "Tâche \(stamp) — simple"))81        let dated = try #require(await tasks.add(title: "Tâche \(stamp) — datée", due: day, priority: .high))82        let done = try #require(await tasks.add(title: "Tâche \(stamp) — faite hors ligne"))83        let removed = try #require(await tasks.add(title: "Tâche \(stamp) — supprimée hors ligne"))84        await tasks.setDone(done, true)85        await tasks.setPriority(plain, .low)86        #expect(await tasks.delete(removed) != nil)87        #expect(tasks.pending.isSuperset(of: [plain.id, dated.id, done.id]))88        #expect(await app.syncAndWait() == .offline, "the network really is unreachable; nothing was lost by trying")89        await app.store.close()9091        // 2. the app is killed and relaunched, still offline: everything is there92        app = try AppModel(configuration: configuration(directory: deviceA, online: false))93        tasks = TasksModel(app: app)94        await tasks.load()95        let mine = tasks.tasks.filter { $0.title.contains(stamp) }96        #expect(Set(mine.map(\.id)) == [plain.id, dated.id, done.id])97        #expect(mine.first { $0.id == dated.id }?.dueAt == TaskDue.noonUTC(day))98        #expect(mine.first { $0.id == done.id }?.isDone == true)99        #expect(mine.first { $0.id == plain.id }?.priority == "low")100        #expect(tasks.pending.isSuperset(of: [plain.id, dated.id, done.id]))101        await app.store.close()102103        // 3. network back: the server lists them, once each, with the ids chosen offline104        app = try AppModel(configuration: configuration(directory: deviceA, online: true))105        #expect(await app.syncAndWait() == .completed)106        #expect(await app.syncAndWait() == .completed)107        tasks = TasksModel(app: app)108        await tasks.load()109        #expect(tasks.rejected.isEmpty, "nothing was refused: \(tasks.rejected.map { $0.operation.lastError ?? "" })")110        #expect(tasks.pending.isDisjoint(with: [plain.id, dated.id, done.id]))111        let listed = try await app.api.tasks(includeDone: true).filter { $0.title.contains(stamp) }112        #expect(listed.count == 3, "each task exists once on the server: \(listed.map(\.title))")113        #expect(Set(listed.map(\.id)) == [plain.id, dated.id, done.id])114        let serverDated = try #require(listed.first { $0.id == dated.id })115        #expect(serverDated.priority == "high" && serverDated.dueAt == TaskDue.noonUTC(day), "the bare day arrived as noon UTC")116        #expect(listed.first { $0.id == done.id }?.isDone == true)117        #expect(listed.first { $0.id == plain.id }?.priority == "low")118        #expect(!listed.contains { $0.id == removed.id })119120        // 4. completed "on the web" (another session, through the API) → pulled by the device121        let web = try AppModel(configuration: configuration(directory: deviceB, online: true))122        _ = try await web.api.updateTask(id: plain.id, TaskChanges(status: .done))123        #expect(await app.syncAndWait() == .completed)124        await tasks.load()125        #expect(tasks.tasks.first { $0.id == plain.id }?.isDone == true, "the completion made elsewhere is on the device")126        // and the other device sees the same list127        #expect(await web.syncAndWait() == .completed)128        let other = TasksModel(app: web)129        await other.load()130        #expect(Set(other.tasks.filter { $0.title.contains(stamp) }.map(\.id)) == [plain.id, dated.id, done.id])131132        // clean up the integration server133        for id in [plain.id, dated.id, done.id] { if let task = tasks.tasks.first(where: { $0.id == id }) { await tasks.delete(task) } }134        #expect(await app.syncAndWait() == .completed)135        #expect(try await app.api.tasks(includeDone: true).filter { $0.title.contains(stamp) }.isEmpty)136        await app.store.close(); await web.store.close()137    }138}139
Files main
Menu

Theme