Cotton code
116 lines · 7.6 KB · SwiftRaw
import CottonKitimport Foundationimport XCTest@testable import CottonUIfinal class CommandAnswerTests: XCTestCase {    private static let ask = #"{"table":"transaction","data":{"description":"spent 450 on groceries","occurred_on":"2026-10-01","notes":"example-source"},"question":"From which account?","column":"money_account_id","options":[{"id":"example-bank","label":"Example bank"},{"id":"example-wallet","label":"Example wallet"}]}"#    private static let created = #"{"change":{"id":"native-created-change","record_id":"example-movement","before":null,"after":{"description":"spent 450 on groceries","money_account_id":"example-bank"},"undoable":true,"receipt":{"kind":"added","said":"Recorded groceries"}},"record":{"table":"transaction","id":"example-movement","data":{"description":"spent 450 on groceries","money_account_id":"example-bank","occurred_on":"2026-10-01","notes":"example-source"}}}"#    private func asked(_ answer: String) throws -> CreateQuestion {        do {            _ = try outcome(answer)            throw ActionRefused("Expected a nonwriting question")        } catch let question as CreateQuestion { return question }    }    func testCommandQuestionsKeepTheNativeContinuationWithoutReturningAChange() throws {        for suffix in ["", #", "change":null, "record":null"#] {            let question = try asked("{\"ask\":\(Self.ask)\(suffix)}")            XCTAssertEqual(question.table, "transaction")            XCTAssertEqual(question.data, ["description": .text("spent 450 on groceries"), "occurred_on": .text("2026-10-01"), "notes": .text("example-source")])            XCTAssertEqual(question.options.map(\.id), ["example-bank", "example-wallet"])            XCTAssertTrue(question.openCreated)        }    }    func testMalformedCommandContinuationsCannotBecomeSuccessfulReceipts() {        for answer in [            #"{"ask":{"question":"Which account?","column":"money_account_id","options":[]}}"#,            #"{"ask":{"table":"transaction","question":"Which account?","column":"money_account_id"}}"#,            #"{"pending":"true"}"#,            #"{"pending":true,"change":{"id":"already-written"}}"#,            "{\"ask\":\(Self.ask),\"change\":{\"id\":\"already-written\",\"undoable\":true}}",        ] {            XCTAssertThrowsError(try asked(answer)) { error in                XCTAssertTrue(error is DecodingError)            }        }    }    func testCreatedCommandCarriesItsTargetAlongsideTheRealChangeAndUndo() throws {        let json = "{\"command\":\"record\",\"kind\":\"create\",\"receipt\":\"Recorded groceries\",\"undo\":null,\"answer\":\(Self.created),\"open\":null}"        let change = try JSONDecoder().decode(CommandOutcome.self, from: Data(json.utf8)).change(table: "money_account", record: "example-source")        XCTAssertEqual(change.created, RecordLink(table: "transaction", id: "example-movement"))        XCTAssertNil(change.opened, "an open-only outcome would drop the write receipt")        XCTAssertEqual(change.id, "native-created-change")        XCTAssertNil(change.command)        XCTAssertTrue(change.undoable)        XCTAssertEqual(change.said?.said, "Recorded groceries")    }    /// An article's Fetch lands on the download it made at the object, which    /// comes by sync: the page waits for it rather than opening a row not here.    func testARecordMadeAtTheObjectLandsOnceSyncBringsIt() throws {        let landed = #"{"command":"fetch","kind":"create","receipt":"Queued for your Mac","undo":null,"answer":{"fetch":"fetch-1"},"open":{"table":"fetch","id":"fetch-1","by_sync":true}}"#        let change = try JSONDecoder().decode(CommandOutcome.self, from: Data(landed.utf8)).change(table: "page", record: "example-page")        XCTAssertEqual(change.opened, .landed(RecordLink(table: "fetch", id: "fetch-1")))        let here = #"{"command":"chat","kind":"open","receipt":null,"undo":null,"answer":null,"open":{"table":"thread","id":"example-chat"}}"#        let opened = try JSONDecoder().decode(CommandOutcome.self, from: Data(here.utf8)).change(table: "thread_member", record: "example-member")        XCTAssertEqual(opened.opened, .record(RecordLink(table: "thread", id: "example-chat")))    }    private func outcome(_ answer: String, undo: String = "null") throws -> ChangeRecord {        let json = """        {"command":"delete","kind":"delete","receipt":"Deleted Invented note","undo":\(undo),"answer":\(answer),"open":null}        """        return try JSONDecoder().decode(CommandOutcome.self, from: Data(json.utf8)).change(table: "note", record: "example-note")    }    func testGenericDeleteKeepsTheDurableUndoHandleAndDeletedRow() throws {        let change = try outcome(#"{"change":{"id":"example-change","record_id":"example-note","byline":"user","before":{"title":"Invented note"},"after":null,"undoable":true},"record":{"id":"example-note","data":{"title":"Invented note","body":"Synthetic words."},"deleted_at":"2026-10-07T00:00:00Z"}}"#)        XCTAssertEqual(change.id, "example-change")        XCTAssertTrue(change.undoable)        XCTAssertNil(change.command, "records.undo must receive the durable change id")        XCTAssertEqual(change.before?.id, "example-note")        XCTAssertEqual(change.before?["title"], .text("Invented note"))        XCTAssertEqual(change.before?["body"], .text("Synthetic words."))        XCTAssertNil(change.after)    }    func testReturnedUpdatePreservesUnchangedColumnsAndExplicitClears() throws {        let change = try outcome(#"{"change":{"id":"example-update","record_id":"example-note","before":{"archived_at":"2026-10-06T00:00:00Z"},"after":{"archived_at":null},"undoable":true},"record":{"id":"example-note","data":{"title":"Invented note"}}}"#)        XCTAssertEqual(change.before?["archived_at"], .text("2026-10-06T00:00:00Z"))        XCTAssertEqual(change.after?["archived_at"], .null)        XCTAssertEqual(change.after?["title"], .text("Invented note"))    }    func testCommandReceiptNamesTheIntentAndKeepsTheWritesDurableUndo() throws {        let json = #"{"command":"move","kind":"update","receipt":"Moved to Allotment","undo":null,"answer":{"change":{"id":"move-change","record_id":"example-todo","before":{"project":null},"after":{"project":"allotment"},"undoable":true,"receipt":{"kind":"changed","said":"Changed Mend the fence"}},"record":{"id":"example-todo","data":{"title":"Mend the fence","project":"allotment"}}},"open":null}"#        let change = try JSONDecoder().decode(CommandOutcome.self, from: Data(json.utf8))            .change(table: "todo", record: "example-todo")        XCTAssertEqual(change.said?.said, "Moved to Allotment")        XCTAssertEqual(change.said?.kind, "command")        XCTAssertEqual(change.id, "move-change")        XCTAssertTrue(change.undoable)        XCTAssertNil(change.command, "the native write's durable Undo remains authoritative")        XCTAssertEqual(change.before?["project"], .null)        XCTAssertEqual(change.after?["project"], .text("allotment"))        XCTAssertEqual(change.after?["title"], .text("Mend the fence"))    }    func testAChangedRecordWithoutAnUndoDeclarationIsMalformed() {        XCTAssertThrowsError(try outcome(#"{"change":{"id":"incomplete"}}"#))    }    func testEngineAnswersKeepTheirNamedInverseAndDoNotInventAChange() throws {        for answer in [#"{"id":"example-note","status":"done"}"#, "[]", "true", #""Done""#, "null"] {            let change = try outcome(answer, undo: #""reopen""#)            XCTAssertEqual(change.command, CommandTaken(table: "note", record: "example-note", undo: "reopen"))            XCTAssertTrue(change.undoable)            XCTAssertNil(change.before)            XCTAssertNil(change.after)        }    }}