import CottonKit import Foundation import SwiftUI import XCTest @testable import CottonUI @MainActor final class DatabaseTableCatalogTests: XCTestCase { func testSwitchReadsTheNewCatalogAndALateOldReadCannotReplaceIt() async throws { let core = DelayedDatabaseCatalogCore() let catalog = DatabaseTableCatalog { database in let scoped = DatabaseScopedCore(underlying: core, database: database) // No fixture: each database's own catalogue is what is read. let records = CoreRecords(core: scoped) return DatabaseTableCatalog.Source(tables: .core(records, writer: ScreenWriter(core: scoped))) { reload in if reload { try await records.refreshCatalog() } return try await records.tableDefinitions() } } let personal = Task { await catalog.refresh(database: "personal") } await core.personalArrived() await catalog.refresh(database: "yoga") XCTAssertNotNil(catalog.tables.definitions["classes"]) XCTAssertNil(catalog.tables.definitions["private_notes"]) await core.releasePersonal() await personal.value XCTAssertNotNil(catalog.tables.definitions["classes"], "Personal answered last but Yoga is still selected") XCTAssertNil(catalog.tables.definitions["private_notes"]) // Each catalogue was read from its own database, Personal first; how // many calls each read takes is the reader's business. let sent = await core.databases XCTAssertEqual(sent.reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } }, ["personal", "yoga"]) await catalog.refresh(database: "personal") XCTAssertNil(catalog.tables.definitions["classes"]) XCTAssertNotNil(catalog.tables.definitions["private_notes"]) } /// RULE: Until a window has read the shown database's catalogue its definitions say they are not read, so the board reads nothing through the bundled set; a failed read lets the board draw what it holds. func testTheBundledSetSaysItIsNotReadUntilTheCatalogueIs() async throws { let core = DelayedDatabaseCatalogCore() await core.releasePersonal() let bundle = try TestResources.bundle() let fails = FailSwitch() let catalog = DatabaseTableCatalog { database in let scoped = DatabaseScopedCore(underlying: core, database: database) let records = CoreRecords(core: scoped, bundle: bundle) return DatabaseTableCatalog.Source(tables: .core(records, writer: ScreenWriter(core: scoped))) { _ in if fails.on { throw CancellationError() } return try await records.tableDefinitions() } } // uxfix10: a switch back to the large personal database read its board // through the bundled set for 1.9 s, and that read ran on to 6.3 s. XCTAssertFalse(catalog.tables.definitions.isRead, "a new window holds the bundled set") await catalog.refresh(database: "yoga") XCTAssertTrue(catalog.tables.definitions.isRead) catalog.point(at: "personal") XCTAssertFalse(catalog.tables.definitions.isRead, "turned to another database, it holds the bundled set again") fails.on = true await catalog.refresh(database: "personal") XCTAssertTrue(catalog.tables.definitions.isRead, "a read that failed is not waited on for ever") XCTAssertTrue(TableDefinitions([]).isRead, "a set made from definitions is read") } /// Rigby walk, 22 Oct 2026: Messages and Notebook flashed "This app cannot show these records" for one frame before their empty state — the refusal was drawn on the set a window holds while its catalogue read was in flight. /// /// RULE: A read in flight never draws a refusal: the unknown-table refusal is said only on the answer of the catalogue read, never on the set a window holds before it nor on a screen handed no definitions at all. func testAReadInFlightNeverDrawsTheUnknownTableRefusal() async throws { let core = DelayedDatabaseCatalogCore() await core.releasePersonal() let catalog = DatabaseTableCatalog { database in let scoped = DatabaseScopedCore(underlying: core, database: database) let records = CoreRecords(core: scoped) return DatabaseTableCatalog.Source(tables: .core(records, writer: ScreenWriter(core: scoped))) { _ in try await records.tableDefinitions() } } XCTAssertFalse(UnknownTable.refuses(catalog.tables.definitions), "the held set refused before its read answered") XCTAssertFalse(UnknownTable.refuses(EnvironmentValues().tableDefinitions), "no definitions handed down refused") await catalog.refresh(database: "yoga") XCTAssertNil(catalog.tables.definitions["no_such_table"]) XCTAssertTrue(UnknownTable.refuses(catalog.tables.definitions), "the answered catalogue lacks the table: that is the refusal") } } private final class FailSwitch: @unchecked Sendable { var on = false } private actor DelayedDatabaseCatalogCore: CottonCalling { private(set) var databases: [String] = [] private var arrivals: [CheckedContinuation] = [] private var waiting: [CheckedContinuation] = [] private var released = false func personalArrived() async { if databases.contains("personal") { return } await withCheckedContinuation { arrivals.append($0) } } func releasePersonal() { released = true waiting.forEach { $0.resume() }; waiting = [] } func callRaw(_ method: String, requestJSON: String) async throws -> String { let request = try JSONDecoder().decode([String: JSONValue].self, from: Data(requestJSON.utf8)) let database = request["database"]?.string ?? "personal" databases.append(database) if database == "personal", !released { arrivals.forEach { $0.resume() }; arrivals = [] await withCheckedContinuation { waiting.append($0) } } let id = database == "yoga" ? "classes" : "private_notes" let definition = TableDefinition(id: id, name: id, plural: id, picture: nil, columns: [ColumnDefinition(key: "title", type: .text)], title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList), page: [PageSection(heading: nil, columns: ["title"])]) let table = try JSONSerialization.jsonObject(with: JSONEncoder().encode(definition)) if method == CottonMethod.definitionsCatalogue { let bytes = try JSONSerialization.data(withJSONObject: ["ok": true, "data": CatalogueAnswers.data(tables: [table as? [String: Any] ?? [:]])]) return String(decoding: bytes, as: UTF8.self) } let answer: [String: Any] = ["tools": [["definition": ["id": id, "name": id, "tables": [id], "instructions": "", "automations": [], "author": ["device": "test", "name": "Test"]], "signature": "unsigned"]], "table_definitions": [["definition": table, "orphaned": false]], "refused": []] let bytes = try JSONSerialization.data(withJSONObject: ["ok": true, "data": answer]) return String(decoding: bytes, as: UTF8.self) } func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {} func close() async {} }