Cotton code
129 lines · 7.7 KB · SwiftRaw
// What a list, a page and a receipt draw when a read or an undo goes wrong,// and the titles a page section's slips draw their link columns with.//// The defects these hold (review of #1378): a page section's slips saw only// the page record's own link titles, so a note's person drew blank inside// the person's page; a link title that could not be read, a link into a table no// definition names, and a change that did not say whether it could be undone// were each answered with a quiet default; an undo the core refused said// "Couldn't undo that." over the core's own reason; and nothing told the root's// lists that a sync or an assistant's write had moved their rows.import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class ReadFailuresAreSaidTests: XCTestCase {    private func definitions() throws -> [TableDefinition] {        let loaded = FixtureDefinitions.load(from: try TestResources.bundle())        XCTAssertEqual(loaded.failures.count, 0)        return loaded.definitions    }    private func definition(_ id: String) throws -> TableDefinition {        try XCTUnwrap(try definitions().first { $0.id == id }, "\(id) is shipped")    }    private static let person = TableRecord(id: "s1", values: ["full_name": .text("Example person"), "avatar_photo_id": .text("p1")])    private static let note = TableRecord(        id: "o1", values: ["body": .text("An invented note."), "person_id": .text("s1")])    /// RULE: A page section's slip draws its link columns with the titles its own list read over the page's, because the page's titles name only the page record's links and a person's notes would draw their person blank.    func testASectionSlipDrawsTheLinkTitlesItsListRead() async throws {        let notes = try definition("person_note")        let store = FixtureRecords(definitions: try definitions(), records: ["person": [Self.person], "person_note": [Self.note]])        let section = RecordListModel(definition: notes, store: store, core: ListCoreFake(), where: ["person_id": .text("s1")], seeds: ListSeeds())        await section.reload(project: nil, query: "")        XCTAssertEqual(section.records.map(\.id), ["o1"])        let column = notes.column("person_id")        // The page's own titles: the person's page reads the links IN the        // person, which never name the person itself.        let page = LinkTitles(["p1": "Example photo"])        XCTAssertNil(FaceText.line(Self.note["person_id"], column: column, links: page.byID), "the defect: blank")        let drawn = RecordsSection.slipTitles(page: page, list: section.linkTitles)        XCTAssertEqual(FaceText.line(Self.note["person_id"], column: column, links: drawn.byID), "Example person")        XCTAssertEqual(drawn.byID["p1"], "Example photo", "the page's titles stay under the list's")    }    /// RULE: A link into a table no definition names is refused by the core's records with the table's id, because skipping it drew that column blank with no sign anything was wrong.    func testALinkIntoAnUnknownTableIsRefused() async throws {        let core = ScriptedCore(["tools.list": .ok(#"{"tools":[],"table_definitions":[],"refused":[]}"#)])        let store = CoreRecords(core: core, bundle: try TestResources.bundle())        do {            _ = try await store.linkTitles(for: [RecordLink(table: "no_such_table", id: "x1")])            XCTFail("a link into an unknown table was answered")        } catch let error as RecordsError {            XCTAssertEqual(error, .unknownTable("no_such_table"))        }    }    /// RULE: A change the core answers without saying whether it can be undone is a malformed answer, never one assumed undoable, because an Undo offered on a guess is an Undo the core then refuses.    func testAChangeWithoutUndoableIsRefused() 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"},"reason":null},"record":{"table":"note","id":"n1","data":{"title":"Plan"}}}"#),        ])        let store = CoreRecords(core: core, bundle: try TestResources.bundle())        do {            _ = try await store.create(table: "note", data: ["title": .text("Plan")])            XCTFail("a change with no undoable was drawn")        } catch {}    }    /// RULE: An undo the core refuses shows the core's own reason on the receipt, because "Couldn't undo that." over a reason the core gave hides why.    func testARefusedUndoCarriesTheCoresReason() async throws {        let core = ScriptedCore([            "records.undo": .refuse(code: "write_refused", message: "That change was already undone on another device."),        ])        let store = CoreRecords(core: core, bundle: try TestResources.bundle())        let change = ChangeRecord(            id: "ch-1", byline: "You", before: nil, after: TableRecord(id: "n1", values: ["title": .text("Plan")]),            undoable: true, reason: nil)        let model = ChangeReceiptModel(change: change)        let back = await model.undo(through: store)        XCTAssertNil(back)        XCTAssertTrue(model.failed)        XCTAssertEqual(model.failure, "That change was already undone on another device.")        let facts = ChangeReceiptFacts.of(            change, table: nil, canUndo: true, hasRecords: true, undone: false, failed: model.failed, failure: model.failure)        XCTAssertEqual(facts.note, "That change was already undone on another device.")        let plain = ChangeReceiptFacts.of(change, table: nil, canUndo: true, hasRecords: true, undone: false, failed: true)        XCTAssertEqual(plain.note, ChangeReceiptFacts.failedNote, "with no reason said, the plain failure")    }}/// A store whose every read answers but whose link titles are refused.private final class TitlesRefused: Records, @unchecked Sendable {    private let base: FixtureRecords    private let refusal: ActionRefused    init(_ base: FixtureRecords, _ refusal: ActionRefused) {        self.base = base        self.refusal = refusal    }    func tableDefinitions() async throws -> [TableDefinition] { try await base.tableDefinitions() }    func count(table: String) async throws -> Int { try await base.count(table: table) }    func lastChanged(table: String) async throws -> String? { try await base.lastChanged(table: table) }    func toolDefinitions() async throws -> [ToolDefinition] { try await base.toolDefinitions() }    func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage {        try await base.list(table: table, project: project, query: query, page: page, where: filter)    }    func linkTitles(for links: [RecordLink]) async throws -> LinkTitles { throw refusal }    func get(table: String, id: String) async throws -> TableRecord? { try await base.get(table: table, id: id) }    func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord {        try await base.create(table: table, data: data)    }    func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord {        try await base.update(table: table, id: id, patch: patch)    }    func delete(table: String, id: String) async throws -> ChangeRecord { try await base.delete(table: table, id: id) }    func reorder(table: String, ids: [String]) async throws -> ChangeRecord { try await base.reorder(table: table, ids: ids) }    func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord {        try await base.link(table: table, id: id, column: column, target: target)    }    func undo(change: String) async throws -> ChangeRecord { try await base.undo(change: change) }}