bitburner-src/test/jest/Netscript/RunScript.test.ts
Snarling e0272ad4af
FILES: Path rework & typesafety (#479)
* Added new types for various file paths, all in the Paths folder.
* TypeSafety and other helper functions related to these types
* Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands
* Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way
* Server.textFiles is now a map
* TextFile no longer uses a fn property, now it is filename
* Added a shared ContentFile interface for shared functionality between TextFile and Script.
* related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa.
* File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root.
* Singularized the MessageFilename and LiteratureName enums
* Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath).
* Fix several issues with tab completion, which included pretty much a complete rewrite
* Changed the autocomplete display options so there's less chance it clips outside the display area.
* Turned CompletedProgramName into an enum.
* Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine.
* For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 10:26:57 -04:00

121 lines
4.0 KiB
TypeScript

import { startWorkerScript } from "../../../src/NetscriptWorker";
import { config as EvaluatorConfig } from "../../../src/NetscriptJSEvaluator";
import { Server } from "../../../src/Server/Server";
import { RunningScript } from "../../../src/Script/RunningScript";
import { AddToAllServers, DeleteServer } from "../../../src/Server/AllServers";
import { WorkerScriptStartStopEventEmitter } from "../../../src/Netscript/WorkerScriptStartStopEventEmitter";
import { AlertEvents } from "../../../src/ui/React/AlertManager";
import type { Script } from "src/Script/Script";
import { ScriptFilePath } from "src/Paths/ScriptFilePath";
// Replace Blob/ObjectURL functions, because they don't work natively in Jest
global.Blob = class extends Blob {
code: string;
constructor(blobParts?: BlobPart[], options?: BlobPropertyBag) {
super();
this.code = (blobParts ?? [])[0] + "";
}
};
global.URL.revokeObjectURL = function () {};
// Critical: We have to overwrite this, otherwise we get Jest's hooked
// implementation, which will not work without passing special flags to Node,
// and tends to crash even if you do.
EvaluatorConfig.doImport = importActual;
test.each([
{
name: "NS1 test /w import",
expected: ["false home 8", "Script finished running"],
scripts: [
{
name: "import.script",
code: `
export function getInfo() {
return stock.has4SData();
}
`,
},
{
name: "simple_test.script",
code: `
import { getInfo } from "import.script";
var access = getInfo();
var server = getServer();
printf("%s %s %d", access, server.hostname, server.maxRam);
`,
},
],
},
{
name: "NS2 test /w import",
expected: ["false home 8", "Script finished running"],
scripts: [
{
name: "import.js",
code: `
export function getInfo(ns) {
return ns.stock.has4SData();
}
`,
},
{
name: "simple_test.js",
code: `
import { getInfo } from "./import.js";
export async function main(ns) {
var access = getInfo(ns);
var server = ns.getServer();
ns.printf("%s %s %d", access, server.hostname, server.maxRam);
}
`,
},
],
},
])("Netscript execution: $name", async function ({ expected: expectedLog, scripts }) {
global.URL.createObjectURL = function (blob) {
return "data:text/javascript," + encodeURIComponent(blob.code);
};
let server = {} as Server;
let eventDelete = () => {};
let alertDelete = () => {};
try {
const alerted = new Promise((resolve) => {
alertDelete = AlertEvents.subscribe((x) => resolve(x));
});
server = new Server({ hostname: "home", adminRights: true, maxRam: 8 });
AddToAllServers(server);
for (const s of scripts) {
expect(server.writeToScriptFile(s.name as ScriptFilePath, s.code)).toEqual({ overwritten: false });
}
const script = server.scripts.get(scripts[scripts.length - 1].name as ScriptFilePath) as Script;
expect(script.filename).toEqual(scripts[scripts.length - 1].name);
const ramUsage = script.getRamUsage(server.scripts);
if (!ramUsage) throw new Error(`ramUsage calculated to be ${ramUsage}`);
const runningScript = new RunningScript(script, ramUsage as number);
expect(startWorkerScript(runningScript, server)).toBeGreaterThan(0);
// We don't care about start, so subscribe after that. Await script death.
const result = await Promise.race([
alerted,
new Promise((resolve) => {
eventDelete = WorkerScriptStartStopEventEmitter.subscribe(() => {
if (!server.runningScripts.includes(runningScript)) {
resolve(null);
}
});
}),
]);
// If an error alert was thrown, we catch it here.
expect(result).toBeNull();
expect(runningScript.logs).toEqual(expectedLog);
} finally {
eventDelete();
if (server) DeleteServer(server.hostname);
alertDelete();
}
});