Cotton code
101 lines · 5.9 KB · SwiftRaw
// The definition keys a directory needs, for any table: the A–Z rail// (`index`), a search by part of a word over named columns (`search`), a// table its engine never deletes (`delete: false`), a "+" that opens an app// route (`create.path`), a subtitle of several columns, text sorted as a// person reads it, and a polaroid table's grid of polaroids. Every record is// invented.import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class DirectoryKeysTests: XCTestCase {    private func directory(_ extra: String = "", slip: String = #""subtitle":["org","role","city"]"#) throws -> TableDefinition {        try TableDefinition.decode(Data("""            {"id":"example","name":"Example","plural":"Examples","builtin":false,             "columns":[{"key":"name","type":"text"},{"key":"org","type":"text"},{"key":"role","type":"text"},                        {"key":"city","type":"text"},{"key":"note","type":"longtext"}],             "title":"name","slip":{"title":"name",\(slip)},"tile":{"face":"polaroid-grid"},             "page":[{"heading":null,"columns":["name"]}]\(extra)}            """.utf8))    }    private func person(_ id: String, _ name: String, org: String? = nil, role: String? = nil, city: String? = nil) -> TableRecord {        var values: [String: RecordValue] = ["name": .text(name)]        if let org { values["org"] = .text(org) }        if let role { values["role"] = .text(role) }        if let city { values["city"] = .text(city) }        return TableRecord(id: id, values: values)    }    /// RULE: index, search, delete, create.path and a subtitle of several columns decode and survive a round trip — the subtitle written back as the list it was, one column as one column — and read as before when absent (a table deletes; "+" opens a blank page).    func testTheDirectoryKeysDecodeAndTheirAbsenceReadsAsBefore() throws {        let full = try directory(#","index":"name","search":["name","org","city"],"delete":false,"create":{"label":"Import contacts","path":"/people/import"}"#)        XCTAssertEqual(full.index, "name")        XCTAssertEqual(full.search, ["name", "org", "city"])        XCTAssertFalse(full.deletes)        XCTAssertEqual(full.create, ListCreate(label: "Import contacts", path: "/people/import"))        XCTAssertEqual(full.slip.subtitle, "org")        XCTAssertEqual(full.slip.subtitles, ["org", "role", "city"])        XCTAssertEqual(try JSONDecoder().decode(TableDefinition.self, from: JSONEncoder().encode(full)), full)        let one = try directory(slip: #""subtitle":"org""#)        let written = try XCTUnwrap(String(data: try JSONEncoder().encode(one.slip), encoding: .utf8))        XCTAssertTrue(written.contains(#""subtitle":"org""#), written)        let bare = try directory(slip: #""subtitle":null"#)        XCTAssertNil(bare.index)        XCTAssertEqual(bare.search, [])        XCTAssertTrue(bare.deletes)        XCTAssertNil(bare.create)        XCTAssertEqual(bare.slip.subtitles, [])        XCTAssertNil(try JSONDecoder().decode(ListCreate.self, from: Data(#"{"label":"New"}"#.utf8)).path)    }    /// RULE: A list sorted by a text column reads as a person reads it — case and accents folded, numbers by size — so "anil" stands beside "Anand" and "élodie" among the E's.    func testTextSortsAsAPersonReadsIt() throws {        let definition = try directory(#","sort":{"column":"name"}"#)        let names = ["zoe", "Élodie", "anil", "Anand", "Bea", "eve", "9 Lives", "10 Downing"]        let sorted = definition.sorted(names.enumerated().map { person("\($0.offset)", $0.element) })        XCTAssertEqual(sorted.compactMap { $0["name"].text }, ["9 Lives", "10 Downing", "Anand", "anil", "Bea", "Élodie", "eve", "zoe"])    }    /// RULE: An indexed list reads to its end, so every letter has its records to land on — and stops at a page that fails rather than asking for ever.    func testAnIndexedListReadsToItsEnd() async throws {        let definition = try directory(#","index":"name","sort":{"column":"name"}"#)        let many = (0..<120).map { person("p\($0)", String(format: "Person %03d", $0)) }        let model = RecordListModel(            definition: definition, store: FixtureRecords(definitions: [definition], records: ["example": many]), core: ListCoreFake(),            seeds: ListSeeds())        await model.reload(project: nil, query: "")        XCTAssertEqual(model.records.count, 50, "the reader's own page")        await model.readToEnd()        XCTAssertEqual(model.records.count, 120)        XCTAssertFalse(model.hasMore)    }    /// RULE: A table naming its search columns is searched over those alone, by any part of a word ("kar" finds Karkasson; an org or a city finds its people); one naming none is searched over every text column, as before.    func testSearchReadsTheNamedColumnsByPartOfAWord() async throws {        let definition = try directory(#","search":["name","org","city"]"#)        let store = FixtureRecords(definitions: [definition], records: ["example": [            person("1", "Ivo Karkasson", org: "Example Co"),            person("2", "Bea", city: "Example Town"),            TableRecord(id: "3", values: ["name": .text("Cy"), "note": .text("karaoke night")]),        ]])        func found(_ query: String) async throws -> [String] {            try await store.list(table: "example", project: nil, query: query, page: 0).records.map(\.id)        }        let kar = try await found("kar")        XCTAssertEqual(kar, ["1"], "a note the search does not name is not searched")        let town = try await found("town")        XCTAssertEqual(town, ["2"])        let everywhere = try await FixtureRecords(definitions: [try directory()], records: ["example": [            TableRecord(id: "3", values: ["name": .text("Cy"), "note": .text("karaoke night")]),        ]]).list(table: "example", project: nil, query: "kara", page: 0).records.map(\.id)        XCTAssertEqual(everywhere, ["3"])    }}