Cotton code
396 lines · 25.4 KB · SwiftRaw
// The interpreter's model: the built-in definitions in the shared format, their// synthetic records, the verbs' fixture implementation and the faces' reading// of a record (rebuild note 7b95efa4). Every fixture is invented.import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUIfinal class TableDefinitionTests: XCTestCase {    /// The resources as the source tree holds them, read as a bundle: under    /// `swift test` the harness's `Bundle.main` is `xctest`, so    /// `CottonUIResources.bundle` is nil on the Mac (`ToolCardTests`).    private static var resources: Bundle? {        Bundle(url: SourceSweep.iosSources.appendingPathComponent("CottonUI/Resources"))    }    private func builtins() throws -> [TableDefinition] {        let loaded = FixtureDefinitions.load(from: try XCTUnwrap(Self.resources))        XCTAssertEqual(loaded.failures, [])        return loaded.definitions    }    /// RULE: Every built-in table definition decodes from the shared format and names only columns it declares.    func testEveryBuiltinDefinitionDecodesAndNamesOnlyItsOwnColumns() throws {        let definitions = try builtins()        let byID = Dictionary(uniqueKeysWithValues: definitions.map { ($0.id, $0) })        for definition in definitions {            let keys = Set(definition.columns.map(\.key))            XCTAssertEqual(keys.count, definition.columns.count, "\(definition.id): a column key twice")            let named = [definition.title, definition.date, definition.project, definition.order,                         definition.slip.title, definition.slip.trailing,                         definition.slip.photo, definition.slip.toggle, definition.slip.player,                         definition.slip.trailingPicture, definition.slip.figure, definition.slip.stub,                         definition.slip.caption?.status, definition.group?.column, definition.dimmed?.column,                         definition.sort?.column, definition.listedWhen, definition.archived,                         definition.slip.subtitleFallback, definition.recent?.column,                         definition.slip.titleFallback, definition.opened, definition.pager, definition.index,                         definition.byMonth, definition.readonlyWhen,                         definition.slip.answers?.column, definition.slip.byline?.column,                         definition.handOver?.when?.column,                         definition.filter?.column, definition.hidden?.column,                         definition.polaroid?.caption, definition.polaroid?.title, definition.polaroid?.subtitle,                         definition.opens?.column, definition.opens?.tableColumn,                         definition.countWords?.column, definition.deletion?.size,                         definition.slip.badge?.column].compactMap { $0 }                + definition.slip.subtitles + definition.search                + definition.page.compactMap(\.when?.column) + definition.page.compactMap(\.answers?.column)                + definition.page.flatMap { $0.hand?.keys ?? [] }                + definition.page.flatMap(\.actions).flatMap(\.sets.keys)                + definition.columns.flatMap { [$0.provenance?.by, $0.provenance?.at, $0.provenance?.since, $0.reach?.channel] }                    .compactMap { $0 }                + definition.columns.flatMap { [$0.until, $0.caption, $0.captionFallback, $0.poster, $0.opens?.column].compactMap { $0 } + ($0.size ?? []) }                + definition.exports.map(\.column)                + definition.page.flatMap(\.columns) + definition.page.compactMap(\.picture)                + definition.page.compactMap(\.web)                + (definition.slip.caption?.columns ?? []) + (definition.slip.caption?.dates ?? [])                + (definition.cover?.footer ?? [])            for key in named {                XCTAssertTrue(keys.contains(key), "\(definition.id) names \(key), which it does not declare")            }            // Another table's records, under a page or a list: a table this            // database has, linked back to this one by a link column it            // declares — or one no tool here makes (tools are records a            // database imports), which draws nothing until a tool brings it.            for section in definition.page + definition.lists {                guard let list = section.list else { continue }                XCTAssertTrue(section.columns.isEmpty, "\(definition.id): a section is columns or a list, not both")                let tables = [(list.table, list.link)] + list.with.map { ($0.table, Optional($0.link)) }                for (table, link) in tables {                    guard let other = byID[table] else { continue }                    if let link {                        XCTAssertEqual(other.column(link)?.type, .link, "\(definition.id) lists \(table) by \(link), not a link")                        XCTAssertEqual(other.column(link)?.linkTo, definition.id, "\(table).\(link) does not link to \(definition.id)")                    }                }            }            XCTAssertTrue(definition.lists.allSatisfy { $0.list?.link == nil }, "\(definition.id): a list's sections have no record to link to")            for column in definition.columns {                for (from, to) in column.moves ?? [:] {                    let choices = Set(column.choices ?? [])                    XCTAssertTrue(choices.contains(from) && choices.isSuperset(of: to), "\(definition.id).\(column.key) moves outside its choices")                }                // The crate's rule (`validate_column_keys`, units): a number's or                // a size's count, or the template a date read as ago or counted                // down is said in.                XCTAssertTrue(                    column.units == nil || column.type == .number || column.type == .bytes                        || (column.type == .date && (column.format == .ago || column.format == .countdown)),                    "\(definition.id).\(column.key): units count a number or a size, or word a date read as ago or counted down"                )            }            if let toggle = definition.column(definition.slip.toggle) {                XCTAssertTrue(toggle.type == .bool || (toggle.type == .choice && (toggle.choices?.count ?? 0) >= 2),                              "\(definition.id): a toggle is a yes-no or a choice of two or more")            }            for link in definition.columns where link.type == .link {                XCTAssertNotNil(link.linkTo, "\(definition.id).\(link.key) links to nothing")            }        }    }    /// RULE: A url column is edited as text and reads as the address written, whole — a face never shortens what a tap opens.    func testAUrlColumnEditsAsTextAndReadsWhole() throws {        let definition = try TableDefinition.decode(Data("""            {"id":"example","name":"Example","plural":"Examples","builtin":false,             "columns":[{"key":"title","type":"text"},{"key":"site","type":"url","placeholder":"https://"}],             "title":"title","slip":{"title":"title","subtitle":"site"},"tile":{"face":"slip-list"},             "page":[{"heading":null,"columns":["title","site"]}]}            """.utf8))        let site = try XCTUnwrap(definition.column("site"))        XCTAssertEqual(site.type, .url)        XCTAssertEqual(FaceText.line(.text("https://example.com/a/very/long/path"), column: site), "https://example.com/a/very/long/path")        XCTAssertEqual(FaceText.line(.text(""), column: site), "https://")    }    /// RULE: A tile summary decodes as the crate writes it — op, column, where and label — and the figure the core answers reads in words the tile can draw: an amount with its currency, a date as a day, "mixed currencies" rather than a sum across two, a dash over no row.    /// The arithmetic itself never happens here.    func testATileSummaryDecodesAndItsFigureReadsInWords() throws {        let definition = try TableDefinition.decode(Data("""            {"id":"subscription","name":"Subscription","plural":"Subscriptions","builtin":false,             "columns":[{"key":"title","type":"text"},{"key":"status","type":"choice","choices":["active","cancelled"],"default":"active"},                        {"key":"amount","type":"amount","currency":"GBP"},{"key":"next_renewal","type":"date"}],             "title":"title","slip":{"title":"title","subtitle":"status"},             "tile":{"face":"slip-list","summary":[{"op":"sum","column":"amount","where":{"status":"active"},"label":"a month"},{"op":"min","column":"next_renewal","label":"next renewal"},{"op":"count"}]},             "page":[{"heading":null,"columns":["title","status","amount","next_renewal"]}]}            """.utf8))        XCTAssertEqual(definition.tile.summary.map(\.op), [.sum, .min, .count])        XCTAssertEqual(definition.tile.summary[0].filter, ["status": .text("active")])        XCTAssertEqual(try TableDefinition.decode(JSONEncoder().encode(definition)), definition)        let plain = try TableDefinition.decode(Data(#"{"id":"a","name":"A","plural":"As","builtin":false,"columns":[{"key":"title","type":"text"}],"title":"title","slip":{"title":"title"},"tile":{"face":"slip-list"},"page":[]}"#.utf8))        XCTAssertEqual(plain.tile.summary, [])        XCTAssertFalse(String(decoding: try JSONEncoder().encode(plain), as: UTF8.self).contains("summary"), "an empty summary is left out, as the crate leaves it out")        let figures = try JSONDecoder().decode([SummaryFigure].self, from: Data("""            [{"op":"sum","column":"amount","label":"a month","value":4598,"currency":"GBP","words":"£45.98 a month"},             {"op":"count","value":3,"words":"3"}]            """.utf8))        XCTAssertEqual(SummaryFigure.line(figures, in: definition), "£45.98 a month \u{00B7} 3", "the core's words, drawn as given")        XCTAssertNil(SummaryFigure.line([], in: definition))    }    /// RULE: Every synthetic record is obviously invented and decodes against its table.    func testARecordRoundTripsAsOneFlatObject() throws {        let json = #"{"id":"example-1","title":"Example","done":true,"n":2}"#        let record = try JSONDecoder().decode(TableRecord.self, from: Data(json.utf8))        XCTAssertEqual(record.id, "example-1")        XCTAssertEqual(record["done"], .bool(true))        XCTAssertEqual(record["n"], .number(2))        let again = try JSONDecoder().decode(TableRecord.self, from: JSONEncoder().encode(record))        XCTAssertEqual(again, record)    }    // ── Reading a record ───────────────────────────────────────────────────    /// RULE: A record's tint comes from its id alone, so it never changes with its project or its state.    func testATintComesFromTheIdAlone() {        XCTAssertEqual(FaceTint.dye(for: "example-todo-1"), FaceTint.dye(for: "example-todo-1"))        XCTAssertEqual(FaceTint.cap(for: "example-project-garden"), FaceTint.cap(for: "example-project-garden"))        let dyes = Set((0..<60).map { FaceTint.dye(for: "example-\($0)") })        XCTAssertEqual(dyes, Set(FaceTint.slipDyes), "sixty ids should reach every slip dye")    }    func testADateColumnReadsAsADayAndATimeWhenItHasOne() throws {        var calendar = Calendar(identifier: .gregorian)        calendar.timeZone = TimeZone(identifier: "UTC")!        let locale = Locale(identifier: "en_GB")        XCTAssertEqual(FaceText.parse("2026-10-01")?.hasTime, false)        XCTAssertEqual(FaceText.dayKey("2026-10-01T09:30:00Z", calendar: calendar), "2026-10-01")    }    func testALinkReadsAsItsTargetsTitleOrNothing() {        let column = ColumnDefinition(key: "project", type: .link, linkTo: "project")        XCTAssertEqual(FaceText.line(.text("p1"), column: column, links: ["p1": "Example Garden"]), "Example Garden")        XCTAssertNil(FaceText.line(.text("p2"), column: column, links: ["p1": "Example Garden"]))    }    func testASectionCountsWhatItShowsOfTheWhole() {        let part = SectionFace.count(shown: 3, total: 12)        XCTAssertTrue(part.contains("3") && part.contains("12"), "a part shows both the shown and the whole")        XCTAssertEqual(SectionFace.count(shown: 2, total: 2), "2")    }    // ── The verbs, answered by the fixtures ────────────────────────────────    func testTheFixtureVerbsFilterByProjectAndSearch() async throws {        let records = FixtureRecords.bundled(from: Self.resources)        let garden = try await records.list(table: "todo", project: "example-project-garden", query: nil, page: 0)        XCTAssertEqual(Set(garden.records.map(\.id)), ["example-todo-1", "example-todo-2"])        let found = try await records.list(table: "todo", project: nil, query: "PIANO", page: 0)        XCTAssertEqual(found.records.map(\.id), ["example-todo-3"])        XCTAssertNil(found.next)    }    /// RULE: A list narrowed by column values holds exactly the records whose columns hold every one of them, and an empty filter narrows nothing.    func testTheFixtureVerbsNarrowToEveryColumnValueGiven() async throws {        let records = FixtureRecords.bundled(from: Self.resources)        let open: [String: RecordValue] = ["status": .text("open")]        let opened = try await records.list(table: "todo", project: nil, query: nil, page: 0, where: open)        XCTAssertEqual(Set(opened.records.map(\.id)), ["example-todo-1", "example-todo-2", "example-todo-4", "example-todo-6"])        var urgent = open        urgent["priority"] = .number(1)        let high = try await records.first(table: "todo", where: urgent)        XCTAssertEqual(high?.id, "example-todo-2")        let none = try await records.list(            table: "todo", project: nil, query: nil, page: 0,            where: ["status": .text("done"), "project": .text("example-project-garden")])        XCTAssertEqual(none.records, [])        let all = try await records.list(table: "todo", project: nil, query: nil, page: 0, where: [:])        let whole = try await records.list(table: "todo", project: nil, query: nil, page: 0)        XCTAssertEqual(all.records, whole.records)    }    func testTheFixtureVerbsPaginate() async throws {        let definition = TableDefinition(            id: "sampled", name: "Sample", plural: "Samples",            columns: [ColumnDefinition(key: "title", type: .text)], title: "title",            slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList), page: [])        let many = (0..<120).map { TableRecord(id: String(format: "example-%03d", $0), values: ["title": .text("Example \($0)")]) }        let records = FixtureRecords(definitions: [definition], records: ["sampled": many])        let first = try await records.list(table: "sampled", project: nil, query: nil, page: 0)        XCTAssertEqual(first.records.count, FixtureRecords.pageSize)        XCTAssertEqual(first.next, 1)        let last = try await records.list(table: "sampled", project: nil, query: nil, page: 2)        XCTAssertEqual(last.records.count, 20)        XCTAssertNil(last.next)    }    /// RULE: Every write through the verbs answers a change with a byline, and undoing it restores the record.    func testEveryWriteAnswersAChangeThatUndoes() async throws {        let records = FixtureRecords.bundled(from: Self.resources)        let change = try await records.update(table: "todo", id: "example-todo-1", patch: ["status": .text("done")])        XCTAssertFalse(change.byline.isEmpty)        XCTAssertEqual(change.before?["status"], .text("open"))        XCTAssertEqual(change.after?["status"], .text("done"))        _ = try await records.undo(change: change.id)        let restored = try await records.get(table: "todo", id: "example-todo-1")        XCTAssertEqual(restored?["status"], .text("open"))        let created = try await records.create(table: "note", data: ["body": .text("Invented.")])        let id = try XCTUnwrap(created.after?.id)        _ = try await records.undo(change: created.id)        let gone = try await records.get(table: "note", id: id)        XCTAssertNil(gone)        let deleted = try await records.delete(table: "note", id: "example-note-2")        _ = try await records.undo(change: deleted.id)        let back = try await records.get(table: "note", id: "example-note-2")        XCTAssertNotNil(back)    }    /// RULE: A definition decodes the slip's player and trailing_picture, the cover-grid and receipt tiles and a top-level page_parts, and one that leaves them out is a plain page with no player or picture.    func testTheNewDefinitionKeysDecodeAndTheirAbsenceIsPlain() throws {        func definition(_ extra: String, slip: String = "", tile: String = "slip-list") throws -> TableDefinition {            try TableDefinition.decode(Data("""                {"id":"example","name":"Example","plural":"Examples","builtin":false,                 "columns":[{"key":"title","type":"text"},{"key":"clip","type":"file"},{"key":"map","type":"photo"}],                 "title":"title","slip":{"title":"title"\(slip)},"tile":{"face":"\(tile)"},                 "page":[{"heading":null,"columns":["title"]}]\(extra)}                """.utf8))        }        let bare = try definition("")        XCTAssertEqual(bare.pageParts, PagePart.plain)        XCTAssertNil(bare.slip.player)        XCTAssertNil(bare.slip.trailingPicture)        let full = try definition(#","page_parts":["title","facts","script","grid"]"#, slip: #","player":"clip","trailing_picture":"map""#, tile: "cover-grid")        XCTAssertEqual(full.pageParts, [.title, .facts, .script, .grid])        XCTAssertEqual(full.slip.player, "clip")        XCTAssertEqual(full.slip.trailingPicture, "map")        XCTAssertEqual(full.tile.face, .coverGrid)        XCTAssertEqual(try definition("", tile: "receipt").tile.face, .receipt)        XCTAssertEqual(try definition(#","page_parts":["title","facts","content","grid"]"#).pageParts, [.title, .facts, .content, .grid])        let again = try JSONDecoder().decode(TableDefinition.self, from: JSONEncoder().encode(full))        XCTAssertEqual(again, full)    }    /// RULE: A column's default decodes as the value it is, a column without one has none, and it survives a round trip — the crate applies it on create, the app only carries it.    func testAColumnDefaultDecodesAndItsAbsenceIsNone() throws {        let definition = try TableDefinition.decode(Data("""            {"id":"example","name":"Example","plural":"Examples","builtin":false,             "columns":[{"key":"title","type":"text"},                        {"key":"status","type":"choice","choices":["active","paused"],"default":"active"},                        {"key":"count","type":"number","default":1},                        {"key":"paid","type":"bool","default":false}],             "title":"title","slip":{"title":"title"},"tile":{"face":"slip-list"},             "page":[{"heading":null,"columns":["title"]}]}            """.utf8))        XCTAssertNil(definition.column("title")?.defaultValue)        XCTAssertEqual(definition.column("status")?.defaultValue, .text("active"))        XCTAssertEqual(definition.column("count")?.defaultValue, .number(1))        XCTAssertEqual(definition.column("paid")?.defaultValue, .bool(false))        let again = try JSONDecoder().decode(TableDefinition.self, from: JSONEncoder().encode(definition))        XCTAssertEqual(again, definition)    }    /// RULE: A conversation's footer, media, started, header, placeholder and also keys decode, and a conversation that leaves them out reads with none.    func testTheConversationKeysDecodeAndTheirAbsenceIsNone() throws {        let full = try JSONDecoder().decode(ConversationLayout.self, from: Data("""            {"table":"example_message","links":["to_id"],"body":"body","at":"sent_at",             "mine":{"column":"from","values":["owner"]},"footer":"footer","media":"media",             "started":{"at":"started_at","words":["machine"]},"header":["state_line","facts"],             "placeholder":"Say something","also":[{"table":"example_turn","links":["thread_id"],             "body":"text","at":"at","mine":{"column":"role","values":["user"]}}]}            """.utf8))        XCTAssertEqual(full.footer, "footer")        XCTAssertEqual(full.media, "media")        XCTAssertEqual(full.started, ConversationStarted(at: "started_at", words: ["machine"]))        XCTAssertEqual(full.header, ["state_line", "facts"])        XCTAssertEqual(full.placeholder, "Say something")        XCTAssertEqual(full.also, [ConversationSource(            table: "example_turn", links: ["thread_id"], body: "text", at: "at",            mine: ConversationMine(column: "role", values: ["user"]))])        let again = try JSONDecoder().decode(ConversationLayout.self, from: JSONEncoder().encode(full))        XCTAssertEqual(again, full)        // A started line with no words is the time alone.        let bare = try JSONDecoder().decode(ConversationStarted.self, from: Data(#"{"at":"started_at"}"#.utf8))        XCTAssertEqual(bare.words, [])    }    /// RULE: An also source's face decodes — slip needs no body or mine, absent reads as a note — and a note source encodes no face.    func testAnAlsoSourceFaceDecodesAndANoteNeedsNone() throws {        let slip = try JSONDecoder().decode(ConversationSource.self, from: Data(            #"{"table":"example_run","links":["thread_id"],"at":"queued_at","face":"slip"}"#.utf8))        XCTAssertEqual(slip, ConversationSource(table: "example_run", links: ["thread_id"], at: "queued_at", face: .slip))        XCTAssertNil(slip.body)        XCTAssertNil(slip.mine)        XCTAssertEqual(try JSONDecoder().decode(ConversationSource.self, from: JSONEncoder().encode(slip)), slip)        let absent = try JSONDecoder().decode(ConversationSource.self, from: Data(            #"{"table":"example_run","links":["thread_id"],"body":"name","at":"queued_at"}"#.utf8))        XCTAssertEqual(absent.face, .note, "a source without a face draws the record as a note")        let note = ConversationSource(            table: "example_turn", links: ["thread_id"], body: "text", at: "at",            mine: ConversationMine(column: "role", values: ["user"]))        XCTAssertEqual(note.face, .note)        let written = try XCTUnwrap(String(data: JSONEncoder().encode(note), encoding: .utf8))        XCTAssertFalse(written.contains("face"), "a note source writes no face key: \(written)")    }    /// RULE: A definition's live key decodes and round-trips, its absence is no cadence, and its pause is held between a second and a day.    func testTheLiveKeyDecodesAndItsPauseIsHeld() throws {        let live = try TableDefinition.decode(Data("""            {"id":"example","name":"Example","plural":"Examples","builtin":false,             "columns":[{"key":"title","type":"text"}],"title":"title","slip":{"title":"title"},             "tile":{"face":"slip-list"},"page":[],"live":{"every":5}}            """.utf8))        XCTAssertEqual(live.live, LiveReading(every: 5))        XCTAssertEqual(live.live?.interval, .seconds(5))        XCTAssertEqual(try JSONDecoder().decode(TableDefinition.self, from: JSONEncoder().encode(live)), live)        XCTAssertTrue(try builtins().allSatisfy { $0.live == nil || $0.live!.every >= LiveReading.floor })        let todo = try XCTUnwrap(try builtins().first { $0.id == "todo" })        XCTAssertNil(todo.live, "a table that names no cadence is read when opened and when told to")        XCTAssertEqual(LiveReading(every: 0).interval, .seconds(1))        XCTAssertEqual(LiveReading(every: -3).interval, .seconds(1))        XCTAssertEqual(LiveReading(every: 0.25).interval, .seconds(1))        XCTAssertEqual(LiveReading(every: 2.5).interval, .milliseconds(2500))        XCTAssertEqual(LiveReading(every: 1e300).interval, .seconds(86_400))        XCTAssertEqual(LiveReading(every: .nan).interval, .seconds(1))    }    // ── The shared faces' keys (toggle_on, stamps, caption, group) ──    private func todoRecord(_ status: String) -> TableRecord {        TableRecord(id: "example-todo-\(status)", values: ["title": .text("An example todo"), "status": .text(status)])    }    /// RULE: A definition decodes toggle_on, a column's stamps and past_name, the slip caption and the list group, and one that leaves them out reads as before.    func testTheGoalKeysDecodeAndTheirAbsenceReadsAsBefore() throws {        let full = try TableDefinition.decode(Data("""            {"id":"example","name":"Example","plural":"Examples","builtin":false,             "columns":[{"key":"title","type":"text"},{"key":"when","type":"date","past_name":"Was"},                        {"key":"state","type":"choice","choices":["open","shut"],"stamps":{"shut":"done"}}],             "title":"title","slip":{"title":"title","toggle":"state","toggle_on":["shut"],                                     "caption":{"status":"state","dates":["when"]}},             "tile":{"face":"slip-list"},"page":[],             "group":{"column":"state","sections":[{"heading":null,"values":["open"]},{"heading":"Shut","values":["shut"]}]}}            """.utf8))        XCTAssertEqual(full.slip.toggleOn, ["shut"])        XCTAssertEqual(full.column("state")?.stamps, ["shut": "done"])        XCTAssertEqual(full.column("when")?.pastName, "Was")        XCTAssertEqual(full.slip.caption, SlipCaption(status: "state", dates: ["when"]))        XCTAssertEqual(full.group?.sections.map(\.heading), [nil, "Shut"])        let again = try JSONDecoder().decode(TableDefinition.self, from: JSONEncoder().encode(full))        XCTAssertEqual(again, full)    }}