Add drawing canvas (canvas module, DrawingView, drawing_* tests) and levels 13-14 (classes, saved patterns)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 17:40:53 +02:00
parent 4689d25700
commit d3b7c611f1
46 changed files with 1250 additions and 22 deletions
+58
View File
@@ -251,6 +251,64 @@ test('niveau 07 : boucle while avec plusieurs saisies successives dans l\'interf
assert.deepEqual(errors, []);
});
test('niveau 13 : le dessin s\'affiche, se décrit en texte et repart d\'une feuille vierge à chaque exécution', { 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}#/levels/13-classes`);
await page.waitForSelector('.explain', { timeout: 60000 });
const next = () => page.locator('.notebook-action button').last().click();
const run = async (code) => {
const cell = page.locator('.cell').last();
await cell.locator('textarea').fill(code);
await cell.locator('.cell-run').click();
await page.waitForFunction(() => document.querySelector('.cell:last-of-type')?.getAttribute('aria-busy') !== 'true');
await page.waitForTimeout(150);
return cell;
};
await next();
await run('class Dog:\n def __init__(self, name):\n self.name = name\n\n def bark(self):\n print(self.name, "aboie !")\n\nrex = Dog("Rex")\nrex.bark()');
await next();
await next();
await run('class Counter:\n def __init__(self):\n self.count = 0\n\n def add(self):\n self.count += 1\n\nc = Counter()\nc.add()\nc.add()\nc.add()\nprint(c.count)');
await next();
await next();
// Étape du dessin : un seul trait d'abord (échec explicite), puis la bonne réponse.
let cell = await run('import canvas\ncanvas.line(0, 0, 100, 0, "red")');
assert.match(await cell.locator('.cell-feedback').textContent(), /Il manque le trait bleu/);
assert.equal(await cell.locator('.cell-drawing canvas').getAttribute('aria-label'), 'Dessin de 1 trait(s). Couleurs : rouge.');
cell = await run('import canvas\ncanvas.line(0, 0, 100, 0, "red")\ncanvas.line(0, 0, 0, 100, "blue")');
assert.match(await cell.locator('.cell-feedback').textContent(), /correct/);
const canvas = cell.locator('.cell-drawing canvas');
assert.equal(await canvas.getAttribute('aria-label'), 'Dessin de 2 trait(s). Couleurs : rouge, bleu.');
assert.match(await cell.locator('.drawing-summary').textContent(), /2 trait/);
// Relancer la même cellule ne superpose pas les dessins.
await cell.locator('.cell-run').click();
await page.waitForTimeout(500);
assert.match(await cell.locator('.drawing-summary').textContent(), /2 trait/);
// Pixels réels : rouge à droite de l'origine (200 + 50, 200), bleu au-dessus (200, 200 - 50), blanc ailleurs.
const pixel = (x, y) => canvas.evaluate((node, [px, py]) => Array.from(node.getContext('2d').getImageData(px, py, 1, 1).data), [x, y]);
const [r1, g1, b1] = await pixel(250, 200);
assert.ok(r1 > 150 && g1 < 80 && b1 < 80, `rouge attendu, obtenu ${[r1, g1, b1]}`);
const [r2, g2, b2] = await pixel(200, 150);
assert.ok(b2 > 150 && r2 < 60, `bleu attendu, obtenu ${[r2, g2, b2]}`);
assert.deepEqual(await pixel(320, 320), [255, 255, 255, 255]);
// La liste textuelle des traits est disponible.
await cell.locator('.cell-drawing summary').click();
assert.match(await cell.locator('.drawing-list').textContent(), /De \(0, 0\) à \(100, 0\), rouge/);
// Une erreur de couleur est expliquée, sans casser l'application.
cell = await run('import canvas\ncanvas.line(0, 0, 10, 10, "rose")');
assert.match(await cell.locator('.cell-feedback').textContent(), /couleur inconnue/);
assert.deepEqual(errors, []);
});
test('navigation : lien direct vers un niveau, tiroirs accessibles, précédent/suivant', { skip, timeout: 120000 }, async () => {
const page = await (await browser.newContext()).newPage();
const errors = [];
+18
View File
@@ -0,0 +1,18 @@
import { test } from 'node:test';
import assert from 'node:assert';
import { describeDrawing, describeSegment } from '../../app/js/ui/DrawingView.js';
import { I18n } from '../../app/js/i18n/i18n.js';
import { readFileSync } from 'node:fs';
const load = (lang) => JSON.parse(readFileSync(new URL(`../../app/js/i18n/${lang}.json`, import.meta.url)));
const i18n = new I18n({ fr: load('fr'), en: load('en') }, 'fr');
const t = (key, params) => i18n.t(key, params);
test('description textuelle du dessin', () => {
assert.equal(describeDrawing([], t), 'Feuille vide : aucun trait tracé.');
const drawing = [[0, 0, 100, 0, 'red'], [100, 0, 100, 100, 'red'], [0, 0, 0, 50, 'blue']];
assert.equal(describeDrawing(drawing, t), 'Dessin de 3 trait(s). Couleurs : rouge, bleu.');
assert.equal(describeSegment([0, 0, 70.71, 70.7099, 'blue'], t), 'De (0, 0) à (70.71, 70.71), bleu');
i18n.setLang('en');
assert.equal(describeDrawing(drawing, t), 'Drawing of 3 line(s). Colours: red, blue.');
});
+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', '04-math', '05-decide', '06-lists', '07-while', '08-functions', '09-dicts', '10-files', '11-libraries', '12-errors']);
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', '08-functions', '09-dicts', '10-files', '11-libraries', '12-errors', '13-classes', '14-project']);
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');
+14
View File
@@ -15,4 +15,18 @@ assert.deepEqual(bad.results.map((r) => r.reason), [null, 'type_mismatch', 'stdo
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');
// Tests sur le dessin (canvas.line)
const square = [[0, 0, 100, 0, 'red'], [100, 0, 100, 100, 'red'], [100, 100, 0, 100, 'red'], [0, 100, 0, 0, 'blue']];
const draw = (tests, drawing) => v.validate(tests, { stdout: '', result: { ok: true, error: null, variables: {}, drawing } }).results.map((r) => r.reason);
assert.deepEqual(draw([{ kind: 'drawing_segments', value: '4' }, { kind: 'drawing_segments', value: '3+' }], square), [null, null]);
assert.deepEqual(draw([{ kind: 'drawing_segments', value: '5' }], square), ['drawing_too_few']);
assert.deepEqual(draw([{ kind: 'drawing_segments', value: '2' }], square), ['drawing_too_many']);
assert.deepEqual(draw([{ kind: 'drawing_segments', value: '5+' }], square), ['drawing_too_few']);
assert.deepEqual(draw([{ kind: 'drawing_segments', value: 'quatre' }], square), ['invalid_test']);
assert.deepEqual(draw([{ kind: 'drawing_has_line', value: '0,0 100,0' }, { kind: 'drawing_has_line', value: '100,0 0,0 red' }, { kind: 'drawing_has_line', value: '0.2,0 99.8,0.3' }], square), [null, null, null], 'sens libre, tolérance 0,5');
assert.deepEqual(draw([{ kind: 'drawing_has_line', value: '0,0 100,0 blue' }, { kind: 'drawing_has_line', value: '0,0 100,100' }, { kind: 'drawing_has_line', value: '0,0 100,0 pink' }], square), ['drawing_line_missing', 'drawing_line_missing', 'invalid_test']);
assert.deepEqual(draw([{ kind: 'drawing_colors', value: 'red, blue' }, { kind: 'drawing_colors', value: 'green' }, { kind: 'drawing_colors', value: '' }], square), [null, 'drawing_color_missing', 'invalid_test']);
assert.deepEqual(draw([{ kind: 'drawing_segments', value: '1' }], undefined), ['drawing_missing']);
assert.deepEqual(draw([{ kind: 'drawing_segments', value: '1' }], []), ['drawing_too_few']);
console.log('validation ok');
Binary file not shown.
+33
View File
@@ -64,5 +64,38 @@ class RunnerTest(unittest.TestCase):
self.assertIsNone(run("x = float('inf')", ["x"])["variables"]["x"]["value"])
class CanvasTest(unittest.TestCase):
def setUp(self) -> None:
runner.reset_namespace()
def test_segments_are_returned_and_rounded(self) -> None:
result = run("import canvas\ncanvas.line(0, 0, 100.123456, 0, 'red')\ncanvas.line(0, 0, 0, 50)")
self.assertTrue(result["ok"])
self.assertEqual(result["drawing"], [[0.0, 0.0, 100.12, 0.0, "red"], [0.0, 0.0, 0.0, 50.0, "black"]])
def test_each_run_starts_from_a_blank_sheet(self) -> None:
run("import canvas\ncanvas.line(0, 0, 1, 1)")
self.assertEqual(len(run("import canvas\ncanvas.line(0, 0, 2, 2)")["drawing"]), 1)
def test_clear_empties_the_drawing(self) -> None:
self.assertEqual(run("import canvas\ncanvas.line(0, 0, 1, 1)\ncanvas.clear()")["drawing"], [])
def test_invalid_arguments_raise_clear_errors(self) -> None:
self.assertEqual(run("import canvas\ncanvas.line('a', 0, 1, 1)")["error"]["type"], "TypeError")
self.assertEqual(run("import canvas\ncanvas.line(0, 0, 1, 1, 'pink')")["error"]["type"], "ValueError")
self.assertEqual(run("import canvas, math\ncanvas.line(0, 0, math.inf, 1)")["error"]["type"], "ValueError")
self.assertEqual(run("import canvas\ncanvas.line(True, 0, 1, 1)")["error"]["type"], "TypeError")
def test_segment_limit(self) -> None:
result = run("import canvas\nfor i in range(6000):\n canvas.line(0, 0, i, 0)")
self.assertEqual(result["error"]["type"], "RuntimeError")
self.assertEqual(len(result["drawing"]), runner.CANVAS_MAX_SEGMENTS)
def test_isolated_replay_does_not_touch_learner_state(self) -> None:
run("import canvas\nx = 1\ncanvas.line(0, 0, 1, 1)")
replay = json.loads(runner.run_cell("import canvas\ncanvas.line(5, 5, 6, 6)", "[]", True))
self.assertEqual(replay["drawing"], [[5.0, 5.0, 6.0, 6.0, "black"]])
if __name__ == "__main__":
unittest.main()