210 lines · 13.4 KB · SwiftRaw
// R4 and Spec 5 on the Swift side (architect notes 27fcb084 and 99ba6232):// the receipt prints the words the core answers, a command is one of four// kinds run by one runner, and its Undo is the command its definition names.// Every record is invented.import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class CoreReceiptWordsTests: XCTestCase { private static let errand = TableDefinition( id: "errand", name: "Errand", plural: "Errands", builtin: true, engine: "todos", columns: [ ColumnDefinition(key: "title", type: .text), ColumnDefinition(key: "done", type: .bool), ColumnDefinition(key: "person_id", type: .link), ColumnDefinition(key: "site", type: .url), ], title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["title", "done"])]) private func facts(_ change: ChangeRecord, canUndo: Bool = true) -> ChangeReceiptFacts { ChangeReceiptFacts.of(change, table: Self.errand, canUndo: canUndo, hasRecords: true, undone: false, failed: false) } private func command(_ json: String) throws -> RecordCommand { try JSONDecoder().decode(RecordCommand.self, from: Data(json.utf8)) } // ── R4: the receipt's words are the core's ────────────────────────── /// RULE: A change that carries the core's receipt prints its sentence and nothing composed here: a switch or a state is the sentence alone, with no before and after. func testAReceiptPrintsTheCoresSentence() throws { let before = TableRecord(id: "example-1", values: ["title": .text("Call the plumber"), "done": .bool(false)]) let after = TableRecord(id: "example-1", values: ["title": .text("Call the plumber"), "done": .bool(true)]) let switched = ChangeRecord( id: "change-1", byline: "You", before: before, after: after, said: ChangeSaid(kind: "switched", said: "Marked Call the plumber done")) XCTAssertEqual(facts(switched).lines.map(\.kind), [.said("Marked Call the plumber done")]) let added = ChangeRecord( id: "change-2", byline: "You", before: nil, after: after, said: ChangeSaid(kind: "added", said: "Added Call the plumber")) XCTAssertEqual(facts(added).lines.map(\.kind), [.said("Added Call the plumber")]) XCTAssertTrue(facts(added).offersUndo, "an add carries Undo") } /// RULE: A before and after is shown only for a change of words, as the core lists them; a journal append is the added sentence alone. func testOnlyWordsCarryABeforeAndAfter() throws { let edited = ChangeRecord( id: "change-3", byline: "You", before: nil, after: nil, said: ChangeSaid( kind: "edited", said: "Edited Bike shed list", words: [ChangeSaid.Words(name: "Title", before: "Shed list", after: "Bike shed list")])) XCTAssertEqual( facts(edited).lines.map(\.kind), [.said("Edited Bike shed list"), .changed(name: "Title", before: "Shed list", after: "Bike shed list")]) let appended = ChangeRecord( id: "change-4", byline: "You", before: nil, after: nil, said: ChangeSaid( kind: "appended", said: "The ferry was late.", words: [ChangeSaid.Words(name: "Entry", before: "An invented morning.", after: "An invented morning.\nThe ferry was late.")])) XCTAssertEqual(facts(appended).lines.map(\.kind), [.said("The ferry was late.")]) } /// RULE: The wire change's receipt is decoded as the core sends it — kind, said and words — and one without words reads as none. func testTheCoresReceiptDecodes() throws { let full = try JSONDecoder().decode( ChangeSaid.self, from: Data(#"{"kind":"edited","said":"Edited Kite","words":[{"name":"Title","before":null,"after":"Kite"}]}"#.utf8)) XCTAssertEqual(full, ChangeSaid(kind: "edited", said: "Edited Kite", words: [ChangeSaid.Words(name: "Title", before: nil, after: "Kite")])) let bare = try JSONDecoder().decode(ChangeSaid.self, from: Data(#"{"kind":"added","said":"Added Kite"}"#.utf8)) XCTAssertEqual(bare.words, []) } // ── Spec 5: a command is one of four kinds ────────────────────────── /// RULE: A command decodes its kind — create, update, delete or open — with receipt, undo and opens; verb is absent on an open, and a kind outside the four does not decode. func testACommandDecodesItsKind() throws { let pin = try command(#"{"id":"pin","label":"Pin","kind":"update","verb":"set_thread_pinned","receipt":"Pinned","undo":"unpin"}"#) XCTAssertEqual(pin.kind, .update) XCTAssertEqual(pin.receipt, "Pinned") XCTAssertEqual(pin.undo, "unpin") let open = try command(#"{"id":"person","label":"Open person","kind":"open","opens":"person_id"}"#) XCTAssertEqual(open.kind, .open) XCTAssertNil(open.verb) XCTAssertEqual(open.opens, "person_id") XCTAssertEqual(try JSONDecoder().decode(RecordCommand.self, from: JSONEncoder().encode(pin)), pin) XCTAssertThrowsError(try command(#"{"id":"x","label":"X","kind":"script"}"#)) } func testMethodCommandPreservesItsDeviceTargetAndBindings() throws { let hold = try command(#"{"id":"hold","label":"Hold here","kind":"update","method":"repo.hold","bindings":{"repo_id":"$id"},"when":{"held_here":false}}"#) XCTAssertNil(hold.verb) XCTAssertEqual(hold.method, "repo.hold") let record = TableRecord(id: "synthetic-repo", values: ["held_here": .bool(false)]) XCTAssertTrue(hold.applies(to: record)) XCTAssertEqual(hold.arguments(for: record), ["repo_id": .text("synthetic-repo")]) XCTAssertEqual(try JSONDecoder().decode(RecordCommand.self, from: JSONEncoder().encode(hold)), hold) } /// RULE: A list in command.when means any listed value, while separate /// columns still all have to match; an empty list never offers the act. func testCommandConditionsMatchAnyListedValueAndEveryColumn() throws { let pause = try command(#"{"id":"pause","label":"Pause","when":{"state":["Reading","Needs sign-in","Failed"],"locked":false}}"#) for state in ["Reading", "Needs sign-in", "Failed"] { XCTAssertTrue(pause.applies(to: TableRecord(id: "synthetic", values: ["state": .text(state)]))) XCTAssertFalse(pause.applies(to: TableRecord(id: "synthetic", values: ["state": .text(state), "locked": .bool(true)]))) } let unavailable: [RecordValue] = [.null, .text("Paused"), .list([.text("Reading")]), .bool(false)] for value in unavailable { XCTAssertFalse(pause.applies(to: TableRecord(id: "synthetic", values: ["state": value]))) } let absent = try command(#"{"id":"x","label":"X","when":{"flag":[false,"ready"]}}"#) XCTAssertTrue(absent.applies(to: TableRecord(id: "synthetic", values: [:]))) let empty = try command(#"{"id":"x","label":"X","when":{"state":[]}}"#) XCTAssertFalse(empty.applies(to: TableRecord(id: "synthetic", values: [:]))) } func testCommandConditionsCanExcludeValuesWithoutChangingNullOrAllColumnSemantics() throws { let one = try command(#"{"id":"x","label":"X","when":{"state":{"not":"dead"},"locked":false}}"#) let many = try command(#"{"id":"x","label":"X","when":{"state":{"not":["dead","expired"]}}}"#) for state in ["live", "dead", "expired"] { let row = TableRecord(id: "synthetic", values: ["state": .text(state)]) XCTAssertEqual(one.applies(to: row), state != "dead") XCTAssertEqual(many.applies(to: row), state == "live") } XCTAssertFalse(one.applies(to: TableRecord(id: "synthetic", values: ["state": .text("live"), "locked": .bool(true)]))) let absent = TableRecord(id: "synthetic", values: [:]) XCTAssertTrue(many.applies(to: absent)) XCTAssertFalse(try command(#"{"id":"x","label":"X","when":{"state":{"not":[false]}}}"#).applies(to: absent)) XCTAssertTrue(try command(#"{"id":"x","label":"X","when":{"state":{"not":[]}}}"#).applies(to: absent)) XCTAssertFalse(try command(#"{"id":"x","label":"X","when":{"state":{"not":[],"extra":true}}}"#).applies(to: absent)) } /// RULE: An open is offered only while its column holds something to open, and every delete asks first whether or not it says destructive. func testAnOpenNeedsItsColumnAndADeleteAsksFirst() throws { let open = try command(#"{"id":"person","label":"Open person","kind":"open","opens":"person_id"}"#) XCTAssertFalse(open.applies(to: TableRecord(id: "example-1", values: ["person_id": .null]))) XCTAssertTrue(open.applies(to: TableRecord(id: "example-1", values: ["person_id": .text("example-person")]))) XCTAssertFalse(open.asksFirst) let delete = try command(#"{"id":"delete","label":"Delete this errand","kind":"delete","verb":"delete_errand"}"#) XCTAssertTrue(delete.asksFirst) let pin = try command(#"{"id":"pin","label":"Pin","kind":"update","verb":"set_thread_pinned"}"#) XCTAssertFalse(pin.asksFirst) } /// RULE: A command's change says the core's receipt and offers Undo only when the core names the command that takes it back; an open answers what to open and wears no receipt. func testACommandsOutcomeIsItsReceiptItsUndoOrWhatItOpens() throws { func outcome(_ json: String) throws -> ChangeRecord { try JSONDecoder().decode(CommandOutcome.self, from: Data(json.utf8)).change(table: "errand", record: "example-1") } let pinned = try outcome(#"{"command":"pin","kind":"update","receipt":"Pinned","undo":"unpin","answer":{"pinned":true},"open":null}"#) XCTAssertEqual(facts(pinned).lines.map(\.kind), [.said("Pinned")]) XCTAssertTrue(facts(pinned).offersUndo) XCTAssertEqual(pinned.command, CommandTaken(table: "errand", record: "example-1", undo: "unpin")) let cleared = try outcome(#"{"command":"clear","kind":"update","receipt":"Chat cleared","undo":null,"answer":{},"open":null}"#) XCTAssertFalse(facts(cleared).offersUndo) XCTAssertNil(facts(cleared).note) let person = try outcome(#"{"command":"person","kind":"open","receipt":null,"undo":null,"answer":null,"open":{"table":"person","id":"example-person"}}"#) XCTAssertEqual(person.opened, .record(RecordLink(table: "person", id: "example-person"))) XCTAssertNil(person.said) let site = try outcome(#"{"command":"site","kind":"open","receipt":null,"undo":null,"answer":null,"open":{"url":"https://example.com/a"}}"#) XCTAssertEqual(site.opened, .address("https://example.com/a")) } /// RULE: A command's Undo runs the command its definition names on the same record through the one runner, never the change undo, and the receipt then reads as undone. func testACommandsUndoRunsTheNamedCommand() async throws { let store = CommandsStore() let pinned = ChangeRecord( id: "command-1", byline: "You", before: nil, after: nil, undoable: true, said: ChangeSaid(kind: "command", said: "Pinned"), command: CommandTaken(table: "errand", record: "example-1", undo: "unpin")) let model = ChangeReceiptModel(change: pinned) let back = await model.undo(through: store) XCTAssertNotNil(back) XCTAssertEqual(store.ran, ["errand/example-1/unpin"]) XCTAssertEqual(store.undone, []) XCTAssertTrue(model.undone) // A store that runs no commands never leaves the Undo silent. let deaf = ChangeReceiptModel(change: pinned) let nothing = await deaf.undo(through: FixtureRecords(definitions: [Self.errand], records: [:])) XCTAssertNil(nothing) XCTAssertTrue(deaf.failed) }}@MainActorprivate final class CommandsStore: RecordCommands { var ran: [String] = [] var undone: [String] = [] func tableDefinitions() async throws -> [TableDefinition] { [] } func count(table: String) async throws -> Int { 0 } func get(table: String, id: String) async throws -> TableRecord? { nil } func command(table: String, id: String, command: RecordCommand, picked: String?) async throws -> ChangeRecord { ran.append("\(table)/\(id)/\(command.id)") return ChangeRecord(id: "command-back", byline: "You", before: nil, after: nil, said: ChangeSaid(kind: "command", said: "Unpinned")) } func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage { RecordPage(records: [], next: nil) } func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord { throw RecordsError.unknownTable(table) } func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord { throw RecordsError.unknownTable(table) } func delete(table: String, id: String) async throws -> ChangeRecord { throw RecordsError.unknownTable(table) } func reorder(table: String, ids: [String]) async throws -> ChangeRecord { throw RecordsError.unknownTable(table) } func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord { throw RecordsError.unknownTable(table) } func undo(change: String) async throws -> ChangeRecord { undone.append(change) throw RecordsError.unknownChange(change) }}