472 lines · 25.8 KB · SwiftRaw
// The list's reader over the fixture verbs and a fake core (`ListCoreFake`):// its pages, its re-reads, its seeds, its receipts and its undo. What the list// shows is the core's (`shell_list_tests.rs`). Every record is invented.import CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class RecordListModelTests: XCTestCase { private static let chore = TableDefinition( id: "chore", name: "Chore", plural: "Chores", columns: [ ColumnDefinition(key: "title", type: .text, required: true), ColumnDefinition(key: "done", type: .bool), ColumnDefinition(key: "position", type: .number), ColumnDefinition(key: "project", type: .link, linkTo: "project"), ], title: "title", project: "project", order: "position", slip: SlipLayout(title: "title", toggle: "done"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["title", "done"])] ) /// The reader's own page when the list names none. private static let page = 50 private func chores(_ count: Int) -> [TableRecord] { (1...count).map { n in TableRecord(id: "example-chore-\(n)", values: [ "title": .text("Example chore \(n)"), "done": .bool(false), "position": .number(Double(n)), "project": .text(n.isMultiple(of: 2) ? "example-project-even" : "example-project-odd"), ]) } } private func model(_ count: Int) -> RecordListModel { let store = FixtureRecords(definitions: [Self.chore], records: ["chore": chores(count)]) return RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: ListSeeds()) } /// RULE: A list reads one page at a time and the next page lands after the last slip, never twice. func testAListReadsOnePageAtATimeAndAppendsTheNext() async { let list = model(Self.page + 10) await list.reload(project: nil, query: "") XCTAssertEqual(list.records.count, Self.page) XCTAssertTrue(list.hasMore) await list.loadMore() XCTAssertEqual(list.records.count, Self.page + 10) XCTAssertEqual(Set(list.records.map(\.id)).count, list.records.count) XCTAssertFalse(list.hasMore) await list.loadMore() XCTAssertEqual(list.records.count, Self.page + 10) } /// RULE: An ask for the next page made while one is on its way is served when it lands, never dropped, so a list pages to its end (People stopped at its 100th person when the marker's one ask came mid-read). func testAnAskDuringAReadIsServedNotDropped() async { let list = model(Self.page * 3 + 5) await list.reload(project: nil, query: "") XCTAssertEqual(list.records.count, Self.page) async let first: Void = list.loadMore() async let second: Void = list.loadMore() _ = await (first, second) XCTAssertEqual(list.records.count, Self.page * 3, "the second ask reads the page after the first's") let reading = Task { await list.loadMore() } await list.readToEnd() await reading.value XCTAssertEqual(list.records.count, Self.page * 3 + 5, "readToEnd waits for a read on its way and goes on") XCTAssertFalse(list.hasMore) XCTAssertEqual(Set(list.records.map(\.id)).count, list.records.count) } /// RULE: Coming back to a list re-reads the pages it had read, at their depth — never only the first page — so a list scrolled through several pages keeps every slip above the one opened and its scroll with them (S2 at scale: Todos, Notes, Calendar). func testAReturnKeepsEveryPageAlreadyRead() async throws { let list = model(Self.page + 10) await list.reload(project: nil, query: "") await list.loadMore() XCTAssertEqual(list.records.count, Self.page + 10) await list.refresh() XCTAssertEqual(list.records.count, Self.page + 10, "a refresh reads to the depth it had") XCTAssertFalse(list.hasMore) } /// RULE: An undo re-reads the list as deep as it was read, never only its first page, so the reader stays where they were (S2: undoing a Calendar delete jumped the list from Mon 12 back to Wed 7). func testAnUndoKeepsEveryPageAlreadyRead() async throws { let list = model(Self.page + 10) await list.reload(project: nil, query: "") await list.loadMore() XCTAssertEqual(list.records.count, Self.page + 10) await list.undone() XCTAssertEqual(list.records.count, Self.page + 10, "an undo reads to the depth the list had") XCTAssertFalse(list.hasMore) } /// RULE: A record a page deleted or archived leaves the list at once, before any re-read — People's 1,500-row re-read kept it 10–17 s (S6, walk6 12:10Z). func testAPageRemovalLeavesAtOnce() async throws { let list = model(5) await list.reload(project: nil, query: "") let third = try XCTUnwrap(list.records.first { $0.id == "example-chore-3" }) let change = ChangeRecord(id: "example-change", byline: "", before: third, after: nil) list.received(change) list.removed(by: change) XCTAssertEqual(list.records.map(\.id), ["example-chore-1", "example-chore-2", "example-chore-4", "example-chore-5"]) XCTAssertEqual(list.lastChange, change) } /// RULE: A failed re-read keeps healthy rows and reports a reading problem until success, because a read failure must never claim that a write changed nothing. func testFailedRefreshReportsReadingProblem() async { let store = FailingRecords(FixtureRecords(definitions: [Self.chore], records: ["chore": chores(3)])) let list = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: ListSeeds()) await list.reload(project: nil, query: "") let shown = list.records await store.fail(true) await list.reload(project: nil, query: "") XCTAssertEqual(list.phase, .loaded) XCTAssertEqual(list.records, shown) XCTAssertNotNil(list.readProblem) await store.fail(false) await list.reload(project: nil, query: "") XCTAssertNil(list.readProblem) } /// RULE: A refused next page keeps the existing rows and shows its sentence until a successful retry, because pagination must not hide read failures. func testAFailedNextPageShowsItsProblemUntilRetry() async { let store = FailingRecords(FixtureRecords(definitions: [Self.chore], records: ["chore": chores(60)])) let list = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: ListSeeds()) await list.reload(project: nil, query: "") await store.fail(true) await list.loadMore() XCTAssertEqual(list.phase, .loaded) XCTAssertEqual(list.records.count, Self.page) XCTAssertNotNil(list.readProblem) XCTAssertTrue(list.hasMore) await store.fail(false) await list.loadMore() XCTAssertNil(list.readProblem) XCTAssertEqual(list.records.count, 60) } /// RULE: A list whose read fails says so rather than showing an empty table. func testAFailedReadIsNotAnEmptyList() async { let store = FixtureRecords(definitions: [], records: [:]) // Its own seeds: a seed another test left would be drawn and kept, // which is the frame a failed first read keeps (walker 294 row G). let list = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: ListSeeds()) await list.reload(project: nil, query: "") XCTAssertEqual(list.phase, .failed) } /// A list that is read again while on screen (a poll, a sync) and whose /// re-read fails keeps the rows it has: only a first read fails the list. func testAFailedReReadKeepsTheRowsOnScreen() async { let store = FailingRecords(FixtureRecords(definitions: [Self.chore], records: ["chore": chores(3)])) let list = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: ListSeeds()) await list.reload(project: nil, query: "") XCTAssertEqual(list.records.count, 3) await store.fail(true) await list.reload(project: nil, query: "") XCTAssertEqual(list.phase, .loaded) XCTAssertEqual(list.records.count, 3, "a failed re-read emptied the list") XCTAssertNotNil(list.readProblem, "the retained rows must say the refresh failed") // A new search that fails is a first read of that search: it fails. await list.reload(project: nil, query: "chore 2") XCTAssertEqual(list.phase, .failed) } /// RULE: A live table's re-read reads every page the list was scrolled through, in place: a record changed behind the list shows its change, and no row read by a later page goes missing. func testALiveReReadReadsAsDeepAsTheListWasScrolled() async throws { let store = FixtureRecords(definitions: [Self.chore], records: ["chore": chores(Self.page + 10)]) let list = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: ListSeeds()) await list.reload(project: nil, query: "") await list.loadMore() XCTAssertEqual(list.records.count, Self.page + 10) let deep = "example-chore-\(Self.page + 5)" _ = try await store.update(table: "chore", id: deep, patch: ["title": .text("Example chore changed elsewhere")]) await list.refresh() XCTAssertEqual(list.records.count, Self.page + 10, "the re-read dropped the rows of the second page") XCTAssertEqual(list.records.first { $0.id == deep }?["title"].text, "Example chore changed elsewhere") XCTAssertFalse(list.hasMore) XCTAssertEqual(list.phase, .loaded) } /// RULE: A live re-read that fails keeps the rows on screen, and one asked for before the first read landed reads nothing. func testAFailedLiveReReadKeepsTheRowsAndAnEarlyOneReadsNothing() async { let store = FailingRecords(FixtureRecords(definitions: [Self.chore], records: ["chore": chores(3)])) let list = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: ListSeeds()) await list.refresh() XCTAssertEqual(list.phase, .loading, "a tick before the first read is not a read") XCTAssertEqual(list.records, []) await list.reload(project: nil, query: "") await store.fail(true) await list.refresh() XCTAssertEqual(list.phase, .loaded) XCTAssertEqual(list.records.count, 3, "a failed tick emptied the list") XCTAssertNotNil(list.readProblem) await store.fail(false) await list.refresh() XCTAssertNil(list.readProblem) } /// RULE: A list drawn from its saved rows keeps reading on its beat until a read lands, even when its first read failed: a seed holding a device asking to join, whose first read fails, keeps its rows beside the could-not-read line, and once the answer without that row lands on the beat alone — nobody pulls — no pending row is left on the list or in the seed (walker296: an answered join request stood on the Mac's Devices list, the 5-second beat re-reading nothing because no read had ever landed). func testASeedWhoseFirstReadFailedReadsOnItsBeatUntilTheAnswerLeavesNoPendingRow() async throws { // A synthetic devices table: the shipped device.json went with the kit move (13e1775e7). let device = try TableDefinition.decode(Data(""" {"id":"device","name":"Device","plural":"Devices","builtin":false, "columns":[{"key":"name","type":"text"},{"key":"status","type":"text"}],"title":"name", "slip":{"title":"name"},"tile":{"face":"slip-list"},"page":[{"heading":null,"columns":["name","status"]}], "group":{"column":"status","sections":[{"heading":"Asking to join","values":["waiting"]}, {"heading":"Joined","values":["this device","approved"]}]}} """.utf8)) let mac = TableRecord(id: "example-device-mac", values: ["name": .text("Example Mac"), "status": .text("this device")]) let phone = TableRecord(id: "example-device-phone", values: ["name": .text("Example Phone"), "status": .text("waiting")]) let store = FailingRecords(FixtureRecords(definitions: [device], records: ["device": [mac, phone]])) let seeds = ListSeeds() let key = ListSeeds.Key(table: "device", filter: [:], project: nil, archived: false, section: nil) // An earlier open kept the answer holding both. await RecordListModel(definition: device, store: store, core: ListCoreFake(), seeds: seeds).reload(project: nil, query: "") XCTAssertEqual(Set(seeds.answer(for: key)?.rows.map(\.id) ?? []), [mac.id, phone.id]) let list = RecordListModel(definition: device, store: store, core: ListCoreFake(), seeds: seeds) // The open: the seed draws at once and the first read fails over it. await store.fail(true) await list.reload(project: nil, query: "") XCTAssertEqual(list.phase, .loaded, "a failed first read blanked the seed") XCTAssertEqual(Set(list.records.map(\.id)), [mac.id, phone.id], "the seed's rows stay beside the line") XCTAssertNotNil(list.readProblem) // The request is answered elsewhere; the next read answers without it. _ = try await store.delete(table: "device", id: phone.id) await store.fail(false) // The beat, and nothing else. list.dataMoved() for _ in 0..<400 where list.settled == 0 { try await Task.sleep(for: .milliseconds(5)) } XCTAssertEqual(list.settled, 1) XCTAssertEqual(list.records.map(\.id), [mac.id], "the answered request still stood on the list") XCTAssertNil(list.readProblem) XCTAssertEqual(seeds.answer(for: key)?.rows.map(\.id), [mac.id], "the seed still holds the answered request") } /// RULE: A read that lands over a seed on screen says so once (`seedsReplaced`), so the deck deals that read's order; a re-read after it does not. func testAReadLandingOverASeedIsCountedOnce() async throws { let device = try TableDefinition.decode(Data(""" {"id":"device","name":"Device","plural":"Devices","builtin":false, "columns":[{"key":"name","type":"text"}],"title":"name", "slip":{"title":"name"},"tile":{"face":"slip-list"},"page":[{"heading":null,"columns":["name"]}]} """.utf8)) let one = TableRecord(id: "example-device-one", values: ["name": .text("Example one")]) let two = TableRecord(id: "example-device-two", values: ["name": .text("Example two")]) let store = FixtureRecords(definitions: [device], records: ["device": [one, two]]) let seeds = ListSeeds() let key = ListSeeds.Key(table: "device", filter: [:], project: nil, archived: false, section: nil) await RecordListModel(definition: device, store: store, core: ListCoreFake(), seeds: seeds).reload(project: nil, query: "") XCTAssertNotNil(seeds.answer(for: key), "an earlier open kept its answer") let list = RecordListModel(definition: device, store: store, core: ListCoreFake(), seeds: seeds) await list.reload(project: nil, query: "") XCTAssertEqual(list.seedsReplaced, 1, "the first read over the seed") await list.reload(project: nil, query: "") XCTAssertEqual(list.seedsReplaced, 1, "a re-read over the read's own rows") } /// RULE: A live re-read reads the project and search the rows on screen were read for. func testALiveReReadKeepsTheProjectAndSearch() async { let core = ListCoreFake() let store = FixtureRecords(definitions: [Self.chore], records: ["chore": chores(9)]) let list = RecordListModel(definition: Self.chore, store: store, core: core, seeds: ListSeeds()) await list.reload(project: "example-project-even", query: " chore ") await list.refresh() XCTAssertEqual(core.asks, 2) XCTAssertEqual(core.asked.last?["project"] as? String, "example-project-even") XCTAssertEqual(core.asked.last?["query"] as? String, "chore") XCTAssertEqual(list.records.map(\.id), ["example-chore-2", "example-chore-4", "example-chore-6", "example-chore-8"]) } func testVisibleUndoRestoresTheListBeforeItsReceiptSettles() async throws { let store = FixtureRecords(definitions: [Self.chore], records: ["chore": chores(3)]) let list = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: ListSeeds()) await list.reload(project: nil, query: "") let before = list.records let change = try await list.delete(before[1]) XCTAssertEqual(list.total, 2) let receipt = ChangeReceiptModel(change: change) let back = await receipt.undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNotNil(back) XCTAssertTrue(receipt.undone) XCTAssertEqual(list.records, before, "the callback has not run yet") XCTAssertEqual(list.total, 3) await list.undone(change) XCTAssertTrue(list.lastChangeUndone) let recreated = ChangeReceiptModel(change: change) let repeated = await recreated.undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNotNil(repeated) XCTAssertEqual(list.records, before) } func testUndoReadFailureRetriesTheReadWithoutRepeatingTheInverse() async throws { let store = FailingRecords(FixtureRecords(definitions: [Self.chore], records: ["chore": chores(3)])) let list = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: ListSeeds()) await list.reload(project: nil, query: "") let change = try await list.delete(list.records[1]) await store.fail(true) let receipt = ChangeReceiptModel(change: change) let refused = await receipt.undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNil(refused) XCTAssertTrue(receipt.failed) XCTAssertFalse(receipt.undone) await store.fail(false) let retry = ChangeReceiptModel(change: change) let back = await retry.undo(through: store, perform: list.receiptUndo(for: change)) XCTAssertNotNil(back) XCTAssertTrue(retry.undone) XCTAssertEqual(list.total, 3) XCTAssertNil(list.readProblem) let calls = await store.undoCalls XCTAssertEqual(calls, 1) } func testACommandOnlyAnswerWaitsForTheAuthoritativeRowBeforeItsReceipt() async throws { let store = WaitingCommandRecords( FixtureRecords(definitions: [Self.chore], records: ["chore": chores(3)]), returnsRows: false) let list = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), where: ["done": .bool(false)], seeds: ListSeeds()) await list.reload(project: nil, query: "") let first = try XCTUnwrap(list.records.first) let writing = Task { try await list.run(RecordCommand(id: "done", label: "Mark done"), on: first) } await store.waitForRead() XCTAssertNil(list.lastChange) XCTAssertEqual(list.total, 3, "the command has no row or count to apply before the read") await store.releaseRead() let change = try await writing.value XCTAssertEqual(list.lastChange, change) XCTAssertFalse(list.records.contains { $0.id == first.id }) XCTAssertEqual(list.total, 2) } func testARefusedCommandKeepsTheRowsAndReceipt() async throws { let store = WaitingCommandRecords(FixtureRecords(definitions: [Self.chore], records: ["chore": chores(3)])) await store.refuseCommands() let list = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: ListSeeds()) await list.reload(project: nil, query: "") let before = list.records let prior = ChangeRecord(id: "prior-change", byline: "", before: nil, after: nil) list.received(prior, foreign: true) do { _ = try await list.run(RecordCommand(id: "done", label: "Mark done"), on: before[0]) XCTFail("the fixture refuses the command") } catch { XCTAssertEqual(error as? RecordsError, .unknownRecord(before[0].id)) } XCTAssertEqual(list.records, before) XCTAssertEqual(list.lastChange, prior) XCTAssertEqual(list.total, 3) } func testACommandReadCannotReplaceANewerReceipt() async throws { let store = WaitingCommandRecords(FixtureRecords(definitions: [Self.chore], records: ["chore": chores(3)])) let list = RecordListModel(definition: Self.chore, store: store, core: ListCoreFake(), seeds: ListSeeds()) await list.reload(project: nil, query: "") let first = try XCTUnwrap(list.records.first) let writing = Task { try await list.run(RecordCommand(id: "done", label: "Mark done"), on: first) } await store.waitForRead() let newer = ChangeRecord(id: "newer-change", byline: "", before: nil, after: nil) list.received(newer, foreign: true) await store.releaseRead() _ = try await writing.value XCTAssertEqual(list.lastChange, newer) }}/// Fixture verbs whose `list` can be made to fail.private actor FailingRecords: Records { private let inner: FixtureRecords private var failing = false private(set) var undoCalls = 0 init(_ inner: FixtureRecords) { self.inner = inner } func fail(_ on: Bool) { failing = on } 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 { if failing { throw RecordsError.unknownTable(table) } return 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 { 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 += 1 return try await inner.undo(change: change) }}// A command succeeds while its following read waits on an explicit barrier.private actor WaitingCommandRecords: RecordCommands { private let inner: FixtureRecords private let returnsRows: Bool private var refusing = false func refuseCommands() { refusing = true } private var blocked = false private var readStarted = false private var waiting: CheckedContinuation<Void, Never>? private var reading: CheckedContinuation<Void, Never>? init(_ inner: FixtureRecords, returnsRows: Bool = true) { self.inner = inner self.returnsRows = returnsRows } func waitForRead() async { if readStarted { return } await withCheckedContinuation { waiting = $0 } } func releaseRead() { blocked = false reading?.resume() reading = nil } func command(table: String, id: String, command: RecordCommand, picked: String?) async throws -> ChangeRecord { if refusing { throw RecordsError.unknownRecord(id) } let change = try await inner.update(table: table, id: id, patch: ["done": .bool(true)]) blocked = true if returnsRows { return change } return ChangeRecord(id: change.id, byline: "You", before: nil, after: nil, command: CommandTaken(table: table, record: id, undo: "reopen")) } 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 { if blocked { readStarted = true waiting?.resume() waiting = nil await withCheckedContinuation { reading = $0 } } return 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 { 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 { try await inner.undo(change: change) }}