Cotton code
152 lines · 10.2 KB · SwiftRaw
import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI/// One decoder of the definition format (architect, 14 Oct 2026): the core/// reads, resolves and decodes the definitions, and the app draws what the/// core hands over (`definitions.catalogue`, `DefinitionCatalogue`). These/// guards hold the app's side of that.final class BundledDefinitionDecodingTests: XCTestCase {    private final class Marker {}    private func snapshot(in bundle: Bundle) throws -> (raw: Data, catalogue: DefinitionCatalogue) {        let url = try XCTUnwrap(bundle.url(forResource: "catalogue", withExtension: "json", subdirectory: "Fixtures"),                                "the bundle carries no fixture of the core's answer")        let raw = try Data(contentsOf: url)        return (raw, DefinitionCatalogue.read(try DefinitionCatalogues.read(raw)))    }    /// RULE: A definition the core accepts always draws: every table, board and theme in the core's catalogue of a database that took the kit (the fixture the core generates from that answer) reads into the app's view types with no failure, in the compiled resource bundle as well as the source tree — so the app can never trap on a definition its core answers.    func testEveryDefinitionTheCoreAnswersDraws() throws {        let compiled = try XCTUnwrap(CottonUIResources.bundle ?? CottonUIResources.locate(from: Bundle(for: Marker.self)),                                     "The compiled CottonUI resource bundle is missing; no tree fallback is allowed")        let source = try XCTUnwrap(Bundle(url: SourceSweep.iosSources.appendingPathComponent("CottonUI/Resources")))        for (name, bundle) in [("compiled", compiled), ("source", source)] {            let (raw, catalogue) = try snapshot(in: bundle)            XCTAssertEqual(catalogue.failures, [], "\(name): the core answers definitions this app cannot draw")            let answer = try XCTUnwrap(JSONSerialization.jsonObject(with: raw) as? [String: Any])            let tables = ((answer["tables"] as? [[String: Any]]) ?? []).compactMap { $0["id"] as? String }            XCTAssertFalse(tables.isEmpty, "\(name): the answer carries no tables")            XCTAssertEqual(catalogue.tables.map(\.id), tables.sorted(), "\(name): every table the core answers is drawn")            XCTAssertEqual(Set(catalogue.boards.keys), Set((answer["boards"] as? [String: Any] ?? [:]).keys))            XCTAssertEqual(Set(catalogue.themeRows.keys), Set((answer["themes"] as? [String: Any] ?? [:]).keys))        }    }    /// RULE: Every column type the core can write decodes through the phone's shipped decoder: a table of the core's catalogue carrying one column of each `DefinitionColumnType` — which the core's own guard holds equal to Rust's `ColumnType::ALL` — reads into the app's view types with nothing failing (294, walker293: a phone refused Personal's money_account on `account_number`).    func testEveryColumnTypeTheCoreWritesDecodes() throws {        let compiled = try XCTUnwrap(CottonUIResources.bundle ?? CottonUIResources.locate(from: Bundle(for: Marker.self)))        let url = try XCTUnwrap(compiled.url(forResource: "catalogue", withExtension: "json", subdirectory: "Fixtures"))        var answer = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])        var tables = try XCTUnwrap(answer["tables"] as? [[String: Any]])        let index = try XCTUnwrap(tables.firstIndex { $0["id"] as? String == "person" })        var columns = try XCTUnwrap(tables[index]["columns"] as? [[String: Any]])        for kind in DefinitionColumnType.allCases {            columns.append(["key": "every_\(kind.rawValue)", "type": kind.rawValue])        }        tables[index]["columns"] = columns        answer["tables"] = tables        let catalogue = DefinitionCatalogue.read(try DefinitionCatalogues.read(JSONSerialization.data(withJSONObject: answer)))        XCTAssertEqual(catalogue.failures, [])        let drawn = try XCTUnwrap(catalogue.tables.first { $0.id == "person" })        XCTAssertEqual(Set(drawn.columns.filter { $0.key.hasPrefix("every_") }.map(\.type)), Set(DefinitionColumnType.allCases))    }    /// RULE: Handing the definitions over can fail only as a plain refusal: no precondition, fatalError or try! over the definitions in the code that reads them or in CoreRecords — a failed hand-over is the open screen saying why, never a crash.    func testAFailedHandOverIsNeverACrash() throws {        for file in ["CottonUI/Definitions/CoreRecords.swift", "CottonUI/Definitions/DefinitionCatalogue.swift",                     "CottonUI/Definitions/FixtureDefinitions.swift", "CottonUI/Definitions/BoardDefinition.swift",                     "CottonPaper/Theme/ThemeDefaults.swift", "CottonKit/DefinitionCatalogues.swift"] {            let code = SourceSweep.withoutComments(try String(contentsOf: SourceSweep.source(file), encoding: .utf8))            for trap in ["precondition(", "fatalError(", "preconditionFailure(", "try!"] {                XCTAssertFalse(code.contains(trap), "\(file) can trap: \(trap)")            }        }    }    /// RULE: The app never reads a definition file: no Swift under Sources or App opens the bundle's Definitions folder — the core is the one decoder of the definition format, and the app draws what `definitions.catalogue` hands over (phone cut 273 crashed on a file the core accepted and the app's own decoder refused).    func testNoSwiftReadsADefinitionFile() throws {        let root = SourceSweep.repoRoot.appendingPathComponent("apps/cotton")        var read = 0        for folder in ["Sources", "App"] {            let walker = FileManager.default.enumerator(at: root.appendingPathComponent(folder), includingPropertiesForKeys: nil)            while let url = walker?.nextObject() as? URL {                guard url.pathExtension == "swift" else { continue }                read += 1                let code = SourceSweep.withoutComments(try String(contentsOf: url, encoding: .utf8))                for opens in [#"subdirectory: "Definitions"#, #""Definitions/"#, "Resources/Definitions"] {                    XCTAssertFalse(code.contains(opens), "\(url.path) reads a definition file (\(opens))")                }            }        }        XCTAssertGreaterThan(read, 0, "the walk found the app's Swift")    }    /// RULE: The definition code decodes only what the core handed over: under Sources/CottonUI/Definitions a bundle file is opened only for the core's catalogue snapshot (`Shipped`) or the synthetic records (`Fixtures`), never by enumerating a folder, and only through `readBundledJSON` — so no `JSONDecoder` or `Decodable` type there can ever be fed a definition file the core has not decoded (two decoders of one format are two truths; phone cut 273 crashed on that).    func testDefinitionCodeDecodesOnlyWhatTheCoreHandedOver() throws {        let folder = SourceSweep.iosSources.appendingPathComponent("CottonUI/Definitions")        let walker = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: nil)        let lookup = try NSRegularExpression(pattern: #"forResource:[^)]*subdirectory:\s*"([^"]*)""#)        var read = 0        while let url = walker?.nextObject() as? URL {            guard url.pathExtension == "swift" else { continue }            read += 1            let code = SourceSweep.withoutComments(try String(contentsOf: url, encoding: .utf8))            let name = url.lastPathComponent            for opener in ["forResourcesWithExtension", "contentsOf:", "contentsOfFile", "FileManager.default.contents"] {                XCTAssertFalse(code.contains(opener), "\(name) opens a file itself (\(opener))")            }            if name != "FixtureDefinitions.swift" {                XCTAssertFalse(code.contains("FileHandle("), "\(name) opens a file outside readBundledJSON")            }            let lookups = code.components(separatedBy: "url(forResource:").count - 1            let matches = lookup.matches(in: code, range: NSRange(code.startIndex..., in: code))            XCTAssertEqual(matches.count, lookups, "\(name) looks up a bundle file without naming its folder")            for match in matches {                let folder = String(code[Range(match.range(at: 1), in: code)!])                XCTAssertTrue(["Shipped", "Fixtures"].contains(folder), "\(name) reads bundle folder \(folder)")            }        }        XCTAssertGreaterThan(read, 0, "the walk found the definition code")    }    /// A value of each column's own type — the Swift twin of the core's    /// `synthetic` (`crates/cotton-core/src/records/page_tests.rs`).    private func synthetic(_ definition: TableDefinition) -> TableRecord {        var values: [String: RecordValue] = [:]        for column in definition.columns {            let one: RecordValue            switch column.type {            case .text: one = .text("Harbour lane")            case .accountNumber: one = .text("12345678901234")            case .longtext: one = .text("A few lines about it.\nAnd one more.")            case .date: one = .text("2026-10-07")            case .time: one = .text("09:30")            case .number: one = .number(3)            case .bytes: one = .number(3_000)            case .amount: one = .number(150_000)            case .choice: one = .text(column.choices?.first ?? "open")            case .link: one = .text("id-\(column.key)-linked")            case .photo, .file: one = .text("objects/print.jpg")            case .bool: one = .bool(true)            case .url: one = .text("https://example.org/harbour")            case .place: one = .text("Hyderabad")            }            values[column.key] = column.multiple ? .list([one]) : one        }        return TableRecord(id: "id-\(definition.id)", values: values)    }    /// JSON with every null dropped, so the core's answer and the app's    /// re-encoding compare by what they say rather than how they spell absence.    private func said(_ value: Any) -> Any? {        switch value {        case is NSNull: return nil        case let object as [String: Any]: return object.compactMapValues(said) as NSDictionary        case let array as [Any]: return array.compactMap(said) as NSArray        default: return value        }    }}