Some initial test cases for isolated VM.

This commit is contained in:
mike12345567 2024-02-19 19:37:18 +00:00
parent 601c02a4ac
commit c52b6aa0d1
3 changed files with 3126 additions and 0 deletions

View File

@ -0,0 +1,33 @@
import fs from "fs"
import path from "path"
import { IsolatedVM, VM2 } from "../vm"
function runJSWithIsolatedVM(script: string, context?: any) {
const runner = new IsolatedVM()
if (context) {
runner.withContext(context)
}
return runner.execute(`(function(){\n${script}\n})();`)
}
function runJSWithVM2(script: string, context?: any) {
const runner = new VM2(context)
return runner.execute(script)
}
function compare(script: string, context?: any) {
const resultIsolated = runJSWithIsolatedVM(script, context)
const resultVM = runJSWithVM2(script, context)
expect(resultIsolated).toEqual(resultVM)
return resultIsolated
}
describe("Test isolated vm directly", () => {
it("should handle a very large file", () => {
const marked = fs.readFileSync(path.join(__dirname, "marked.txt"), "utf-8")
const result = compare(marked, {
trigger: { row: { Message: "dddd" } },
})
expect(result).toBe("<p>dddd</p>\n")
})
})

View File

@ -1,5 +1,7 @@
import { validate as isValidUUID } from "uuid"
import { processStringSync, encodeJSBinding } from "@budibase/string-templates"
import fs from "fs"
import path from "path"
const { runJsHelpersTests } = require("@budibase/string-templates/test/utils")
@ -70,4 +72,77 @@ describe("jsRunner (using isolated-vm)", () => {
})
})
})
// the test cases here were extracted from templates/real world examples of JS in Budibase
describe("should real world tests of JS", () => {
const context = {
"Unit Value": 2,
Quantity: 1,
}
it("handle test case 1", async () => {
const result = await processJS(
`
var Gross = $("[Unit Value]") * $("[Quantity]")
return Gross.toFixed(2)`,
context
)
expect(result).toBeDefined()
expect(result).toBe("2.00")
})
it("handle test case 2", async () => {
const context = {
"Purchase Date": "2021-01-21T12:00:00",
}
const result = await processJS(
`
var purchase = new Date($("[Purchase Date]"));
let purchaseyear = purchase.getFullYear();
let purchasemonth = purchase.getMonth();
var today = new Date ();
let todayyear = today.getFullYear();
let todaymonth = today.getMonth();
var age = todayyear - purchaseyear
if (((todaymonth - purchasemonth) < 6) == true){
return age
}
`,
context
)
expect(result).toBeDefined()
expect(result).toBe(3)
})
it("should handle test case 3", async () => {
const context = {
Escalate: true,
"Budget ($)": 1100,
}
const result = await processJS(
`
if ($("[Escalate]") == true) {
if ($("Budget ($)") <= 1000)
{return 2;}
if ($("Budget ($)") > 1000)
{return 3;}
}
else {
if ($("Budget ($)") <= 1000)
{return 1;}
if ($("Budget ($)") > 1000)
if ($("Budget ($)") < 10000)
{return 2;}
else
{return 3}
}
`,
context
)
expect(result).toBeDefined()
expect(result).toBe(3)
})
})
})

File diff suppressed because it is too large Load Diff