Cotton code
121 lines · 6.5 KB · SwiftRaw
// Each list's last drawn answer, kept on disk: a cold open of a list the phone// has drawn before draws them at once and then reads (architect, 12 Oct 2026:// "does not look like an offline-first app"). Every record is invented.import CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class ListSeedsTests: XCTestCase {    private static let chore = TableDefinition(        id: "chore", name: "Chore", plural: "Chores",        columns: [ColumnDefinition(key: "title", type: .text, required: true)],        title: "title",        slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList),        page: [PageSection(heading: nil, columns: ["title"])]    )    private var directory: URL!    override func setUp() async throws {        directory = FileManager.default.temporaryDirectory.appendingPathComponent("list-seeds-\(UUID().uuidString)", isDirectory: true)    }    override func tearDown() async throws {        try? FileManager.default.removeItem(at: directory)    }    private func store(_ count: Int, definition: TableDefinition = chore) -> GatedRecords {        let rows = (1...count).map { TableRecord(id: "example-\(definition.id)-\($0)", values: ["title": .text("Example \($0)")]) }        return GatedRecords(FixtureRecords(definitions: [definition], records: [definition.id: rows]))    }    /// Draws a list once with `seeds`, as a launch that showed it.    private func drawn(_ seeds: ListSeeds, database: String?, definition: TableDefinition = chore) async -> [TableRecord] {        let list = RecordListModel(definition: definition, store: store(3, definition: definition), core: ListCoreFake(), database: database, seeds: seeds)        await list.reload(project: nil, query: "")        await seeds.flushed()        return list.records    }    /// RULE: A cold open of a list drawn before shows its rows at once — before the read answers, with no skeleton — off the seed kept on disk, and the read then lands over them.    func testAColdOpenOfADrawnBeforeListDrawsAtOnce() async throws {        let before = await drawn(ListSeeds(directory: directory), database: "example-database")        XCTAssertEqual(before.count, 3)        // A new process: nothing in memory, the same directory.        let cold = ListSeeds(directory: directory)        let records = store(3)        await records.hold()        let list = RecordListModel(definition: Self.chore, store: records, core: ListCoreFake(), database: "example-database", seeds: cold)        let read = Task { await list.reload(project: nil, query: "") }        for _ in 0..<400 where await records.waiting == 0 { try await Task.sleep(for: .milliseconds(5)) }        XCTAssertEqual(list.phase, .loaded, "the skeleton stood over a list drawn before")        XCTAssertEqual(list.records.map(\.id), before.map(\.id), "the rows drew before the read answered")        await records.release()        await read.value        XCTAssertEqual(list.firstReads, 1)    }    /// RULE: A second open of a list after launch draws without the skeleton, off the rows the first open drew.    func testASecondOpenAfterLaunchDrawsWithoutTheSkeleton() async throws {        let seeds = ListSeeds()        _ = await drawn(seeds, database: nil)        let records = store(3)        await records.hold()        let again = RecordListModel(definition: Self.chore, store: records, core: ListCoreFake(), seeds: seeds)        let read = Task { await again.reload(project: nil, query: "") }        for _ in 0..<400 where await records.waiting == 0 { try await Task.sleep(for: .milliseconds(5)) }        XCTAssertEqual(again.phase, .loaded)        XCTAssertEqual(again.records.count, 3)        await records.release()        await read.value    }    /// RULE: A seed is the database's own: a list in another database never draws it.    func testASeedNeverDrawsInAnotherDatabase() async throws {        _ = await drawn(ListSeeds(directory: directory), database: "example-database-a")        let cold = ListSeeds(directory: directory)        let key = ListSeeds.Key(table: "chore", filter: [:], project: nil, archived: false, section: nil, database: "example-database-b")        XCTAssertNil(cold.answer(for: key))        XCTAssertNotNil(cold.answer(for: ListSeeds.Key(            table: "chore", filter: [:], project: nil, archived: false, section: nil, database: "example-database-a")))    }    /// RULE: Nothing a vault holds is written to disk — not the passwords' table, not a table with a value written blind or a password column — while its list still draws again at once within the process.    func testNoSecretRowIsWrittenToDisk() async throws {        let blind = TableDefinition(            id: "example_token", name: "Token", plural: "Tokens",            columns: [                ColumnDefinition(key: "title", type: .text, required: true),                ColumnDefinition(key: "token", type: .text, secret: true),            ],            title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["title"])])        XCTAssertFalse(ListSeeds.keepsOnDisk(blind))        // The passwords' table says it is sealed: its name is not read.        let sealed = try TableDefinition.decode(Data(contentsOf: SourceSweep.kitTable("secret")))        XCTAssertFalse(ListSeeds.keepsOnDisk(sealed))        XCTAssertTrue(ListSeeds.keepsOnDisk(Self.chore))        let seeds = ListSeeds(directory: directory)        _ = await drawn(seeds, database: "example-database", definition: blind)        let written = (try? FileManager.default.subpathsOfDirectory(atPath: directory.path)) ?? []        XCTAssertFalse(written.contains { $0.hasSuffix(".json") }, "a secret table's rows reached the disk: \(written)")        XCTAssertNotNil(seeds.answer(for: ListSeeds.Key(            table: "example_token", filter: [:], project: nil, archived: false, section: nil, database: "example-database")))    }    /// RULE: An erase takes every seed, on disk and in memory.    func testAnEraseTakesEverySeed() async throws {        let seeds = ListSeeds(directory: directory)        _ = await drawn(seeds, database: "example-database")        seeds.forgetAll()        await seeds.flushed()        XCTAssertFalse(FileManager.default.fileExists(atPath: directory.path))        XCTAssertNil(ListSeeds(directory: directory).answer(for: ListSeeds.Key(            table: "chore", filter: [:], project: nil, archived: false, section: nil, database: "example-database")))    }}