Repository Public
1// SP Notes iOS2// File: Tests/OfflineScenarioTests.swift3// Description: The mandatory offline scenario, through the application model and the real development server (never production):4// sync, go offline, edit several notes, create one, attach a local picture, kill the app, relaunch offline — everything5// is there —, reconnect — the server receives everything, and a second device sees it.6// Runs only with TEST_RUNNER_SPNOTES_LIVE_URL and TEST_RUNNER_SPNOTES_LIVE_TOKEN (see Scripts/test-live.sh).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Testing12import UIKit13import 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("Scénario hors ligne (serveur de développement)", .enabled(if: liveURL != nil && liveToken != nil && liveURL?.host?.hasSuffix("spboucher.ai") == false), .serialized)21struct OfflineScenarioTests {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: "1.0.0"))26 api.requestTimeout = online ? 30 : 227 return AppConfiguration(api: api, dataDirectory: directory, inMemoryStore: false, injectedToken: liveToken)28 }2930 private func document(_ paragraphs: [String]) -> NoteDocument { NoteDocument(markdown: paragraphs.joined(separator: "\n\n")) }3132 private func pngData() -> Data {33 UIGraphicsImageRenderer(size: CGSize(width: 64, height: 48)).image { context in34 UIColor.systemOrange.setFill(); context.fill(CGRect(x: 0, y: 0, width: 64, height: 48))35 UIColor.white.setFill(); context.fill(CGRect(x: 8, y: 8, width: 20, height: 12))36 }.pngData()!37 }3839 @Test func nothingIsLostAcrossOfflineEditsRelaunchAndReconnection() async throws {40 let stamp = String(UUID().uuidString.prefix(8))41 let deviceA = FileManager.default.temporaryDirectory.appendingPathComponent("spn-offline-A-\(stamp)", isDirectory: true)42 let deviceB = FileManager.default.temporaryDirectory.appendingPathComponent("spn-offline-B-\(stamp)", isDirectory: true)43 defer { try? FileManager.default.removeItem(at: deviceA); try? FileManager.default.removeItem(at: deviceB) }4445 // 1–2. open the app and synchronise: two notes exist on the server and on the device46 var app = try AppModel(configuration: configuration(directory: deviceA, online: true))47 let first = try await app.createNote(title: "Scénario \(stamp) — un", document: document(["Premier paragraphe", "Deuxième paragraphe"]))48 let second = try await app.createNote(title: "Scénario \(stamp) — deux", document: document(["Texte initial"]))49 #expect(await app.syncAndWait() == .completed)50 #expect(try await app.store.page(id: first)?.isDirty == false)51 await app.store.close()5253 // 3. airplane mode54 app = try AppModel(configuration: configuration(directory: deviceA, online: false))55 // 4. modify several documents56 try await app.save(noteId: first, title: "Scénario \(stamp) — un (modifié hors ligne)", document: document(["Premier paragraphe", "Deuxième paragraphe réécrit hors ligne", "Troisième, ajouté hors ligne"]))57 try await app.save(noteId: second, title: "Scénario \(stamp) — deux", document: document(["Texte initial", "Suite écrite sans réseau"]))58 try await app.setTags(second, ["hors-ligne", stamp.lowercased()])59 try await app.setPinned(second, true)60 // 5. create a note61 let created = try await app.createNote(title: "Scénario \(stamp) — créée hors ligne", document: document(["Note née sans Internet"]))62 // 6. add a local picture63 let png = pngData()64 let node = try await app.attach(data: png, filename: "photo-\(stamp).png", mime: "image/png", to: created)65 var withImage = try NoteDocument(json: try #require(try await app.store.page(id: created)).content)66 withImage.insertBlockAtom(node, after: withImage.lines.count - 1)67 try await app.save(noteId: created, title: "Scénario \(stamp) — créée hors ligne", document: withImage)68 let attachmentId = try #require(AttachmentFiles.attachmentID(fromSource: node.stringAttr("src") ?? ""))69 #expect(await app.syncAndWait() == .offline) // the network really is unreachable; nothing was lost by trying70 // 7–8. close the app completely (a new process would start from the files alone)71 await app.store.close()7273 // 9–10. reopen without Internet: every modification is there74 app = try AppModel(configuration: configuration(directory: deviceA, online: false))75 let offlineFirst = try #require(try await app.store.page(id: first))76 #expect(offlineFirst.title == "Scénario \(stamp) — un (modifié hors ligne)")77 #expect(offlineFirst.plainText.contains("Troisième, ajouté hors ligne"))78 #expect(offlineFirst.isDirty)79 let offlineSecond = try #require(try await app.store.page(id: second))80 #expect(offlineSecond.plainText.contains("Suite écrite sans réseau"))81 #expect(offlineSecond.tags.contains("hors-ligne") && offlineSecond.pinned)82 let offlineCreated = try #require(try await app.store.page(id: created))83 #expect(offlineCreated.needsCreate && offlineCreated.plainText.contains("Note née sans Internet"))84 let attachment = try #require(try await app.store.attachment(id: attachmentId))85 #expect(attachment.state == .pendingUpload || attachment.state == .failed)86 #expect(try Data(contentsOf: app.files.url(relativePath: try #require(attachment.localPath))) == png)87 // offline search finds the offline text88 #expect(try await app.store.search(query: "réécrit hors ligne").contains { $0.page.id == first })89 await app.store.close()9091 // 11–12. network back: everything reaches the server92 app = try AppModel(configuration: configuration(directory: deviceA, online: true))93 #expect(await app.syncAndWait() == .completed)94 #expect(await app.syncAndWait() == .completed)95 for id in [first, second, created] { #expect(try await app.store.page(id: id)?.isDirty == false, "note \(id) still has unsynced changes") }96 #expect(try await app.store.conflicts().isEmpty)97 let serverFirst = try await app.api.page(id: first).page98 #expect(serverFirst.title == "Scénario \(stamp) — un (modifié hors ligne)")99 #expect(NoteDocument(node: try JSONDecoder().decode(PMNode.self, from: serverFirst.content.data)).plainText().contains("Troisième, ajouté hors ligne"))100 let serverCreated = try await app.api.page(id: created).page101 #expect(serverCreated.id == created) // the id chosen offline is the server's id: links made offline stay valid102 #expect(try await app.api.pageTags(pageID: second).contains("hors-ligne"))103 let downloaded = FileManager.default.temporaryDirectory.appendingPathComponent("spn-check-\(stamp).png")104 _ = try await app.api.downloadFile(id: attachmentId, to: downloaded)105 #expect(try Data(contentsOf: downloaded) == png)106 try? FileManager.default.removeItem(at: downloaded)107108 // a second device (another iPhone, the Mac, the web) receives it all109 let other = try AppModel(configuration: configuration(directory: deviceB, online: true))110 #expect(await other.syncAndWait() == .completed)111 #expect(try await other.store.page(id: created)?.plainText.contains("Note née sans Internet") == true)112 #expect(try await other.store.page(id: first)?.plainText.contains("Deuxième paragraphe réécrit hors ligne") == true)113 #expect(try await other.store.page(id: second)?.pinned == true)114 let received = try await other.localFile(forAttachment: attachmentId)115 #expect(try Data(contentsOf: received) == png)116117 // clean up the development server (to the trash)118 for id in [first, second, created] { try await app.trash(id) }119 #expect(await app.syncAndWait() == .completed)120 await app.store.close(); await other.store.close()121 }122}123