SPB Git

Repository Public

NextKnowledgeFixtureTests.swift 16.2 KB 284 lines swift

1// SP Notes Core2// File: Tests/SPNotesAPITests/NextKnowledgeFixtureTests.swift3// Description: Knowledge health, brief, living blocks, semantic zoom, tags and parent cycles decode the real answers of4//              the scratch backend (group `knowledge`, recorded by Scripts/recorders/knowledge.py).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import XCTest10@testable import SPNotesAPI1112final class NextKnowledgeFixtureTests: XCTestCase {13    // MARK: health1415    func testKnowledgeHealth() throws {16        let health = try NextFixture.decode(KnowledgeHealth.self, "knowledge", "health")17        XCTAssertNotNil(health.computedAt)18        XCTAssertEqual(health.inactiveDays, 30)19        XCTAssertGreaterThanOrEqual(health.score.pages, 8)2021        XCTAssertEqual(health.orphans.count, health.orphans.items.count)22        XCTAssertEqual(health.orphans.ids, health.orphans.items.map(\.id))23        let orphan = try XCTUnwrap(health.orphans.items.first { $0.title == "Fixture · savoir · lectures" })24        XCTAssertEqual(orphan.section, "databases")25        XCTAssertNotNil(orphan.updatedAt)2627        let broken = try XCTUnwrap(health.brokenLinks.items.first { $0.title == "Fixture · savoir · revue" })28        XCTAssertEqual(broken.kind, "page")29        XCTAssertEqual(broken.reason, "missing")30        XCTAssertEqual(broken.targetId?.count, 36)31        XCTAssertEqual(broken.blockId?.count, 10, "the block that holds the link")32        XCTAssertNil(broken.targetBlockId)33        XCTAssertTrue(health.brokenLinks.ids.contains(broken.pageId))3435        let missing = try XCTUnwrap(health.missingReferences.items.first { $0.title == "Fixture · savoir · revue" })36        XCTAssertEqual(missing.reason, "missing")37        XCTAssertEqual(missing.refId.count, 36)38        XCTAssertEqual(missing.blockId, broken.blockId, "the same paragraph holds both")3940        let twins = health.potentialDuplicates.items.filter { $0.title == "Fixture · savoir · doublon" }41        XCTAssertEqual(Set(twins.compactMap(\.reason)), ["title", "content"])42        XCTAssertTrue(twins.allSatisfy { $0.pageIds.count == 2 })4344        let untitled = try XCTUnwrap(health.untitled.items.first)45        XCTAssertEqual(untitled.empty, true)46        XCTAssertEqual(untitled.section, "notes")47        XCTAssertTrue(health.untitled.ids.contains(untitled.id))48        XCTAssertTrue(health.inactiveProjects.items.isEmpty)49        XCTAssertEqual(health.inactiveProjects.count, 0)5051        XCTAssertGreaterThanOrEqual(health.openTasks.count, 3)52        XCTAssertGreaterThanOrEqual(health.openTasks.overdue, 1)53        XCTAssertGreaterThanOrEqual(health.openTasks.withoutDate, 1)54        let late = try XCTUnwrap(health.openTasks.items.first { $0.title == "Fixture · tâche en retard" })55        XCTAssertEqual(late.overdue, true)56        XCTAssertEqual(late.priority, "low")57        XCTAssertEqual(late.dueAt.map(APIDate.string(from:)), "2026-01-15T12:00:00.000Z")58        XCTAssertNotNil(late.pageId)59        let loose = try XCTUnwrap(health.openTasks.items.first { $0.title == "Fixture · tâche sans date" })60        XCTAssertNil(loose.dueAt)61        XCTAssertNil(loose.pageId)62        XCTAssertEqual(loose.overdue, false)63        XCTAssertTrue(health.openTasks.ids.contains(late.id))6465        let issues = health.orphans.count + health.brokenLinks.count + health.missingReferences.count + health.potentialDuplicates.count66            + health.untitled.count + health.inactiveProjects.count + health.openTasks.overdue67        XCTAssertEqual(health.score.issues, issues, "issues = the section counts, with overdue tasks in place of all open ones")6869        XCTAssertEqual(try NextFixture.decode(KnowledgeHealth.self, "knowledge", "health-inactive-1").inactiveDays, 1)70        // Observed: inactiveDays=0 is clamped to 1, not refused.71        XCTAssertEqual(try NextFixture.decode(KnowledgeHealth.self, "knowledge", "health-bad-days").inactiveDays, 1)72    }7374    // MARK: brief7576    func testBrief() throws {77        let brief = try NextFixture.decode(DailyBrief.self, "knowledge", "brief")78        XCTAssertEqual(brief.timeZone, "America/Toronto")79        XCTAssertEqual(brief.date, "2026-11-19")80        XCTAssertNotNil(brief.generatedAt)81        XCTAssertLessThanOrEqual(brief.recentNotes.count, 8)82        XCTAssertEqual(brief.recentNotes.compactMap(\.updatedAt), brief.recentNotes.compactMap(\.updatedAt).sorted(by: >), "most recently modified first")83        let database = try XCTUnwrap(brief.recentNotes.first { $0.title == "Fixture · savoir · lectures" })84        XCTAssertEqual(database.type, "database")85        XCTAssertEqual(database.section, "databases")86        XCTAssertEqual(brief.recentNotes.first { $0.title == "Fixture · savoir · revue" }?.wordCount, 38)87        XCTAssertFalse(brief.recentNotes.contains { $0.title == "Fixture · capture à classer" }, "inbox pages are left out")8889        let project = try XCTUnwrap(brief.activeProjects.first { $0.title == "Fixture · savoir · projet" })90        XCTAssertEqual(project.pages, 3)91        XCTAssertEqual(project.openTasks, 2)92        XCTAssertNotNil(project.lastActivityAt)9394        let overdue = try XCTUnwrap(brief.tasks.overdue.first { $0.title == "Fixture · tâche en retard" })95        XCTAssertEqual(overdue.status, "todo")96        XCTAssertEqual(overdue.pageTitle, "Fixture · savoir · données")97        XCTAssertNil(overdue.blockId)98        let soon = try XCTUnwrap(brief.tasks.dueSoon.first { $0.title == "Relire la section 2" })99        XCTAssertEqual(soon.priority, "high")100        XCTAssertEqual(soon.blockId?.count, 10, "a task born from a taskItem keeps its block")101        XCTAssertTrue(brief.tasks.dueToday.isEmpty)102103        XCTAssertGreaterThanOrEqual(brief.unfiledCaptures.count, 1)104        let capture = try XCTUnwrap(brief.unfiledCaptures.items.first { $0.title == "Fixture · capture à classer" })105        XCTAssertEqual(capture.kind, "note")106        XCTAssertNotNil(capture.inboxAt)107        XCTAssertEqual(brief.linkSuggestions.count, brief.linkSuggestions.items.count)108        XCTAssertTrue(brief.toRevisit.isEmpty)109        // The scratch database holds a summary written by the backend's own tests with an injected model.110        let summary = try XCTUnwrap(brief.aiSummary)111        XCTAssertEqual(summary.ai, true)112        XCTAssertFalse(summary.text.isEmpty)113        XCTAssertNotNil(summary.model)114        XCTAssertNotNil(summary.at)115        XCTAssertNil(summary.costUsd)116117        let auckland = try NextFixture.decode(DailyBrief.self, "knowledge", "brief-auckland")118        XCTAssertEqual(auckland.timeZone, "Pacific/Auckland")119        XCTAssertEqual(auckland.date, "2026-11-20", "« today » is the calendar day in the requested zone")120        XCTAssertEqual(try NextFixture.decode(DailyBrief.self, "knowledge", "brief-default").timeZone, "America/Toronto")121        let bad = try NextFixture.error("knowledge", "brief-bad-tz")122        XCTAssertEqual(bad.status, 400)123        XCTAssertEqual(bad.code, APIError.NextCode.badRequest)124    }125126    // MARK: living blocks127128    func testQueryTasks() throws {129        let result = try NextFixture.decode(LiveQueryResult.self, "knowledge", "query-tasks")130        XCTAssertEqual(result.source, LiveQuerySource.tasks)131        XCTAssertEqual(result.columns.map(\.key), ["title", "status", "priority", "dueAt", "pageTitle", "project"])132        XCTAssertEqual(result.columns.map(\.type), [LiveQueryColumnType.text, LiveQueryColumnType.select, LiveQueryColumnType.select, LiveQueryColumnType.date,133                                                    LiveQueryColumnType.page, LiveQueryColumnType.text])134        XCTAssertEqual(result.total, 1)135        XCTAssertEqual(result.limit, 10)136        XCTAssertNotNil(result.resolvedAt)137        let row = try XCTUnwrap(result.rows.first)138        XCTAssertEqual(row.id.count, 36)139        XCTAssertNotNil(row.pageId)140        XCTAssertEqual(row.string("title"), "Relire la section 2")141        XCTAssertEqual(row.string("status"), "todo")142        XCTAssertEqual(row.date("dueAt").map(APIDate.string(from:)), "2026-11-25T12:00:00.000Z")143        XCTAssertEqual(row.string("blockId")?.count, 10)144        XCTAssertNil(row.value("project"), "JSON null reads as nil")145        XCTAssertNil(row.value("nope"))146        XCTAssertEqual(result.table.columns, result.columns.map(\.label))147        XCTAssertEqual(result.table.rows, [[.text("Relire la section 2"), .text("todo"), .text("high"), .text("2026-11-25T12:00:00.000Z"), .text("Fixture · savoir · revue"), .null]])148        XCTAssertNil(result.databaseId)149150        let due = try NextFixture.decode(LiveQueryResult.self, "knowledge", "query-tasks-due")151        XCTAssertEqual(due.rows.map { $0.string("title") }, ["Fixture · tâche en retard"])152        XCTAssertEqual(due.limit, 25, "the server default")153        XCTAssertNil(due.rows[0].string("blockId"))154    }155156    func testQueryPagesDatabaseReferencesBacklinks() throws {157        let pages = try NextFixture.decode(LiveQueryResult.self, "knowledge", "query-pages")158        XCTAssertEqual(pages.source, LiveQuerySource.pages)159        XCTAssertEqual(pages.total, 2)160        XCTAssertEqual(pages.columns.first { $0.key == "tags" }?.type, LiveQueryColumnType.tags)161        let page = try XCTUnwrap(pages.rows.first { $0.string("title") == "Fixture · savoir · revue" })162        XCTAssertEqual(page.id, page.pageId)163        XCTAssertEqual(page.strings("tags"), ["fixture-revue", "fixture-savoir"])164        XCTAssertEqual(page.number("wordCount"), 38)165        XCTAssertNotNil(page.date("updatedAt"))166        XCTAssertEqual(pages.table.rows.first { $0.first == .text("Fixture · savoir · revue") }?[2], .text("fixture-revue, fixture-savoir"), "tags are flattened in the table")167        XCTAssertEqual(pages.table.rows.first?.last?.text, "38")168169        let limited = try NextFixture.decode(LiveQueryResult.self, "knowledge", "query-pages-limit")170        XCTAssertEqual(limited.rows.count, 1)171        XCTAssertEqual(limited.limit, 1)172        XCTAssertEqual(limited.total, 2, "total counts beyond limit")173174        let database = try NextFixture.decode(LiveQueryResult.self, "knowledge", "query-database")175        XCTAssertEqual(database.source, LiveQuerySource.database)176        XCTAssertEqual(database.name, "Fixture · savoir · lectures")177        XCTAssertEqual(database.databaseId?.count, 36)178        XCTAssertEqual(database.viewId?.count, 36)179        XCTAssertEqual(database.columns.map(\.label), ["Name", "Année"])180        XCTAssertEqual(database.columns.map(\.type), [LiveQueryColumnType.page, LiveQueryColumnType.number])181        let record = try XCTUnwrap(database.rows.first)182        XCTAssertNotEqual(record.id, record.pageId, "a database row has its own id and a page")183        XCTAssertEqual(record.string(database.columns[0].key), "Fixture · Engle (1982)", "values are keyed by property id")184        XCTAssertEqual(record.number(database.columns[1].key), 1982)185        XCTAssertEqual(database.table.rows, [[.text("Fixture · Engle (1982)"), .number(1982)]])186        XCTAssertEqual(database.table.rows[0][1].text, "1982")187188        let references = try NextFixture.decode(LiveQueryResult.self, "knowledge", "query-references")189        XCTAssertEqual(references.source, LiveQuerySource.references)190        let reference = try XCTUnwrap(references.rows.first)191        XCTAssertNil(reference.pageId)192        XCTAssertEqual(reference.strings("authors"), ["Greene, William H."])193        XCTAssertEqual(reference.number("year"), 2018)194        XCTAssertEqual(reference.string("verified"), "user")195        XCTAssertEqual(references.table.rows[0][3], .null)196197        let backlinks = try NextFixture.decode(LiveQueryResult.self, "knowledge", "query-backlinks")198        XCTAssertEqual(backlinks.source, LiveQuerySource.backlinks)199        let source = try XCTUnwrap(backlinks.rows.first)200        XCTAssertEqual(source.string("title"), "Fixture · savoir · revue")201        XCTAssertEqual(source.strings("via"), ["link"])202203        // A row round-trips through Codable (the store may cache a resolved query).204        let data = try APIJSON.encoder().encode(database)205        XCTAssertEqual(try APIJSON.decoder().decode(LiveQueryResult.self, from: data), database)206    }207208    func testQueryErrors() throws {209        for name in ["query-no-database", "query-bad-status", "query-bad-date", "query-no-page"] {210            let error = try NextFixture.error("knowledge", name)211            XCTAssertEqual(error.status, 400, name)212            XCTAssertEqual(error.code, APIError.NextCode.badRequest, name)213        }214        let validation = try NextFixture.error("knowledge", "query-validation")215        XCTAssertNil(validation.code)216        for source in LiveQuerySource.all { XCTAssertTrue(validation.message.contains(source)) }217        let missing = try NextFixture.error("knowledge", "query-database-not-found")218        XCTAssertTrue(missing.isNotFound)219        XCTAssertFalse(missing.isRouteMissing)220    }221222    // MARK: zoom223224    func testZoom() throws {225        let outline = try NextFixture.decode(PageZoom.self, "knowledge", "zoom-2")226        XCTAssertEqual(outline.level, 2)227        XCTAssertFalse(outline.ai, "the outline is computed without any model")228        XCTAssertEqual(outline.title, "Fixture · savoir · revue")229        XCTAssertEqual(outline.version, 1)230        XCTAssertNil(outline.content)231        XCTAssertNil(outline.synopsis)232        let sections = try XCTUnwrap(outline.sections)233        XCTAssertEqual(sections.map(\.heading), [nil, "Volatilité conditionnelle", "Tâches"])234        XCTAssertEqual(sections.map(\.level), [0, 1, 2], "the text before the first heading is a level-0 section")235        XCTAssertEqual(sections[0].firstSentence, "Introduction avant le premier titre.")236        XCTAssertEqual(sections[0].words, 10)237        XCTAssertEqual(sections[1].firstSentence, "Le manuel de référence est Greene 2018.", "citation labels are part of the sentence")238        XCTAssertTrue(sections.allSatisfy { $0.blockId?.count == 10 && $0.blocks == 1 })239        XCTAssertEqual(try NextFixture.decode(PageZoom.self, "knowledge", "zoom-default"), outline, "level 2 is the default")240241        let full = try NextFixture.decode(PageZoom.self, "knowledge", "zoom-3")242        XCTAssertEqual(full.level, 3)243        XCTAssertNil(full.sections)244        let content = try XCTUnwrap(full.content)245        XCTAssertTrue(content.string.contains(#""type":"doc""#))246        XCTAssertTrue(content.string.contains(try XCTUnwrap(sections[1].blockId)), "the outline's block ids are those of the document")247        XCTAssertEqual(try NextFixture.decode(PageZoom.self, "knowledge", "zoom-2-empty").sections, [])248249        // Level 1 on the foundation server.250        let unavailable = try NextFixture.error("knowledge", "zoom-1")251        XCTAssertEqual(unavailable.status, 501)252        XCTAssertEqual(unavailable.code, APIError.NextCode.notImplemented)253        XCTAssertTrue(unavailable.isNotImplemented)254        XCTAssertTrue(unavailable.isRouteMissing)255        // Note: `isRetryable` (2.0 rule: every 5xx) is true for a 501; test `isRouteMissing` before retrying.256        XCTAssertEqual(try NextFixture.error("knowledge", "zoom-bad-level").code, APIError.NextCode.badRequest)257        XCTAssertTrue(try NextFixture.error("knowledge", "zoom-not-found").isNotFound)258    }259260    // MARK: tags, cycles261262    func testTagsCountPages() throws {263        let tags = try NextFixture.decode([TagSummary].self, "knowledge", "tags")264        XCTAssertEqual(tags.first { $0.name == "fixture-savoir" }?.pages, 2, "pages is the number of live pages carrying the tag")265        XCTAssertEqual(tags.first { $0.name == "fixture-revue" }?.pages, 1)266        XCTAssertTrue(tags.allSatisfy { $0.id.count == 36 && $0.color != nil && $0.pages != nil })267    }268269    func testParentErrors() throws {270        let cycle = try NextFixture.error("knowledge", "page-cycle")271        XCTAssertEqual(cycle.status, 409)272        XCTAssertEqual(cycle.code, APIError.NextCode.cycle)273        XCTAssertFalse(cycle.isConflict, "a cycle is not an edit conflict")274        XCTAssertNil(cycle.serverCopy)275        let parent = try NextFixture.error("knowledge", "page-bad-parent")276        XCTAssertEqual(parent.status, 400)277        XCTAssertEqual(parent.code, APIError.NextCode.badParent)278        let own = try NextFixture.error("knowledge", "page-parent-self")279        XCTAssertEqual(own.status, 400)280        XCTAssertNil(own.code)281        XCTAssertEqual(try NextFixture.error("knowledge", "page-bad-id").code, APIError.NextCode.badRequest)282    }283}284
Files main
Menu

Theme