From b75cfc6605af54b7da72b956c4676c59e717dc07 Mon Sep 17 00:00:00 2001 From: Eric Anderson Date: Tue, 24 Nov 2026 10:10:30 -0800 Subject: [PATCH] Add pxt simtest for running programs headless - Added pxt simtest. It compiles each test program on top of a base project and runs it in a Node vm context with no DOM, with the virtual host and the silent audio host installed, so runs are deterministic. It uses the target's DOM-free bundle when there is one; a target with only sim.js runs on that, and any DOM use fails the test. - A program passes when it finishes in time without a runtime error and writes the serial lines its @serial comments expect. - Added tests/simcore-test, ten tests that run the headless runner against a toy board, since pxt has no target of its own to run pxt simtest on. They check the runner and the host layers, nothing target-specific. - Added the gulp task testsimcore with the existing testTask helper and added it to gulp test. - Updated the README with the porting steps for a target and the headless run section. Build, the new suite and the existing test tasks pass. No change to the pxsim API. --- .../instructions/simulator.instructions.md | 11 +- cli/cli.ts | 130 ++++++++- cli/simtest.ts | 184 +++++++++++++ gulpfile.js | 3 + pxtsimcore/README.md | 61 +++++ tests/simcore-test/fixtures/toybundle.ts | 67 +++++ tests/simcore-test/simcorerunner.ts | 257 ++++++++++++++++++ tests/simcore-test/tsconfig.json | 25 ++ 8 files changed, 732 insertions(+), 6 deletions(-) create mode 100644 cli/simtest.ts create mode 100644 tests/simcore-test/fixtures/toybundle.ts create mode 100644 tests/simcore-test/simcorerunner.ts create mode 100644 tests/simcore-test/tsconfig.json diff --git a/.github/instructions/simulator.instructions.md b/.github/instructions/simulator.instructions.md index de74fb1f2928..ceed3303ee85 100644 --- a/.github/instructions/simulator.instructions.md +++ b/.github/instructions/simulator.instructions.md @@ -1,6 +1,6 @@ --- description: "Instructions for PXT simulator development" -applyTo: "pxtsim/**/*.ts,pxtsimcore/**,sim/**/*.ts,**/sim/*.ts" +applyTo: "pxtsim/**/*.ts,pxtsimcore/**,cli/simtest.ts,tests/simcore-test/**,sim/**/*.ts,**/sim/*.ts" --- # PXT Simulator Development Instructions @@ -28,7 +28,7 @@ applyTo: "pxtsim/**/*.ts,pxtsimcore/**,sim/**/*.ts,**/sim/*.ts" ## Board State and View - `board()` is the state, used by shims and `state/*`; `boardView()` is for view code; state files never reference `visuals` -- A board state must construct and run with no view +- A board state must construct and run with no view, because headless runs and `pxt simtest` build it that way - Tests inject input through the board state the same way the visuals do, not by raising DAL events by id ## Audio/Media Handling @@ -39,6 +39,13 @@ applyTo: "pxtsim/**/*.ts,pxtsimcore/**,sim/**/*.ts,**/sim/*.ts" - Use MediaStream API for recording functionality - Always clean up audio resources when stopping simulation +## Headless Runs + +- `pxt simtest` and the simcore tests run on the virtual host (`pxsim.host.createVirtualHost`) and the silent audio host, so pauses take no real time and runs are repeatable +- After the top-level code finishes, a run advances virtual time by `--settle` and stops; it never waits for the program to go idle, and its timeout watchdog stays on real time +- Fixtures are TypeScript under `tests/simcore-test/fixtures/`, compiled by the test project; do not generate them at test time or embed them as strings +- A target ships a DOM-free simulator bundle by adding `sim/tsconfig.core.json`, which `pxt buildtarget` compiles to `built/simcore.js` + ## Visual Components - Use SVG for scalable simulator graphics diff --git a/cli/cli.ts b/cli/cli.ts index 50d07bb81f67..fdcf6e2c5bf9 100644 --- a/cli/cli.ts +++ b/cli/cli.ts @@ -31,6 +31,7 @@ import * as pyconv from './pyconv'; import * as gitfs from './gitfs'; import * as crowdin from './crowdin'; import * as youtube from './youtube'; +import * as simtest from './simtest'; import { SUB_WEBAPPS } from './subwebapp'; const rimraf: (f: string, opts: any, cb: (err: Error, res: any) => void) => void = require('rimraf'); @@ -4501,17 +4502,21 @@ function getApiInfoAsync() { }) } -function findTestFile() { +/** + * Returns the main package's only .ts file. Fails with an error naming `command` when the package + * has none or more than one. + */ +function findTestFile(command: string) { let tsFiles = mainPkg.getFiles().filter(fn => U.endsWith(fn, ".ts")) if (tsFiles.length != 1) - U.userError("need exactly one .ts file in package to 'testdir'") + U.userError(`need exactly one .ts file in package to '${command}'`) return tsFiles[0] } function prepTestOptionsAsync() { return prepBuildOptionsAsync(BuildOption.Test) .then(opts => { - let tsFile = findTestFile() + let tsFile = findTestFile("testdir") delete opts.fileSystem[tsFile] opts.sourceFiles = opts.sourceFiles.filter(f => f != tsFile) return opts @@ -4585,7 +4590,7 @@ function testDirAsync(parsed: commandParser.ParsedCommand) { if (currBase != ti.base) { U.userError("Base directory: " + ti.base + " not found.") } else { - let tsf = findTestFile() + let tsf = findTestFile("testdir") let files = mainPkg.config.files let idx = files.indexOf(tsf) U.assert(idx >= 0) @@ -4646,6 +4651,92 @@ function testDirAsync(parsed: commandParser.ParsedCommand) { }) } +function simtestFiles(args: string[]): string[] { + const files: string[] = []; + for (const arg of args.length ? args : ["."]) { + const full = path.resolve(arg); + if (nodeutil.existsDirSync(full)) + fs.readdirSync(full).sort() + .filter(f => f[0] != "." && /\.ts$/.test(f)) + .forEach(f => files.push(path.join(full, f))); + else + files.push(full); + } + return files; +} + +/** + * Runs `pxt simtest`. Each test program is compiled on top of a base project and run headless + * against the target's simulator bundle. A test passes when it finishes in time without a runtime error. + * If it has `// @serial: text` comments, it must also write exactly those lines to the serial port. + */ +async function simtestAsync(parsed: commandParser.ParsedCommand) { + const targetDir = process.cwd(); + const base = path.resolve(parsed.flags["base"] as string || "."); + // Use the DOM-free bundles with --core. Without --core or --sim, use them if the target has + // built simcore.js. + const core = !!parsed.flags["core"] || (!parsed.flags["sim"] && fs.existsSync(path.join("built", "simcore.js"))); + const simBundle = path.resolve(parsed.flags["sim"] as string || path.join("built", core ? "simcore.js" : "sim.js")); + const coreBundle = path.join(nodeutil.pxtCoreDir, "built", core ? "pxtsimcore.js" : "pxtsim.js"); + const timeoutMs = (parsed.flags["timeout"] as number) || 5000; + const settleMs = parsed.flags["settle"] === undefined ? 300 : parsed.flags["settle"] as number; + + if (!fs.existsSync(coreBundle)) + U.userError(`simulator bundle not found: ${coreBundle}`); + if (!fs.existsSync(simBundle)) { + if (core && !parsed.flags["sim"]) + U.userError(`DOM-free simulator bundle not found: ${simBundle}; the target has no sim/tsconfig.core.json, or has not been built with 'pxt buildtarget'. 'pxt simtest' without --core runs against the full simulator bundle when the target has no DOM-free one.`); + U.userError(`simulator bundle not found: ${simBundle}`); + } + if (!fs.existsSync(path.join(base, pxt.CONFIG_NAME))) + U.userError(`no ${pxt.CONFIG_NAME} in base project ${base}; use --base `); + + const tests = simtestFiles(parsed.args); + if (!tests.length) + U.userError("no test programs found"); + + process.chdir(base); + mainPkg = new pxt.MainPackage(new Host()); + const failures: string[] = []; + try { + for (const file of tests) { + const name = path.basename(file); + const source = fs.readFileSync(file, "utf8"); + let failure: string; + try { + await mainPkg.loadAsync(); + // the test replaces the base project's only .ts file + (mainPkg.host() as Host).fileOverrides = { [findTestFile("simtest")]: source }; + const opts = await prepBuildOptionsAsync(BuildOption.Run, true); + const res = pxtc.compile(opts); + if (!res.success || !res.outfiles[pxtc.BINARY_JS]) { + reportDiagnostics(res.diagnostics); + failure = "compilation failed"; + } else { + const result = await simtest.runHeadlessAsync(res.outfiles[pxtc.BINARY_JS], [coreBundle, simBundle], { timeoutMs, settleMs }); + failure = simtest.checkRun(result, simtest.parseSerialExpectations(source)); + } + } catch (e) { + failure = String(e && e.message || e); + } + // each test starts from the base project's original file list + mainPkg = new pxt.MainPackage(new Host()); + if (failure) { + failures.push(name); + console.log(`FAIL ${name}: ${failure}`); + } else { + console.log(`ok ${name}`); + } + } + } finally { + process.chdir(targetDir); + } + + console.log(`${tests.length - failures.length}/${tests.length} simulator tests passed`); + if (failures.length) + process.exit(1); +} + function replaceFileExtension(file: string, extension: string) { return file && file.substr(0, file.length - path.extname(file).length) + extension; } @@ -7724,6 +7815,37 @@ ${pxt.crowdin.KEY_VARIABLE} - crowdin key advancedCommand("test", "run tests on current package", testAsync); advancedCommand("testassembler", "test the assemblers", testAssemblers); advancedCommand("testdir", "compile files in directory one by one", testDirAsync, ""); + p.defineCommand({ + name: "simtest", + help: "run programs headless against the target's simulator bundle (DOM-free bundles with --core)", + argString: "...", + advanced: true, + flags: { + base: { + description: "project to compile each test on top of (default: current directory)", + argument: "dir", + type: "string" + }, + sim: { + description: "the target's simulator bundle (default: built/simcore.js when 'pxt buildtarget' has emitted it from sim/tsconfig.core.json, else built/sim.js)", + argument: "file", + type: "string" + }, + core: { + description: "require the DOM-free simulator bundles, pxtsimcore.js and the target's built/simcore.js, and stop when the target has not built one" + }, + timeout: { + description: "real milliseconds a run may take, settling included (default: 5000)", + argument: "ms", + type: "number" + }, + settle: { + description: "virtual milliseconds the program runs after its top-level code finishes (default: 300)", + argument: "ms", + type: "number" + } + } + }, simtestAsync); advancedCommand("testpkgconflicts", "tests package conflict detection logic", testPkgConflictsAsync); advancedCommand("testdbg", "tests hardware debugger", dbgTestAsync); diff --git a/cli/simtest.ts b/cli/simtest.ts new file mode 100644 index 000000000000..343bf0839ffc --- /dev/null +++ b/cli/simtest.ts @@ -0,0 +1,184 @@ +/// + +import * as fs from "fs"; +import * as vm from "vm"; + +/** The outcome of running one compiled program in a context that has no browser globals. */ +export interface HeadlessRunResult { + /** Lines written to the serial port or console, in order. */ + serial: string[]; + /** Every message the runtime posted other than serial output and status. */ + messages: pxsim.SimulatorMessage[]; + error?: string; + timedOut: boolean; + /** + * The virtual host the program ran on, already stopped. Its `now()` returns the virtual time + * the run reached. + */ + readonly host: pxsim.host.VirtualHost; +} + +export interface HeadlessRunOptions { + /** Maximum real time, in milliseconds, for the whole run, settling included. */ + timeoutMs: number; + /** Virtual milliseconds the program runs after its top-level code finishes, before the run ends. */ + settleMs: number; + /** Seed for the virtual host's random numbers. Defaults to `pxsim.host.DEFAULT_SEED`. */ + seed?: number; +} + +/** + * Runs a compiled program headless in a fresh vm context. The context has the JavaScript + * built-ins plus a few Node globals, such as `console`, `performance`, the timers and + * `TextEncoder`, but no DOM. Any use of the DOM by the simulator code fails the run. + * + * The program runs on a virtual host from `pxsim.host.createVirtualHost`, which supplies the + * clock, timers, frames and random numbers. Pauses take no real time, and two runs of the same + * program with the same seed produce the same output. The run goes until the top-level code + * finishes, then for `settleMs` more virtual milliseconds, and then it ends. + * + * Errors while shutting down the runtime and board are ignored. Rejects if a bundle fails to load + * or the last bundle does not set `pxsim.initHeadlessRuntime`. + * @param bundles simulator scripts to load, in order: pxtsimcore first, then the target's bundle + */ +export async function runHeadlessAsync(js: string, bundles: string[], options: HeadlessRunOptions): Promise { + const timeouts = new Set>(); + const intervals = new Set>(); + const sandbox: any = { + console, + setTimeout: (callback: (...args: any[]) => void, delay?: number, ...args: any[]) => { + const timer = setTimeout(() => { + timeouts.delete(timer); + callback(...args); + }, delay); + timeouts.add(timer); + return timer; + }, + clearTimeout: (timer: ReturnType) => { + timeouts.delete(timer); + clearTimeout(timer); + }, + setInterval: (callback: (...args: any[]) => void, delay?: number, ...args: any[]) => { + const timer = setInterval(callback, delay, ...args); + intervals.add(timer); + return timer; + }, + clearInterval: (timer: ReturnType) => { + intervals.delete(timer); + clearInterval(timer); + }, + performance, + btoa, + atob, + TextEncoder, + TextDecoder, + URL, + URLSearchParams, + }; + const context = vm.createContext(sandbox); + try { + for (const bundle of bundles) + vm.runInContext(fs.readFileSync(bundle, "utf8"), context, { filename: bundle }); + + if (vm.runInContext("typeof pxsim.initHeadlessRuntime", context) !== "function") + throw new Error(`${bundles[bundles.length - 1]} does not set pxsim.initHeadlessRuntime`); + + sandbox.__seed = options.seed; + sandbox.__yieldToEventLoop = () => new Promise(resolve => setImmediate(resolve)); + sandbox.__host = vm.runInContext("pxsim.host.createVirtualHost({ seed: __seed, yieldToEventLoop: __yieldToEventLoop })", context); + vm.runInContext("__host.use()", context); + // Headless runs always use the silent audio host, even if a bundle registered another one. + vm.runInContext("pxsim.audiohost.setAudioHost({})", context); + sandbox.__js = js; + sandbox.__options = options; + return await vm.runInContext(` + new Promise(resolve => { + const result = { serial: [], messages: [], timedOut: false, host: __host }; + let runtime; + let finished = false; + let serialBuffer = ""; + const finish = () => { + if (finished) return; + finished = true; + clearTimeout(timer); + __host.stop(); + try { runtime && runtime.kill(); } catch (e) { } + try { runtime && runtime.board && runtime.board.kill(); } catch (e) { } + try { runtime && runtime.boardView && runtime.boardView.kill(); } catch (e) { } + if (serialBuffer) result.serial.push(serialBuffer); + resolve(result); + }; + const timer = setTimeout(() => { result.timedOut = true; finish(); }, __options.timeoutMs); + const addSerial = data => { + const lines = (serialBuffer + String(data)).split(/\\r?\\n/); + serialBuffer = lines.pop(); + result.serial.push(...lines); + }; + pxsim.initCurrentRuntime = pxsim.initHeadlessRuntime; + pxsim.Runtime.messagePosted = msg => { + if (msg.type === "bulkserial") + msg.data.forEach(m => addSerial(m.data)); + else if (msg.type === "serial") + addSerial(msg.data); + else if (msg.type !== "status") + result.messages.push(msg); + }; + try { + runtime = new pxsim.Runtime({ type: "run", code: __js }); + } catch (e) { + result.error = String(e && e.stack || e); + return finish(); + } + runtime.errorHandler = e => { + result.error = String(e && e.stack || e); + finish(); + }; + const fail = e => { + if (!finished) runtime.errorHandler(e); + }; + Promise.resolve() + .then(() => { + if (!finished) + return runtime.board.initAsync({ type: "run", code: __js }); + }) + .then(() => { + if (finished) return; + let topLevelDone = false; + runtime.run(() => { topLevelDone = true; }); + return __host.runUntil(() => topLevelDone); + }) + .then(() => { + if (!finished) + return __host.advance(__options.settleMs); + }) + .then(finish, fail); + }) + `, context); + } finally { + timeouts.forEach(timer => clearTimeout(timer)); + intervals.forEach(timer => clearInterval(timer)); + timeouts.clear(); + intervals.clear(); + } +} + +/** Returns the serial lines a test expects, taken from its `// @serial: text` comments. */ +export function parseSerialExpectations(source: string): string[] { + const expected: string[] = []; + const re = /^\s*\/\/\s*@serial:[ \t]?(.*?)\s*$/gm; + let m: RegExpExecArray; + while ((m = re.exec(source))) + expected.push(m[1]); + return expected; +} + +/** Returns a description of why the run failed, or undefined when it passed. */ +export function checkRun(result: HeadlessRunResult, expectedSerial: string[]): string | undefined { + if (result.error) + return `runtime error: ${result.error}`; + if (result.timedOut) + return "timed out before the run finished"; + if (expectedSerial.length && JSON.stringify(result.serial) !== JSON.stringify(expectedSerial)) + return `serial output mismatch\n expected: ${JSON.stringify(expectedSerial)}\n actual: ${JSON.stringify(result.serial)}`; + return undefined; +} diff --git a/gulpfile.js b/gulpfile.js index 062987f2689a..986418cf7659 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -772,6 +772,7 @@ const testerr = testTask("errors-test", "errorrunner.js"); const testfmt = testTask("format-test", "formatrunner.js"); const testembed = testTask("embed-test", "embedrunner.js"); const testsimdriver = testTask("simdriver-test", "simdriverrunner.js"); +const testsimcore = testTask("simcore-test", "simcorerunner.js"); const testpydecomp = testTask("pydecompile-test", "pydecompilerunner.js"); const testpycomp = testTask("pyconverter-test", "pyconvertrunner.js"); const testpytraces = testTask("runtime-trace-tests", "tracerunner.js"); @@ -823,6 +824,7 @@ const testAll = gulp.series( testfmt, testembed, testsimdriver, + testsimcore, testpydecomp, testpycomp, testpytraces, @@ -951,6 +953,7 @@ exports.testerr = testerr; exports.testfmt = testfmt; exports.testembed = testembed; exports.testsimdriver = testsimdriver; +exports.testsimcore = testsimcore; exports.testpydecomp = testpydecomp; exports.testpycomp = testpycomp; exports.testpytraces = testpytraces; diff --git a/pxtsimcore/README.md b/pxtsimcore/README.md index 9b42076e4142..fcd56cb12b13 100644 --- a/pxtsimcore/README.md +++ b/pxtsimcore/README.md @@ -163,3 +163,64 @@ and builds `common-simcore.js` and `common-sim.js`, which `pxt buildtarget` copi To run in a browser, load `pxtsim.js` and `sim.js`. To run without a DOM, load `pxtsimcore.js` and `simcore.js`. Never load both pairs: `pxtsim.js` already contains core. +## Porting a target + +pxt-microbit was the first target to ship a DOM-free bundle, and its `sim/core/` is the example. +These are the steps it took, in order. + +1. Partition the code. State, shims and runtime calls go to `sim/core/`. Anything that uses + `document`, `window`, a canvas, an SVG or an audio context goes to `sim/visuals/`. When one + member does both, keep the state and the decision in core and move the drawing to the view. +2. Split the board. A state class extends `CoreBoard`, a view class implements `RuntimeBoardView`, + and a small `boardaccess.ts` in core declares the board class the shims name: + ```ts + export class DalBoard extends DalBoardState { } + export function board(): DalBoard { return runtime.board as DalBoard; } + export function boardView(): RuntimeBoardView | undefined { return runtime.boardView; } + ``` +3. Set the entry points as under "Board state and view", each only if it is still unset. +4. Where the old board redrew after a state change, call `runtime.queueDisplayUpdate()` and redraw + in the view's `updateView`. +5. Replace every direct use of the clock and timers left in core with `host.clock()` and + `host.timers()`. Headless runs install a virtual host that replaces both; a global call left in + core bypasses it and breaks determinism. +6. A shim that needs the DOM, such as audio recording, calls an interface in core whose default + reports the feature as unsupported. The view bundle installs the DOM version when it loads. +7. Write the two configs as under "Target core bundles". Both include files from + pxt-common-packages: the core config the state files from `libs//sim/core/`, and the view + config the matching view files from `libs//sim/`. +8. Add a `/// ` wherever a file extends or calls another file as the bundle loads. + `headless.ts` references `boardaccess.ts` for this reason. +9. Every shim the simulator defines must be in `simcore.js`, or a headless run fails at that call. + List them before the split and check each against the core bundle's `.d.ts` after. +10. Build with `pxt buildtarget`, exercise every input of the browser simulator by hand, and add + `pxt simtest` programs under `tests/sim/` to the target's CI. + +## Running programs headless + +`pxt simtest` runs test programs in Node with no browser, through `runHeadlessAsync` in +`cli/simtest.ts`. A test is an ordinary program with its expected serial output in comments: + +```ts +// tests/sim/audio-pin.ts in pxt-microbit +// @serial: tone played +pins.setAudioPinEnabled(false) +music.playTone(262, 100) +console.log("tone played") +``` + +It passes when it compiles, runs without an error, finishes before the timeout and, if it has +`// @serial:` lines, writes exactly those lines in order. + +```sh +pxt simtest --base libs/blocksprj tests/sim # pxt-microbit's CI step, in the target directory +pxt simtest --core tests/sim # require the DOM-free pair; fail without one +pxt simtest --timeout 10000 --settle 0 tests/sim/buttons.ts +``` + +Each test replaces the one `.ts` file in the `--base` project, which defaults to the current +directory. The run loads `pxtsimcore.js` and `simcore.js` when the target has built `simcore.js`, +and `pxtsim.js` and `sim.js` otherwise. Every run installs a virtual host and the silent audio host, +so `pause(1000)` takes no real time. The program runs until its top-level code finishes, then for +`--settle` more virtual milliseconds (default 300), and never waits for it to go idle, so a +`forever` loop still passes. `--timeout` is real time and defaults to 5 seconds. diff --git a/tests/simcore-test/fixtures/toybundle.ts b/tests/simcore-test/fixtures/toybundle.ts new file mode 100644 index 000000000000..4f458198584b --- /dev/null +++ b/tests/simcore-test/fixtures/toybundle.ts @@ -0,0 +1,67 @@ +/// + +// The toy simulator bundle the simcore tests run on. It is the bare board with idle handlers, +// plus a few things the tests look for: +// +// - a `probe` message, posted first, describing the context it loaded in +// - a `boardcleanup` message when the board is killed +// - `control.millis`, which reads the runtime's running time +// - `testAudio.playAsync`, which plays two silent instruction steps of 300 ms and 200 ms and then +// posts a `testaudio` message with the running time it resolved at + +declare namespace pxsim.control { + let millis: () => number; +} + +declare namespace pxsim { + let testAudio: { playAsync(): Promise }; +} + +/** The first message the toy bundle posts: what the context it loaded in defines. */ +interface ProbeMessage extends pxsim.SimulatorMessage { + type: "probe"; + globals: { [name: string]: string }; +} + +/** Posted when `testAudio.playAsync` resolves, with the running time it resolved at. */ +interface TestAudioMessage extends pxsim.SimulatorMessage { + type: "testaudio"; + resolvedAt: number; +} + +pxsim.initHeadlessRuntime = function () { + pxsim.initBareRuntime(); + const probe: ProbeMessage = { + type: "probe", + globals: { + window: typeof window, + document: typeof document, + navigator: typeof navigator, + location: typeof location, + self: typeof self, + HTMLElement: typeof HTMLElement, + Element: typeof Element, + localStorage: typeof localStorage + } + }; + pxsim.Runtime.postMessage(probe); + pxsim.runtime.startIdle(); + pxsim.runtime.board.kill = function () { + pxsim.Runtime.messagePosted({ type: "boardcleanup" }); + }; + pxsim.control.millis = function () { return pxsim.runtime.runningTime(); }; + const step = pxsim.music.INSTRUCTION_STEP_BYTES; + const duration = pxsim.music.INSTRUCTION_DURATION_OFFSET; + const instructions = new Uint8Array(2 * step); + instructions[duration] = 300 & 0xff; + instructions[duration + 1] = 300 >> 8; + instructions[step + duration] = 200; + pxsim.testAudio = { + playAsync: function () { + return pxsim.audiohost.audio().playInstructionsAsync(instructions).then(function () { + const done: TestAudioMessage = { type: "testaudio", resolvedAt: pxsim.runtime.runningTime() }; + pxsim.Runtime.postMessage(done); + }); + } + }; +}; diff --git a/tests/simcore-test/simcorerunner.ts b/tests/simcore-test/simcorerunner.ts new file mode 100644 index 000000000000..9683190b00f2 --- /dev/null +++ b/tests/simcore-test/simcorerunner.ts @@ -0,0 +1,257 @@ +/// + +/* eslint-disable import/no-unassigned-import mocha-no-side-effect-code */ +import "mocha"; +import * as chai from "chai"; +import * as fs from "fs"; +import * as path from "path"; +import * as vm from "vm"; + +import * as util from "../common/testUtils"; +import type { HeadlessRunOptions } from "../../built/simtest"; + +// setup +function initGlobals() { + const g = global as any; + g.pxt = pxt; + g.ts = ts; + g.pxtc = pxtc; + g.btoa = (str: string) => Buffer.from(str, "binary").toString("base64"); + g.atob = (str: string) => Buffer.from(str, "base64").toString("binary"); +} +initGlobals(); + +pxt.setAppTarget(util.testAppTarget); + +const simtest = require(path.resolve(process.cwd(), "built", "simtest.js")) as typeof import("../../built/simtest"); + +const BROWSER_GLOBALS = ["window", "document", "navigator", "location", "self", "HTMLElement", "Element", "localStorage"]; + +const core = path.resolve(process.cwd(), "built", "pxtsimcore.js"); +/** Where the test project emits the compiled fixtures under fixtures/. */ +const bundleDir = path.resolve(process.cwd(), "built", "tests", "simcore-test", "fixtures"); + +/** + * The toy bundle, compiled with this test project from fixtures/toybundle.ts. Its `probe` message + * reports the type of each name in BROWSER_GLOBALS. + */ +const toyBundle = path.join(bundleDir, "toybundle.js"); + +/** Declares `control.millis`, which the toy board provides. */ +const MILLIS_SHIM = ` +declare namespace control { + //% shim=control::millis + function millis(): number; +} +`; + +const RANDOM_PROGRAM = ` + for (let i = 0; i < 3; i++) + console.log("r" + Math.randomRange(0, 1000)) +`; + +const options = { timeoutMs: 5000, settleMs: 300 }; + +/** Creates a vm context with no browser globals and loads pxtsimcore.js alone into it. */ +function createCoreContext() { + const context = vm.createContext({ console, setTimeout, clearTimeout, setInterval, clearInterval, performance, btoa, atob, TextEncoder, TextDecoder, URL, URLSearchParams }); + vm.runInContext(fs.readFileSync(core, "utf8"), context, { filename: core }); + return context; +} + +async function compileAsync(source: string) { + return (await util.stsAsync(source)).outfiles[pxtc.BINARY_JS]; +} + +/** Runs compiled JS headless on the toy board, with `options` overridden by `overrides`. */ +function runCompiledAsync(js: string, overrides: Partial = {}) { + return simtest.runHeadlessAsync(js, [core, toyBundle], { ...options, ...overrides }); +} + +async function runAsync(source: string, overrides: Partial = {}) { + return runCompiledAsync(await compileAsync(source), overrides); +} + +describe("pxtsimcore in a context without browser globals", () => { + it("has no browser globals", async function () { + this.timeout(20000); + const result = await runAsync(`pause(1)`); + const probe = result.messages.find(msg => msg.type === "probe") as ProbeMessage; + for (const name of BROWSER_GLOBALS) + chai.expect(probe.globals[name], name).equals("undefined"); + }); +}); + +describe("pxt simtest runner", () => { + it("collects serial lines from a program", async function () { + this.timeout(20000); + const result = await runAsync(`console.log("one"); console.log("two"); pause(10)`); + chai.expect(result.serial).deep.equals(["one", "two"]); + chai.expect(result.error).equals(undefined); + chai.expect(simtest.checkRun(result, ["one", "two"])).equals(undefined); + chai.expect(simtest.checkRun(result, ["one"])).includes("serial output mismatch"); + }); + + it("runs background fibers through virtual settle time and leaves no timer", async function () { + this.timeout(20000); + const js = await compileAsync(`control.runInBackground(() => { pause(60000); console.log("woke") })`); + const originalSetTimeout = global.setTimeout; + const originalClearTimeout = global.clearTimeout; + const originalSetInterval = global.setInterval; + const originalClearInterval = global.clearInterval; + let created = 0; + const pending = new Set(); + (global as any).setTimeout = (callback: (...args: any[]) => void, delay?: number, ...args: any[]) => { + let timer: any; + timer = originalSetTimeout(() => { + pending.delete(timer); + callback(...args); + }, delay); + created++; + pending.add(timer); + return timer; + }; + (global as any).clearTimeout = (timer: any) => { + pending.delete(timer); + originalClearTimeout(timer); + }; + (global as any).setInterval = (callback: (...args: any[]) => void, delay?: number, ...args: any[]) => { + const timer = originalSetInterval(() => callback(...args), delay); + created++; + pending.add(timer); + return timer; + }; + (global as any).clearInterval = (timer: any) => { + pending.delete(timer); + originalClearInterval(timer); + }; + try { + const result = await runCompiledAsync(js, { settleMs: 61000 }); + chai.expect(result.error).equals(undefined); + chai.expect(result.timedOut).equals(false); + chai.expect(result.serial).deep.equals(["woke"]); + chai.expect(result.host.now()).at.least(61000); + chai.expect(created).greaterThan(0); + chai.expect(pending.size).equals(0); + } finally { + global.setTimeout = originalSetTimeout; + global.clearTimeout = originalClearTimeout; + global.setInterval = originalSetInterval; + global.clearInterval = originalClearInterval; + } + }); + + it("reports a runtime error", async function () { + this.timeout(20000); + const result = await runAsync(`let a: number[] = null; console.log(a.length)`); + chai.expect(result.messages.some(msg => msg.type === "boardcleanup")).equals(true); + chai.expect(simtest.checkRun(result, [])).includes("runtime error"); + }); +}); + +describe("deterministic time and randomness", () => { + it("advances a virtual host defined by pxtsimcore alone in a context without browser globals", async function () { + this.timeout(20000); + const context = createCoreContext(); + const result = JSON.parse(await vm.runInContext(`(async () => { + const host = pxsim.host.createVirtualHost(); + const fired = []; + host.timers.setTimeout(() => fired.push(host.now()), 100); + await host.advance(150); + return JSON.stringify({ fired, now: host.now() }); + })()`, context)); + chai.expect(result.fired).deep.equals([100]); + chai.expect(result.now).equals(150); + }); + + it("reports virtual time through control.millis", async function () { + this.timeout(20000); + const result = await runAsync(MILLIS_SHIM + ` + console.log("t" + control.millis()) + pause(1000) + console.log("t" + control.millis()) + `); + chai.expect(result.serial).deep.equals(["t0", "t1000"]); + }); + + it("draws the same random numbers from the same seed, and a fixed sequence without one", async function () { + this.timeout(20000); + const js = await compileAsync(RANDOM_PROGRAM); + const first = (await runCompiledAsync(js, { seed: 42 })).serial; + const second = (await runCompiledAsync(js, { seed: 42 })).serial; + const other = (await runCompiledAsync(js, { seed: 7 })).serial; + chai.expect(first.length).equals(3); + chai.expect(second).deep.equals(first); + chai.expect(other).not.deep.equals(first); + const unseeded = (await runCompiledAsync(js)).serial; + const unseededAgain = (await runCompiledAsync(js)).serial; + chai.expect(unseeded.length).equals(3); + chai.expect(unseededAgain).deep.equals(unseeded); + }); + + it("plays instructions for the buffer's duration on the silent audio host", async function () { + this.timeout(20000); + const result = await runAsync(MILLIS_SHIM + ` + namespace testAudio { + //% promise shim=testAudio::playAsync + export function play(): void { } + } + testAudio.play() + console.log("t" + control.millis()) + `); + const played = result.messages.find(msg => msg.type === "testaudio") as TestAudioMessage; + chai.expect(played.resolvedAt).equals(500); + chai.expect(result.serial).deep.equals(["t500"]); + }); + + it("plays a song to its end on the silent audio host's metronome", async function () { + this.timeout(20000); + // 150 bpm at 4 ticks per beat is 100 ms per tick; 2 measures of 4 beats is 32 ticks + const song: pxt.assets.music.Song = { + measures: 2, + beatsPerMeasure: 4, + beatsPerMinute: 150, + ticksPerBeat: 4, + tracks: [{ + id: 0, + instrument: { + waveform: 1, + ampEnvelope: { attack: 10, decay: 100, sustain: 500, release: 100, amplitude: 1024 } + }, + notes: [{ startTick: 0, endTick: 4, notes: [{ note: 49, enharmonicSpelling: "normal" }] }] + }] + }; + const context = createCoreContext(); + const result = JSON.parse(await vm.runInContext(`(async () => { + const host = pxsim.host.createVirtualHost(); + host.use(); + const sequencer = new pxsim.music.Sequencer(); + await sequencer.initAsync(); + let stoppedAt; + sequencer.addEventListener("stop", () => stoppedAt = host.now()); + sequencer.start(${JSON.stringify(song)}, false); + const duration = sequencer.duration(); + await host.advance(duration - 1); + const before = { state: sequencer.state(), tick: sequencer.currentTick() }; + await host.advance(1); + const after = { state: sequencer.state(), tick: sequencer.currentTick() }; + return JSON.stringify({ duration, maxTick: sequencer.maxTick(), before, after, stoppedAt }); + })()`, context)); + chai.expect(result.duration).equals(3200); + chai.expect(result.maxTick).equals(32); + chai.expect(result.before).deep.equals({ state: "play", tick: 31 }); + chai.expect(result.after).deep.equals({ state: "stop", tick: 32 }); + chai.expect(result.stoppedAt).equals(3200); + }); + + it("times out a busy loop that never pauses", async function () { + this.timeout(20000); + const js = await compileAsync(` + let x = 0 + while (true) { x++ } + `); + const result = await runCompiledAsync(js, { timeoutMs: 1000 }); + chai.expect(result.timedOut).equals(true); + chai.expect(simtest.checkRun(result, [])).includes("timed out"); + }); +}); diff --git a/tests/simcore-test/tsconfig.json b/tests/simcore-test/tsconfig.json new file mode 100644 index 000000000000..a7cf2135ccd7 --- /dev/null +++ b/tests/simcore-test/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "target": "es2017", + "noImplicitAny": true, + "noImplicitReturns": true, + "declaration": true, + "outDir": "../../built/tests", + "rootDir": "..", + "newLine": "LF", + "module": "commonjs", + "types": [ + "chai", + "mocha", + "node" + ], + "sourceMap": false, + "skipLibCheck": true + }, + "files": [ + "simcorerunner.ts", + "fixtures/toybundle.ts", + "../common/testUtils.ts", + "../common/testHost.ts" + ] +}