SPB Git

Repository Public License

ScriptEngineTests.swift 3.9 KB 71 lines swift

1import Foundation2import PrismCore3import Testing4@testable import PrismScriptRuntime56@MainActor @Suite struct ScriptEngineTests {7    @Test func globalFunctionsAreCalledWithJSON() throws {8        let engine = ScriptEngine()9        try engine.load(script: "function add(a, b) { return a + b } function shape(o) { return { n: o.items.length, first: o.items[0] } }", name: "main")10        #expect(try engine.call("add", [2, 3]) == 5)11        #expect(try engine.call("shape", [["items": ["a", "b"]]]) == ["n": 2, "first": "a"])12        #expect(engine.has("add") && !engine.has("missing"))13        #expect(throws: ScriptError.self) { try engine.call("missing") }14    }1516    @Test func componentsHaveTheirOwnScope() throws {17        let engine = ScriptEngine()18        try engine.define(component: "a", source: "var n = 1; function render(p) { return { type: 'text', text: 'A' + p.label + n } } function bump() { n += 1; return n }")19        try engine.define(component: "b", source: "function render(p) { return { type: 'text', text: 'B' } }")20        #expect(try engine.call("render", [["label": "x"]], component: "a")["text"] == "Ax1")21        #expect(try engine.call("bump", component: "a") == 2)22        #expect(try engine.call("render", [[:]], component: "b")["text"] == "B")23        #expect(!engine.has("bump", component: "b") && !engine.has("render"))24    }2526    @Test func theHostIsTheOnlyWayOut() throws {27        let engine = ScriptEngine()28        var seen: [String] = []29        engine.host = { op, args in30            seen.append("\(op):\(JSONValue.array(args).canonicalString())")31            if op == "insert" { throw ScriptError("This app cannot store data.") }32            return op == "get" ? 41 : .null33        }34        try engine.load(script: """35        function next() { var v = app.get('count') + 1; app.set('count', v); return v }36        function save() { try { app.insert('t', {}) } catch (e) { return String(e.message) } }37        function ambient() { return [typeof require, typeof fetch, typeof XMLHttpRequest, typeof setTimeout, typeof process, typeof __host].join(',') }38        """, name: "main")39        #expect(try engine.call("next") == 42)40        #expect(seen == ["get:[\"count\"]", "set:[\"count\",42]"])41        #expect(try engine.call("save") == "This app cannot store data.")42        #expect(try engine.call("ambient") == "undefined,undefined,undefined,undefined,undefined,undefined")43    }4445    @Test func errorsNameTheFunctionAndLine() throws {46        let engine = ScriptEngine()47        #expect(ScriptEngine.syntaxError("function ok() { return 1 }") == nil)48        #expect(ScriptEngine.syntaxError("function broken( { ") != nil)49        #expect(ScriptEngine.syntaxError("return 1", asFunctionBody: true) == nil)50        #expect(throws: ScriptError.self) { try engine.load(script: "function (", name: "bad") }51        try engine.load(script: "function boom() {\n  return nothing.here\n}", name: "main")52        do { try engine.call("boom"); Issue.record("expected an error") } catch {53            #expect(error.localizedDescription.contains("boom") && error.localizedDescription.contains("nothing"))54        }55        #expect(throws: ScriptError.self) { try engine.call("constructor.constructor") }56        #expect(!ScriptEngine.isIdentifier("__invoke") && !ScriptEngine.isIdentifier("a b") && ScriptEngine.isIdentifier("onTap2"))57    }5859    @Test func anEndlessLoopIsStoppedAndTheEngineKeepsWorking() throws {60        let engine = ScriptEngine(timeLimit: 0.2)61        try #require(engine.hasTimeLimit, "the JavaScriptCore watchdog is not available on this macOS")62        try engine.load(script: "function spin() { while (true) {} } function fine() { return 'ok' }", name: "main")63        let started = Date()64        do { try engine.call("spin"); Issue.record("expected the loop to be stopped") } catch {65            #expect(error.localizedDescription.contains("stopped"))66        }67        #expect(Date().timeIntervalSince(started) < 3)68        #expect(try engine.call("fine") == "ok")69    }70}71
Files main
Menu

Theme