Cotton code
169 lines · 9.0 KB · SwiftRaw
import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI/// After a write the list made, its rows and its count are read again: the/// database's, never the rows held less one (S6, architect 1735). Each/// heading's and link's count is the core's (`shell_list_tests.rs`).@MainActorfinal class SharedCountsTests: XCTestCase {    private static let pulls: TableDefinition = {        var definition = TableDefinition(            id: "pull", name: "Pull", plural: "Pulls",            columns: [ColumnDefinition(key: "title", type: .text), ColumnDefinition(key: "state", type: .text)],            title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList),            page: [PageSection(heading: nil, columns: ["title", "state"])])        definition.group = ListGrouping(column: "state", sections: [            ListGroup(heading: "Open", values: ["open"]),            ListGroup(heading: "Merged", values: ["merged"], closed: true),        ])        return definition    }()    /// A table of pulls that archives, drawn as a column of slips or as a grid of polaroids: one model reads both.    private static func archiving(_ face: TileFace) -> TableDefinition {        var definition = TableDefinition(            id: "pull", name: "Pull", plural: "Pulls",            columns: [                ColumnDefinition(key: "title", type: .text), ColumnDefinition(key: "state", type: .text),                ColumnDefinition(key: "archived_at", type: .date),            ],            title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: face),            page: [PageSection(heading: nil, columns: ["title", "state"])], archived: "archived_at")        definition.group = pulls.group        return definition    }    /// RULE: After a delete, a Select delete, an archive or a bring back the list made, its rows and its count are the database's again — never the rows held less one.    func testAfterAWriteTheListMadeItsRowsAndCountsAreTheDatabasesAgain() async throws {        let store = LiveRecords(open: 3, merged: 40, archived: 2)        let model = RecordListModel(definition: Self.archiving(.slipList), store: store, core: ListCoreFake(), seeds: ListSeeds())        await model.reload(project: nil, query: "")        XCTAssertEqual(model.total, 43)        // A delete: the database lets go of the row and, as a database may, of one more beside it.        await store.alsoDrops("m2")        try await model.delete(XCTUnwrap(model.records.first { $0.id == "m1" }))        XCTAssertFalse(model.records.contains { $0.id == "m2" }, "the rows are read again with it")        XCTAssertEqual(model.total, 41)        _ = await model.delete(ids: ["m3", "m4"])        XCTAssertEqual(model.total, 39, "Select's delete")        // An archive: the write the core's Archive names (`press[].write`).        try await model.write(XCTUnwrap(model.records.first { $0.id == "m5" }), ["archived_at": .text("2026-10-06T09:00:00.000Z")])        XCTAssertFalse(model.records.contains { $0.id == "m5" })        XCTAssertEqual(model.total, 38, "an archive")        // Bring back is made on the list of the archived; the list returned to reads again (Back).        let put = RecordListModel(            definition: Self.archiving(.slipList), store: store, core: ListCoreFake(), archived: true, seeds: ListSeeds())        await put.reload(project: nil, query: "")        XCTAssertEqual(put.records.count, 3)        try await put.write(XCTUnwrap(put.records.first { $0.id == "m5" }), ["archived_at": .null])        XCTAssertEqual(put.records.map(\.id).sorted(), ["a1", "a2"])        XCTAssertEqual(put.total, 2)        await model.refresh()        XCTAssertEqual(model.total, 39, "a bring back")    }    /// RULE: A re-read that meets the next page on its way is never dropped: it is made when that page lands, so a write on a long list still moves its count.    func testAReReadThatMeetsAPageOnItsWayIsMadeWhenThePageLands() async throws {        let store = LiveRecords(open: 3, merged: 40, archived: 0, pageSize: 10)        let model = RecordListModel(            definition: Self.archiving(.slipList), store: store, core: ListCoreFake(), pageSize: 10, seeds: ListSeeds())        await model.reload(project: nil, query: "")        XCTAssertEqual(model.records.count, 10)        await store.hold(page: 10)        let paging = Task { await model.loadMore() }        while await !store.holding { await Task.yield() }        await store.drop("m39")        await model.refresh()        XCTAssertEqual(model.total, 43, "the page is still on its way")        await store.release()        await paging.value        XCTAssertEqual(model.total, 42, "made when the page landed")    }}/// A database of pulls: every read answers what it holds NOW — the live rows/// a page at a time, each group's whole count, and how many are archived.private actor LiveRecords: Records {    private var rows: [TableRecord]    private let pageSize: Int    private var dropsToo: String?    private var heldPage: Int?    private var gate: CheckedContinuation<Void, Never>?    private var changes = 0    var holding: Bool { gate != nil }    init(open: Int, merged: Int, archived: Int, pageSize: Int = 500) {        func row(_ id: String, _ state: String, archived: Bool = false) -> TableRecord {            var values: [String: RecordValue] = ["title": .text(id), "state": .text(state)]            if archived { values["archived_at"] = .text("2026-10-05T09:00:00.000Z") }            return TableRecord(id: id, values: values)        }        rows = (1...max(open, 1)).prefix(open).map { row("o\($0)", "open") }            + (1...max(merged, 1)).prefix(merged).map { row("m\($0)", "merged") }            + (1...max(archived, 1)).prefix(archived).map { row("a\($0)", "merged", archived: true) }        self.pageSize = pageSize    }    func alsoDrops(_ id: String) { dropsToo = id }    func drop(_ id: String) { rows.removeAll { $0.id == id } }    func hold(page: Int) { heldPage = page }    func release() {        heldPage = nil        gate?.resume()        gate = nil    }    private func isArchived(_ row: TableRecord) -> Bool { row["archived_at"].text != nil }    private var live: [TableRecord] { rows.filter { !isArchived($0) } }    private func page(of all: [TableRecord], from start: Int) -> RecordPage {        let end = min(all.count, start + pageSize)        let live = self.live        return RecordPage(            records: start < end ? Array(all[start..<end]) : [], next: end < all.count ? end : nil, total: all.count,            sections: ["open", "merged"].map { state in PlanSection(key: state, count: live.filter { $0["state"].text == state }.count) },            archived: rows.count - live.count)    }    func tableDefinitions() async throws -> [TableDefinition] { [] }    func count(table: String) async throws -> Int { live.count }    func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage {        if heldPage == page { await withCheckedContinuation { gate = $0 } }        return self.page(of: live, from: page)    }    func archivedCount(table: String, project: String?, query: String?, where filter: [String: RecordValue]) async throws -> Int? {        rows.count - live.count    }    func listArchived(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage {        let put = rows.filter(isArchived)        return RecordPage(records: put, next: nil, total: put.count)    }    func get(table: String, id: String) async throws -> TableRecord? { rows.first { $0.id == id } }    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 {        guard let index = rows.firstIndex(where: { $0.id == id }) else { throw RecordsError.unknownTable(table) }        let before = rows[index]        for (key, value) in patch {            if case .null = value { rows[index].values[key] = nil } else { rows[index].values[key] = value }        }        changes += 1        return ChangeRecord(id: "change-\(changes)", byline: "You", before: before, after: rows[index])    }    func delete(table: String, id: String) async throws -> ChangeRecord {        guard let before = rows.first(where: { $0.id == id }) else { throw RecordsError.unknownTable(table) }        rows.removeAll { $0.id == id || $0.id == dropsToo }        dropsToo = nil        changes += 1        return ChangeRecord(id: "change-\(changes)", byline: "You", before: before, after: nil)    }    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 { throw RecordsError.unknownChange(change) }}