Add LevelLinter (static checks) and LevelChecker (execution checks) shared by tests and the future author editor

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 16:44:05 +02:00
parent a97995342f
commit 2205d64ea3
16 changed files with 1637 additions and 51 deletions
+80
View File
@@ -0,0 +1,80 @@
// Vérifications statiques : les vrais niveaux n'ont aucune erreur ; des niveaux fautifs fabriqués sont
// détectés avec le bon code, au bon endroit.
import { readFileSync, readdirSync } from 'node:fs';
import assert from 'node:assert';
import yaml from '../../app/js/lib/js-yaml/js-yaml.mjs';
import { LevelLinter } from '../../app/js/core/LevelLinter.js';
const root = new URL('../../', import.meta.url).pathname;
const schema = JSON.parse(readFileSync(`${root}levels/schema/level.schema.json`, 'utf8'));
const linter = new LevelLinter(schema);
const ids = readdirSync(`${root}levels`).filter((name) => /^\d\d-/.test(name));
const load = (id) => yaml.load(readFileSync(`${root}levels/${id}/level.yaml`, 'utf8'));
const codes = (problems, severity) => problems.filter((p) => !severity || p.severity === severity).map((p) => p.code);
const find = (problems, code) => problems.find((p) => p.code === code);
// --- Tous les niveaux existants : aucune erreur (les avertissements et infos sont permis).
for (const id of ids) {
const problems = linter.lint(load(id), { knownLevelIds: ids.filter((other) => other !== id) });
assert.deepEqual(codes(problems, 'error'), [], `${id} : ${JSON.stringify(problems.filter((p) => p.severity === 'error'))}`);
}
const base = () => structuredClone(load('05-decide'));
const lint = (level, options = {}) => linter.lint(level, { knownLevelIds: ids, ...options });
// --- Schéma : messages ciblés (et pas le déluge d'erreurs d'enveloppe du validateur).
let level = base(); delete level.mission.goal;
assert.deepEqual(find(lint(level), 'schema_required').path, ['mission']);
assert.equal(find(lint(level), 'schema_required').params.field, 'goal');
level = base(); level.id = 'Mauvais Id';
assert.deepEqual(find(lint(level), 'schema_pattern').path, ['id']);
level = base(); level.steps[1].type = 'video';
assert.deepEqual(find(lint(level), 'schema_enum').path, ['steps', 1, 'type']);
level = base(); level.steps[1].tests[0].kind = 'nope';
assert.ok(codes(lint(level), 'error').length > 0);
level = base(); level.steps[1].bonus = true;
assert.equal(find(lint(level), 'schema_unknown_field').params.field, 'bonus');
assert.ok(lint(level).length <= 2, 'pas de cascade de messages');
level = base(); level.difficulty = 99;
assert.deepEqual(find(lint(level), 'schema_range').path, ['difficulty']);
assert.equal(lint('pas un objet').at(0).code, 'schema_type');
// --- Traductions.
level = base(); delete level.title.en;
assert.deepEqual(find(lint(level), 'missing_english').path, ['title']);
level = base(); level.steps[1].hints.en = [];
assert.deepEqual(find(lint(level), 'missing_english').path, ['steps', 1, 'hints']);
level = base(); level.mission.goal.en = ' ';
assert.ok(find(lint(level), 'missing_english'));
assert.equal(find(lint(level, { requireEnglish: false }), 'missing_english'), undefined, 'option requireEnglish');
level = base(); level.steps[3].hints.en.pop();
assert.equal(find(lint(level), 'hint_count_differs').severity, 'warning');
// --- Références.
level = base(); level.requires = ['99-inconnu'];
assert.equal(find(lint(level), 'requires_unknown').params.id, '99-inconnu');
level = base(); level.requires = [level.id];
assert.ok(find(lint(level), 'requires_self'));
assert.equal(find(lint(base()), 'id_already_exists').severity, 'warning');
assert.equal(find(linter.lint(base(), { knownLevelIds: null }), 'id_already_exists'), undefined);
// --- Règles de contribution et tests.
level = base(); delete level.steps[1].solution;
assert.deepEqual(find(lint(level), 'solution_missing').path, ['steps', 1, 'solution']);
level = base(); delete level.mission.solution;
assert.deepEqual(find(lint(level), 'solution_missing').path, ['mission', 'solution']);
level = base(); delete level.steps[1].hints;
assert.equal(find(lint(level), 'hints_missing').severity, 'warning');
level = base(); level.steps[1].tests = [{ kind: 'function_called_with', value: 'f' }];
assert.equal(find(lint(level), 'kind_unsupported').params.kind, 'function_called_with');
level = base(); level.steps[1].tests = [{ kind: 'var_equals', value: 3 }];
assert.ok(find(lint(level), 'test_name_missing'));
level = base(); level.steps[1].tests = [{ kind: 'stdout_equals' }];
assert.ok(find(lint(level), 'test_value_missing'));
level = base(); level.steps[1].tests = [{ kind: 'stdout_matches_regex', value: '([' }];
assert.ok(find(lint(level), 'regex_invalid'));
level = base(); level.steps[1].tests = [{ kind: 'var_type_is', name: 'x', value: 'entier' }];
assert.equal(find(lint(level), 'type_unusual').severity, 'warning');
assert.ok(find(lint(load('01-hello')), 'voice_to_generate'), 'rappel : narration à générer');
console.log('level linter ok');
+40 -51
View File
@@ -1,71 +1,60 @@
// 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).
// Pour chaque niveau : la solution de référence de chaque étape et de la mission passe tous les tests, et
// le code de départ ne les passe pas. Pyodide réel (vendor/pyodide requis). Utilise LevelChecker, le même
// module que l'éditeur de niveaux ; vérifie aussi qu'il détecte bien des niveaux fautifs fabriqués.
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 { LevelChecker } from '../../app/js/core/LevelChecker.js';
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`);
const load = (id) => yaml.load(readFileSync(`${root}levels/${id}/level.yaml`, 'utf8'));
const summary = (problems) => problems.map((problem) => `${problem.code}@${problem.path.join('.')}`);
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;
const checker = new LevelChecker({ client });
try {
// --- Tous les niveaux existants.
let checked = 0;
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`);
}
}
const { exercises, problems } = await checker.check(load(id));
assert.deepEqual(summary(problems), [], `${id}`);
checked += exercises.length;
}
assert.ok(checked > 0);
// --- Niveaux fautifs fabriqués : chaque défaut est détecté, au bon endroit.
const base = () => structuredClone(load('04-math'));
let level = base(); level.steps[1].solution = 'print(1 + 1)';
assert.deepEqual(summary((await checker.check(level)).problems), ['solution_fails@steps.1']);
level = base(); level.steps[1].starter = level.steps[1].solution;
assert.deepEqual(summary((await checker.check(level)).problems), [], 'départ = solution : étape « exécuter pour voir »');
level = base(); level.steps[1].starter = '# Exécute pour voir\nprice = 12\nquantity = 3\nprint(price * quantity)';
assert.deepEqual(summary((await checker.check(level)).problems), [], 'départ = solution + commentaires de ligne : idem');
level = base(); level.steps[1].starter = 'print(36)';
assert.deepEqual(summary((await checker.check(level)).problems), ['starter_passes@steps.1'], 'départ qui passe déjà sans être la solution');
level = base(); level.steps[1].solution = 'print(';
const syntax = (await checker.check(level)).problems;
assert.deepEqual(summary(syntax), ['solution_error@steps.1']);
assert.equal(syntax[0].params.type, 'SyntaxError');
level = base(); level.mission.solution = 'print("rien")';
assert.deepEqual(summary((await checker.check(level)).problems), ['solution_fails@mission']);
level = base(); level.steps[1].starter = 'print(';
assert.deepEqual(summary((await checker.check(level)).problems), ['starter_error@steps.1']);
console.log(`${checked} exercices vérifiés`);
} finally {
client.dispose();
}
assert.deepEqual(problems, []);
assert.ok(checked > 0);
console.log(`${checked} exercices vérifiés`);
});