217 lines · 10.3 KB · SwiftRaw
import CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class BulkUndoTests: XCTestCase { private static let table = TableDefinition( id: "batch_note", name: "Note", plural: "Notes", columns: [ColumnDefinition(key: "title", type: .text), ColumnDefinition(key: "position", type: .number)], title: "title", order: "position", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["title"])]) private func fixture() async -> (RecordListModel, BatchRecords) { let rows = (1...5).map { TableRecord(id: "note-\($0)", values: ["title": .text("Invented note \($0)"), "position": .number(Double($0))]) } let store = BatchRecords(FixtureRecords(definitions: [Self.table], records: [Self.table.id: rows])) let list = RecordListModel(definition: Self.table, store: store, core: ListCoreFake(), seeds: ListSeeds()) await list.reload(project: nil, query: "") return (list, store) } func testTheVisibleReceiptUndoesEverySuccessfulDeleteOnce() async throws { let (list, store) = await fixture() let before = list.records let result = await list.delete(ids: ["note-1", "note-2", "note-1"]) XCTAssertEqual(result.deleted, ["note-1", "note-2"]) XCTAssertTrue(result.failed.isEmpty) XCTAssertEqual(list.total, 3) let change = try XCTUnwrap(list.lastChange) XCTAssertTrue(change.said?.said.contains("2") == true, "the receipt carries the count deleted") XCTAssertNil(change.before, "one row must not impersonate the batch") let receipt = ChangeReceiptModel(change: change) let back = await receipt.undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNotNil(back) XCTAssertTrue(receipt.undone) XCTAssertEqual(list.total, 5, "the rows and count arrive before the receipt says Undone") XCTAssertEqual(list.records, before) await list.undone(change) XCTAssertEqual(list.records, before) XCTAssertEqual(list.total, 5) XCTAssertTrue(list.lastChangeUndone) let calls = await store.undoCalls XCTAssertEqual(calls.count, 2) XCTAssertEqual(Set(calls).count, 2) // Even a freshly created card cannot send the completed inverses again. let recreated = ChangeReceiptModel(change: change) let repeated = await recreated.undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNotNil(repeated) let after = await store.undoCalls XCTAssertEqual(after, calls) } func testPartialDeleteStillOffersOneUndoForEverythingThatSucceeded() async throws { let (list, store) = await fixture() await store.refuseDelete("note-3") let result = await list.delete(ids: ["note-1", "note-2", "note-3"]) XCTAssertEqual(result.deleted, ["note-1", "note-2"]) XCTAssertEqual(result.failed, ["note-3"]) let change = try XCTUnwrap(list.lastChange) let receipt = ChangeReceiptModel(change: change) let back = await receipt.undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNotNil(back) await list.undone(change) XCTAssertEqual(Set(list.records.map(\.id)), Set((1...5).map { "note-\($0)" })) XCTAssertEqual(list.total, 5) } func testPartialUndoSurvivesCardRecreationAndRetriesOnlyWhatRemains() async throws { let (list, store) = await fixture() _ = await list.delete(ids: ["note-1", "note-2"]) await store.failUndoOnce(at: 2) let change = try XCTUnwrap(list.lastChange) let first = ChangeReceiptModel(change: change) let failed = await first.undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNil(failed) XCTAssertTrue(first.failed) XCTAssertFalse(first.undone) XCTAssertEqual(list.total, 4, "the successful half is visible before Retry") let initialCalls = await store.undoCalls XCTAssertEqual(initialCalls.count, 2) let retry = ChangeReceiptModel(change: change) let back = await retry.undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNotNil(back) await list.undone(change) let calls = await store.undoCalls let refused = try XCTUnwrap(initialCalls.last) XCTAssertEqual(calls, initialCalls + [refused], "the first successful inverse is never resent") XCTAssertEqual(list.total, 5) XCTAssertEqual(list.records.count, 5) } func testTwoCardsCannotRunTheSameBatchConcurrently() async throws { let (list, store) = await fixture() _ = await list.delete(ids: ["note-1", "note-2"]) let change = try XCTUnwrap(list.lastChange) await store.holdNextUndo() let first = ChangeReceiptModel(change: change) let writing = Task { await first.undo(through: store, perform: list.receiptUndo(for: change)) } await store.waitForUndo() let second = ChangeReceiptModel(change: change) let refused = await second.undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNil(refused) let heldCalls = await store.undoCalls XCTAssertEqual(heldCalls.count, 1) await store.releaseUndo() let back = await writing.value XCTAssertNotNil(back) let retried = await second.undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNotNil(retried) let calls = await store.undoCalls XCTAssertEqual(calls.count, 2) await list.undone(change) XCTAssertEqual(list.total, 5) } func testAnEntirelyRefusedSelectionKeepsThePreviousReceipt() async { let (list, store) = await fixture() await store.refuseDelete("note-1") let prior = ChangeRecord(id: "prior", byline: "", before: nil, after: nil) list.received(prior, foreign: true) let result = await list.delete(ids: ["note-1"]) XCTAssertTrue(result.deleted.isEmpty) XCTAssertEqual(result.failed, ["note-1"]) XCTAssertEqual(list.lastChange, prior) XCTAssertEqual(list.total, 5) } func testOneSuccessfulDeleteKeepsItsOrdinaryReceiptRoute() async throws { let (list, store) = await fixture() _ = await list.delete(ids: ["note-1"]) let change = try XCTUnwrap(list.lastChange) XCTAssertEqual(change.before?.id, "note-1") let back = await ChangeReceiptModel(change: change).undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNotNil(back) await list.undone(change) XCTAssertEqual(list.total, 5) } func testABatchWithAnIrreversibleWriteDoesNotPromiseAFullUndo() async throws { let store = BatchRecords(FixtureRecords(definitions: [Self.table], records: [:])) let batch = BulkUndo(store: store) let changes = [ ChangeRecord(id: "one", byline: "You", before: nil, after: nil), ChangeRecord(id: "two", byline: "You", before: nil, after: nil, undoable: false, reason: "Cannot restore this record."), ] let receipt = batch.remember(changes, done: "Deleted 2", undone: nil) XCTAssertEqual(receipt?.undoable, false) XCTAssertEqual(receipt?.reason, "Cannot restore this record.") do { _ = try await batch.undo(try XCTUnwrap(receipt).id) XCTFail("an irreversible batch must refuse before sending any inverse") } catch ChangeUndoError.unavailable { let calls = await store.undoCalls XCTAssertTrue(calls.isEmpty) } }}private actor BatchRecords: Records { private let inner: FixtureRecords private var refused: Set<String> = [] private var failAt: Int? private var willHoldUndo = false private var holdingUndo = false private var undoStarted: CheckedContinuation<Void, Never>? private var undoRelease: CheckedContinuation<Void, Never>? func holdNextUndo() { willHoldUndo = true } func waitForUndo() async { if holdingUndo { return } await withCheckedContinuation { undoStarted = $0 } } func releaseUndo() { undoRelease?.resume() undoRelease = nil } private(set) var undoCalls: [String] = [] init(_ inner: FixtureRecords) { self.inner = inner } func refuseDelete(_ id: String) { refused.insert(id) } func failUndoOnce(at call: Int) { failAt = call } func tableDefinitions() async throws -> [TableDefinition] { try await inner.tableDefinitions() } func count(table: String) async throws -> Int { try await inner.count(table: table) } func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage { try await inner.list(table: table, project: project, query: query, page: page, where: filter) } func get(table: String, id: String) async throws -> TableRecord? { try await inner.get(table: table, id: id) } func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord { try await inner.create(table: table, data: data) } func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord { try await inner.update(table: table, id: id, patch: patch) } func delete(table: String, id: String) async throws -> ChangeRecord { if refused.contains(id) { throw RecordsError.unknownRecord(id) } return try await inner.delete(table: table, id: id) } func reorder(table: String, ids: [String]) async throws -> ChangeRecord { try await inner.reorder(table: table, ids: ids) } func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord { try await inner.link(table: table, id: id, column: column, target: target) } func undo(change: String) async throws -> ChangeRecord { undoCalls.append(change) if willHoldUndo { willHoldUndo = false holdingUndo = true undoStarted?.resume() undoStarted = nil await withCheckedContinuation { undoRelease = $0 } holdingUndo = false } if undoCalls.count == failAt { failAt = nil throw RecordsError.unknownChange(change) } return try await inner.undo(change: change) }}