Add levels 04-07, code_contains test kind, StepValidator and reference-solution checks

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 12:50:19 +02:00
parent bb6bd8bc78
commit 4834979372
54 changed files with 1107 additions and 56 deletions
+45
View File
@@ -195,3 +195,48 @@ test('narration : fichier Piper lu jusqu\'au bout (politique autoplay par défau
assert.equal(await page.evaluate(() => window.__audio.errors), 0);
assert.deepEqual(errors, []);
});
test('niveau 07 : boucle while avec plusieurs saisies successives dans l\'interface', { skip, timeout: 120000 }, async () => {
const page = await (await browser.newContext()).newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.goto(base);
await page.waitForSelector('.progress-map .level-button', { timeout: 60000 });
await page.locator('.level-button', { hasText: 'Répéter avec une condition' }).click();
await page.waitForSelector('.explain');
const next = () => page.locator('.notebook-action button').last().click();
// Passe les étapes jusqu'à la mission (explications seulement : on saute les exercices en les validant).
const solveStep = async (code, answers = []) => {
const cell = page.locator('.cell').last();
await cell.locator('textarea').fill(code);
await cell.locator('.cell-run').click();
for (const answer of answers) {
await cell.locator('.cell-input-field').waitFor({ state: 'visible', timeout: 15000 });
await cell.locator('.cell-input-field').fill(answer);
await cell.locator('.cell-input-field').press('Enter');
}
await page.waitForFunction(() => document.querySelector('.cell:last-of-type')?.getAttribute('aria-busy') !== 'true');
await page.waitForTimeout(150);
return (await cell.locator('.cell-feedback').textContent()).trim();
};
await next();
assert.match(await solveStep('count = 5\nwhile count > 0:\n print(count)\n count = count - 1\nprint("Partez !")'), /correct/);
await next();
await next();
assert.match(await solveStep('total = 0\nnumber = 1\nwhile total < 50:\n total = total + number\n number = number + 1\nprint(total, number)'), /correct/);
await next();
await next();
const password = 'while True:\n word = input("Mot de passe ? ")\n if word == "python":\n break\n else:\n print("Essaie encore")\nprint("Bienvenue")';
assert.match(await solveStep(password, ['nope', 'python']), /correct/);
await next();
await next();
// Mission : trois saisies interactives successives (3, 9, 7) dans la même exécution.
const mission = 'secret = 7\nattempts = 0\nwhile True:\n guess = int(input("Ton choix (1-10) ? "))\n attempts = attempts + 1\n if guess == secret:\n print("Bravo, trouvé en", attempts, "essais")\n break\n elif guess < secret:\n print("Trop petit")\n else:\n print("Trop grand")';
assert.match(await solveStep(mission, ['3', '9', '7']), /correct/);
await page.waitForSelector('.toast');
assert.match(await page.textContent('.toast-region'), /\+70 XP/);
assert.deepEqual(errors, []);
});
+28
View File
@@ -0,0 +1,28 @@
// Polyfill de `Worker` pour Node : fait tourner le vrai python-worker.js (via worker-shim.mjs) derrière
// l'interface que PyodideWorkerClient attend dans un navigateur. Pyodide réel, aucune simulation.
import { Worker as NodeThread } from 'node:worker_threads';
const root = new URL('../../../', import.meta.url).pathname;
export function installNodeWorker() {
globalThis.crossOriginIsolated = true; // active SharedArrayBuffer (interruption et input)
globalThis.Worker = class {
#thread = new NodeThread(new URL('./worker-shim.mjs', import.meta.url), {
workerData: { workerPath: `${root}app/js/workers/python-worker.js`, runnerPath: `${root}app/python/pyquest_runner.py` },
});
addEventListener(type, listener) {
if (type === 'message') this.#thread.on('message', (data) => listener({ data }));
if (type === 'error') this.#thread.on('error', (error) => listener({ message: error.message }));
}
postMessage(message) {
this.#thread.postMessage(message);
}
terminate() {
return this.#thread.terminate();
}
};
return { indexURL: `${root}vendor/pyodide/` };
}
+1 -1
View File
@@ -5,7 +5,7 @@ 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', '03-input']);
assert.deepEqual((await e.listLevels()).map((l) => l.id), ['00-intro', '01-hello', '02-variables', '03-input', '04-math', '05-decide', '06-lists', '07-while']);
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');
@@ -0,0 +1,71 @@
// Pour chaque niveau : la solution de référence de chaque étape et de la mission doit passer tous
// les tests, et le code de départ ne doit pas les passer (sinon l'exercice serait déjà résolu).
// Pyodide réel (vendor/pyodide requis) ; exécute exactement la logique de l'application
// (StepValidator, ValidationEngine, PyodideWorkerClient).
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { test } from 'node:test';
import assert from 'node:assert';
import yaml from '../../app/js/lib/js-yaml/js-yaml.mjs';
import { PyodideWorkerClient } from '../../app/js/core/PyodideWorkerClient.js';
import { StepValidator } from '../../app/js/core/StepValidator.js';
import { ValidationEngine } from '../../app/js/core/ValidationEngine.js';
import { installNodeWorker } from './helpers/node-worker.mjs';
const root = new URL('../../', import.meta.url).pathname;
// Code sans commentaires ni lignes vides, pour comparer départ et solution.
const bare = (code) =>
code
.split('\n')
.filter((line) => line.trim() !== '' && !line.trim().startsWith('#'))
.join('\n');
const hasPyodide = existsSync(`${root}vendor/pyodide/pyodide.mjs`);
test('les solutions de référence passent, les codes de départ échouent', { skip: !hasPyodide && 'vendor/pyodide absent', timeout: 300000 }, async () => {
const { indexURL } = installNodeWorker();
const client = new PyodideWorkerClient({ indexURL, workerUrl: 'ignored' });
const stepValidator = new StepValidator({ client, validator: new ValidationEngine() });
// Comme l'application : exécution « interactive » de l'apprenant, puis validation des tests.
const attempt = async (code, tests) => {
// Saisies de l'exécution interactive : celles du premier test scripté, sinon aucune.
const queue = [...(tests.find((t) => t.inputs)?.inputs ?? [])];
let stdout = '';
const result = await client.run(code, {
collect: ValidationEngine.variablesToCollect(tests),
onStdout: (text) => (stdout += text),
onStderr: (text) => (stdout += text),
onInput: async () => (queue.length > 0 ? queue.shift() : null),
});
return stepValidator.validate(code, tests, { stdout, result });
};
const failures = (outcome) => outcome.results.filter((r) => !r.passed).map((r) => `${r.kind}:${r.reason}`);
const problems = [];
let checked = 0;
try {
for (const id of readdirSync(`${root}levels`).filter((name) => /^\d\d-/.test(name))) {
const level = yaml.load(readFileSync(`${root}levels/${id}/level.yaml`, 'utf8'));
await client.reset();
const exercises = [
...level.steps.map((step, i) => ({ label: `${id} étape ${i + 1}`, step })).filter(({ step }) => step.type === 'code'),
...(level.mission.tests?.length ? [{ label: `${id} mission`, step: { ...level.mission, solution: level.mission.solution } }] : []),
];
for (const { label, step } of exercises) {
assert.ok(step.solution, `${label} : solution manquante`);
const solved = await attempt(step.solution, step.tests);
checked += 1;
if (!solved.passed) problems.push(`${label} : la solution échoue (${failures(solved)})`);
// Les étapes « exécuter pour voir » ont un code de départ égal à la solution.
if (bare(step.starter) !== bare(step.solution)) {
const starter = await attempt(step.starter, step.tests);
if (starter.passed) problems.push(`${label} : le code de départ passe déjà les tests`);
}
}
}
} finally {
client.dispose();
}
assert.deepEqual(problems, []);
assert.ok(checked > 0);
console.log(`${checked} exercices vérifiés`);
});