Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions .github/instructions/simulator.instructions.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
130 changes: 126 additions & 4 deletions cli/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 <dir>`);

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;
}
Expand Down Expand Up @@ -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, "<dir>");
p.defineCommand({
name: "simtest",
help: "run programs headless against the target's simulator bundle (DOM-free bundles with --core)",
argString: "<file|dir>...",
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);

Expand Down
184 changes: 184 additions & 0 deletions cli/simtest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
/// <reference path="../built/pxtsim.d.ts"/>

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<HeadlessRunResult> {
const timeouts = new Set<ReturnType<typeof setTimeout>>();
const intervals = new Set<ReturnType<typeof setInterval>>();
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<typeof setTimeout>) => {
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<typeof setInterval>) => {
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<void>(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;
}
Loading
Loading