1
0
silverbullet/plugos/runtime.test.ts

116 lines
2.7 KiB
TypeScript
Raw Normal View History

import {createSandbox} from "./environments/node_sandbox";
import {expect, test} from "@jest/globals";
import {System} from "./system";
test("Run a Node sandbox", async () => {
2022-03-23 14:41:12 +00:00
let system = new System("server");
system.registerSyscalls([], {
2022-03-25 11:03:06 +00:00
addNumbers: (ctx, a, b) => {
return a + b;
},
failingSyscall: () => {
throw new Error("#fail");
},
});
system.registerSyscalls(["restricted"], {
2022-03-25 11:03:06 +00:00
restrictedSyscall: () => {
return "restricted";
},
});
system.registerSyscalls(["dangerous"], {
2022-03-25 11:03:06 +00:00
dangerousSyscall: () => {
return "yay";
},
});
let plug = await system.load(
"test",
{
2022-03-25 11:03:06 +00:00
requiredPermissions: ["dangerous"],
functions: {
addTen: {
code: `(() => {
return {
default: (n) => {
return n + 10;
}
};
})()`,
},
addNumbersSyscall: {
code: `(() => {
return {
default: async (a, b) => {
2022-03-24 09:48:56 +00:00
return await self.syscall("addNumbers", a, b);
}
};
})()`,
},
errorOut: {
code: `(() => {
return {
default: () => {
throw Error("BOOM");
}
};
})()`,
},
errorOutSys: {
code: `(() => {
return {
default: async () => {
2022-03-24 09:48:56 +00:00
await self.syscall("failingSyscall");
}
};
})()`,
},
2022-03-25 11:03:06 +00:00
restrictedTest: {
code: `(() => {
return {
default: async () => {
await self.syscall("restrictedSyscall");
}
};
})()`,
},
dangerousTest: {
code: `(() => {
return {
default: async () => {
return await self.syscall("dangerousSyscall");
}
};
})()`,
},
},
},
2022-03-25 11:03:06 +00:00
createSandbox
);
expect(await plug.invoke("addTen", [10])).toBe(20);
for (let i = 0; i < 100; i++) {
expect(await plug.invoke("addNumbersSyscall", [10, i])).toBe(10 + i);
}
try {
await plug.invoke("errorOut", []);
expect(true).toBe(false);
} catch (e: any) {
expect(e.message).toBe("BOOM");
}
try {
await plug.invoke("errorOutSys", []);
expect(true).toBe(false);
} catch (e: any) {
expect(e.message).toBe("#fail");
}
2022-03-25 11:03:06 +00:00
try {
await plug.invoke("restrictedTest", []);
expect(true).toBe(false);
} catch (e: any) {
expect(e.message).toBe(
"Missing permission 'restricted' for syscall restrictedSyscall"
);
}
expect(await plug.invoke("dangerousTest", [])).toBe("yay");
2022-03-21 14:21:34 +00:00
await system.unloadAll();
});