mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Add tooling: Makefile, level validation, build, Pyodide vendoring, tests, docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
import { AudioEngine } from '../../app/js/core/AudioEngine.js';
|
||||
import { VoiceEngine } from '../../app/js/core/VoiceEngine.js';
|
||||
import assert from 'node:assert';
|
||||
let osc = 0;
|
||||
const node = () => ({ connect: (n) => n, start() {}, stop() {}, frequency: {}, gain: { setValueAtTime() {}, linearRampToValueAtTime() {} } });
|
||||
const ctx = { state: 'suspended', currentTime: 0, destination: {}, resume: async function () { this.state = 'running'; }, createOscillator: () => { osc++; return node(); }, createGain: node };
|
||||
const a = new AudioEngine({ contextFactory: () => ctx });
|
||||
assert.equal(a.play('success_small'), false); // pas débloqué
|
||||
await a.unlock();
|
||||
assert.equal(a.play('success_small'), true); assert.equal(osc, 2);
|
||||
assert.equal(a.play('nope'), false);
|
||||
a.setEnabled(false); assert.equal(a.play('error'), false);
|
||||
a.setEnabled(true); a.setVolume(5); assert.equal(a.volume, 1);
|
||||
// Voix
|
||||
const spoken = [];
|
||||
class U { constructor(t) { this.text = t; } }
|
||||
const synth = { cancel() { spoken.push('cancel'); }, getVoices: () => [{ lang: 'en-GB' }, { lang: 'fr-CA' }, { lang: 'fr-FR' }],
|
||||
speak(u) { spoken.push(u); setTimeout(() => u.onend(), 0); } };
|
||||
const v = new VoiceEngine({ synth, Utterance: U });
|
||||
assert.equal(await v.speak('Utilise `print()` ici', 'fr'), true);
|
||||
const u = spoken.at(-1); assert.equal(u.text, 'Utilise print() ici'); assert.equal(u.voice.lang, 'fr-FR'); assert.equal(u.lang, 'fr-FR');
|
||||
v.setRate(9); assert.equal(v.rate, 2);
|
||||
v.setEnabled(false); assert.equal(await v.speak('x'), false);
|
||||
assert.equal(new VoiceEngine({ synth: null, Utterance: undefined }).supported, false);
|
||||
console.log('audio/voice ok');
|
||||
@@ -0,0 +1,26 @@
|
||||
import { ErrorTranslator } from '../../app/js/core/ErrorTranslator.js';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import assert from 'node:assert';
|
||||
const d = new URL('../../app/js/i18n/', import.meta.url).pathname;
|
||||
const fr = JSON.parse(readFileSync(d + 'errors.fr.json')), en = JSON.parse(readFileSync(d + 'errors.en.json'));
|
||||
assert.deepEqual(Object.keys(fr), Object.keys(en));
|
||||
for (const k of Object.keys(fr)) assert.deepEqual(Object.keys(fr[k]), ['title', 'explanation', 'tip']);
|
||||
const t = new ErrorTranslator({ fr, en });
|
||||
// Messages réels produits par CPython (version locale) pour valider les motifs.
|
||||
const cases = ['print(nom)', 'print("a', 'print("a"', 'if x\n pass', 'print "a"', '1+"a"', '"a"+1', '"a"()', 'int("abc")', 'float("x,y")', '[1][5]', '{}["k"]', '(1).foo', 'import nope', '1/0', 'if True:\npass', 'def f(a): pass\nf()', '2x', 'x = 1\ndef g():\n print(x)\n x = 2\ng()'];
|
||||
const py = execFileSync('python3', ['-I', '-c', `
|
||||
import json,sys
|
||||
out=[]
|
||||
for c in json.loads(sys.argv[1]):
|
||||
try: exec(compile(c,'<c>','exec'),{})
|
||||
except BaseException as e: out.append({'type':type(e).__name__,'message':str(e),'lineno':getattr(e,'lineno',None),'traceback':''})
|
||||
print(json.dumps(out))`, JSON.stringify(cases)]);
|
||||
for (const e of JSON.parse(py)) {
|
||||
const r = t.translate(e, 'fr');
|
||||
console.log(e.type.padEnd(20), '|', r.title);
|
||||
assert.ok(!/\{\w+\}/.test(r.title + r.explanation + r.tip), 'placeholder non résolu: ' + r.title);
|
||||
}
|
||||
assert.equal(t.translate({ type: 'NameError', message: "name 'nom' is not defined" }, 'en').title, 'Python doesn\'t know "nom"');
|
||||
assert.equal(t.translate({ type: 'Weird', message: 'boom' }).title, 'Une erreur est survenue : Weird');
|
||||
console.log('translator ok');
|
||||
@@ -0,0 +1,40 @@
|
||||
// Exécuté dans un worker_threads : émule l'environnement navigateur minimal attendu par
|
||||
// python-worker.js (self, fetch de file://) pour le tester sous Node avec le vrai Pyodide.
|
||||
import { parentPort, workerData } from 'node:worker_threads';
|
||||
import { readFile, copyFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
const listeners = [];
|
||||
globalThis.self = {
|
||||
addEventListener: (type, listener) => listeners.push(listener),
|
||||
postMessage: (message) => parentPort.postMessage(message),
|
||||
};
|
||||
// Les messages reçus avant le chargement du worker sont mis en file puis rejoués.
|
||||
const queue = [];
|
||||
let loaded = false;
|
||||
parentPort.on('message', (data) => {
|
||||
if (loaded) {
|
||||
listeners.forEach((listener) => listener({ data }));
|
||||
} else {
|
||||
queue.push(data);
|
||||
}
|
||||
});
|
||||
|
||||
// Le runner Python est demandé par URL relative au worker : on le redirige vers le fichier réel.
|
||||
const realFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (input, ...rest) => {
|
||||
if (String(input).includes('pyquest_runner.py')) {
|
||||
const text = await readFile(workerData.runnerPath, 'utf8');
|
||||
return { ok: true, text: async () => text };
|
||||
}
|
||||
return realFetch(input, ...rest);
|
||||
};
|
||||
|
||||
// Node lit un .js sans package.json comme CommonJS : on charge une copie .mjs du worker.
|
||||
const copy = join(tmpdir(), `pyquest-worker-${process.pid}.mjs`);
|
||||
await copyFile(workerData.workerPath, copy);
|
||||
await import(pathToFileURL(copy).href);
|
||||
loaded = true;
|
||||
queue.splice(0).forEach((data) => listeners.forEach((listener) => listener({ data })));
|
||||
@@ -0,0 +1,15 @@
|
||||
import { LessonEngine } from '../../app/js/core/LessonEngine.js';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import assert from 'node:assert';
|
||||
const root = new URL('../../', import.meta.url).pathname.replace(/\/$/, '');
|
||||
const e = new LessonEngine({ levelsUrl: 'http://x/levels/', fetchFn: async (u) => {
|
||||
try { const t = await readFile(root + new URL(u).pathname, 'utf8'); return { ok: true, text: async () => t }; }
|
||||
catch { return { ok: false, status: 404 }; } } });
|
||||
assert.deepEqual((await e.listLevels()).map((l) => l.id), ['00-intro', '01-hello', '02-variables']);
|
||||
const s = await e.startLevel('02-variables', 'en');
|
||||
assert.equal(s.title, 'Variables and types'); assert.equal(s.stepCount, 7);
|
||||
assert.equal(s.step.type, 'explain');
|
||||
while (s.next()); assert.ok(s.onMission); assert.equal(s.mission.tests[0].message, 'tip must equal bill * rate.');
|
||||
const f = await e.startLevel('01-hello', 'fr'); f.next(); f.next(); assert.deepEqual(f.step.hints.length, 2);
|
||||
await assert.rejects(e.loadLevel('99-nope'));
|
||||
console.log('lesson ok');
|
||||
@@ -0,0 +1,25 @@
|
||||
import { ProgressStore } from '../../app/js/core/ProgressStore.js';
|
||||
import { MemoryKeyValueStore } from '../../app/js/core/KeyValueStores.js';
|
||||
import assert from 'node:assert';
|
||||
const d = (s) => new Date(s + 'T10:00:00');
|
||||
const kv = new MemoryKeyValueStore();
|
||||
const p = new ProgressStore(kv); await p.load();
|
||||
let r = await p.completeLevel('00-intro', 10, d('2026-10-14'));
|
||||
assert.deepEqual([r.xpGained, r.newBadges, r.streak.current], [10, ['first_level'], 1]);
|
||||
r = await p.completeLevel('00-intro', 10, d('2026-10-14'));
|
||||
assert.deepEqual([r.xpGained, r.alreadyCompleted], [0, true]);
|
||||
r = await p.completeLevel('01-hello', 20, d('2026-10-15'));
|
||||
assert.equal(r.streak.current, 2);
|
||||
r = await p.completeLevel('02-variables', 70, d('2026-10-17')); // jour manqué
|
||||
assert.deepEqual([r.streak.current, r.streak.best, r.newBadges.sort()], [1, 2, ['three_levels', 'xp_100']]);
|
||||
assert.equal(p.snapshot().xp, 100);
|
||||
// Persistance + export/import
|
||||
const p2 = new ProgressStore(kv); assert.equal((await p2.load()).xp, 100);
|
||||
const other = new ProgressStore(new MemoryKeyValueStore()); await other.load();
|
||||
await other.completeLevel('05-decide', 40, d('2026-10-20'));
|
||||
const merged = await p2.import(other.export());
|
||||
assert.equal(merged.xp, 140); assert.equal(Object.keys(merged.completedLevels).length, 4);
|
||||
assert.equal(merged.streak.lastDay, '2026-10-20');
|
||||
await assert.rejects(p2.import('{"version":99}'));
|
||||
await assert.rejects(new ProgressStore(kv).completeLevel('x', 1));
|
||||
console.log('progress ok');
|
||||
@@ -0,0 +1,62 @@
|
||||
// Test d'intégration : le vrai python-worker.js avec le vrai Pyodide (vendor/pyodide requis).
|
||||
// Ignoré si Pyodide n'est pas installé (make vendor-pyodide).
|
||||
import { Worker } from 'node:worker_threads';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert';
|
||||
|
||||
const root = new URL('../../', import.meta.url).pathname;
|
||||
const indexURL = `${root}vendor/pyodide/`;
|
||||
|
||||
test('worker Python sous Pyodide', { skip: !existsSync(`${indexURL}pyodide.mjs`) && 'vendor/pyodide absent' }, async () => {
|
||||
const worker = new Worker(new URL('./helpers/worker-shim.mjs', import.meta.url), {
|
||||
workerData: { workerPath: `${root}app/js/workers/python-worker.js`, runnerPath: `${root}app/python/pyquest_runner.py` },
|
||||
});
|
||||
const interruptBuffer = new SharedArrayBuffer(1);
|
||||
const waiters = new Map();
|
||||
const stdout = [];
|
||||
worker.on('message', (message) => {
|
||||
if (message.type === 'stdout') stdout.push(message.text);
|
||||
const key = message.type === 'result' ? message.id : 'init';
|
||||
if (['result', 'ready', 'init_error'].includes(message.type)) waiters.get(key)?.(message);
|
||||
});
|
||||
const wait = (key) =>
|
||||
new Promise((resolve, reject) => {
|
||||
waiters.set(key, resolve);
|
||||
worker.once('error', reject);
|
||||
});
|
||||
const run = (id, code, collect = []) => {
|
||||
const done = wait(id);
|
||||
worker.postMessage({ type: 'run_code', id, code, collect });
|
||||
return done;
|
||||
};
|
||||
|
||||
try {
|
||||
const init = wait('init');
|
||||
worker.postMessage({ type: 'init', indexURL, interruptBuffer });
|
||||
assert.deepEqual(await init, { type: 'ready', interruptible: true });
|
||||
|
||||
let result = await run(1, 'x = 10.0\nprint("hé")\nprint(x)', ['x']);
|
||||
assert.equal(result.ok, true);
|
||||
assert.deepEqual(stdout.join(''), 'hé\n10.0\n');
|
||||
assert.deepEqual(result.variables.x, { type: 'float', repr: '10.0', value: 10 });
|
||||
|
||||
result = await run(2, 'print(nom)');
|
||||
assert.deepEqual([result.error.type, result.error.lineno], ['NameError', 1]);
|
||||
|
||||
result = await run(3, 'y = x + 1', ['y']); // l'espace de noms persiste
|
||||
assert.equal(result.variables.y.value, 11);
|
||||
|
||||
result = await run(4, 'input("?")');
|
||||
assert.equal(result.error.type, 'EOFError');
|
||||
|
||||
const looping = run(5, 'while True:\n pass');
|
||||
setTimeout(() => (new Uint8Array(interruptBuffer)[0] = 2), 500);
|
||||
assert.equal((await looping).error.type, 'KeyboardInterrupt');
|
||||
|
||||
result = await run(6, 'print("après")'); // le worker reste utilisable
|
||||
assert.equal(result.ok, true);
|
||||
} finally {
|
||||
await worker.terminate();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { ValidationEngine } from '../../app/js/core/ValidationEngine.js';
|
||||
import assert from 'node:assert';
|
||||
const v = new ValidationEngine();
|
||||
const ok = { ok: true, error: null, variables: { total: { type: 'float', value: 10, repr: '10.0' } } };
|
||||
const tests = [
|
||||
{ kind: 'var_equals', name: 'total', value: 10.0 },
|
||||
{ kind: 'var_type_is', name: 'total', value: 'float' },
|
||||
{ kind: 'stdout_equals', value: '10.0\n' },
|
||||
{ kind: 'stdout_matches_regex', value: '^[^\\n]+\\n$' },
|
||||
];
|
||||
assert.deepEqual(ValidationEngine.variablesToCollect(tests), ['total']);
|
||||
assert.ok(v.validate(tests, { stdout: '10.0\n', result: ok }).passed);
|
||||
const bad = v.validate(tests, { stdout: '10\n', result: { ...ok, variables: { total: { type: 'int', value: 10 } } } });
|
||||
assert.deepEqual(bad.results.map((r) => r.reason), [null, 'type_mismatch', 'stdout_mismatch', null]);
|
||||
assert.equal(v.validate([{ kind: 'no_syntax_error' }], { stdout: '', result: { ok: false, error: { type: 'SyntaxError' }, variables: {} } }).results[0].reason, 'syntax_error');
|
||||
assert.equal(v.validate([{ kind: 'no_syntax_error' }], { stdout: '', result: { ok: false, error: { type: 'NameError' }, variables: {} } }).passed, false);
|
||||
assert.equal(v.validate([{ kind: 'var_equals', name: 'x', value: 1 }], { stdout: '', result: ok }).results[0].reason, 'variable_missing');
|
||||
console.log('validation ok');
|
||||
@@ -0,0 +1,26 @@
|
||||
import { PyodideWorkerClient } from '../../app/js/core/PyodideWorkerClient.js';
|
||||
import assert from 'node:assert';
|
||||
let spawned = 0;
|
||||
globalThis.Worker = class {
|
||||
constructor() { spawned++; this.l = {}; this.mode = spawned; }
|
||||
addEventListener(t, f) { this.l[t] = f; }
|
||||
terminate() { this.dead = true; }
|
||||
postMessage(m) {
|
||||
const r = (d) => queueMicrotask(() => !this.dead && this.l.message({ data: d }));
|
||||
if (m.type === 'init') r({ type: 'ready', interruptible: false });
|
||||
if (m.type === 'run_code' && m.code === 'ok') { r({ type: 'stdout', id: m.id, text: 'hi\n' }); r({ type: 'result', id: m.id, ok: true, error: null, variables: {} }); }
|
||||
}
|
||||
};
|
||||
const c = new PyodideWorkerClient({ indexURL: '/v/', workerUrl: 'x' });
|
||||
let out = '';
|
||||
const res = await c.run('ok', { onStdout: (t) => (out += t) });
|
||||
assert.equal(out, 'hi\n'); assert.equal(res.ok, true); assert.equal(res.type, undefined);
|
||||
const hang = c.run('loop');
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
c.interrupt();
|
||||
const h = await hang;
|
||||
assert.equal(h.error.type, 'KeyboardInterrupt');
|
||||
assert.equal(spawned, 2);
|
||||
assert.equal((await c.run('ok')).ok, true);
|
||||
c.dispose();
|
||||
console.log('client ok');
|
||||
Reference in New Issue
Block a user