Cotton code
160 lines · 9.8 KB · SwiftRaw
import CottonValuesimport Foundationimport XCTestimport SwiftUI@testable import CottonUI@MainActorfinal class SwiftKeysCatchupTests: XCTestCase {    private func decode(column: String = "", slip: String = "", extra: String = "", titleColumn: String = "", columns: String = "") throws -> TableDefinition {        try TableDefinition.decode(Data("""        {"id":"example","name":"Example","plural":"Examples","builtin":false,         "columns":[{"key":"title","type":"text"\(titleColumn)},{"key":"body","type":"longtext"},                    {"key":"state","type":"choice","choices":["open","missed"]\(column)}\(columns)],         "title":"title","slip":{"title":"title"\(slip)},"tile":{"face":"slip-list"},         "page":[{"columns":["title","body","state"]}]\(extra)}        """.utf8))    }    private func record(_ values: [String: RecordValue]) -> TableRecord {        TableRecord(id: "example-record", values: values)    }    private func roundTrip(_ definition: TableDefinition) throws {        XCTAssertEqual(try TableDefinition.decode(JSONEncoder().encode(definition)), definition)    }    /// RULE: red_when names raw values that wear red ink; other values and definitions without the rule keep their face's ink, so state never changes paper tint.    func testRedWhenDecodesAndChoosesInkFromTheRawValue() throws {        let d = try decode(column: #", "red_when":["missed"]"#)        let c = try XCTUnwrap(d.column("state"))        XCTAssertEqual(c.redWhen, ["missed"])        XCTAssertNil(try decode().column("state")?.redWhen)        try roundTrip(d)    }    /// RULE: placeholder is the empty column's word on faces, including null and empty text; a written value still reads as itself and no placeholder preserves the old empty reading.    func testPlaceholderDecodesAndReadsOnlyForEmptyValues() throws {        let d = try decode(column: #", "placeholder":"Once""#)        let c = try XCTUnwrap(d.column("state"))        XCTAssertEqual(c.placeholder, "Once")        XCTAssertEqual(FaceText.line(.null, column: c), "Once")        XCTAssertEqual(FaceText.slipLine(.text(""), column: c), "Once")        XCTAssertEqual(FaceText.line(.text("open"), column: c), "Open")        XCTAssertNil(FaceText.line(.null, column: try decode().column("state")))        try roundTrip(d)    }    /// RULE: A list's one layout is the definition's `layout` with `grid.columns` across, and absent is the slips — never a choice a device makes (owner, 15 Oct 2026).    func testTheLayoutIsTheDefinitionsOwn() throws {        let d = try decode(extra: #", "layout":"sheet", "grid":{"columns":4}"#)        XCTAssertEqual(d.layout, .sheet)        XCTAssertEqual(d.grid?.columns, 4)        XCTAssertEqual(try decode(extra: #", "layout":"cards""#).layout, .cards)        XCTAssertEqual(try decode().layout, .list)        XCTAssertNil(try decode().grid)        try roundTrip(d)    }    /// RULE: top-level lists decode as separate linked sections under the table's list; they do not become the page's column sections and absent lists stay empty.    func testTopLevelListsDecodeAsLinkedSections() throws {        let d = try decode(extra: #", "lists":[{"heading":"Recent","list":{"table":"other","link":"example_id","empty":"None yet"}}]"#)        XCTAssertEqual(d.lists, [PageSection(heading: "Recent", list: SectionList(table: "other", link: "example_id", empty: "None yet"))])        XCTAssertEqual(d.page.filter { $0.list != nil }, [])        XCTAssertEqual(try decode().lists, [])        try roundTrip(d)    }    /// RULE: SectionList.face accepts slip or page, with absent or unknown meaning slip; page draws the linked record's own card so a script can be read straight through.    func testSectionListFaceDecodesAndSelectsTheFace() throws {        for (word, face) in [("slip", SectionListFace.slip), ("page", SectionListFace.page)] {            let d = try decode(extra: ", \"lists\":[{\"list\":{\"table\":\"other\",\"face\":\"\(word)\"}}]")            XCTAssertEqual(d.lists.first?.list?.face, face)            XCTAssertEqual(d.lists.first?.list?.drawingFace, face)            try roundTrip(d)        }        XCTAssertEqual(SectionList(table: "other").drawingFace, .slip)        // A face word the core does not know never reaches the app: the core's        // SectionFace refuses it, and Swift reads only what the core decoded.    }    /// RULE: Every key in this Rust-owned sample survives Swift decoding and encoding, including nested keys; an unknown key fails this guard rather than silently losing the shared format.    func testEveryKeyInARustDefinitionSampleIsKnownToSwift() throws {        // Rust owns these paths. Missing files must fail, never shrink the sample.        for name in ["note", "person"] {            let data = try Data(contentsOf: Self.kit.appendingPathComponent("\(name).json"))            let definition = try TableDefinition.decode(data)            let original = try JSONSerialization.jsonObject(with: data)            let encoded = try JSONSerialization.jsonObject(with: JSONEncoder().encode(definition))            assertKeys(original, encoded, path: name)        }    }    /// The personal kit's tables (crates/cotton-core/kits/personal/tables): one    /// definition per table, the one the object serves.    private static var kit: URL {        kits.appendingPathComponent("personal/tables")    }    /// Every kit (crates/cotton-core/kits/<app>).    private static var kits: URL {        let root = ProcessInfo.processInfo.environment["COTTON_TEST_REPO_ROOT"].map { URL(fileURLWithPath: $0) } ?? SourceSweep.repoRoot        return root.appendingPathComponent("crates/cotton-core/kits")    }    /// RULE: A definition's tables (its package's physical tables, which the core renders into storage) survive Swift decoding and encoding exactly for every table the kit ships, because a definition the app reads and passes on must never lose or reshape its storage.    func testEveryPackageTableSurvivesSwiftExactly() throws {        let files = try [Self.kit, Self.kits.appendingPathComponent("shell/tables")].flatMap { tables -> [URL] in            try FileManager.default.contentsOfDirectory(atPath: tables.path)                .filter { $0.hasSuffix(".json") }.map { tables.appendingPathComponent($0) }        }        XCTAssertFalse(files.isEmpty, "\(Self.kit.path) holds the kit's tables")        for url in files {            let file = url.lastPathComponent            let data = try Data(contentsOf: url)            guard let tables = (try JSONSerialization.jsonObject(with: data) as? [String: Any])?["tables"] else { continue }            let encoded = try JSONSerialization.jsonObject(with: JSONEncoder().encode(TableDefinition.decode(data))) as? [String: Any]            XCTAssertEqual(encoded?["tables"] as? NSArray, tables as? NSArray, "\(file): tables changed on the way through Swift")        }    }    /// RULE: A computed column's three shapes — lookup, rollup and formula — survive Swift decoding and encoding key for key from the Rust-owned fixture, and a computed column is read-only whether or not it says so.    func testEveryComputedShapeIsKnownToSwiftAndReadOnly() throws {        let root = ProcessInfo.processInfo.environment["COTTON_TEST_REPO_ROOT"].map { URL(fileURLWithPath: $0) } ?? SourceSweep.repoRoot        let data = try Data(contentsOf: root.appendingPathComponent("crates/cotton-core/tests/fixtures/definitions-parity-7/computed_parity.json"))        let definition = try TableDefinition.decode(data)        let computed = definition.columns.filter { $0.computed != nil }        let original = try JSONSerialization.jsonObject(with: data)        let declared = ((original as? [String: Any])?["columns"] as? [[String: Any]] ?? []).filter { $0["computed"] != nil }        XCTAssertFalse(declared.isEmpty)        XCTAssertEqual(computed.count, declared.count, "every computed column of the fixture decodes to a shape")        XCTAssertTrue(computed.allSatisfy(\.readonly))        let encoded = try JSONSerialization.jsonObject(with: JSONEncoder().encode(definition))        assertKeys(original, encoded, path: "computed_parity")    }    private func assertKeys(_ original: Any, _ encoded: Any, path: String) {        if let object = original as? [String: Any], let read = encoded as? [String: Any] {            for (key, value) in object {                // Codable omits known nil slots. Check their actual CodingKeys too.                if value is NSNull {                    let known: [String]                    if path.contains(".tables[") { known = DefinitionPackageColumn.CodingKeys.allCases.map(\.stringValue) }                    else if path.contains(".columns[") { known = ColumnDefinition.CodingKeys.allCases.map(\.stringValue) }                    else if path.hasSuffix(".list") { known = SectionList.CodingKeys.allCases.map(\.stringValue) }                    else if path.contains(".slip") { known = SlipLayout.CodingKeys.allCases.map(\.stringValue) }                    else if path.contains(".group.sections[") { known = ListGroup.CodingKeys.allCases.map(\.stringValue) }                    else if path.contains(".page[") || path.contains(".lists[") { known = PageSection.CodingKeys.allCases.map(\.stringValue) }                    else { known = TableDefinition.CodingKeys.allCases.map(\.stringValue) }                    XCTAssertTrue(known.contains(key), "\(path).\(key) is unknown")                } else {                    XCTAssertNotNil(read[key], "\(path).\(key) is unknown or lost")                    if let next = read[key] { assertKeys(value, next, path: "\(path).\(key)") }                }            }        } else if let array = original as? [Any], let read = encoded as? [Any] {            XCTAssertEqual(array.count, read.count, path)            for (index, pair) in zip(array, read).enumerated() { assertKeys(pair.0, pair.1, path: "\(path)[\(index)]") }        }    }}