Files
Ustagammon/tests/browser/fin-de-partie.mjs
T

578 lines
26 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.
// fin-de-partie.mjs -- la fin de partie et le bilan en page (étape 1m ;
// charte, ecrans-etape-1.md, 1e, « Révision du 2026-11-13 »), dans un vrai
// navigateur sans écran (Playwright), sur le site servi par l'image de
// production.
//
// Copyright (C) 2026 les auteurs d'Ustagammon.
// Licence : GPLv3 ou ultérieure (voir LICENSE).
//
// Usage : node fin-de-partie.mjs <adresse du site> <chromium|firefox> <dossier des captures>
// Lancé par tests/browser.sh. Vérifie :
// - l'enchaînement : le plateau final reste au moins 600 ms, puis le bilan
// arrive, sans panneau ni voile, à son adresse, avec la barre haute ;
// - les places réservées : l'en-tête tout de suite, la ligne « Le maître
// analyse la partie : … », les tuiles et les jauges vides, le cadre en
// pointillés ; aucun bloc ne bouge quand l'analyse arrive (boîtes
// comparées au pixel près, en portrait et en paysage) ;
// - la barre d'actions fixe en bas, « Voir l'analyse » inactif puis actif ;
// seule la page défile ; en 844 × 390, tout tient sans défilement ;
// - la carte du coup à revoir : un lien entier, un chevron, un seul bouton ;
// - le retour du téléphone : le plateau final, en lecture seule, avec
// « Partie terminée · Voir le bilan » ;
// - une fin de match : « Bilan du match », puis la même carte dans le bilan
// du match ;
// - textes d'au moins 12 px, pas d'erreur, pas de violation de la politique
// de sécurité.
// Captures (Chromium) dans <dossier des captures>/fin-de-partie/, en
// 412×915 et 915×412. Dans Chromium, l'analyse est ralentie (CPU bridé,
// protocole DevTools) le temps de capturer la page en cours d'analyse.
import { mkdirSync } from "node:fs";
import { chromium, firefox } from "playwright";
import { hiddenUnderActionBar, tallButtons } from "./recette.mjs";
const [base, browserName, shots] = process.argv.slice(2);
const browserType = { chromium, firefox }[browserName];
if (!base || !browserType || !shots) {
console.error("usage : node fin-de-partie.mjs <adresse> <chromium|firefox> <dossier des captures>");
process.exit(2);
}
const full = browserName === "chromium";
const dir = `${shots}/fin-de-partie`;
mkdirSync(dir, { recursive: true });
const PORTRAIT = { width: 412, height: 915 };
const LANDSCAPE = { width: 915, height: 412 };
const PHONE_LANDSCAPE = { width: 844, height: 390 };
const problems = [];
const log = (text) => console.log(`[${browserName}] ${text}`);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let captures = 0;
function check(condition, message) {
if (!condition) {
throw new Error(message);
}
}
const browser = await browserType.launch();
const context = await browser.newContext({
viewport: PORTRAIT,
deviceScaleFactor: 1,
locale: "fr-FR",
});
await context.addInitScript(() => {
let state = 11;
Math.random = () => {
state = (state * 1103515245 + 12345) % 2147483648;
return state / 2147483648;
};
// La vibration de fin de partie et l'arrivée au bilan, datées dans la
// page : le plateau final doit rester 600 ms entre les deux.
window.__endAt = null;
window.__bilanAt = null;
Object.defineProperty(Navigator.prototype, "vibrate", {
configurable: true,
value: (pattern) => {
const p = Array.isArray(pattern) ? pattern.join(",") : String(pattern);
if (p === "60" || p === "30,50,30,50,60") {
window.__endAt = performance.now();
window.__bilanAt = null;
}
return true;
},
});
window.addEventListener("hashchange", () => {
if (/\/bilan$/.test(location.hash) && window.__bilanAt === null) {
window.__bilanAt = performance.now();
}
});
window.__csp = [];
document.addEventListener("securitypolicyviolation", (e) =>
window.__csp.push(`${e.effectiveDirective} ${e.blockedURI}`),
);
});
const page = await context.newPage();
page.on("pageerror", (error) => problems.push(`erreur de la page : ${error.message}`));
page.on("console", (message) => {
if (message.type() === "error") {
problems.push(`console : ${message.text()}`);
}
});
const cdp = full ? await context.newCDPSession(page) : null;
/** Bride le processeur (Chromium) : l'analyse en arrière-plan ralentit. */
async function throttle(rate) {
if (cdp !== null) {
await cdp.send("Emulation.setCPUThrottlingRate", { rate });
}
}
/** Attend une condition dans la page (sans page.waitForFunction, qui passe
* par eval, interdit par la politique de sécurité du site). */
async function until(what, fn, arg, ms = 120_000) {
for (let waited = 0; waited < ms; waited += 100) {
if (await page.evaluate(fn, arg)) {
return;
}
await sleep(100);
}
await page.screenshot({ path: `${dir}/${browserName}-bloque.png` }).catch(() => {});
throw new Error(`attente trop longue : ${what}`);
}
const idle = () => until("écran libre", () => !document.body.classList.contains("busy"));
/** Une capture (Chromium seulement), après la règle commune : rien
* d'interactif sous une barre d'action, aucun bouton étiré. */
async function capture(name, size) {
if (!full) {
return;
}
await page.setViewportSize(size);
await sleep(300);
const hidden = await hiddenUnderActionBar(page);
check(hidden.length === 0, `${name} : caché sous la barre d'action : ${hidden.join(", ")}`);
const tall = await tallButtons(page);
check(tall.length === 0, `${name} : boutons étirés : ${tall.join(", ")}`);
await page.screenshot({ path: `${dir}/${name}-${size.width}x${size.height}.png` });
captures++;
}
/** Les textes visibles de la page, sous 12 px. */
const smallTexts = () =>
page.evaluate(() => {
const small = [];
for (const el of document.querySelectorAll("body *:not(svg *)")) {
const own = [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim());
if (!own || el.closest("[hidden]") !== null || el.getClientRects().length === 0) {
continue;
}
const size = parseFloat(getComputedStyle(el).fontSize);
if (size < 12) {
small.push(`${el.id || el.className} ${size}px`);
}
}
return small;
});
/** Les boîtes des blocs du bilan, dans le repère de la page. */
const BLOCKS = [
"#summary-title",
"#summary-detail",
"#summary-reading-slot",
"#summary-counts",
"#gauge-play",
"#gauge-dice",
"#summary-glossary",
"#summary-review",
"#summary-review .review-link",
"#summary-review .summary-review-actions",
"#summary-settings",
"#summary-bar",
];
const boxes = () =>
page.evaluate((selectors) => {
const out = {};
for (const s of selectors) {
const el = document.querySelector(s);
if (el === null) {
out[s] = null;
continue;
}
const r = el.getBoundingClientRect();
const fixed = getComputedStyle(el).position === "fixed";
const y = fixed ? 0 : scrollY;
out[s] = [r.left, r.top + y, r.width, r.height].map((v) => Math.round(v * 2) / 2);
}
// Mesurée avant l'analyse, ou après ?
out.ready = document.getElementById("summary").dataset.ready === "true";
return out;
}, BLOCKS);
function sameBoxes(before, after, where) {
check(!before.ready && after.ready, `${where} : mesures avant ou après l'analyse manquantes`);
for (const s of BLOCKS) {
check(
JSON.stringify(before[s]) === JSON.stringify(after[s]),
`${where} : « ${s} » a bougé à l'arrivée de l'analyse : ${JSON.stringify(before[s])} -> ${JSON.stringify(after[s])}`,
);
}
}
/** Joue un tour du joueur : lancer, puis le premier pion jouable et sa
* première arrivée, jusqu'au coup complet ; prendre les doubles ; passer
* quand aucun coup n'est possible. Renvoie false si la partie est finie. */
async function playTurn() {
for (let step = 0; step < 400; step++) {
const s = await page.evaluate(() => {
const shown = (id) => {
const el = document.getElementById(id);
return el !== null && !el.hidden && !el.disabled;
};
return {
over: /\/bilan$/.test(location.hash) || !document.getElementById("again").hidden,
busy: document.body.classList.contains("busy"),
panel: !document.getElementById("panel-veil").hidden,
take: shown("take"),
confirm: shown("confirm"),
skip: shown("skip"),
roll: shown("roll"),
land: document.querySelector("#board .hit.can-land") !== null,
move: document.querySelector("#board .hit.can-move") !== null,
};
});
if (s.over) {
return false;
}
if (s.busy) {
await sleep(100);
} else if (s.panel) {
await page.click("#panel-primary");
} else if (s.take) {
await page.click("#take");
} else if (s.confirm) {
await page.click("#confirm");
await idle();
return true;
} else if (s.skip) {
await page.click("#skip");
await idle();
return true;
} else if (s.land) {
await page.locator("#board .hit.can-land").first().click();
} else if (s.move) {
await page.locator("#board .hit.can-move").first().click();
} else if (s.roll) {
await page.click("#roll");
} else {
await sleep(100);
}
}
throw new Error("tour du joueur bloqué");
}
/** À votre tour, avant de lancer : abandonne, en concédant le plus grand
* genre proposé (l'ordinateur accepte). Renvoie l'heure de l'acceptation. */
async function resign() {
await until("drapeau", () => {
const flag = document.getElementById("resign");
return !flag.hidden && !flag.disabled && !document.body.classList.contains("busy");
});
await page.click("#resign");
await until("feuille d'abandon", () => !document.getElementById("resign-veil").hidden);
await page.locator("#resign-choices .resign-choice:not([disabled])").last().click();
await page.click("#resign-confirm");
await until("réponse de l'ordinateur", () => document.getElementById("resign-veil").hidden,
null, 60_000);
const accepted = await page.evaluate(() =>
document.getElementById("resign-refusal").hidden);
check(accepted, "l'ordinateur refuse l'abandon du plus grand genre proposé");
return Date.now();
}
// ------------------------------------- 1. Une partie libre, puis son bilan
await page.goto(`${base}#/nouvelle-partie`);
await until("moteur chargé", () => !document.getElementById("new-game-start").disabled);
await page.click("#new-game-free");
await page.click("#new-game-level-beginner");
// Sans le conseil du maître : toutes vos décisions restent à analyser à la
// fin, ce qui laisse voir la page avant l'analyse.
if ((await page.getAttribute("#new-game-advice", "aria-checked")) === "true") {
await page.click("#new-game-advice");
}
await page.click("#new-game-start");
await until("partie commencée", () => location.hash === "#/" && !document.body.classList.contains("busy"));
let playing = true;
for (let turn = 0; turn < 20 && playing; turn++) {
playing = await playTurn();
}
// L'analyse ralentie (Chromium), pour voir la page avant elle.
await throttle(30);
if (playing) {
await resign();
}
await until("bilan arrivé", () => /^#\/parties\/[a-z0-9-]+\/bilan$/.test(location.hash) &&
!document.getElementById("summary").hidden, null, 60_000);
const arrived = await page.evaluate(() => ({
title: document.getElementById("summary-title")?.textContent ?? "",
detail: document.getElementById("summary-detail")?.textContent ?? "",
ready: document.getElementById("summary").dataset.ready === "true",
status: document.getElementById("summary-status")?.textContent ?? null,
placeholder: document.querySelector("#summary-review .review-placeholder") !== null,
emptyTiles: document.querySelectorAll("#summary-counts .summary-count.empty").length,
analysis: document.getElementById("summary-analysis")?.getAttribute("aria-disabled"),
analysisHref: document.getElementById("summary-analysis")?.getAttribute("href"),
close: document.getElementById("summary-close") !== null,
veils: [...document.querySelectorAll(".veil")].filter((v) => !v.hidden).map((v) => v.id),
topbar: document.querySelector(".topbar").getClientRects().length > 0,
game: !document.getElementById("game").hidden,
}));
check(/^(Perdue par abandon|Vous gagnez|L'ordinateur gagne)/.test(arrived.title),
`titre du bilan : ${arrived.title}`);
check(arrived.detail !== "", "le résultat n'est pas affiché tout de suite");
check(!arrived.close && arrived.veils.length === 0 && arrived.topbar && !arrived.game,
`le bilan n'est pas une page : ${JSON.stringify(arrived)}`);
const analysingSeen = !arrived.ready;
if (analysingSeen) {
check(/^Le maître analyse la partie : \d+ coups? sur \d+\.$/.test(arrived.status ?? ""),
`ligne d'attente : ${arrived.status}`);
check(arrived.placeholder && arrived.emptyTiles === 3,
`places réservées : ${JSON.stringify(arrived)}`);
check(arrived.analysis === "true" && arrived.analysisHref === null,
"« Voir l'analyse » actif avant l'analyse");
} else {
check(!full, "Chromium : l'analyse finie avant l'arrivée du bilan, malgré le CPU bridé");
log("analyse déjà finie à l'arrivée du bilan : places réservées non vues");
}
await sleep(400);
const portraitBefore = await boxes();
let landscapeBefore = null;
const stillAnalysing = () =>
page.evaluate(() => document.getElementById("summary").dataset.ready !== "true");
if (analysingSeen) {
check(!portraitBefore.ready, "412x915 : l'analyse a fini avant la mesure des places réservées");
await capture("1-en-cours-d-analyse", PORTRAIT);
check(!full || (await stillAnalysing()), "412x915 : l'analyse a fini avant la capture");
await page.setViewportSize(LANDSCAPE);
await sleep(300);
landscapeBefore = await boxes();
await capture("1-en-cours-d-analyse", LANDSCAPE);
check(!full || (await stillAnalysing()), "915x412 : l'analyse a fini avant la capture");
await page.setViewportSize(PORTRAIT);
await sleep(300);
}
await throttle(1);
await until("bilan prêt", () => document.getElementById("summary").dataset.ready === "true",
null, 300_000);
await until("mini-plateau", () =>
document.querySelector("#summary-board .board-frame") !== null ||
document.querySelector("#summary .summary-none") !== null);
// Le fondu fini (160 ms).
await sleep(400);
if (analysingSeen) {
sameBoxes(portraitBefore, await boxes(), "412x915");
await page.setViewportSize(LANDSCAPE);
await sleep(300);
if (!landscapeBefore.ready) {
sameBoxes(landscapeBefore, await boxes(), "915x412");
}
await page.setViewportSize(PORTRAIT);
await sleep(300);
log("aucun bloc ne bouge à l'arrivée de l'analyse (portrait et paysage)");
}
const ready = await page.evaluate(() => {
const card = document.getElementById("summary-revisit");
return {
reading: document.getElementById("summary-reading")?.textContent ?? "",
analysis: document.getElementById("summary-analysis")?.getAttribute("href") ?? null,
disabled: document.getElementById("summary-analysis")?.getAttribute("aria-disabled"),
primary: document.getElementById("summary-primary")?.textContent,
settings: document.getElementById("summary-settings")?.tagName,
card: card === null ? null : {
tag: card.tagName,
href: card.getAttribute("href"),
chevron: card.querySelector(".review-chevron") !== null,
played: card.querySelector(".summary-played")?.textContent ?? "",
master: card.querySelector(".summary-master")?.textContent ?? "",
},
buttons: [...document.querySelectorAll("#summary-review .button, #summary-review button")]
.map((b) => b.textContent.trim()),
none: document.querySelector("#summary .summary-none")?.textContent ?? null,
bar: getComputedStyle(document.getElementById("summary-bar")).position,
};
});
check(ready.reading.startsWith("D'après mon analyse"), `lecture : ${ready.reading}`);
check(/^#\/parties\/[a-z0-9-]+\/analyse$/.test(ready.analysis ?? "") && ready.disabled === null,
`« Voir l'analyse » prêt : ${ready.analysis}`);
check(ready.primary === "Rejouer" && ready.settings === "A", `actions : ${JSON.stringify(ready)}`);
check(ready.bar === "fixed", `barre d'actions : ${ready.bar}`);
if (ready.card !== null) {
check(ready.card.tag === "A" && /\/analyse\/\d+$/.test(ready.card.href) && ready.card.chevron,
`carte du coup à revoir : ${JSON.stringify(ready.card)}`);
check(/^(Vous avez |Votre coup : |Votre décision : )/.test(ready.card.played) &&
ready.card.master.length > 0, `coup à revoir en mots : ${JSON.stringify(ready.card)}`);
check(ready.buttons.length === 1 && ready.buttons[0].includes("Demander à une IA"),
`boutons de la carte : ${ready.buttons}`);
log(`coup à revoir : « ${ready.card.played} » / « ${ready.card.master} »`);
} else {
check(ready.none !== null, "ni coup à revoir ni « Aucun coup à revoir »");
}
const small = await smallTexts();
check(small.length === 0, `textes sous 12 px : ${small.join(", ")}`);
await capture("2-pret", PORTRAIT);
await capture("2-pret", LANDSCAPE);
// Seule la page défile : la barre reste en bas, rien ne passe dessous.
if (full) {
await page.setViewportSize(PORTRAIT);
await page.evaluate(() => window.scrollTo(0, document.scrollingElement.scrollHeight));
await sleep(300);
const bottom = await page.evaluate(() => {
const bar = document.getElementById("summary-bar").getBoundingClientRect();
const last = document.getElementById("summary-settings").getBoundingClientRect();
return { bar: Math.round(bar.bottom), barTop: bar.top, last: last.bottom, height: innerHeight };
});
check(bottom.bar === bottom.height && bottom.last <= bottom.barTop,
`défilement jusqu'en bas : ${JSON.stringify(bottom)}`);
await page.screenshot({ path: `${dir}/3-defilement-bas-412x915.png` });
captures++;
await page.evaluate(() => window.scrollTo(0, 0));
}
// En 844 × 390, deux colonnes, sans défilement.
await page.setViewportSize(PHONE_LANDSCAPE);
await sleep(300);
const fits = await page.evaluate(() => ({
scroll: document.scrollingElement.scrollHeight,
height: innerHeight,
width: document.scrollingElement.scrollWidth,
}));
check(fits.scroll <= fits.height && fits.width <= 844, `844x390 : la page défile : ${JSON.stringify(fits)}`);
if (full) {
await page.screenshot({ path: `${dir}/2-pret-844x390.png` });
captures++;
}
await page.setViewportSize(PORTRAIT);
await sleep(200);
// ---------------------- 2. Le retour du téléphone : le plateau final
await page.goBack();
await until("plateau final", () => location.hash === "#/" && !document.getElementById("game").hidden &&
!document.getElementById("over-line").hidden);
const final = await page.evaluate(() => ({
line: document.getElementById("over-line").textContent,
href: document.getElementById("over-summary").getAttribute("href"),
movable: document.querySelectorAll("#board .hit.can-move").length,
panel: !document.getElementById("panel-veil").hidden,
}));
check(final.line === "Partie terminée · Voir le bilan" && /\/bilan$/.test(final.href) &&
final.movable === 0 && !final.panel, `plateau final : ${JSON.stringify(final)}`);
await capture("4-plateau-final", PORTRAIT);
await page.setViewportSize(LANDSCAPE);
await sleep(300);
const chip = await page.evaluate(() => ({
band: document.getElementById("band-text")?.textContent ?? "",
href: document.getElementById("over-chip")?.getAttribute("href") ?? null,
}));
check(chip.band.includes("Partie terminée") && /\/bilan$/.test(chip.href ?? ""),
`plateau final en paysage : ${JSON.stringify(chip)}`);
await capture("4-plateau-final", LANDSCAPE);
await page.setViewportSize(PORTRAIT);
await sleep(200);
// « Voir le bilan » le rouvre.
await page.click("#over-summary");
await until("bilan rouvert", () => /\/bilan$/.test(location.hash) &&
document.getElementById("summary").dataset.ready === "true");
log("retour : plateau final en lecture seule, « Partie terminée · Voir le bilan »");
// ---------------------------------------- 3. Une fin de match en 3 points
await page.goto(`${base}#/nouvelle-partie`);
await until("écran « Nouvelle partie »", () => !document.getElementById("new-game-start").disabled);
await page.click("#new-game-match");
await page.click("#new-game-length-3");
await page.click("#new-game-level-beginner");
await page.click("#new-game-start");
await until("match commencé", () => location.hash === "#/" && !document.body.classList.contains("busy"));
let games = 1;
for (;;) {
check(games <= 4, "le match ne finit pas");
for (let turn = 0; turn < 5; turn++) {
if (!(await playTurn())) {
break;
}
}
if (await page.evaluate(() => document.getElementById("again").hidden)) {
await resign();
// Le plateau final reste : pas de bilan avant 600 ms, ni panneau,
// ni voile, ni « Rejouer ».
const early = await page.evaluate(() => ({
hash: location.hash,
panel: !document.getElementById("panel-veil").hidden,
again: !document.getElementById("again").hidden,
game: !document.getElementById("game").hidden,
}));
check(early.hash === "#/" && !early.panel && !early.again && early.game,
`fin de partie, avant le bilan : ${JSON.stringify(early)}`);
await until("bilan arrivé", () => /\/bilan$/.test(location.hash), null, 30_000);
const delay = Math.round(await page.evaluate(() => window.__bilanAt - window.__endAt));
check(Number.isFinite(delay) && delay >= 600,
`le bilan arrive ${delay} ms après la vibration de fin, avant les 600 ms du plateau final`);
log(`partie ${games} : bilan arrivé ${delay} ms après la fin`);
}
await until("bilan de la partie prêt", () => /\/bilan$/.test(location.hash) &&
document.getElementById("summary").dataset.ready === "true", null, 300_000);
const primary = await page.textContent("#summary-primary");
if (primary === "Bilan du match") {
break;
}
check(primary === "Partie suivante", `fin de partie dans un match : « ${primary} »`);
await page.click("#summary-primary");
await until("partie suivante", () => location.hash === "#/" &&
!document.body.classList.contains("busy") && document.getElementById("again").hidden);
games++;
}
await sleep(400);
const matchEnd = await page.evaluate(() => ({
line: document.getElementById("summary-match")?.textContent ?? "",
detail: document.getElementById("summary-detail")?.textContent ?? "",
}));
check(matchEnd.line.includes("Bilan du match") && /Score final|vous \d+, l'ordinateur \d+/.test(matchEnd.detail),
`fin de match : ${JSON.stringify(matchEnd)}`);
await capture("5-fin-de-match", PORTRAIT);
await capture("5-fin-de-match", LANDSCAPE);
await page.setViewportSize(PORTRAIT);
log(`match fini en ${games} partie(s) : ${matchEnd.detail}`);
// La carte « décision à revoir » du bilan du match : la même.
await page.click("#summary-primary");
await until("bilan du match", () => /^#\/matchs\/[a-z0-9-]+\/bilan$/.test(location.hash) &&
document.getElementById("match-summary").dataset.ready === "true", null, 300_000);
const matchCard = await page.evaluate(() => {
const card = document.getElementById("match-revisit");
return card === null
? { none: document.querySelector("#match-to-review .summary-none")?.textContent ?? null }
: {
tag: card.tagName,
chevron: card.querySelector(".review-chevron") !== null,
played: card.querySelector(".summary-played")?.textContent ?? "",
buttons: [...document.querySelectorAll("#match-to-review .button, #match-to-review button")]
.map((b) => b.textContent.trim()),
};
});
if (matchCard.none === undefined) {
check(matchCard.tag === "A" && matchCard.chevron && matchCard.buttons.length === 1,
`carte du bilan du match : ${JSON.stringify(matchCard)}`);
} else {
check(matchCard.none !== null, "bilan du match : ni décision à revoir, ni phrase");
}
if (full) {
// La courbe se complète en arrière-plan (la page se redessine) : on
// attend qu'elle soit complète pour capturer la carte.
await until("courbe du match complète", () =>
!document.getElementById("match-summary").textContent.includes("se complète"), null, 300_000);
for (const size of [PORTRAIT, LANDSCAPE]) {
await page.setViewportSize(size);
await sleep(400);
await page.evaluate(() => document.getElementById("match-to-review")?.scrollIntoView({ block: "center" }));
await sleep(300);
await page.screenshot({ path: `${dir}/6-bilan-du-match-carte-${size.width}x${size.height}.png` });
captures++;
}
}
log(`bilan du match : ${JSON.stringify(matchCard)}`);
const csp = await page.evaluate(() => window.__csp);
for (const violation of csp) {
problems.push(`politique de sécurité : ${violation}`);
}
await browser.close();
if (problems.length > 0) {
for (const problem of problems) {
console.error(`[${browserName}] ${problem}`);
}
process.exit(1);
}
log(`fin de partie : ${captures} captures`);