Cotton code
229 lines · 13.4 KB · SwiftRaw
// The root's records are the owner's: every built-in table is read and// written through the core's generic verbs (`CoreRecords`, `records.*`), and// the shipping sources never put the fixture tables where the root publishes.//// The defect these hold: until it was fixed, the root published the built-in// definitions over the bundled synthetic records (`AppTables.fixtures`), with// only imported tables reaching the core — so a person's Notes, Journal and// Thoughts lists showed invented examples, every write landed in memory and// vanished on the next launch, and the one input asked nobody.import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class CoreRecordsTests: XCTestCase {    /// RULE: A command's record picker sends its filter with the first paged search, because filtering loaded rows can hide every valid choice beyond that page.    func testTheRecordPickerFiltersBeforeItAsksForTheFirstPage() async throws {        let core = ScriptedCore([            CottonMethod.recordsList: .ok(#"{"records":[{"table":"person","id":"category-garden","data":{"name":"Garden","subtype":"category"}}],"next_page":50,"total":120}"#),        ])        let store = CoreRecords(core: core, bundle: try resources())        let filter: [String: RecordValue] = ["subtype": .text("category"), "section": .list([.text("income"), .text("spending")])]        let rows = try await LinkPicking.records(in: store, table: "person", query: "  garden\n", where: filter)        XCTAssertEqual(rows.map(\.id), ["category-garden"])        let sent = try await request(core, CottonMethod.recordsList)        XCTAssertEqual(sent["where"], .object(filter))        XCTAssertEqual(sent["query"], .text("garden"))        XCTAssertEqual(sent["page"], .number(0))        XCTAssertEqual(sent["limit"], .number(50))        let methods = await core.methodsCalled()        XCTAssertEqual(methods, [CottonMethod.recordsList])    }    // RULE: Everything reads the whole table’s latest change from native metadata, independent of the first page’s display order.    func testLastChangedReadsNativeWholeTableMetadata() async throws {        let core = ScriptedCore([            CottonMethod.recordsList: .ok(#"{"table":"note","last_changed":"2026-10-06T09:00:00Z"}"#),        ])        let store = CoreRecords(core: core, bundle: try resources())        let changed = try await store.lastChanged(table: "note")        XCTAssertEqual(changed, "2026-10-06T09:00:00Z")        let sent = try await request(core, CottonMethod.recordsList)        XCTAssertEqual(sent["table"], .text("note"))        XCTAssertEqual(sent["last_changed"], .bool(true))        XCTAssertNil(sent["page"])        await core.answer(CottonMethod.recordsList, .ok(#"{"table":"note","last_changed":null}"#))        let empty = try await store.lastChanged(table: "note")        XCTAssertNil(empty)    }    // RULE: A count asks only for native metadata; even a one-record email list builds all thread views before pagination.    func testCountAsksForMetadataWithoutPaging() async throws {        let core = ScriptedCore([CottonMethod.recordsList: .ok(#"{"table":"email_thread","total":1200}"#)])        let store = CoreRecords(core: core, bundle: try resources())        let count = try await store.count(table: "email_thread")        XCTAssertEqual(count, 1200)        let sent = try await request(core, CottonMethod.recordsList)        XCTAssertEqual(sent["count_only"], .bool(true))        XCTAssertNotNil(sent["today"])        XCTAssertNil(sent["limit"])        XCTAssertNil(sent["page"])    }    private func resources() throws -> Bundle {        try TestResources.bundle()    }    private func request(_ core: ScriptedCore, _ method: String) async throws -> [String: RecordValue] {        let calls = await core.calls        let call = try XCTUnwrap(calls.last { $0.method == method }, "\(method) was never asked")        return try JSONDecoder().decode([String: RecordValue].self, from: Data(call.requestJSON.utf8))    }    /// Ordinary rows skip the inline-action query; Settings keeps its    /// providers, including Sessions' Allow and Withdraw buttons.    func testOnlySettingsTablesCanOfferInlineActions() throws {        let store = CoreRecords(core: ScriptedCore([:]), bundle: try resources())        for table in ["todo", "event", "msg_thread", "email_thread", "money_account", "invented_table"] {            XCTAssertFalse(store.offersSlipActions(table: table), table)        }        for source in SettingsRecords.sources {            XCTAssertTrue(store.offersSlipActions(table: source.table), source.table)        }    }    /// RULE: A built-in table's list is the core's `records.list`, narrowed by the core rather than in Swift, because a list drawn from anything else shows rows that are not the owner's.    func testABuiltinListIsTheCoresList() async throws {        let core = ScriptedCore([            "records.list": .ok(#"{"table":"todo","records":[{"table":"todo","id":"t1","data":{"text":"Call the bank","standing":"open"},"updated_at":"2026-10-01T09:00:00Z"}],"next_page":50,"total":51}"#),        ])        let store = CoreRecords(core: core, bundle: try resources())        let page = try await store.list(table: "todo", project: nil, query: "bank", page: 0, where: ["standing": .text("open")])        XCTAssertEqual(page.records.map(\.id), ["t1"])        XCTAssertEqual(page.records.first?["updated_at"], .text("2026-10-01T09:00:00Z"), "the row's stamp reaches the faces")        XCTAssertEqual(page.next, 50, "the core's cursor is handed back as it was answered")        let sent = try await request(core, "records.list")        XCTAssertEqual(sent["table"], .text("todo"))        XCTAssertEqual(sent["query"], .text("bank"))        XCTAssertEqual(sent["where"], .object(["standing": .text("open")]))        XCTAssertEqual(sent["limit"], .number(50))        XCTAssertNotNil(sent["today"]?.text, "records.list needs the owner's day for the money views")        let count = try await store.count(table: "todo")        XCTAssertEqual(count, 51, "the count is the core's total, not a walk of every page")        let methods = await core.methodsCalled()        XCTAssertEqual(methods, ["records.list", "records.list"], "a built-in never waits on the tools catalogue")    }    /// RULE: A record the core no longer holds reads as nothing (record_not_found), never as a failure — the page says gone, not "could not be read".    func testAGoneRecordReadsAsNothing() async throws {        let core = ScriptedCore([            "records.get": .refuse(code: "record_not_found", message: "Notes has no record n9"),        ])        let store = CoreRecords(core: core, bundle: try resources())        let gone = try await store.get(table: "note", id: "n9")        XCTAssertNil(gone)        await core.answer("records.get", .refuse(code: "unreadable", message: "the file is locked"))        do {            _ = try await store.get(table: "note", id: "n9")            XCTFail("a real refusal is still thrown")        } catch let error as CottonCallError { XCTAssertEqual(error.code, "unreadable") }    }    /// RULE: A built-in write is the core's `records.create` and its undo the core's `records.undo` with the change's id, because a write that lands anywhere else is lost and an undo that re-writes `before` itself overrides the core.    func testABuiltinCreateAndItsUndoAreTheCoresVerbs() async throws {        let core = ScriptedCore([            "records.create": .ok(#"{"change":{"id":"ch-1","table":"note","record_id":"n1","verb":"create","byline":"user","before":null,"after":{"title":"Plan"},"undoable":true,"reason":null},"record":{"table":"note","id":"n1","data":{"title":"Plan"}}}"#),            "records.undo": .ok(#"{"change":{"id":"ch-2","table":"note","record_id":"n1","verb":"delete","byline":"user","before":{"title":"Plan"},"after":null,"undoable":false,"reason":"already undone"},"undone":{"id":"ch-1"},"record":null}"#),        ])        let store = CoreRecords(core: core, bundle: try resources())        XCTAssertTrue(store.answersUndo)        let made = try await store.create(table: "note", data: ["title": .text("Plan")])        XCTAssertEqual(made.id, "ch-1")        XCTAssertEqual(made.byline, "You", "the owner's own app writes as user")        XCTAssertNil(made.before)        XCTAssertEqual(made.after, TableRecord(id: "n1", values: ["title": .text("Plan")]))        XCTAssertTrue(made.undoable)        let created = try await request(core, "records.create")        XCTAssertEqual(created["table"], .text("note"))        XCTAssertEqual(created["data"], .object(["title": .text("Plan")]))        let undone = try await store.undo(change: made.id)        XCTAssertEqual(undone.id, "ch-2")        XCTAssertEqual(undone.before, TableRecord(id: "n1", values: ["title": .text("Plan")]))        XCTAssertNil(undone.after)        XCTAssertFalse(undone.undoable)        XCTAssertEqual(undone.reason, "already undone")        let sent = try await request(core, "records.undo")        XCTAssertEqual(sent, ["change_id": .text("ch-1")])        let methods = await core.methodsCalled()        XCTAssertEqual(methods, ["records.create", "records.undo"])    }    /// RULE: A page's link titles are read by the linked records' ids, one `records.list { ids }` per table, because paging a whole linked table to find a few rows costs a read of every row in it on every page that links there.    func testLinkTitlesAreReadByTheLinkedIds() async throws {        let core = ScriptedCore([            "records.list": .ok(#"{"table":"note","records":[{"table":"note","id":"n2","data":{"title":"Harbour plan","@said":{"slip":{"name":"Harbour plan"}}}},{"table":"note","id":"n1","data":{"title":"Tide table","@said":{"slip":{"name":"Tide table"}}}}],"next_page":null,"total":2}"#),        ])        let store = CoreRecords(core: core, bundle: try resources())        let links = [RecordLink(table: "note", id: "n2"), RecordLink(table: "note", id: "n1"), RecordLink(table: "note", id: "n2")]        let titles = try await store.linkTitles(for: links)        XCTAssertEqual(titles.byID, ["n1": "Tide table", "n2": "Harbour plan"])        let methods = await core.methodsCalled()        XCTAssertEqual(methods, ["records.list"], "one ask for the table, no walk of its pages")        let sent = try await request(core, "records.list")        XCTAssertEqual(sent["ids"], .list([.text("n2"), .text("n1")]), "each linked id once, in the order linked")        XCTAssertNil(sent["page"], "an ask by ids takes no page")        XCTAssertNil(sent["limit"])    }}final class RootRecordsGuardTests: XCTestCase {    /// RULE: No shipping source builds the app's tables over the fixture records, and the root names no fixture store, parser or Ask, because the fixtures in the root showed invented rows in place of the owner's and dropped every write.    ///    /// The fixtures stay for tests and previews: `*Preview*.swift` is    /// skipped, and `AppTables.fixtures` lives in the test target    /// (`Support/AppTablesFixtures.swift`).    func testTheShippingRootNeverDrawsTheFixtures() throws {        let sources = try SourceSweep.swiftSources()        let shipping = sources.filter { source in            !AppSources.fileName(source.name).contains("Preview")        }        let root = try XCTUnwrap(shipping.first { $0.name == "CottonUI/Boot/RootView.swift" })        for maker in Self.fixtureStoreMakers {            XCTAssertTrue(shipping.contains { $0.name == maker }, "\(maker) is gone: take it off fixtureStoreMakers")        }        var broken: [String] = []        for source in shipping {            let code = SourceSweep.withoutComments(source.text)            if code.contains("AppTables.fixtures") || code.contains(".fixtures(includePackages") {                broken.append("\(source.name) calls AppTables.fixtures")            }            if code.contains("AppTables("), code.contains("FixtureRecords") {                broken.append("\(source.name) builds AppTables beside FixtureRecords")            }            if !Self.fixtureStoreMakers.contains(source.name), Self.makesFixtureStore(code) {                broken.append("\(source.name) makes a FixtureRecords store")            }        }        for name in ["FixtureRecords"] where root.text.contains(name) {            broken.append("RootView.swift mentions \(name)")        }        XCTAssertEqual(broken, [], "The root's tables are the core's (AppTables.core over CoreRecords).")    }    /// The shipping files that may make a fixture store: the store's own file.    static let fixtureStoreMakers: Set<String> = [        "CottonUI/Definitions/FixtureRecords.swift",    ]    /// A fixture store made directly — `FixtureRecords.bundled()` or    /// `FixtureRecords(...)` — not only through `AppTables`: a screen that    /// lists from one shows invented rows as surely as the root did.    static func makesFixtureStore(_ code: String) -> Bool {        code.contains("FixtureRecords.bundled(") || code.range(of: #"\bFixtureRecords\s*\("#, options: .regularExpression) != nil    }    func testTheGuardSeesAFixtureStoreMadeDirectly() {        XCTAssertTrue(Self.makesFixtureStore("let store = FixtureRecords.bundled()"))        XCTAssertTrue(Self.makesFixtureStore("let store = FixtureRecords(definitions: d, records: r)"))        XCTAssertFalse(Self.makesFixtureStore("let store = CoreRecords(core: core)"))        XCTAssertFalse(Self.makesFixtureStore("func fixtureRecords() -> FixtureRecords {"))    }}