SPB Git

Repository Public License

FamilyCTests.swift 25.0 KB 383 lines swift

1import AppKit2import Foundation3import SwiftUI4import Testing5import PrismComponentCatalog6import PrismComponentSDK7import PrismCore8import PrismDataRuntime9import PrismObjectModel10@testable import PrismRenderer1112/// The 53 component types of catalog family C.13let familyCTypeNames: [String] = [14    "prism.chart.area", "prism.chart.scatter", "prism.chart.stackedBar", "prism.chart.horizontalBar", "prism.chart.multiLine", "prism.chart.heatmap",15    "prism.chart.histogram", "prism.chart.gauge", "prism.chart.radar", "prism.chart.funnel", "prism.chart.sparkline", "prism.chart.treemap",16    "prism.chart.waterfall", "prism.chart.candlestick", "prism.chart.bullet", "prism.chart.bubble",17    "prism.pivot", "prism.dataGrid", "prism.cardList", "prism.gallery", "prism.recordDetail", "prism.recordCard", "prism.lookup", "prism.relatedList",18    "prism.countBadge", "prism.groupedList", "prism.leaderboard", "prism.comparison", "prism.summaryRow", "prism.filterBar", "prism.sortMenu",19    "prism.columnStats", "prism.jsonViewer", "prism.recordTimeline", "prism.activityFeed", "prism.comments", "prism.chat", "prism.progressList",20    "prism.dataList", "prism.statGrid", "prism.rankList", "prism.duplicateFinder",21    "prism.priceTag", "prism.cartSummary", "prism.invoice", "prism.productCard", "prism.quantity", "prism.receipt", "prism.converter",22    "prism.profileCard", "prism.reactionBar", "prism.likeButton", "prism.poll",23]2425/// Behaviour of catalog family C: the pure computations, and the components driven through the real runtime.26@MainActor27@Suite struct FamilyCTests {28    typealias M = FamilyCMath2930    func rows(_ list: [[String: JSONValue]]) -> [[String: JSONValue]] { list }3132    let sales: [[String: JSONValue]] = [33        ["region": "North", "quarter": "Q1", "revenue": 100], ["region": "North", "quarter": "Q2", "revenue": 150],34        ["region": "South", "quarter": "Q1", "revenue": 80], ["region": "South", "quarter": "Q1", "revenue": 20],35        ["region": "South", "quarter": "Q3", "revenue": 60],36    ]3738    // MARK: Catalog contract3940    @Test func rendererCoversExactlyTheFamilyManifests() {41        let expected = Set(familyCTypeNames)42        #expect(expected.count == 53)43        #expect(FamilyCComponents.types == expected)44        #expect(expected.isSubset(of: Set(Catalog.manifests.map(\.type))), "every family C type has a manifest")45        for type in expected {46            let m = Catalog.registry.manifest(type)47            #expect(m != nil, "\(type) is not in the registry")48            #expect(["charts", "data", "commerce", "social"].contains(m?.category ?? ""), "\(type)")49            #expect((m?.keywords.count ?? 0) >= 4, "\(type) needs four keywords")50            // Components that read a table declare the storage permission.51            let readsData = m?.props.contains { $0.kind == .query || $0.name == "table" } ?? false52            if readsData || type == "prism.statGrid" { #expect(m?.permissions.contains(Permission.storageLocal) == true, "\(type)") }53        }54    }5556    /// Reads the renderer sources: every prop a view reads is declared by its manifest, and every declared prop is read by its view.57    @Test func viewsAndManifestsAgreeOnProps() throws {58        let sources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Sources")59        let files = try FileManager.default.contentsOfDirectory(atPath: sources.path).filter { $0.hasPrefix("Components+FamilyC") }.sorted()60        #expect(files.count >= 6)61        let code = try files.map { try String(contentsOf: sources.appendingPathComponent($0), encoding: .utf8) }.joined(separator: "\n")62        func matches(_ pattern: String, in text: String) throws -> [[String]] {63            let regex = try NSRegularExpression(pattern: pattern)64            return regex.matches(in: text, range: NSRange(text.startIndex..., in: text)).map { m in65                (0..<m.numberOfRanges).map { i in Range(m.range(at: i), in: text).map { String(text[$0]) } ?? "" }66            }67        }68        // The router says which view renders which type.69        var views: [String: String] = [:]70        for m in try matches(#"case "(prism\.[A-Za-z.]+)": (FC[A-Za-z]+)\("#, in: code) { views[m[1]] = m[2] }71        #expect(Set(views.keys) == Set(familyCTypeNames))72        // Props that one shared view reads only for the other of its two types.73        let onlyForSibling: Set<String> = ["prism.chart.scatter.size", "prism.comments.senderColumn", "prism.comments.me", "prism.chat.authorColumn", "prism.chat.author"]74        for type in familyCTypeNames {75            let manifest = try #require(Catalog.registry.manifest(type))76            let view = try #require(views[type])77            let start = try #require(code.range(of: "struct \(view): View {"), "\(view) not found")78            let end = try #require(code.range(of: "\n}\n", range: start.upperBound..<code.endIndex))79            let body = String(code[start.lowerBound..<end.upperBound])80            var read = Set<String>()81            for m in try matches(#"(?:props\[|FC\.column\(o, )(?:[a-z]+ \? )?"([A-Za-z]+)"(?: : "([A-Za-z]+)")?"#, in: body) { read.formUnion(m.dropFirst().filter { !$0.isEmpty }) }82            for m in try matches(#"FCChartInput\(runtime, theme, o, columns: ([^\n]*)\)"#, in: body) { read.formUnion(try matches(#""([A-Za-z]+)""#, in: m[1]).map { $0[1] }) }83            if body.contains("FCChartInput(") { read.formUnion(["query", "title"]) }84            if body.contains("input.text") { read.insert("format") }85            if body.contains("input.color") { read.insert("tone") }86            if body.contains("FCSelection(") { read.insert("selection") }87            if body.contains("FC.source(runtime, o") { read.insert("query") }88            if body.contains("fcRecord(") { read.formUnion(["recordId", "table"]) }89            let declared = Set(manifest.props.map(\.name))90            let undeclared = read.subtracting(declared).filter { !onlyForSibling.contains("\(type).\($0)") && manifest.prop($0) == nil }91            #expect(undeclared.isEmpty, "\(type): \(view) reads undeclared props \(undeclared.sorted())")92            #expect(declared.subtracting(read).isEmpty, "\(type): \(view) never reads declared props \(declared.subtracting(read).sorted())")93        }94    }9596    // MARK: Aggregates, pivot, grouping9798    @Test func aggregates() {99        #expect(M.aggregate([1, 2, 3], "sum") == 6)100        #expect(M.aggregate([1, 2, 3], "avg") == 2)101        #expect(M.aggregate([4, 2, 9], "min") == 2 && M.aggregate([4, 2, 9], "max") == 9)102        #expect(M.aggregate([], "count") == 0 && M.aggregate([], "sum") == nil)103        #expect(M.aggregate(rows: sales, column: nil, fn: "count") == 5)104        #expect(M.aggregate(rows: sales, column: "revenue", fn: "sum") == 410)105        let stats = M.stats([3, 1, 8])106        #expect(stats.count == 3 && stats.min == 1 && stats.max == 8 && stats.sum == 12 && stats.average == 4)107        #expect(M.stats([]).average == nil)108    }109110    @Test func pivotCrossTabulatesWithTotals() {111        let p = M.pivot(sales, row: "region", column: "quarter", value: "revenue", fn: "sum")112        #expect(p.rowKeys == ["North", "South"] && p.columnKeys == ["Q1", "Q2", "Q3"])113        #expect(p.cell("North", "Q1") == 100 && p.cell("South", "Q1") == 100 && p.cell("North", "Q3") == nil)114        #expect(p.rowTotals == ["North": 250, "South": 160])115        #expect(p.columnTotals == ["Q1": 200, "Q2": 150, "Q3": 60])116        #expect(p.grandTotal == 410)117        // An average total is the average of the rows, not of the cell averages.118        let avg = M.pivot(sales, row: "region", column: "quarter", value: "revenue", fn: "avg")119        #expect(avg.cell("South", "Q1") == 50 && avg.rowTotals["South"] == 160.0 / 3 && avg.grandTotal == 82)120        let count = M.pivot(sales, row: "region", column: "quarter", value: nil, fn: "count")121        #expect(count.cell("South", "Q1") == 2 && count.grandTotal == 5)122        #expect(M.pivot([], row: "a", column: "b", value: nil, fn: "count") == M.Pivot())123    }124125    @Test func groupingRankingAndLeaderboard() {126        let groups = M.group(sales, by: "region")127        #expect(groups.map(\.key) == ["North", "South"] && groups.map(\.rows.count) == [2, 3])128        #expect(M.rank(sales, label: "quarter", value: "revenue", fn: "sum", limit: 2) == [.init(label: "Q1", value: 200), .init(label: "Q2", value: 150)])129        #expect(M.rank(sales, label: "region", value: nil, fn: "count", limit: 5).map(\.label) == ["South", "North"])130        let board = M.leaderboard(sales, value: "revenue", limit: 3)131        #expect(board.map(\.value) == [150, 100, 80])132        #expect(M.leaderboard(sales, value: "revenue", highestFirst: false, limit: 1).first?.value == 20)133        #expect(M.leaderboard([["revenue": "n/a"]], value: "revenue", limit: 3).isEmpty)134    }135136    @Test func duplicatesAreGroupedLargestFirst() {137        let people: [[String: JSONValue]] = [138            ["id": 1, "email": "a@x.io"], ["id": 2, "email": "b@x.io"], ["id": 3, "email": "A@x.io "], ["id": 4, "email": ""],139            ["id": 5, "email": "c@x.io"], ["id": 6, "email": "c@x.io"], ["id": 7, "email": "c@x.io"], ["id": 8, "email": ""],140        ]141        let groups = M.duplicates(people, column: "email")142        #expect(groups.map(\.value) == ["c@x.io", "a@x.io"])143        #expect(groups[0].rows.compactMap { $0["id"]?.intValue } == [5, 6, 7] && groups[1].rows.compactMap { $0["id"]?.intValue } == [1, 3])144        #expect(M.duplicates(people, column: "email", caseSensitive: true).map(\.value) == ["c@x.io"])145        #expect(M.duplicates(people, column: "id").isEmpty, "empty and unique values are not duplicates")146    }147148    // MARK: Chart computations149150    @Test func histogramBins() {151        let bins = M.histogram([0, 1, 2, 3, 4, 5, 6, 7, 8, 10], bins: 5)152        #expect(bins.count == 5 && bins.map(\.count) == [2, 2, 2, 2, 2])153        #expect(bins.first?.lower == 0 && bins.last?.upper == 10 && bins[1].lower == 2 && bins[1].upper == 4)154        #expect(bins.reduce(0) { $0 + $1.count } == 10, "the maximum falls in the last bin")155        #expect(M.histogram([5, 5, 5], bins: 4) == [M.Bin(lower: 4.5, upper: 5.5, count: 3)])156        #expect(M.histogram([], bins: 4).isEmpty && M.histogram([.nan, .infinity], bins: 4).isEmpty)157        #expect(M.histogram([1, 2], bins: 0).count == 1 && M.histogram([1, 2], bins: 5000).count == 100)158    }159160    @Test func waterfallRunningTotals() {161        let steps = M.waterfall([100, -30, 50, -120])162        #expect(steps.map(\.start) == [0, 100, 70, 120] && steps.map(\.end) == [100, 70, 120, 0])163        #expect(steps.map(\.delta) == [100, -30, 50, -120])164        #expect(M.waterfall([]).isEmpty)165    }166167    @Test func treemapFillsTheBoundsProportionally() {168        let bounds = CGRect(x: 0, y: 0, width: 400, height: 200)169        let values: [Double] = [6, 6, 4, 3, 2, 2, 1]170        let rects = M.treemap(values, in: bounds)171        #expect(rects.count == values.count)172        let total = values.reduce(0, +)173        for (v, r) in zip(values, rects) {174            #expect(abs(Double(r.width * r.height) - v / total * 80_000) < 0.01, "area is proportional to the value")175            #expect(bounds.insetBy(dx: -0.001, dy: -0.001).contains(r))176        }177        for i in rects.indices { for j in rects.indices where j > i { #expect(rects[i].insetBy(dx: 0.01, dy: 0.01).intersects(rects[j].insetBy(dx: 0.01, dy: 0.01)) == false, "tiles \(i) and \(j) overlap") } }178        // Squarified: the paper's example never produces slivers.179        #expect(rects.allSatisfy { max($0.width / $0.height, $0.height / $0.width) < 4 })180        let sparse = M.treemap([0, 5, -2], in: bounds)181        #expect(sparse[0] == .zero && sparse[2] == .zero && sparse[1] == bounds)182        #expect(M.treemap([1, 2], in: .zero) == [.zero, .zero])183    }184185    @Test func radarAndGaugeGeometry() {186        let points = M.radarPoints([1, 0.5, 1, 2], center: CGPoint(x: 100, y: 100), radius: 50)187        #expect(abs(points[0].x - 100) < 0.001 && abs(points[0].y - 50) < 0.001, "the first axis points up")188        #expect(abs(points[1].x - 125) < 0.001 && abs(points[1].y - 100) < 0.001, "then clockwise")189        #expect(abs(points[3].x - 50) < 0.001, "fractions are clamped to the rim")190        #expect(M.fraction(25, min: 0, max: 100) == 0.25 && M.fraction(-5, min: 0, max: 100) == 0 && M.fraction(500, min: 0, max: 100) == 1)191        #expect(M.fraction(5, min: 10, max: 10) == 0)192    }193194    // MARK: Commerce195196    @Test func cartAndInvoiceTotals() {197        let cart: [[String: JSONValue]] = [["price": 6.5, "quantity": 4], ["price": 39, "quantity": 1], ["price": 74, "quantity": 1]]198        let lines = M.lines(cart, price: "price", quantity: "quantity")199        let totals = M.totals(lines: lines, taxRate: 0.15)200        #expect(totals == M.Totals(itemCount: 6, subtotal: 139, tax: 20.85, total: 159.85))201        #expect(M.totals(lines: lines, taxRate: 0).total == 139)202        #expect(M.totals(lines: [], taxRate: 0.2) == M.Totals(itemCount: 0, subtotal: 0, tax: 0, total: 0))203        // Without a quantity column each row counts once; cents are rounded.204        #expect(M.totals(lines: M.lines(cart, price: "price", quantity: nil), taxRate: 0).subtotal == 119.5)205        #expect(M.totals(lines: [(price: 0.333, quantity: 3)], taxRate: 0.0825) == M.Totals(itemCount: 3, subtotal: 1, tax: 0.08, total: 1.08))206        #expect(M.discountPercent(amount: 79, original: 99) == 20 && M.discountPercent(amount: 99, original: 99) == nil && M.discountPercent(amount: 10, original: nil) == nil)207    }208209    @Test func receiptLinesAreAligned() {210        let lines = M.receipt(title: "Corner Shop", lines: [("4 x Notebook", "$26.00"), ("A very long product name that cannot fit", "$1.00")], subtotal: "$27.00", tax: "$4.05", total: "$31.05", footer: "Thank you!", width: 30)211        #expect(lines.dropFirst().dropLast().allSatisfy { $0.count == 30 }, "\(lines)")212        #expect(lines[2] == "4 x Notebook" + String(repeating: " ", count: 12) + "$26.00")213        #expect(lines[3].hasSuffix(" $1.00") && lines[3].contains("…"))214        #expect(lines.contains { $0.hasPrefix("TAX") } && lines.contains { $0.hasPrefix("TOTAL") && $0.hasSuffix("$31.05") })215        #expect(!M.receipt(title: "", lines: [], subtotal: "0", tax: nil, total: "0", footer: "").contains { $0.hasPrefix("SUBTOTAL") })216    }217218    @Test func conversionIsTwoWay() {219        #expect(M.convert(250, rate: 0.92, forward: true) == 230)220        #expect(M.convert(230, rate: 0.92, forward: false) == 250)221        #expect(M.convert(1, rate: 1.60934, forward: true, decimals: 3) == 1.609)222        #expect(M.convert(10, rate: 0, forward: false) == nil)223        #expect(M.clampedStep(1, by: -1, min: 1, max: 10) == 1 && M.clampedStep(9, by: 2, min: 1, max: 10) == 10 && M.clampedStep(3, by: 1, min: nil, max: nil) == 4)224    }225226    // MARK: Social227228    @Test func pollPercentagesAddUpToOneHundred() {229        #expect(M.pollPercentages([5, 9, 2]) == [31, 56, 13])230        #expect(M.pollPercentages([1, 1, 1]) == [34, 33, 33])231        #expect(M.pollPercentages([0, 0]) == [0, 0])232        #expect(M.pollPercentages([7]) == [100])233        for votes in [[1.0, 2, 3, 4, 5, 6, 7], [13, 1, 1], [2, 2, 2, 2, 2, 2]] { #expect(M.pollPercentages(votes).reduce(0, +) == 100) }234    }235236    @Test func votingMovesTheVote() {237        var state: JSONValue = ["votes": ["A": 2, "B": 1]]238        state = M.vote(state, for: "A")239        #expect(state == ["votes": ["A": 3, "B": 1], "choice": "A"])240        state = M.vote(state, for: "A")241        #expect(state["votes"]?["A"] == 3, "voting twice for the same option counts once")242        state = M.vote(state, for: "C")243        #expect(state == ["votes": ["A": 2, "B": 1, "C": 1], "choice": "C"])244        #expect(M.vote([:], for: "X") == ["votes": ["X": 1], "choice": "X"])245        #expect(M.react(["👍": 1], with: "👍") == ["👍": 2] && M.react(.null, with: "🎉") == ["🎉": 1])246        #expect(M.initials("Ada Lovelace") == "AL" && M.initials("prism") == "PR" && M.initials("Jean-Luc van Damme") == "JD" && M.initials("") == "?")247    }248249    // MARK: Dates and filters250251    @Test func relativeDates() throws {252        var cal = Calendar(identifier: .gregorian)253        cal.timeZone = try #require(TimeZone(identifier: "UTC"))254        let now = try #require(cal.date(from: DateComponents(year: 2026, month: 3, day: 15, hour: 12)))255        func rel(_ s: String) -> String { M.relativeDate(s, now: now, calendar: cal) }256        #expect(rel("2026-03-15") == "Today" && rel("2026-03-14") == "Yesterday" && rel("2026-03-16") == "Tomorrow")257        #expect(rel("2026-03-12") == "3 days ago" && rel("2026-03-01") == "2 weeks ago" && rel("2026-03-08") == "1 week ago")258        #expect(rel("2026-01-05") == "2 months ago" && rel("2024-03-01") == "2 years ago")259        #expect(rel("2026-03-20") == "In 5 days" && rel("2026-06-20") == "In 3 months")260        #expect(rel("2026-03-15T11:15:00Z") == "45 minutes ago" && rel("2026-03-15T09:00:00Z") == "3 hours ago" && rel("2026-03-15T11:59:40Z") == "Just now")261        #expect(rel("2026-03-15T13:00:00Z") == "In 1 hour" && rel("2026-03-10T09:00:00Z") == "5 days ago")262        #expect(rel("soon") == "soon", "text that is not a date is shown as written")263    }264265    @Test func filterControlsFollowTheColumn() {266        #expect(M.filterControl(type: .text, options: ["A", "B"], distinct: []) == .choice(["A", "B"]))267        #expect(M.filterControl(type: .text, options: [], distinct: ["x", "y"]) == .choice(["x", "y"]))268        #expect(M.filterControl(type: .text, options: [], distinct: (0..<40).map(String.init)) == .text)269        #expect(M.filterControl(type: .text, options: [], distinct: []) == .text)270        #expect(M.filterControl(type: .currency, options: [], distinct: []) == .range && M.filterControl(type: .date, options: [], distinct: []) == .dateRange)271        #expect(M.filterControl(type: .boolean, options: [], distinct: []) == .flag)272        #expect(M.filterKeys("amount", .range) == ["amountMin", "amountMax"] && M.filterKeys("date", .dateRange) == ["dateFrom", "dateTo"] && M.filterKeys("title", .text) == ["title"])273        #expect(M.activeFilterCount(["category": "Food", "amountMin": 20, "amountMax": nil, "title": ""]) == 2 && M.activeFilterCount(.null) == 0)274    }275276    // MARK: Through the runtime277278    func runtime(_ type: String, props: [String: JSONValue]? = nil, events: [String: [JSONValue]] = [:], extraState: [String: JSONValue] = [:]) throws -> AppRuntime {279        var bp = try #require(Catalog.registry.manifest(type)).fixtureBlueprint()280        for (k, v) in extraState { bp.state[k] = v }281        let i = try #require(bp.index(of: "fx"))282        if let props { bp.objects[i].props = props }283        bp.objects[i].events = events284        return try makeRuntime(bp)285    }286287    /// The filter bar's state shape drives ordinary query filters.288    @Test func filterBarStateFiltersAQuery() throws {289        let rt = try runtime("prism.filterBar")290        let query: JSONValue = ["table": "fx_items", "filters": [291            ["column": "category", "op": "eq", "value": ["$expr": "state.f.category"], "unless": ["$expr": "state.f.category == null"]],292            ["column": "title", "op": "contains", "value": ["$expr": "state.f.title"]],293            ["column": "amount", "op": "gte", "value": ["$expr": "state.f.amountMin"], "unless": ["$expr": "state.f.amountMin == null"]],294            ["column": "amount", "op": "lte", "value": ["$expr": "state.f.amountMax"], "unless": ["$expr": "state.f.amountMax == null"]],295            ["column": "date", "op": "gte", "value": ["$expr": "state.f.dateFrom"], "unless": ["$expr": "state.f.dateFrom == null"]],296        ]]297        #expect(rt.rows(query).map { $0["title"]!.displayString } == ["Groceries", "Restaurant"], "the fixture starts with Food and a minimum of 20")298        rt.setState("f.amountMin", 70)299        #expect(rt.rows(query).count == 1)300        rt.setState("f", .object([:]))301        #expect(rt.rows(query).count == 5, "an empty object filters nothing")302        rt.setState("f.title", "re")303        #expect(Set(rt.rows(query).map { $0["title"]!.displayString }) == ["Rent", "Restaurant"])304        rt.setState("f.title", .null)305        rt.setState("f.dateFrom", "2026-02-01")306        rt.setState("f.amountMax", 100)307        #expect(rt.rows(query).map { $0["title"]!.displayString } == ["Cinema", "Restaurant"])308        #expect(!rt.logs.contains { $0.level != .info }, "\(rt.logs.map(\.message))")309    }310311    @Test func sourcesReportWhatTheValidatorCannotCheck() throws {312        let rt = try runtime("prism.chart.stackedBar")313        let o = try #require(rt.blueprint.object("fx"))314        #expect(FC.source(rt, o, columns: ["quarter", "revenue", "region"]).rows.count == 8)315        let missing = FC.source(rt, o, columns: ["quarter", "ghost"])316        #expect(missing.rows.isEmpty && missing.problem?.contains("“ghost” is not a column") == true)317        #expect(FC.source(rt, query: ["table": "nowhere"]).problem == "Table “nowhere” does not exist.")318        #expect(FC.source(rt, query: ["tabel": "x"]).problem?.hasPrefix("The query is not valid") == true)319        #expect(FC.tableSource(rt, table: "fx_sales", filter: ("region", "South")).rows.count == 4)320        #expect(FC.source(rt, o).orProblem(true, "Nope").problem == "Nope")321        #expect(FC.sort(rt, ["column": "revenue", "descending": true]) == DataQuery.Sort(column: "revenue", descending: true) && FC.sort(rt, .null) == nil)322        let sorted = FC.source(rt, o, sort: DataQuery.Sort(column: "revenue", descending: true))323        #expect(sorted.rows.first?["revenue"]?.numericValue == 6200)324        #expect(!rt.logs.contains { $0.level == .error }, "an unreadable source is explained inline, not logged as a failure")325    }326327    @Test func selectionWritesStateAndFiresSelect() throws {328        let rt = try runtime("prism.dataList", events: ["select": [["type": "setState", "key": "picked", "value": ["$expr": "row.title"]]]], extraState: ["picked": ""])329        let o = try #require(rt.blueprint.object("fx"))330        var local: Int?331        let selection = FCSelection(runtime: rt, o: o, local: Binding(get: { local }, set: { local = $0 }))332        #expect(selection.current == 3)333        let row = try #require(rt.rows(["table": "fx_items"]).first { $0["id"]?.intValue == 2 })334        selection.select(row)335        #expect(rt.state["selected"] == 2 && local == 2 && rt.state["picked"] == "Rent")336        #expect(selection.isSelected(row))337    }338339    @Test func recordWritesGoThroughTheStore() throws {340        // The editable grid's commit path: a valid value is stored, an invalid one is refused with a notice.341        let rt = try runtime("prism.dataGrid")342        #expect(rt.write("Saving") { try rt.store.update("fx_items", id: 1, values: ["amount": .string("95.5")]) })343        #expect(try rt.store.record("fx_items", id: 1)?["amount"] == 95.5)344        #expect(!rt.write("Saving") { try rt.store.update("fx_items", id: 1, values: ["amount": .string("lots")]) })345        #expect(rt.notices.last?.tone == "danger")346        #expect(try rt.store.record("fx_items", id: 1)?["amount"] == 95.5)347        // Comments and chat insert a record with the configured author.348        let chat = try runtime("prism.chat")349        let before = chat.rows(["table": "fx_messages"]).count350        #expect(chat.write("Saving") { try chat.store.insert(into: "fx_messages", values: ["author": "Me", "text": "Hello", "date": "2026-03-04"]) })351        #expect(chat.rows(["table": "fx_messages"]).count == before + 1)352    }353354    /// Fixtures with no rows, a missing column or an unknown table still render something, and never log an error.355    @Test(arguments: familyCTypeNames)356    func emptyAndBrokenInputsRenderHonestly(type: String) throws {357        let manifest = try #require(Catalog.registry.manifest(type))358        var bp = try manifest.fixtureBlueprint()359        // 1. The same fixture without any seeded row.360        for i in bp.objects.indices where bp.objects[i].isTable { bp.objects[i].props["seed"] = nil }361        let empty = try makeRuntime(bp)362        let rep = try #require(renderBitmap(AppView(runtime: empty), size: CGSize(width: 640, height: 420)))363        saveSnapshot(rep, "family-c-empty-" + type.replacingOccurrences(of: ".", with: "-"))364        #expect(!empty.logs.contains { $0.level == .error }, "\(type): \(empty.logs.filter { $0.level == .error }.map(\.message))")365        if manifest.props.contains(where: { $0.kind == .query || $0.name == "table" }), !["prism.countBadge", "prism.chart.sparkline", "prism.lookup"].contains(type) {366            #expect(distinctColors(rep) > 1, "\(type) drew nothing for an empty table")367        }368        // 2. Column props pointing at a column that does not exist: an inline message, no crash, no failed query.369        let i = try #require(bp.index(of: "fx"))370        var touched = false371        for spec in manifest.props where spec.kind == .string && !spec.dynamic && bp.objects[i].props[spec.name] != nil && spec.name != "table" && spec.name != "currencyCode" {372            bp.objects[i].props[spec.name] = "ghost_column"373            touched = true374        }375        if touched {376            let broken = try makeRuntime(bp)377            let image = try #require(renderBitmap(AppView(runtime: broken), size: CGSize(width: 640, height: 420)))378            #expect(distinctColors(image) > 1, "\(type) drew nothing for an unknown column")379            #expect(!broken.logs.contains { $0.level == .error }, "\(type): \(broken.logs.filter { $0.level == .error }.map(\.message))")380        }381    }382}383
Files main
Menu

Theme