Files
pplus-web/tests/quarto-render.test.mjs
T
alexm 7000662539
Build, test, deploy / site (push) Successful in 7m44s
A proof's time limit is the reader's to set
The Prove view gives each routine 3 seconds on the clock. On a slow or
busy device that runs out before the proof does, and claims stay open
with nothing to say why.

- The view says when the time, not the proof, stopped the checker, that
  what was not finished is open and not disproved, and offers to prove
  again with the next longer time. The setting is at the foot of the
  view: 3, 10 or 30 seconds or 2 minutes for each routine, kept in the
  browser (pplus.proveclock).
- A proof rendered with Quarto takes prove-seconds on the shortcode or
  pplus-prove-seconds for the site, and the render warns when the time
  ran out.
- The home page's own example is proved with no time on the clock, and
  the tests that hold a proof's outcome give it time to spare, so
  neither depends on the machine.
- core moves to 38e6e2c, whose report says which routines the clock
  stopped.
2026-11-13 07:01:35 -05:00

226 lines
16 KiB
JavaScript

// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
// SPDX-License-Identifier: Apache-2.0
// The rendered views of the Quarto extension (src/quarto/): a program from the files beside a page, run by the app's
// engines and drawn by its views as HTML, under the small document of src/quarto/dom.ts; the CLI pplus.lua calls
// (quarto/_extensions/pplus/render.mjs). The gallery that shows them in the app is tests/quarto-gallery.test.mjs.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import zlib from 'node:zlib';
import { installDocument, SDocument } from '../dist/quarto/dom.js';
import { programHeader, listingText, langOfFile } from '../dist/quarto/program.js';
installDocument();
const { renderStatic, STATIC_VIEWS, stepsPanel } = await import('../dist/quarto/render.js');
const { problemById } = await import('../dist/core/catalog.js');
const ROOT = new URL('..', import.meta.url).pathname;
const CB = problemById('count-base');
const head = (call, expect) => `// CALL: ${call}\n${expect ? `// EXPECT: ${expect}\n` : ''}`;
const PSEUDO = head(CB.call, 'COUNT_BASE returned 3') + CB.sources.pseudo;
test('a program file: its pane, its header lines, and the text a page shows', () => {
assert.equal(langOfFile('x/count.pseudo'), 'pseudo');
assert.equal(langOfFile('mean.tex'), 'matho');
assert.equal(langOfFile('demo.mojo'), 'mojo');
assert.equal(langOfFile('notes.txt'), null);
const h = programHeader('// CALL: F(1)\n// INPUT: 4\n// INPUT: 5\n// EXPECT: F returned 2\n// STOPS: index\nFUNCTION F...');
assert.deepEqual(h, { call: 'F(1)', input: ['4', '5'], expect: ['F returned 2'], stops: 'index', questions: [] });
assert.deepEqual(programHeader('% CALL: X(1)\n% EXPECT: X returned 1\n').expect, ['X returned 1']);
assert.deepEqual(programHeader('# expect-stdout: 3\n# expect-stdout: 4\ndef main():\n pass\n').expect, ['3', '4'], 'a Mojo file\'s corpus header counts as EXPECT');
assert.equal(listingText('// CALL: F(1)\n\nFUNCTION F()\n', 'pseudo'), 'FUNCTION F()');
assert.equal(listingText('# origin: x\n# expect-stdout: 1\n\ndef main():\n # note: mine\n print(1)\n', 'mojo'), 'def main():\n # note: mine\n print(1)');
});
test('the small document builds, finds and writes what the views make', () => {
const doc = new SDocument();
const div = doc.createElement('div');
div.className = 'a b';
div.classList.add('c'); div.classList.toggle('a');
div.style.left = '10%'; div.style.setProperty('--x', '1');
div.dataset.stepNo = '4';
const svg = doc.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('viewBox', '0 0 1 1');
svg.appendChild(doc.createElementNS('http://www.w3.org/2000/svg', 'path'));
const p = doc.createElement('p'); p.textContent = 'x < y & "z"';
const sel = doc.createElement('select');
for (const v of ['one', 'two']) { const o = doc.createElement('option'); o.value = v; o.textContent = v; sel.appendChild(o); }
sel.value = 'two';
const details = doc.createElement('details'); details.open = true;
div.append(svg, p, sel, details);
assert.equal(div.outerHTML, '<div class="b c" style="left: 10%; --x: 1" data-step-no="4"><svg viewBox="0 0 1 1"><path/></svg><p>x &lt; y &amp; "z"</p><select><option value="one" selected="">one</option><option value="two" selected>two</option></select><details open></details></div>'.replace(' selected=""', ''));
assert.equal(div.querySelectorAll('svg path').length, 1, 'the descendant combinator');
assert.equal(div.querySelector('[data-step-no="4"]'), null, 'the root itself is not searched');
assert.equal(div.querySelectorAll('.b, p').length, 1);
assert.equal(p.closest('.c'), div);
assert.throws(() => div.querySelector('div > p'), /only the descendant combinator/);
p.replaceWith(doc.createTextNode('gone'));
assert.equal(div.textContent.includes('gone'), true);
});
test('run: what the program prints, checked against its EXPECT lines, for each notation', () => {
const r = renderStatic({ view: 'run', files: { pseudo: PSEUDO } });
assert.equal(r.lang, 'pseudo');
assert.deepEqual(r.expect, { want: ['COUNT_BASE returned 3'], got: ['COUNT_BASE returned 3'], ok: true });
assert.match(r.html, /prints the 1 line its EXPECT header says/);
assert.match(r.markdown, /```\nCOUNT_BASE returned 3\n```/);
const wrong = renderStatic({ view: 'run', files: { pseudo: PSEUDO.replace('returned 3', 'returned 9') } });
assert.equal(wrong.expect.ok, false);
assert.match(wrong.warnings.join('\n'), /its EXPECT lines say \["COUNT_BASE returned 9"\]/);
const lingo = renderStatic({ view: 'run', files: { lingo: CB.sources.lingo }, call: 'COUNT_BASES(\'A\', "GATTACA")' });
assert.deepEqual(lingo.expect, undefined);
assert.match(lingo.html, /COUNT_BASES returned 3/);
const mojo = renderStatic({ view: 'run', files: { mojo: '# EXPECT: 3\n' + CB.sources.mojo } });
assert.equal(mojo.lang, 'mojo');
assert.ok(mojo.expect.ok);
assert.match(mojo.html, /not the compiler/, 'the interpreter says it is not the compiler');
const compiled = renderStatic({ view: 'run', files: { mojo: CB.sources.mojo }, compiled: { stdout: '3\n', stderr: '', status: 0, version: 'Mojo 9.9.9' } });
// whatever version the rendering machine's compiler reports is what the view says
assert.match(compiled.html, /Mojo 9\.9\.9, on the machine that rendered this page/);
const broken = renderStatic({ view: 'run', files: { pseudo: 'FUNCTION F() RETURNS INTEGER\n RETURN Nope\nENDFUNCTION\n' } });
assert.match(broken.html, /pplus-err/);
assert.ok(broken.warnings.length);
});
test('steps: one row per step of the run, the values after it, and the page drawn at the step asked for', () => {
const r = renderStatic({ view: 'steps', files: { pseudo: PSEUDO }, t: 5 });
const json = /<script type="application\/json" class="pplus-steps-data">([^<]*)<\/script>/.exec(r.html)[1];
const data = JSON.parse(json);
assert.equal(data.lang, 'pseudo');
assert.equal(data.rows.length, data.count);
assert.equal(data.t, 5);
assert.deepEqual(data.cols.map((c) => c.label), ['B', 'T', 'N', 'Total', 'I']);
const at = stepsPanel(data, 5);
assert.match(r.html, new RegExp(`class="pplus-ln is-next" data-line="${at.next}"`));
assert.equal(stepsPanel(data, data.count).out.join('\n'), 'COUNT_BASE returned 3');
assert.equal(stepsPanel(data, 0).now, 'Before the first step.');
const asm = renderStatic({ view: 'steps', files: { asm: problemById('asm-two-pointers').sources.asm }, setup: problemById('asm-two-pointers').setup, max: 20 });
const ad = JSON.parse(/class="pplus-steps-data">([^<]*)</.exec(asm.html)[1]);
assert.equal(ad.lang, 'asm');
assert.equal(ad.count, 20);
assert.ok(ad.truncated);
assert.ok(ad.cols.length && ad.cols.every((c) => /^r[a-z0-9]+$/.test(c.label)), 'a column per register the run writes');
const follow = renderStatic({ view: 'steps', files: { pseudo: PSEUDO }, follow: ['total'] });
assert.deepEqual(JSON.parse(/class="pplus-steps-data">([^<]*)</.exec(follow.html)[1]).cols.map((c) => c.label), ['Total']);
});
test('every rendered view draws for a program that has what it needs, with the app\'s controls taken out', () => {
const files = { pseudo: PSEUDO, speco: problemById('count-base-proved').sources.speco };
for (const view of ['table', 'flow', 'data', 'proof', 'tests', 'check']) {
const r = renderStatic({ view, files });
assert.match(r.html, new RegExp(`^<div class="[^"]*pplus-static pplus-v-${view}`), view);
assert.doesNotMatch(r.html, /<button|<input|<select/, `${view} keeps no control the page cannot use`);
assert.ok(r.markdown.length > 10, `${view} has a Markdown form`);
}
assert.match(renderStatic({ view: 'flow', files }).html, /<svg[^>]*class="flow-svg"/);
// with time to spare: the 3 seconds a rendered proof has by default can run out on a slow machine (prove-seconds)
const proof = renderStatic({ view: 'proof', files, proveSeconds: 600 });
assert.match(proof.html, /4 proved/);
assert.deepEqual(proof.warnings, []);
const check = renderStatic({ view: 'check', files: { pseudo: problemById('five-bugs').sources.pseudo } });
assert.match(check.html, /problem-error/);
assert.match(check.markdown, /\*\*error\*\*, pseudo line \d+: /);
const tests = renderStatic({ view: 'tests', files: { pseudo: problemById('match-off-by-one').sources.pseudo } });
assert.match(tests.html, /way of failing/);
const machine = renderStatic({ view: 'machine', files: { asm: problemById('asm-two-pointers').sources.asm }, setup: problemById('asm-two-pointers').setup });
assert.match(machine.markdown, /\| instructions \| \d+ \|/);
const life = renderStatic({ view: 'life', files: { mojo: fs.readFileSync(ROOT + 'core/library/mojo/stress/lifecycle-moves.mojo', 'utf8') } });
assert.ok((life.html.match(/life-row/g) ?? []).length >= 3);
assert.doesNotMatch(life.html, /Click a mark/, 'a page has no stepper to move');
assert.equal(STATIC_VIEWS.length, 12);
});
test('translate: one file in, every notation out, Mojo labeled as generated', () => {
const r = renderStatic({ view: 'translate', files: { matho: '% CALL: X_BAR(3, [1.0, 2.0, 6.0])\n\\bar{x} = \\frac{1}{n} \\sum_{i=0}^{n-1} x_i\n' } });
assert.deepEqual(r.panes.map((p) => [p.lang, p.authored, p.generated]), [['matho', true, false], ['lingo', false, true], ['pseudo', false, true], ['mojo', false, true]]);
assert.equal(r.panes.find((p) => p.lang === 'lingo').from, 'matho');
assert.match(r.panes.find((p) => p.lang === 'mojo').text, /def x_bar/);
const only = renderStatic({ view: 'translate', files: { lingo: CB.sources.lingo }, to: ['pseudo', 'mojo'] });
assert.deepEqual(only.panes.map((p) => p.lang), ['pseudo', 'mojo']);
const cannot = renderStatic({ view: 'translate', files: { pseudo: PSEUDO }, to: ['matho'] });
assert.equal(cannot.panes[0].text, '');
assert.ok(cannot.panes[0].note, 'a notation that cannot say it says why');
});
test('render.mjs answers a request from pplus.lua, and keeps the answer in its cache', () => {
const cache = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-cache-'));
const ask = (req) => {
const r = spawnSync(process.execPath, [ROOT + 'quarto/_extensions/pplus/render.mjs', ROOT], { input: JSON.stringify(req), encoding: 'utf8', env: { ...process.env, PATH: '/nonexistent' } });
assert.equal(r.status, 0, r.stderr);
return JSON.parse(r.stdout);
};
const a = ask({ view: 'run', files: { pseudo: PSEUDO }, cache });
assert.equal(a.expect.ok, true);
assert.equal(a.node, undefined, 'the element stays behind; its HTML goes');
assert.equal(fs.readdirSync(cache).length, 1);
const b = ask({ view: 'run', files: { pseudo: PSEUDO }, cache });
assert.deepEqual(b, a, 'the same answer, from the cache');
assert.match(ask({ view: 'nonsense', files: { pseudo: PSEUDO } }).error, /unknown view "nonsense"/);
const big = ask({ view: 'tests', files: { pseudo: PSEUDO } });
assert.ok(big.html.length > 65536 && big.html.endsWith('</div>'), `a large answer (${big.html.length} characters) arrives whole through the pipe`);
const none = spawnSync(process.execPath, [ROOT + 'quarto/_extensions/pplus/render.mjs', os.tmpdir()], { input: '{}', encoding: 'utf8' });
assert.match(JSON.parse(none.stdout).error, /no built Programming\+/);
// a Mojo run asks for the compiler only when one is on the PATH; compiler="on" insists on it
const mojo = ask({ view: 'run', files: { mojo: CB.sources.mojo }, compiler: 'on' });
assert.match(mojo.error, /no `mojo` on the PATH/);
});
test('the machine board: every card of the Hardware area, drawn at each step, the drawings shared between steps', async () => {
const { HW_NAMES, HW_PRESETS, hwView } = await import('../dist/quarto/machine.js');
const p = problemById('asm-two-pointers');
const files = { asm: p.sources.asm };
const board = renderStatic({ view: 'hw', files, setup: p.setup, t: 9 });
assert.deepEqual(board.warnings, []);
const data = JSON.parse(/class="pplus-hw-data">([^<]*)</.exec(board.html)[1]);
assert.equal(data.count, 97);
assert.equal(data.shown.length, 98, 'every step of a short run');
assert.deepEqual(data.cards.map((c) => c.id), HW_PRESETS[0].views);
for (const c of data.cards) {
assert.equal(c.at.length, data.shown.length);
assert.ok(c.frames.length <= data.shown.length && c.at.every((i) => i < c.frames.length));
}
assert.ok(data.cards.find((c) => c.id === 'stack').frames.length < 5, 'a card that does not change is drawn once');
assert.equal(data.steps[9].x, 'mov r11, qword ptr [rdx + r9*8]');
// every view of the machine draws on this run without failing, paging with virtual memory switched on
for (const name of Object.keys(HW_NAMES)) {
const r = renderStatic({ view: 'hw', files, setup: p.setup, hw: [name], max: 12 });
assert.deepEqual(r.warnings, [], name);
assert.doesNotMatch(r.html, /has-failed|could not be built/, name);
const frames = JSON.parse(/class="pplus-hw-data">([^<]*)</.exec(r.html)[1]).cards.flatMap((c) => c.frames).join('');
assert.doesNotMatch(frames, /<button|<input|<select/, `${name}: its drawings keep no control`);
}
assert.match(renderStatic({ view: 'hw', files, setup: p.setup, hw: ['paging'], max: 12 }).html, /with virtual memory/);
const sampled = renderStatic({ view: 'hw', files, setup: p.setup, hw: ['registers'], max: 20 });
const sd = JSON.parse(/class="pplus-hw-data">([^<]*)</.exec(sampled.html)[1]);
assert.ok(sd.shown.length <= 21 && sd.shown.at(-1) === 97, 'a long run is sampled, and the last step is always there');
assert.match(sampled.html, /every 5th is drawn/);
const one = renderStatic({ view: 'hw', files, setup: p.setup, hw: ['encoding'], t: 9, stepper: false, listing: false });
assert.doesNotMatch(one.html, /pplus-steps-bar|pplus-hw-data|pplus-hw-listing/, 'stepper="0": one step, nothing to step');
assert.match(one.markdown, /The machine at step 9 of 97, after `mov r11/);
assert.equal(hwView('alu'), 'bits');
assert.equal(hwView('chip'), 'machine');
assert.equal(hwView('run'), null, 'not a machine view');
const none = renderStatic({ view: 'hw', files: { pseudo: PSEUDO } });
assert.match(none.warnings.join(), /no x86-64 file/);
});
test('render.mjs compresses the machine\'s steps, and they come back whole', () => {
const p = problemById('asm-two-pointers');
const r = spawnSync(process.execPath, [ROOT + 'quarto/_extensions/pplus/render.mjs', ROOT], { input: JSON.stringify({ view: 'hw', files: { asm: p.sources.asm }, setup: p.setup, hw: ['pipeline'] }), encoding: 'utf8' });
const res = JSON.parse(r.stdout);
const b64 = /type="application\/x-pplus-deflate" class="pplus-hw-data">([^<]+)</.exec(res.html)[1];
const data = JSON.parse(zlib.inflateRawSync(Buffer.from(b64, 'base64')).toString('utf8'));
assert.equal(data.cards[0].id, 'pipeline');
assert.ok(b64.length < 60000, `the pipeline over 97 steps is ${b64.length} characters`);
});
test('a run that cannot start reports its EXPECT lines as not printed', () => {
const r = renderStatic({ view: 'run', files: { pseudo: '// EXPECT: 3\nPROCEDURE F(\n' } });
assert.deepEqual(r.expect, { want: ['3'], got: [], ok: false });
assert.match(r.warnings.join('\n'), /It does not run yet/);
assert.equal(renderStatic({ view: 'run', files: { pseudo: 'PROCEDURE F(\n' } }).expect, undefined, 'no EXPECT lines, nothing to hold it to');
});