SPB Git

Repository Public

PageTests.swift 20.4 KB 325 lines swift

1// SP Notes Core2// File: Tests/SPNotesStoreTests/PageTests.swift3// Description: Local page mutations: CRUD, dirty-flag transitions, base copy lifecycle, meta fields, tags,4//              trash/restore of subtrees, move cycles, purge, duplicate, queries for the UI.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Testing10@testable import SPNotesStore1112@Suite struct PageTests {13    @Test func createPageIsPendingAndNeedsCreate() async throws {14        let store = try NotesStore.inMemory()15        let page = try await store.createPage(draft("Hello", "first words", tags: ["#Idea", " idea ", "Two"]))16        #expect(page.id == page.id.lowercased() && UUID(uuidString: page.id) != nil)17        #expect(page.needsCreate && page.dirtyContent && page.tagsDirty && page.dirtyMeta.isEmpty)18        #expect(page.syncState == .pending && page.serverVersion == 0 && page.editSeq == 1)19        #expect(page.tags == ["idea", "two"] && page.section == "notes" && page.position == 1)20        #expect(page.plainText == "first words" && page.wordCount == 2)21        #expect(try await store.pageBase(id: page.id) == nil) // nothing on the server yet: no base22        let second = try await store.createPage(draft("Second", id: "ABCDEF00-0000-4000-8000-000000000001"))23        #expect(second.id == "abcdef00-0000-4000-8000-000000000001" && second.position == 2)24        let child = try await store.createPage(draft("Child", parent: second.id, section: nil))25        #expect(child.parentId == second.id && child.position == 1)26        await #expect(throws: StoreError.self) { try await store.createPage(draft("Dup", id: second.id)) }27        await #expect(throws: StoreError.self) { try await store.createPage(draft("Orphan", parent: "missing")) }28        await #expect(throws: StoreError.self) { try await store.createPage(draft("Bad", properties: "[]")) }29        #expect(try await store.pageCount() == 3)30    }3132    @Test func dirtyFlagsAndBaseCopyLifecycle() async throws {33        let store = try NotesStore.inMemory()34        try await store.applyRemote(pages: [remote("p", "Title", "server body", version: 3, properties: #"{"k":1}"#)])35        var page = try await store.must("p")36        #expect(!page.isDirty && page.syncState == .synced && page.serverVersion == 3 && page.editSeq == 0)37        #expect(try await store.pageBase(id: "p") == nil)3839        // Saving identical bytes is a no-op.40        #expect(try await store.edit("p", title: "Title", text: "server body") == false)41        #expect(try await store.must("p") == page)4243        // First content edit: base copy captured, dirty, pending.44        #expect(try await store.edit("p", text: "local one"))45        page = try await store.must("p")46        #expect(page.dirtyContent && !page.needsCreate && page.syncState == .pending && page.editSeq == 1 && page.serverVersion == 3)47        #expect(page.updatedAt > epoch && page.localUpdatedAt == page.updatedAt)48        let base = PageBase(title: "Title", content: doc("server body"), properties: Data(#"{"k":1}"#.utf8), version: 3)49        #expect(try await store.pageBase(id: "p") == base)5051        // Further edits keep the ORIGINAL base.52        try await store.edit("p", title: "New title", text: "local two")53        try await store.setProperties(id: "p", properties: Data(#"{"k":2,"favorite":true}"#.utf8))54        page = try await store.must("p")55        #expect(page.editSeq == 3 && page.favorite && page.title == "New title")56        #expect(try await store.pageBase(id: "p") == base)5758        // Meta and tag edits do not create a base on a clean page.59        try await store.applyRemote(pages: [remote("q", "Other", "x", version: 1)])60        try await store.setPinned(id: "q", true)61        try await store.setTags(id: "q", names: ["a"])62        let other = try await store.must("q")63        #expect(other.dirtyMeta == [.pinned] && other.tagsDirty && !other.dirtyContent && other.syncState == .pending)64        #expect(other.updatedAt == epoch) // meta edits do not touch updatedAt65        #expect(try await store.pageBase(id: "q") == nil)6667        // Push acknowledged with no concurrent edit: clean again, base dropped.68        let pushedAt = Date(timeIntervalSince1970: 1_790_000_000)69        try await store.markPushed(id: "p", serverVersion: 4, updatedAt: pushedAt, pushedEditSeq: 3)70        page = try await store.must("p")71        #expect(!page.isDirty && page.syncState == .synced && page.serverVersion == 4 && page.updatedAt == pushedAt)72        #expect(try await store.pageBase(id: "p") == nil)73        #expect(try await store.counts().pending == 1)7475        // A new edit after the push captures the NEW synced copy as base.76        try await store.edit("p", text: "local three")77        #expect(try await store.pageBase(id: "p")?.version == 4)78        #expect(try await store.pageBase(id: "p")?.content == doc("local two"))79        #expect(try await store.pageBase(id: "p")?.title == "New title")80    }8182    @Test func propertiesMirrorsAndNoOps() async throws {83        let store = try NotesStore.inMemory()84        try await store.applyRemote(pages: [remote("p", "T", "b", properties: #"{"a":1,"b":[1,2]}"#)])85        // Same object with another key order: nothing to do.86        #expect(try await store.setProperties(id: "p", properties: Data(#"{"b":[1,2],"a":1}"#.utf8)) == false)87        #expect(try await store.must("p").isDirty == false)88        #expect(try await store.setFavorite(id: "p", true))89        #expect(try await store.setFavorite(id: "p", true) == false)90        #expect(try await store.setFolder(id: "p", true))91        var page = try await store.must("p")92        #expect(page.favorite && page.isFolder && page.dirtyContent && page.editSeq == 2)93        let object = try JSONSerialization.jsonObject(with: page.properties) as? [String: Any]94        #expect(object?["favorite"] as? Bool == true && object?["folder"] as? Bool == true && object?["a"] as? Int == 1)95        #expect(try await store.pageBase(id: "p")?.properties == Data(#"{"a":1,"b":[1,2]}"#.utf8))96        try await store.setFavorite(id: "p", false)97        page = try await store.must("p")98        #expect(!page.favorite && page.isFolder)99        // Flags passed by the caller win over the JSON.100        try await store.setProperties(id: "p", properties: Data(#"{"z":0}"#.utf8), favorite: true, isFolder: false)101        page = try await store.must("p")102        #expect(page.favorite && !page.isFolder)103        #expect(try await store.summaries(list: .favorites).map(\.id) == ["p"])104        await #expect(throws: StoreError.notFound("page nope")) { try await store.setFavorite(id: "nope", true) }105    }106107    @Test func metaFieldsAreTrackedIndividually() async throws {108        let store = try NotesStore.inMemory()109        try await store.applyRemote(pages: [remote("p", "T", "b")])110        #expect(try await store.setPinned(id: "p", false) == false)111        #expect(try await store.setPinned(id: "p", true))112        #expect(try await store.setArchived(id: "p", true))113        #expect(try await store.setIcon(id: "p", "🔥"))114        #expect(try await store.setIcon(id: "p", "🔥") == false)115        #expect(try await store.setCover(id: "p", "cover.jpg"))116        #expect(try await store.setInbox(id: "p", at: epoch))117        let page = try await store.must("p")118        #expect(page.dirtyMeta == [.pinned, .archived, .icon, .cover, .inboxAt])119        #expect(page.pinned && page.archived && page.icon == "🔥" && page.cover == "cover.jpg" && page.inboxAt == epoch)120        #expect(page.editSeq == 5 && !page.dirtyContent && page.syncState == .pending)121        try await store.markPushed(id: "p", serverVersion: 1, updatedAt: epoch, pushedEditSeq: 5)122        #expect(try await store.must("p").dirtyMeta.isEmpty)123        #expect(try await store.must("p").syncState == .synced)124    }125126    @Test func tagsAreNormalisedLikeTheServer() async throws {127        #expect(NotesStore.normalizeTags(["  #Work ", "work", "##Été", "", "#", String(repeating: "x", count: 60)])128            == ["work", "été", String(repeating: "x", count: 40)])129        #expect(NotesStore.normalizeTags((0..<30).map { "t\($0)" }).count == 20)130131        let store = try NotesStore.inMemory()132        try await store.applyRemote(pages: [remote("p", "T", "b", tags: ["old"]), remote("q", "U", "c", tags: ["old"])],133                                    tags: [RemoteTag(name: "old", color: "#111"), RemoteTag(name: "unused", color: nil)])134        #expect(try await store.tags() == [TagInfo(name: "old", color: "#111", count: 2), TagInfo(name: "unused", color: nil, count: 0)])135        #expect(try await store.setTags(id: "p", names: ["OLD"]) == false) // same set after normalisation136        #expect(try await store.setTags(id: "p", names: ["#New", "old "]))137        let page = try await store.must("p")138        #expect(page.tags == ["new", "old"] && page.tagsDirty && !page.dirtyContent)139        #expect(try await store.tags().map(\.name) == ["new", "old", "unused"])140        #expect(try await store.summaries(tag: "#NEW").map(\.id) == ["p"])141        // Counts are live: trashed and archived notes do not count.142        try await store.trash(id: "q")143        #expect(try await store.tags().first { $0.name == "old" }?.count == 1)144        try await store.setArchived(id: "p", true)145        #expect(try await store.tags().first { $0.name == "old" }?.count == 0)146    }147148    /// root ─ a ─ a1 ─ a11149    ///      └ b150    private func tree(_ store: NotesStore, synced: Bool) async throws {151        if synced {152            try await store.applyRemote(pages: [153                remote("root", "Root", "r", properties: #"{"folder":true}"#), remote("a", "A", "a", parent: "root", position: 1),154                remote("a1", "A1", "a1", parent: "a"), remote("a11", "A11", "a11", parent: "a1"), remote("b", "B", "b", parent: "root", position: 2),155            ])156        } else {157            try await store.createPages([158                draft("Root", "r", id: "root", properties: #"{"folder":true}"#), draft("A", "a", id: "a", parent: "root"),159                draft("A1", "a1", id: "a1", parent: "a"), draft("A11", "a11", id: "a11", parent: "a1"), draft("B", "b", id: "b", parent: "root"),160            ])161        }162    }163164    @Test func trashAndRestoreSubtrees() async throws {165        let store = try NotesStore.inMemory()166        try await tree(store, synced: true)167        #expect(Set(try await store.trash(id: "a")) == ["a", "a1", "a11"])168        #expect(try await store.trash(id: "a").isEmpty) // already in the trash169        #expect(Set(try await store.summaries(list: .trash).map(\.id)) == ["a", "a1", "a11"])170        #expect(Set(try await store.summaries(list: .all).map(\.id)) == ["root", "b"])171        #expect(try await store.children(of: "root").map(\.id) == ["b"])172        #expect(try await store.summary(id: "root")?.hasChildren == true)173        #expect(try await store.counts().trash == 3)174        // Trash is an op, not a dirty state.175        #expect(try await store.must("a").isDirty == false)176        #expect(try await store.queuedOps().map { "\($0.kind):\($0.targetId ?? "")" } == ["trash:a"])177178        // Restoring a child restores it and its descendants only.179        #expect(Set(try await store.restore(id: "a1")) == ["a1", "a11"])180        #expect(try await store.must("a").deletedAt != nil)181        #expect(try await store.must("a11").deletedAt == nil)182        #expect(try await store.queuedOps().map { "\($0.kind):\($0.targetId ?? "")" } == ["trash:a", "restore:a1"])183        #expect(try await store.restore(id: "a1").isEmpty)184        #expect(try await store.opCount() == 2)185        await #expect(throws: StoreError.self) { try await store.trash(id: "missing") }186    }187188    @Test func trashThenRestoreCoalesces() async throws {189        let store = try NotesStore.inMemory()190        try await tree(store, synced: true)191        // Never handed to the engine: the pair cancels out.192        try await store.trash(id: "a")193        #expect(Set(try await store.restore(id: "a")) == ["a", "a1", "a11"])194        #expect(try await store.opCount() == 0)195        #expect(try await store.counts().trash == 0)196197        // A descendant was already in the trash: restore(a) also restores it on the server, so both ops are kept.198        try await store.trash(id: "a11")199        try await store.trash(id: "a")200        try await store.restore(id: "a")201        #expect(try await store.queuedOps().map { "\($0.kind):\($0.targetId ?? "")" } == ["trash:a11", "trash:a", "restore:a"])202        #expect(try await store.must("a11").deletedAt == nil)203        for op in try await store.nextOps(now: Date()) { try await store.completeOp(id: op.id) }204205        // Once the trash op was handed to the engine (possibly in flight), the restore must be queued.206        try await store.trash(id: "b")207        #expect(try await store.nextOps(now: Date()).map(\.kind) == [OpKind.trash])208        try await store.restore(id: "b")209        #expect(try await store.queuedOps().map(\.kind) == [OpKind.trash, OpKind.restore])210        // …and it is held back until the trash op is settled.211        #expect(try await store.nextOps(now: Date()).isEmpty)212    }213214    @Test func moveRejectsCyclesAndCascadesSection() async throws {215        let store = try NotesStore.inMemory()216        try await tree(store, synced: true)217        await #expect(throws: StoreError.cycle) { try await store.move(id: "a", parentId: "a") }218        await #expect(throws: StoreError.cycle) { try await store.move(id: "a", parentId: "a1") }219        await #expect(throws: StoreError.cycle) { try await store.move(id: "root", parentId: "a11") }220        await #expect(throws: StoreError.notFound("parent page ghost")) { try await store.move(id: "a", parentId: "ghost") }221        #expect(try await store.must("a").isDirty == false) // rejected moves change nothing222        #expect(try await store.move(id: "a", parentId: "root", position: 1) == false) // already there223224        try await store.applyRemote(pages: [remote("docs", "Docs", "d", section: "documents")])225        #expect(try await store.move(id: "a", parentId: "docs"))226        let a = try await store.must("a")227        #expect(a.parentId == "docs" && a.section == "documents" && a.dirtyMeta == [.parentId, .section] && a.position == 1)228        // Descendants follow the section.229        #expect(try await store.must("a11").section == "documents")230        #expect(try await store.must("a11").dirtyMeta == [.section])231        #expect(try await store.must("b").section == "notes")232        #expect(try await store.children(of: "docs").map(\.id) == ["a"])233        #expect(try await store.ancestors(of: "a11").map(\.id) == ["a1", "a", "docs"])234        // To the root of another section, at an explicit position.235        #expect(try await store.move(id: "a1", parentId: nil, section: "projects", position: 7.5))236        let a1 = try await store.must("a1")237        #expect(a1.parentId == nil && a1.section == "projects" && a1.position == 7.5 && a1.dirtyMeta == [.parentId, .section, .position])238        #expect(try await store.children(of: nil, section: "projects").map(\.id) == ["a1"])239    }240241    @Test func purgeOfNeverPushedPagesLeavesNoTrace() async throws {242        let store = try NotesStore.inMemory()243        try await tree(store, synced: false)244        try await store.trash(id: "a")245        try await store.snapshot(pageId: "a1", reason: "x")246        try await store.addLocalAttachment(id: "att", pageId: "a1", filename: "f", mime: "m", size: 1, sha256: nil, localPath: "x/f")247        #expect(try await store.opCount() == 1)248        let result = try await store.purge(id: "a")249        #expect(Set(result.pageIds) == ["a", "a1", "a11"] && result.orphanedFiles == ["x/f"])250        #expect(try await store.opCount() == 0) // the page never existed for the server: no op at all251        #expect(try await store.pageCount() == 2)252        #expect(try await store.search(query: "a11", filters: SearchFilters(includeTrash: true)).isEmpty)253        #expect(try await store.localVersions(pageId: "a1").isEmpty)254        #expect(try await store.attachment(id: "att") == nil)255        #expect(try await store.debugValue("SELECT count(*) FROM pages_fts") == "2")256        #expect(try await store.integrityCheck().isEmpty)257    }258259    @Test func purgeOfSyncedPagesQueuesOps() async throws {260        let store = try NotesStore.inMemory()261        try await tree(store, synced: true)262        try await store.trash(id: "a")263        // A page created offline under the purged subtree, and a page moved into it locally.264        try await store.createPage(draft("Local", "l", id: "local", parent: "a1"))265        try await store.move(id: "b", parentId: "a")266        let result = try await store.purge(id: "a")267        #expect(Set(result.pageIds) == ["a", "a1", "a11", "local", "b"])268        // One op per page the server knows (its purge removes a single row, it does not cascade); none for the page never pushed.269        #expect(Set(try await store.queuedOps().map { "\($0.kind):\($0.targetId ?? "")" }) == ["purge:a", "purge:a1", "purge:a11", "purge:b"])270        #expect(try await store.pageCount() == 1)271    }272273    @Test func duplicateAndMarkOpened() async throws {274        let store = try NotesStore.inMemory()275        try await store.applyRemote(pages: [276            remote("p", "Original", "some body", tags: ["t"], properties: #"{"favorite":true}"#, pinned: true, icon: "📄", position: 1),277            remote("n", "Next", "n", position: 2),278        ])279        let copy = try await store.duplicate(id: "p")280        #expect(copy.id != "p" && copy.title == "Original (copy)" && copy.content == doc("some body") && copy.tags == ["t"])281        #expect(copy.needsCreate && copy.favorite && !copy.pinned && copy.icon == "📄" && copy.position == 1.5)282        #expect(try await store.search(query: "original").count == 2)283        #expect(try await store.must("p").isDirty == false)284285        let opened = Date(timeIntervalSince1970: 1_800_000_000)286        try await store.markOpened(id: "n", at: opened)287        let next = try await store.must("n")288        #expect(next.lastOpenedAt == opened && !next.isDirty && next.editSeq == 0 && next.syncState == .synced)289        // "recent" orders by max(updatedAt, lastOpenedAt).290        #expect(try await store.summaries(list: .recent).first?.id == "n")291        #expect(try await store.summaries(list: .all).first?.id == copy.id)292    }293294    @Test func listsCountsAndSummaries() async throws {295        let store = try NotesStore.inMemory()296        let t = { (offset: Double) in epoch.addingTimeInterval(offset) }297        try await store.applyRemote(pages: [298            remote("f", "Folder", "", properties: #"{"folder":true}"#, position: 1, updatedAt: t(1)),299            remote("n1", "One", "one body", parent: "f", tags: ["x", "a"], pinned: true, position: 2, updatedAt: t(2)),300            remote("n2", "Two", "two body", parent: "f", properties: #"{"favorite":true}"#, position: 1, updatedAt: t(3)),301            remote("ar", "Archived", "", archived: true, updatedAt: t(4)),302            remote("tr", "Trashed", "", updatedAt: t(5), deletedAt: t(6)),303            remote("d1", "Doc", "", section: "documents", updatedAt: t(7)),304        ])305        try await store.setInbox(id: "d1", at: t(8))306        #expect(try await store.summaries(list: .all).map(\.id) == ["d1", "n2", "n1", "f"])307        #expect(try await store.summaries(list: .all, section: "notes", limit: 2, offset: 1).map(\.id) == ["n1", "f"])308        #expect(try await store.summaries(list: .pinned).map(\.id) == ["n1"])309        #expect(try await store.summaries(list: .favorites).map(\.id) == ["n2"])310        #expect(try await store.summaries(list: .inbox).map(\.id) == ["d1"])311        #expect(try await store.summaries(list: .archived).map(\.id) == ["ar"])312        #expect(try await store.summaries(list: .trash).map(\.id) == ["tr"])313        #expect(try await store.counts() == ListCounts(all: 4, pinned: 1, favorites: 1, inbox: 1, archived: 1, trash: 1, pending: 1, conflicts: 0))314        #expect(try await store.children(of: "f").map(\.id) == ["n2", "n1"]) // by position315        #expect(try await store.children(of: nil, section: "notes").map(\.id) == ["f"])316        #expect(try await store.children(of: nil, section: "notes", includeArchived: true).map(\.id) == ["ar", "f"])317        #expect(try await store.folderTree().map(\.id) == ["f"])318        let summary = try #require(try await store.summary(id: "n1"))319        #expect(summary.title == "One" && summary.preview == "one body" && summary.tags == ["a", "x"] && summary.pinned && !summary.favorite)320        #expect(summary.parentId == "f" && summary.section == "notes" && summary.syncState == .synced && !summary.hasChildren && !summary.isFolder)321        let folder = try #require(try await store.summary(id: "f"))322        #expect(folder.isFolder && folder.hasChildren)323    }324}325
Files main
Menu

Theme