Cotton code
138 lines · 9.0 KB · SwiftRaw
// The definition keys that let a list ask a question and a page gather what// belongs to its record, for any table: slip `answers` (with `leaves` and// `primary`), the change's `moved_to`, a list section's `limit`, `columns` and// `with`, a page section's `links`, and a section naming a table with no// definition. Every record is invented.import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class AnswerKeysTests: XCTestCase {    /// A question table: "Same as …?" with Merge and Different.    private func question(_ answers: String = #","answers":{"column":"state","values":{"different":"Different","merged":"Merge"},"when":["open"]}"#) throws -> TableDefinition {        try TableDefinition.decode(Data("""            {"id":"question","name":"Question","plural":"Questions","builtin":false,             "columns":[{"key":"asks","type":"text"},{"key":"state","type":"choice","choices":["open","merged","different"]},                        {"key":"person","type":"link","link_to":"person"}],             "title":"asks","slip":{"title":"asks"\(answers)},"tile":{"face":"slip-list"},             "page":[{"heading":null,"columns":["asks"]}]}            """.utf8))    }    private func record(_ id: String, _ state: String?) -> TableRecord {        TableRecord(id: id, values: ["asks": .text("Same as Example \(id)?"), "state": state.map(RecordValue.text) ?? .null, "person": .text("p1")])    }    /// RULE: Slip answers (column, values, when, leaves, primary), a list section's limit, columns and with, and a page section's links decode, survive a round trip, and read as before when absent.    func testTheAnswerKeysDecodeAndTheirAbsenceReadsAsBefore() throws {        let full = try TableDefinition.decode(Data("""            {"id":"example","name":"Example","plural":"Examples","builtin":false,             "columns":[{"key":"title","type":"text"},{"key":"state","type":"choice","choices":["open","kept"]}],             "title":"title","slip":{"title":"title","answers":{"column":"state","values":{"kept":"Keep"},"leaves":false,"primary":"kept"}},             "tile":{"face":"slip-list"},             "page":[{"heading":null,"columns":["title"]},                     {"heading":"Todos","list":{"table":"todo","link":"people","limit":4,"columns":2,"with":[{"table":"note","link":"people"}]}},                     {"heading":"Also linked","links":{"except":["todo"]}}]}            """.utf8))        XCTAssertEqual(full.slip.answers, SlipAnswers(column: "state", values: ["kept": "Keep"], leaves: false, primary: "kept"))        XCTAssertEqual(            full.page[1].list,            SectionList(table: "todo", link: "people", limit: 4, columns: 2, with: [SectionLink(table: "note", link: "people")]))        XCTAssertEqual(full.page[2].links, LinkedSection(except: ["todo"]))        XCTAssertEqual(full.page.filter { $0.list != nil || $0.links != nil }.map(\.heading), ["Todos", "Also linked"])        XCTAssertEqual(try JSONDecoder().decode(TableDefinition.self, from: JSONEncoder().encode(full)), full)        let bare = try question("")        XCTAssertNil(bare.slip.answers)        XCTAssertFalse(bare.isAnswered(record("1", "merged")))        XCTAssertTrue(bare.answerVerbs(record("1", nil)).isEmpty)        let list = try JSONDecoder().decode(SectionList.self, from: Data(#"{"table":"todo"}"#.utf8))        XCTAssertNil(list.limit)        XCTAssertNil(list.columns)        XCTAssertEqual(list.with, [])        XCTAssertEqual(try JSONDecoder().decode(SlipAnswers.self, from: Data(#"{"column":"state","values":{}}"#.utf8)).leaves, true)    }    /// RULE: An answer is written through update into its column, read back as "You answered <words>" with an Undo that brings the question back; a value that is not one of its answers writes nothing. Whether the answered slip leaves the list is the core's (`listed_when`).    func testAnAnswerIsWrittenWithItsReceipt() async throws {        let definition = try question()        let store = FixtureRecords(definitions: [definition], records: ["question": [record("1", "open"), record("2", "open")]])        let model = RecordListModel(definition: definition, store: store, core: ListCoreFake(), seeds: ListSeeds())        await model.reload(project: nil, query: "")        let none = try await model.answer(try XCTUnwrap(model.records.first), "nonsense")        XCTAssertNil(none)        let change = try await model.answer(try XCTUnwrap(model.records.first), "merged")        XCTAssertEqual(change?.after?["state"], .text("merged"))        XCTAssertEqual(model.lastChange, change)        try await model.undo()        XCTAssertNil(model.lastChange)        let back = try await store.get(table: "question", id: "1")        XCTAssertEqual(back?["state"], .text("open"), "the Undo brings the question back")    }    /// RULE: A write that folded a record into another names it (`moved_to`), and the opener hands that record on so the page shows it in the folded record's place; any other write names none.    func testAMoveIsHandedToTheOpener() {        XCTAssertNil(ChangeRecord(id: "c", byline: "You", before: nil, after: nil).movedTo)        final class Moved: @unchecked Sendable { var to: RecordRef? }        let moved = Moved()        let opener = RecordOpener(moved: { moved.to = $0 }) { _, _ in }        opener.move(to: RecordRef(table: "person", id: "survivor"))        XCTAssertEqual(moved.to, RecordRef(table: "person", id: "survivor"))        RecordOpener { _, _ in }.move(to: RecordRef(table: "person", id: "nobody"))    }    /// RULE: Records of several tables merge newest first by each table's date, the undated last, ties in the order read.    func testTheMergedRun() throws {        let notes = TableDefinition(            id: "note", name: "Note", plural: "Notes", columns: [ColumnDefinition(key: "at", type: .date)], title: "at",            date: "at", slip: SlipLayout(title: "at"), tile: TileLayout(face: .slipList), page: [])        var personNotes = notes        personNotes.id = "person_note"        let rows = [            SectionRow(definition: personNotes, record: TableRecord(id: "a", values: ["at": .text("2026-09-01")])),            SectionRow(definition: personNotes, record: TableRecord(id: "b", values: [:])),            SectionRow(definition: notes, record: TableRecord(id: "c", values: ["at": .text("2026-09-20T10:00:00Z")])),            SectionRow(definition: notes, record: TableRecord(id: "d", values: ["at": .text("2026-09-01")])),        ]        XCTAssertEqual(SectionRow.merged(rows).map(\.record.id), ["c", "a", "d", "b"])    }    /// RULE: A list section naming a table with no definition here draws nothing and never fails — its heading appears the day the definition lands — and a `with` table with no definition adds nothing while the defined ones are read through their own link.    func testAnUndefinedTableDrawsNothing() throws {        let todo = TableDefinition(            id: "todo", name: "Todo", plural: "Todos", columns: [ColumnDefinition(key: "people", type: .link, linkTo: "person", multiple: true)],            title: "people", slip: SlipLayout(title: "people"), tile: TileLayout(face: .slipList), page: [])        let definitions = TableDefinitions([todo])        XCTAssertNil(RecordsSection.sources(SectionList(table: "call", link: "person_id"), parent: "p1", in: definitions))        let merged = try XCTUnwrap(RecordsSection.sources(            SectionList(table: "todo", link: "people", with: [SectionLink(table: "note", link: "people"), SectionLink(table: "todo", link: "people")]),            parent: "p1", in: definitions))        XCTAssertEqual(merged.map(\.definition.id), ["todo", "todo"])        XCTAssertEqual(merged.map(\.filter), [["people": .text("p1")], ["people": .text("p1")]])        XCTAssertNil(RecordsSection.sources(SectionList(table: "todo", link: "people"), parent: nil, in: definitions), "a blank page lists none")    }    /// RULE: A filter on a column holding several values (a record's `people` links) matches when one of them is the value — the person page's sections read records linked through edges.    func testAFilterMatchesOneOfSeveralValues() async throws {        let todo = TableDefinition(            id: "todo", name: "Todo", plural: "Todos",            columns: [ColumnDefinition(key: "title", type: .text), ColumnDefinition(key: "people", type: .link, linkTo: "person", multiple: true)],            title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList), page: [])        let store = FixtureRecords(definitions: [todo], records: ["todo": [            TableRecord(id: "1", values: ["title": .text("a"), "people": .list([.text("p1"), .text("p2")])]),            TableRecord(id: "2", values: ["title": .text("b"), "people": .list([.text("p2")])]),            TableRecord(id: "3", values: ["title": .text("c"), "people": .text("p1")]),        ]])        let page = try await store.list(table: "todo", project: nil, query: nil, page: 0, where: ["people": .text("p1")])        XCTAssertEqual(page.records.map(\.id), ["1", "3"])    }}