SPB Git

Repository Public License

RuntimeTests.swift 11.5 KB 229 lines swift

1import AppKit2import Foundation3import SwiftUI4import Testing5import PrismComponentCatalog6import PrismComponentSDK7import PrismCore8import PrismDataRuntime9import PrismObjectModel10@testable import PrismRenderer1112let repoRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()1314func expenseTracker() throws -> AppBlueprint {15    try AppBlueprint.load(Data(contentsOf: repoRoot.appendingPathComponent("templates/expense-tracker/blueprint.json")))16}1718let sampleCSVURL = repoRoot.appendingPathComponent("templates/expense-tracker/sample.csv")1920func tempDir() -> URL {21    let url = FileManager.default.temporaryDirectory.appendingPathComponent("prism-render-\(UUID().uuidString)")22    try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)23    return url24}2526@MainActor27final class ScriptedDialogs: FileDialogs {28    var open: URL?29    var save: URL?30    var askedExtensions: [[String]] = []31    func chooseFileToOpen(allowedExtensions: [String]) -> URL? { askedExtensions.append(allowedExtensions); return open }32    func chooseFileToSave(suggestedName: String) -> URL? { save }33}3435@MainActor36func makeRuntime(_ bp: AppBlueprint, url: URL? = nil) throws -> AppRuntime {37    let rt = try AppRuntime(blueprint: bp, store: AppDataStore(url: url), registry: Catalog.registry)38    rt.locale = Locale(identifier: "en_US")39    rt.currencyCode = "USD"40    return rt41}4243@MainActor44@Suite struct RuntimeTests {45    @Test func theHandWrittenExpenseTrackerIsValid() throws {46        let bp = try expenseTracker()47        let issues = BlueprintValidator.validate(bp, registry: Catalog.registry)48        #expect(issues.isEmpty, "\(issues)")49        #expect(Catalog.registry.coverage(of: bp) == 1)50        #expect(Set(bp.componentTypes).isSuperset(of: ["prism.csvImport", "prism.dropdown", "prism.recordEditor", "prism.chart.bar", "prism.table"]))51    }5253    /// Golden journey step 5, driven through the same runtime the UI uses.54    @Test func importFilterEditRelaunchPersist() throws {55        let dir = tempDir()56        defer { try? FileManager.default.removeItem(at: dir) }57        let db = dir.appendingPathComponent("data.sqlite")58        let bp = try expenseTracker()59        do {60            let rt = try makeRuntime(bp, url: db)61            let dialogs = ScriptedDialogs()62            dialogs.open = sampleCSVURL63            rt.dialogs = dialogs6465            // Import the sample CSV through the import button's code path.66            let report = try #require(rt.importCSV(into: "transactions"))67            #expect(report.imported == 15 && report.skipped == 0)68            #expect(dialogs.askedExtensions == [["csv", "tsv", "txt"]])69            #expect(rt.notices.last?.tone == "success")7071            // Filter by category and by search text; the table and the totals follow the same state.72            let table = try #require(bp.object("transactions_table")?.props["query"])73            #expect(rt.rows(table).count == 15)74            rt.setState("category", "Food")75            #expect(rt.rows(table).count == 5)76            #expect(rt.resolve(["$expr": "round(first(queries.q_total).total, 2)"]) == 402.65)77            rt.setState("search", "dinner")78            #expect(rt.rows(table).map { $0["description"]!.displayString } == ["Dinner, with friends"])79            rt.setState("search", "")80            rt.setState("category", "All")8182            // The dropdown offers exactly the categories present in the data.83            #expect(rt.distinctValues(table: "transactions", column: "category").map(\.displayString) == ["Food", "Fun", "Health", "Housing", "Transport"])8485            // Select a row, edit it through an action, and check dependants refresh.86            let dentist = try #require(rt.rows(table).first { $0["description"] == "Dentist" })87            rt.setState("selectedId", dentist["id"]!)88            #expect(rt.run([["type": "updateRecord", "table": "transactions", "id": ["$bind": "selectedId"], "values": ["amount": 155.5, "category": "Health"]]]))89            #expect(rt.rows(table).first { $0["description"] == "Dentist" }?["amount"] == 155.5)9091            // Monthly chart data.92            let chart = try #require(bp.object("monthly_chart")?.props["query"])93            #expect(rt.rows(chart).map { $0["month"]!.displayString } == ["2026-08", "2026-09", "2026-10", "2026-11"])94            #expect(rt.rows(chart).last?["total"] == 1694.4)9596            rt.setState("category", "Housing")97            rt.persistStateNow()98            rt.store.close()99        }100        // Relaunch: data and state are still there.101        let again = try makeRuntime(bp, url: db)102        #expect(try again.store.count("transactions") == 15)103        #expect(again.state["category"] == "Housing")104        #expect(again.rows(bp.object("transactions_table")?.props["query"]).count == 4)105        #expect(try again.store.record("transactions", id: 15)?["amount"] == 155.5)106    }107108    @Test func actionsCoverTheDeclarativeSet() throws {109        var bp = try expenseTracker()110        bp.state["count"] = 0111        let rt = try makeRuntime(bp)112        #expect(rt.run([["type": "setState", "key": "count", "value": ["$expr": "state.count + 2"]], ["type": "toggleState", "key": "showEditor"]]))113        #expect(rt.state["count"] == 2 && rt.state["showEditor"] == true)114115        #expect(rt.run([["type": "createRecord", "table": "transactions", "values": ["date": "2026-11-20", "description": "Coffee", "amount": 4.5]]]))116        #expect(try rt.store.count("transactions") == 1)117        #expect(try rt.store.record("transactions", id: 1)?["category"] == "Other")118119        // A failing validation stops the sequence and tells the user why.120        let guarded: [JSONValue] = [121            ["type": "validate", "rules": [["when": ["$expr": "state.count < 10"], "message": "Count must reach 10."]]],122            ["type": "deleteRecord", "table": "transactions", "id": 1],123        ]124        #expect(!rt.run(guarded))125        #expect(try rt.store.count("transactions") == 1)126        #expect(rt.notices.last?.message == "Count must reach 10.")127128        // Bad input is reported, never stored.129        #expect(!rt.run([["type": "createRecord", "table": "transactions", "values": ["date": "nope", "description": "x", "amount": 1]]]))130        #expect(rt.notices.last?.tone == "danger")131        #expect(try rt.store.count("transactions") == 1)132133        #expect(rt.run([["type": "when", "condition": ["$expr": "state.count == 2"], "then": [["type": "showNotification", "message": ["$expr": "concat('n=', state.count)"], "tone": "success"]]]]))134        #expect(rt.notices.last?.message == "n=2")135        #expect(rt.run([["type": "deleteRecord", "table": "transactions", "id": 1]]))136        #expect(try rt.store.count("transactions") == 0)137        #expect(!rt.run([["type": "runShell", "command": "id"]]))138        #expect(rt.logs.contains { $0.level == .error && $0.message.contains("runShell") })139    }140141    @Test func eventsCarryValueAndRow() throws {142        var bp = try expenseTracker()143        bp.state["picked"] = ""144        bp = try bp.applying(.setEvent(id: "transactions_table", event: "select", actions: [["type": "setState", "key": "picked", "value": ["$expr": "row.description"]]]))145        let rt = try makeRuntime(bp)146        rt.fire("select", on: "transactions_table", value: 7, row: ["description": "Cinema night"])147        #expect(rt.state["picked"] == "Cinema night")148        rt.fire("click", on: "add_button")149        #expect(rt.state["showEditor"] == true && rt.state["selectedId"] == .null)150    }151152    @Test func permissionsAreEnforcedAtRuntime() throws {153        var bp = try expenseTracker()154        bp.permissions = [Permission.storageLocal]155        bp.objects.removeAll { ["import_button", "export_button"].contains($0.id) }156        bp.objects[bp.index(of: "bar")!].children.removeAll { ["import_button", "export_button"].contains($0) }157        let rt = try makeRuntime(bp)158        let dialogs = ScriptedDialogs(); dialogs.open = sampleCSVURL; dialogs.save = tempDir().appendingPathComponent("x.csv")159        rt.dialogs = dialogs160        #expect(rt.importCSV(into: "transactions") == nil)161        #expect(rt.exportCSV(query: ["table": "transactions"], suggestedName: "x.csv") == nil)162        #expect(dialogs.askedExtensions.isEmpty, "A denied permission must not even open a dialog.")163        #expect(try rt.store.count("transactions") == 0)164        #expect(rt.notices.allSatisfy { $0.tone == "danger" } && rt.notices.count == 2)165    }166167    @Test func exportWritesTheQueryRows() throws {168        let rt = try makeRuntime(try expenseTracker())169        _ = rt.importCSV(from: sampleCSVURL, into: "transactions")170        let dialogs = ScriptedDialogs()171        let out = tempDir().appendingPathComponent("out.csv")172        dialogs.save = out173        rt.dialogs = dialogs174        #expect(rt.run([["type": "exportCSV", "query": ["table": "transactions", "filters": [["column": "category", "value": "Fun"]]], "filename": "fun.csv"]]))175        let rows = try CSV.parse(Data(contentsOf: out))176        #expect(rows.count == 3 && rows[0] == ["Date", "Description", "Category", "Amount"])177    }178179    @Test func badLogicDegradesWithoutCrashing() throws {180        let rt = try makeRuntime(try expenseTracker())181        #expect(rt.resolve(["$expr": "nonsense("]) == .null)182        #expect(rt.rows(["table": "ghost"]).isEmpty)183        #expect(rt.rows(["table": "transactions", "sort": [["column": "ghost"]]]).isEmpty)184        #expect(rt.logs.contains { $0.message.contains("Expression failed") })185        #expect(rt.logs.contains { $0.message.contains("Query failed") })186        rt.setState("not a path!", 1)187        #expect(rt.state["not a path!"] == nil)188    }189190    @Test func reloadMigratesSchemaAndKeepsStateAndData() throws {191        let bp = try expenseTracker()192        let rt = try makeRuntime(bp)193        _ = rt.importCSV(from: sampleCSVURL, into: "transactions")194        rt.setState("category", "Food")195        var next = bp196        next.version = 2197        next.state["budget"] = 2000198        next.objects.append(PrismObject(id: "budgets", type: ObjectType.dataTable, props: ["columns": [["name": "category", "type": "text"], ["name": "limit_amount", "type": "currency"]]]))199        try rt.reload(next)200        #expect(rt.state["category"] == "Food" && rt.state["budget"] == 2000)201        #expect(try rt.store.count("transactions") == 15 && rt.store.count("budgets") == 0)202        try rt.reload(bp)  // roll back203        #expect(try rt.store.count("transactions") == 15)204        #expect(rt.state["budget"] == nil)205    }206}207208@Suite struct ResizableSplitTests {209    typealias Split = ResizableSplit<EmptyView, EmptyView>210211    @Test func paneLengthsFollowTheStartingRuleAndStayWithinLimits() {212        func length(_ total: CGFloat, _ initial: SplitInitial, dragged: CGFloat? = nil) -> CGFloat {213            Split.firstLength(total: total, initial: initial, dragged: dragged, minFirst: 120, minSecond: 120)214        }215        let usable: CGFloat = 1000 - SplitMetrics.handle216        #expect(length(1000, .fraction(0.5)) == usable / 2)217        #expect(length(1000, .first(300)) == 300)218        #expect(length(1000, .second(320)) == usable - 320)219        // Dragging is clamped so neither pane disappears.220        #expect(length(1000, .fraction(0.5), dragged: 5) == 120)221        #expect(length(1000, .fraction(0.5), dragged: 5000) == usable - 120)222        // Too small for both minimums: never negative, never larger than the space.223        #expect(length(150, .first(300)) == 150 - SplitMetrics.handle - 120)224        #expect(length(100, .fraction(0.5)) == 0)225        #expect(length(0, .second(320)) == 0)226        #expect(length(1000, .fraction(7)) == usable - 120)227    }228}229
Files main
Menu

Theme