SPB Git

Repository Public License

BlueprintTests.swift 7.4 KB 149 lines swift

1import Foundation2import Testing3import PrismCore4@testable import PrismObjectModel56func sampleBlueprint() -> AppBlueprint {7    var bp = AppBlueprint(id: "app_demo", name: "Demo", entrypoint: "home")8    bp.objects = [9        PrismObject(id: "home", type: ObjectType.page, name: "Home", children: ["stack"]),10        PrismObject(id: "stack", type: "prism.stack", children: ["title", "list"]),11        PrismObject(id: "title", type: "prism.heading", props: ["text": "Hello"]),12        PrismObject(id: "list", type: "prism.table", dataRef: "items", dependencies: ["items"]),13        PrismObject(id: "items", type: ObjectType.dataTable, name: "items"),14    ]15    return bp16}1718@Suite struct BlueprintTests {19    @Test func roundTripThroughCanonicalJSON() throws {20        let bp = sampleBlueprint()21        let again = try AppBlueprint.load(bp.canonicalData())22        #expect(again == bp)23        #expect(again.contentHash == bp.contentHash)24        #expect(try AppBlueprint.load(bp.prettyData()) == bp)25    }2627    @Test func specExampleObjectDecodes() throws {28        let o = try PrismObject(json: JSONValue.parse("""29        {"id":"obj_expenses_chart","type":"prism.chart.line","schemaVersion":1,"name":"Monthly expenses",30         "inputs":[{"name":"rows","type":"table","required":true}],"outputs":[{"name":"selection","type":"record"}],31         "permissions":[],"dependencies":["obj_transactions"],"ui":{"theme":"system","minWidth":320},"version":1}32        """))33        #expect(o.inputs == [Port(name: "rows", type: "table", required: true)])34        #expect(o.ui["minWidth"] == 320)35        #expect(try PrismObject(json: o.json) == o)36    }3738    @Test func unknownFieldsAndVersionsAreRejected() throws {39        #expect(throws: BlueprintError.self) { try PrismObject(json: ["id": "a", "type": "t", "surprise": 1]) }40        let future: JSONValue = ["schemaVersion": 99, "id": "a", "name": "A", "objects": []]41        #expect(throws: BlueprintError.unsupportedVersion(found: 99, supported: 1)) { try AppBlueprint.load(future.canonicalData()) }42        #expect(throws: BlueprintError.self) { try AppBlueprint.load(Data("[]".utf8)) }43    }4445    @Test func migrationUpgradesOlderDocuments() throws {46        // A synthetic "version 0" that called `props` `properties`.47        let v0: JSONValue = [48            "schemaVersion": 0, "id": "app_old", "name": "Old", "entrypoint": "home",49            "objects": [["id": "home", "type": "prism.page", "properties": ["title": "Hi"]]],50        ]51        let migrator = BlueprintMigrator(steps: [0: { doc in52            guard var o = doc.objectValue else { return doc }53            o["objects"] = .array((o["objects"]?.arrayValue ?? []).map { obj in54                guard var d = obj.objectValue else { return obj }55                if let p = d.removeValue(forKey: "properties") { d["props"] = p }56                return .object(d)57            })58            return .object(o)59        }])60        let bp = try AppBlueprint.load(v0.canonicalData(), migrator: migrator)61        #expect(bp.schemaVersion == 1)62        #expect(bp.object("home")?.props["title"] == "Hi")63        #expect(throws: BlueprintError.self) { try AppBlueprint.load(v0.canonicalData()) }64    }6566    @Test func validBlueprintHasNoIssues() {67        #expect(StructuralValidator.validate(sampleBlueprint()).isEmpty)68    }6970    @Test func validationFindsStructuralProblems() throws {71        var bp = sampleBlueprint()72        bp.objects.append(PrismObject(id: "title", type: "prism.text"))73        bp.objects.append(PrismObject(id: "lonely", type: "prism.text"))74        bp.objects[1].children.append("ghost")75        bp.objects[3].dependencies = ["nowhere"]76        bp.entrypoint = "stack"77        let codes = Set(StructuralValidator.validate(bp).map(\.code))78        #expect(codes.isSuperset(of: ["object.duplicate", "children.missing", "dependency.missing", "entrypoint.invalid", "object.orphan"]))79    }8081    @Test func cyclesAreDetected() {82        var bp = sampleBlueprint()83        bp.objects[2].children = ["stack"]84        #expect(StructuralValidator.validate(bp).contains { $0.code == "children.cycle" })8586        var g = DependencyGraph()87        g.addEdge(from: "a", to: "b"); g.addEdge(from: "b", to: "c")88        #expect(g.findCycle() == nil)89        #expect(g.topologicalOrder() == ["c", "b", "a"])90        g.addEdge(from: "c", to: "a")91        #expect(g.findCycle() != nil)92        #expect(g.topologicalOrder() == nil)93    }9495    @Test func patchesAreDeterministicAndLeaveTheOriginalIntact() throws {96        let bp = sampleBlueprint()97        let button = PrismObject(id: "add", type: "prism.button", props: ["title": "Add"])98        let next = try bp.applying([99            .addObject(button, parent: "stack", index: 1),100            .setProp(id: "title", key: "text", value: "Bonjour"),101            .setEvent(id: "add", event: "click", actions: [["type": "setState", "key": "open", "value": true]]),102            .setBlueprintField(field: "name", value: "Renamed"),103        ])104        #expect(bp.object("add") == nil)105        #expect(next.object("stack")?.children == ["title", "add", "list"])106        #expect(next.object("title")?.props["text"] == "Bonjour")107        #expect(next.name == "Renamed")108        #expect(StructuralValidator.validate(next).isEmpty)109110        let moved = try next.applying(.moveChild(id: "add", toParent: "stack", index: 0))111        #expect(moved.object("stack")?.children == ["add", "title", "list"])112        #expect(throws: BlueprintError.self) { try next.applying(.moveChild(id: "stack", toParent: "title", index: nil)) }113114        let removed = try next.applying(.removeObject(id: "stack"))115        #expect(removed.objects.map(\.id) == ["home", "items"])116        #expect(removed.object("home")?.children.isEmpty == true)117        #expect(throws: BlueprintError.self) { try bp.applying(.setProp(id: "nope", key: "a", value: 1)) }118        #expect(throws: BlueprintError.self) { try bp.applying(.setField(id: "title", field: "id", value: "x")) }119    }120121    @Test func patchJSONRoundTrip() throws {122        let patches: [BlueprintPatch] = [123            .addObject(PrismObject(id: "x", type: "prism.text"), parent: "stack", index: 0),124            .removeObject(id: "x"), .setProp(id: "a", key: "k", value: [1, 2]), .removeProp(id: "a", key: "k"),125            .setField(id: "a", field: "name", value: "N"), .setEvent(id: "a", event: "click", actions: [["type": "navigate"]]),126            .moveChild(id: "a", toParent: "b", index: nil), .setBlueprintField(field: "name", value: "Z"),127        ]128        for p in patches { #expect(try BlueprintPatch(json: p.json) == p) }129        #expect(throws: BlueprintError.self) { try BlueprintPatch(json: ["op": "explode"]) }130    }131132    @Test func diffDescribesChanges() throws {133        let old = sampleBlueprint()134        var new = try old.applying([135            .addObject(PrismObject(id: "chart", type: "prism.chart.bar", name: "By month"), parent: "stack", index: nil),136            .setProp(id: "title", key: "text", value: "Changed"),137            .removeObject(id: "list"),138        ])139        new.permissions = ["network.client"]140        let diff = BlueprintDiff(from: old, to: new)141        #expect(diff.added.map(\.id) == ["chart"])142        #expect(diff.removed.map(\.id) == ["list"])143        #expect(diff.changed.first { $0.id == "title" }?.fields == ["props.text"])144        #expect(diff.addedPermissions == ["network.client"])145        #expect(BlueprintDiff(from: old, to: old).isEmpty)146        #expect(diff.summaryLines.contains("! new permission: network.client"))147    }148}149
Files main
Menu

Theme