escape_game/tests/smoke.cjs

201 lines
9.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
/**
* Smoke test navigateur : rejoue la solution de référence (walkthrough.json)
* avec de VRAIS clics dans le jeu 3D construit (dist/index.html), en mode test
* (?test=1 : transitions instantanées, basse qualité).
*
* Il vérifie ce que les tests de logique ne voient pas : objets 3D introuvables,
* zones masquées ou impossibles à cliquer, erreurs console, écran de victoire.
*
* npm run smoke tous les chapitres
* npm run smoke -- --chapter chapitre1 --shots --hard
*
* Options : --chapter <dossier> --shots (captures dans tests/shots/)
* --hard (mode Difficile) --headed (fenêtre visible) --timeout <ms>
*
* Prérequis : Playwright (npm i -D playwright && npx playwright install chromium),
* ou un Playwright installé globalement.
*/
const fs = require('node:fs');
const path = require('node:path');
const { execSync } = require('node:child_process');
function loadPlaywright() {
try {
return require('playwright');
} catch {
try {
const globalRoot = execSync('npm root -g', { encoding: 'utf8' }).trim();
return require(path.join(globalRoot, 'playwright'));
} catch {
console.error('Playwright introuvable. Installez-le : npm i -D playwright && npx playwright install chromium');
process.exit(2);
}
}
}
const args = process.argv.slice(2);
const opt = (name) => args.includes(`--${name}`);
const val = (name, def) => {
const i = args.indexOf(`--${name}`);
return i >= 0 ? args[i + 1] : def;
};
const ROOT = path.resolve(__dirname, '..');
const DIST = path.join(ROOT, 'dist', 'index.html');
const SHOTS = path.join(ROOT, 'tests', 'shots');
const TIMEOUT = Number(val('timeout', 20000));
const difficulty = opt('hard') ? 'hard' : 'easy';
if (!fs.existsSync(DIST)) {
console.error('dist/index.html absent : lancez d’abord « npm run build ».');
process.exit(2);
}
const chapters = fs
.readdirSync(path.join(ROOT, 'src', 'scenarios'))
.filter((d) => fs.existsSync(path.join(ROOT, 'src', 'scenarios', d, 'walkthrough.json')))
.filter((d) => !val('chapter') || d === val('chapter'));
/** Évalue une attente du walkthrough sur l'état de partie (même syntaxe que les conditions). */
function check(state, c) {
if (c === 'won') return state.won;
if (c.startsWith('scene:')) return state.scene === c.slice(6);
const neg = c.startsWith('!');
const raw = neg ? c.slice(1) : c;
const [kind, rest] = [raw.slice(0, raw.indexOf(':')), raw.slice(raw.indexOf(':') + 1)];
let ok;
if (kind === 'flag') ok = !!state.flags[rest];
else if (kind === 'item') ok = state.inventory.includes(rest);
else if (kind === 'selected') ok = state.selected === rest;
else if (kind === 'solved') ok = !!state.solved[rest];
else if (kind === 'var') {
const m = /^([\w-]+)(=|!=|>=|<=|>|<)(-?[\d.]+)$/.exec(rest);
const v = state.vars[m[1]] ?? 0;
const n = Number(m[3]);
ok = { '=': v === n, '!=': v !== n, '>=': v >= n, '<=': v <= n, '>': v > n, '<': v < n }[m[2]];
}
return neg ? !ok : ok;
}
(async () => {
const { chromium } = loadPlaywright();
const browser = await chromium.launch({
headless: !opt('headed'),
// Permet le rendu WebGL logiciel sur les machines sans GPU (serveurs, CI).
args: ['--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'],
});
let failed = false;
for (const chapter of chapters) {
const wt = JSON.parse(fs.readFileSync(path.join(ROOT, 'src', 'scenarios', chapter, 'walkthrough.json'), 'utf8'));
const page = await browser.newPage({ viewport: { width: 960, height: 600 } });
page.setDefaultTimeout(TIMEOUT);
const problems = [];
// Les messages de performance du pilote GL (rendu logiciel, captures) ne sont pas des bugs du jeu.
const ignored = /GL Driver Message|GPU stall/;
page.on('console', (m) => ['error', 'warning'].includes(m.type()) && !ignored.test(m.text()) && problems.push(`console ${m.type()} : ${m.text()}`));
page.on('pageerror', (e) => problems.push(`erreur JS : ${e.message}`));
const t0 = Date.now();
console.log(`\n▶ ${chapter} (${wt.steps.length} étapes, mode ${difficulty})`);
const state = () => page.evaluate(() => window.__escape.engine.state);
const idle = async () => {
await page.waitForFunction(() => window.__escape && !window.__escape.renderer.busy, null, { polling: 100 });
await page.waitForTimeout(80);
};
const shot = async (name) => {
if (!opt('shots')) return;
fs.mkdirSync(SHOTS, { recursive: true });
await page.screenshot({ path: path.join(SHOTS, `${chapter}-${name}.png`) });
};
const clickZone = async (id) => {
if (id.startsWith('__')) return page.click(`[data-id="${id}"]`);
const pt = await page.evaluate((h) => window.__escape.renderer.clickablePointFor(h), id);
if (!pt) {
// Zone écran (rect) éventuelle
const rect = await page.$(`.hotspot[data-id="${id}"]`);
if (rect) return rect.click();
const s = await state();
throw new Error(`zone "${id}" introuvable ou impossible à cliquer dans la scène "${s.scene}" (objet masqué, hors champ ou zone inactive)`);
}
await page.mouse.move(pt.x, pt.y);
await page.mouse.click(pt.x, pt.y);
};
const slot = (item) => page.click(`.slot[data-item="${item}"]`);
try {
await page.goto(`file://${DIST}?test=1`);
await page.click(`.chapter[data-chapter="${chapter}"] button[data-difficulty="${difficulty}"]`);
await idle();
await shot('00-depart');
const statsStart = await page.evaluate(() => window.__escape.renderer.renderStats());
for (const [i, step] of wt.steps.entries()) {
const label = `étape ${String(i + 1).padStart(2)} ${JSON.stringify(step)}`;
try {
const sceneBefore = (await state()).scene;
if ('click' in step) {
for (let k = 0; k < (step.times ?? 1); k++) {
await clickZone(step.click);
await idle();
}
} else if ('use' in step) {
await slot(step.use);
await clickZone(step.on);
} else if ('combine' in step) {
await slot(step.combine[0]);
await slot(step.combine[1]);
} else if ('note' in step) {
await page.click('.message .clue-btn');
await page.waitForFunction((id) => window.__escape.engine.state.notebook.includes(id), step.note);
} else if ('solve' in step) {
const def = await page.evaluate((id) => window.__escape.engine.scenario.puzzles.find((p) => p.id === id), step.solve);
if (def.type === 'colorCode') {
const ids = def.params.colors.map((c) => c.id);
for (const [slotIdx, colorId] of def.params.solution.entries())
for (let k = 0; k <= ids.indexOf(colorId); k++) await page.click(`.cc-button[data-slot="${slotIdx}"]`);
await page.click('.cc-validate');
} else if (def.type === 'caesar') {
for (let k = 0; k < def.params.shift; k++) await page.click('.cz-next');
} else {
throw new Error(`type de mini-jeu "${def.type}" non géré par tests/smoke.cjs`);
}
await page.waitForFunction((id) => window.__escape.engine.state.solved[id], step.solve);
await page.waitForSelector('.puzzle-overlay', { state: 'detached' });
}
await idle();
const s = await state();
for (const c of step.expect ?? []) if (!check(s, c)) throw new Error(`attendu "${c}" non vérifié (scène ${s.scene}, inventaire [${s.inventory.join(', ')}])`);
if (s.scene !== sceneBefore) await shot(`${String(i + 1).padStart(2, '0')}-${s.scene}`);
console.log(` ✓ ${label}`);
} catch (e) {
throw new Error(`${label}\n → ${e.message.split('\n')[0]}`);
}
}
await page.waitForSelector('.screen.win', { timeout: 5000 });
// Performance : tout doit avoir été préparé au chargement. Une compilation de shader
// en cours de partie provoque un à-coup visible (ex. première rotation vers un mur).
const statsEnd = await page.evaluate(() => window.__escape.renderer.renderStats());
console.log(` GPU : ${statsStart.programs} shaders et ${statsStart.textures} textures au départ, ${statsEnd.programs} et ${statsEnd.textures} à la fin`);
if (statsEnd.programs > statsStart.programs)
problems.push(`${statsEnd.programs - statsStart.programs} shader(s) compilé(s) en cours de partie : à-coup probable, à précharger dans ThreeRenderer.warmUp()`);
if (statsEnd.textures > statsStart.textures) problems.push(`${statsEnd.textures - statsStart.textures} texture(s) envoyée(s) au GPU en cours de partie`);
await shot('99-victoire');
if (problems.length) throw new Error(`problèmes détectés pendant la partie :\n ${problems.join('\n ')}`);
console.log(`✔ ${chapter} : victoire en ${((Date.now() - t0) / 1000).toFixed(1)} s`);
} catch (e) {
failed = true;
fs.mkdirSync(SHOTS, { recursive: true });
const file = path.join(SHOTS, `${chapter}-ECHEC.png`);
await page.screenshot({ path: file }).catch(() => undefined);
console.error(`✘ ${chapter} : ${e.message}`);
if (problems.length && !e.message.startsWith('problèmes détectés')) console.error(` ${problems.join('\n ')}`);
console.error(` capture : ${path.relative(ROOT, file)}`);
}
await page.close();
}
await browser.close();
process.exit(failed ? 1 : 0);
})();