Tests navigateur : bilan en page, et fin-de-partie.mjs (1m)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pierre MARTIN
2026-11-23 16:55:03 +01:00
co-authored by Claude Opus 5.5
parent 2a8d14d02b
commit d74e70f02b
11 changed files with 672 additions and 77 deletions
+15 -3
View File
@@ -36,9 +36,14 @@
# continue, bilan, analyse, « Mes parties », export SGF, prompt), captures
# dans build/browser-shots/match-bilan/.
#
# La fin de partie et le bilan en page (tests/browser/fin-de-partie.mjs,
# étape 1m : plateau final 600 ms, places réservées qui ne bougent pas à
# l'arrivée de l'analyse, barre d'actions fixe, retour au plateau final, fin
# de match), captures dans build/browser-shots/fin-de-partie/.
#
# BROWSERS=chromium et SCRIPTS=accueil (ou play, match, maitre, bilan,
# prompts, nouvelle-partie, retours-joueurs, lecons, progression, plateau,
# match-bilan, retours-2)
# match-bilan, retours-2, fin-de-partie)
# restreignent le test.
#
# Outils : l'image de Playwright (navigateurs) et le paquet playwright,
@@ -52,7 +57,7 @@ cd "$(dirname "$0")/.."
image="${PLAYWRIGHT_IMAGE:?lancer via make test-browser}"
browsers="${BROWSERS:-chromium firefox}"
# Les scripts à lancer (tests/browser/<nom>.mjs), tous par défaut.
scripts="${SCRIPTS:-play accueil match maitre bilan prompts nouvelle-partie retours-joueurs lecons progression plateau match-bilan retours-2}"
scripts="${SCRIPTS:-play accueil match maitre bilan prompts nouvelle-partie retours-joueurs lecons progression plateau match-bilan retours-2 fin-de-partie}"
unset MAKEFLAGS MFLAGS MAKELEVEL
make -s package >/dev/null
@@ -92,7 +97,7 @@ mkdir -p build/browser-shots
cp tests/browser/play.mjs tests/browser/accueil.mjs tests/browser/match.mjs tests/browser/recette.mjs \
tests/browser/maitre.mjs tests/browser/bilan.mjs tests/browser/prompts.mjs tests/browser/nouvelle-partie.mjs \
tests/browser/retours-joueurs.mjs tests/browser/lecons.mjs tests/browser/progression.mjs tests/browser/plateau.mjs \
tests/browser/retours-2.mjs tests/browser/match-bilan.mjs "$tools/"
tests/browser/retours-2.mjs tests/browser/match-bilan.mjs tests/browser/fin-de-partie.mjs "$tools/"
status=0
for browser in $browsers; do
# Réseau de l'hôte : le site est sur 127.0.0.1. Le service worker
@@ -190,5 +195,12 @@ for browser in $browsers; do
-v "$PWD/$tools:/tools" -v "$PWD/build/browser-shots:/shots" -w /tools "$image" \
node match-bilan.mjs "http://localhost:$port/" "$browser" /shots || status=1
fi
if [[ " $scripts " == *" fin-de-partie "* ]]; then
# La fin de partie et le bilan en page (étape 1m) ; captures dans
# build/browser-shots/fin-de-partie/.
docker run --rm --init --ipc=host --network host --user "$(id -u):$(id -g)" -e HOME=/tmp \
-v "$PWD/$tools:/tools" -v "$PWD/build/browser-shots:/shots" -w /tools "$image" \
node fin-de-partie.mjs "http://localhost:$port/" "$browser" /shots || status=1
fi
done
exit "$status"
+12 -7
View File
@@ -197,7 +197,7 @@ await page.click("#explain-done");
await until("feuille fermée", () => document.getElementById("explain-veil").hidden);
// Le joueur passe.
await page.click("#drop");
// Le panneau de fin de partie, puis le bilan à sa place, à son adresse.
// Le bilan, une page, à son adresse (étape 1m).
await until(
"bilan prêt",
() =>
@@ -211,6 +211,7 @@ const summary = await page.evaluate(() => ({
hash: location.hash,
panelHidden: document.getElementById("panel-veil").hidden,
title: document.getElementById("summary-title").textContent,
detail: document.getElementById("summary-detail").textContent,
reading: document.getElementById("summary-reading").textContent,
counts: [...document.querySelectorAll(".summary-count .summary-number")].map(
(n) => n.textContent,
@@ -227,10 +228,10 @@ const id = summary.hash.split("/")[2];
check(summary.panelHidden, "le panneau de fin de partie reste sous le bilan");
check(summary.title === "L'ordinateur gagne la partie simple", `titre : ${summary.title}`);
check(
summary.reading.startsWith("Vous avez passé son double : 1 point pour lui. "),
`lecture : ${summary.reading}`,
summary.detail === "Vous avez passé son double : 1 point pour lui.",
`résultat : ${summary.detail}`,
);
check(summary.reading.includes("D'après mon analyse"), `lecture : ${summary.reading}`);
check(summary.reading.startsWith("D'après mon analyse"), `lecture : ${summary.reading}`);
check(!summary.reading.includes("!"), `lecture : ${summary.reading}`);
// Le refus du double, juste ; le coup 6/5/off, grosse erreur ; le jet
// sans doubler, compté seulement s'il était une faute.
@@ -239,8 +240,12 @@ check(
`décisions : ${summary.counts.join()}`,
);
check(summary.verdict.startsWith("Grosse erreur"), `coup à revoir : ${summary.verdict}`);
check(summary.played === "Votre coup : 6/off", `coup joué : ${summary.played}`);
check(summary.master === "J'aurais joué 6/off 1/off", `coup du maître : ${summary.master}`);
// Le coup à revoir en mots, puis la notation du maître (étape 1m).
check(summary.played === "Vous avez sorti un pion de la flèche 6.", `coup joué : ${summary.played}`);
check(
summary.master === "J'aurais sorti un pion de la flèche 6 et un pion de la flèche 1 (6/off 1/off).",
`coup du maître : ${summary.master}`,
);
check(summary.board, "pas de mini-plateau dans le coup à revoir");
check(summary.play !== "" && summary.dice !== "", "jauges vides");
check(summary.slot, "pas d'emplacement pour « Demander à une IA »");
@@ -422,7 +427,7 @@ if (full) {
if (document.body.classList.contains("busy")) {
return null;
}
if (!document.getElementById("summary-veil").hidden) {
if (!document.getElementById("summary").hidden) {
return "over";
}
if (!document.getElementById("panel-veil").hidden) {
+577
View File
@@ -0,0 +1,577 @@
// 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`);
+3 -3
View File
@@ -156,7 +156,7 @@ async function todo() {
if (!panel.hidden) {
return panel.dataset.kind;
}
if (!document.getElementById("summary-veil").hidden) {
if (!document.getElementById("summary").hidden) {
return "over";
}
const usable = (id) => {
@@ -204,7 +204,7 @@ for (;;) {
document.getElementById("summary")?.dataset.ready === "true", null, 300_000);
const primary = await page.textContent("#summary-primary");
const now = await page.evaluate(() => {
const detail = document.getElementById("summary-reading").textContent;
const detail = document.getElementById("summary-detail").textContent;
const m = /vous (\d+), l'ordinateur (\d+)/.exec(detail);
return m === null ? null : { player: Number(m[1]), computer: Number(m[2]) };
});
@@ -227,7 +227,7 @@ for (;;) {
await page.click("#summary-primary");
games++;
await until("partie suivante", () => !document.body.classList.contains("busy") &&
document.getElementById("summary-veil").hidden);
document.getElementById("summary").hidden);
continue;
}
if (what === "doubled" || what === "take") {
+20 -20
View File
@@ -117,8 +117,8 @@ async function todo() {
if (!panel.hidden) {
return panel.dataset.kind;
}
// Le bilan remplace le panneau de fin de partie (étape 1e).
if (!document.getElementById("summary-veil").hidden) {
// Le bilan, une page, arrive à la fin de la partie (étape 1m).
if (!document.getElementById("summary").hidden) {
return "over";
}
const usable = (id) => {
@@ -331,13 +331,12 @@ for (;;) {
`partie Crawford : videau estompé, pas de « Doubler » ${JSON.stringify(now)}`);
}
if (what === "over") {
// Le bilan, une fois l'analyse prête, à la place du panneau.
// Le bilan, une page, une fois l'analyse prête.
await until("bilan prêt", () =>
!document.getElementById("summary-veil").hidden &&
!document.getElementById("summary").hidden &&
document.getElementById("summary")?.dataset.ready === "true", null, 120_000);
const title = await page.textContent("#summary-title");
const reading = await page.textContent("#summary-reading");
const detail = reading.split(" D'après mon analyse")[0];
const detail = await page.textContent("#summary-detail");
const primary = await page.textContent("#summary-primary");
log(`partie ${games}${crawford ? " (Crawford)" : ""} : ${title} ; ${detail}`);
const settingsLink = await page.evaluate(() => {
@@ -353,6 +352,21 @@ for (;;) {
`fin du match : ${title} ; ${detail}`);
const [, player, computer] = /vous (\d+), l'ordinateur (\d+)/.exec(detail) ?? [];
check(Math.max(Number(player), Number(computer)) >= 3, `score final : ${detail}`);
// Après le match, « Changer les réglages » mène à l'écran des
// choix ; le fermer ramène au résultat, où « Rejouer » relance
// tout de suite un match de même longueur.
await page.click("#summary-settings");
await until("écran « Nouvelle partie » après le match", () =>
location.hash === "#/nouvelle-partie" && document.getElementById("panel-veil").hidden);
await page.click("#new-game-close");
// Retour au bilan ; le retour du téléphone ramène au plateau
// final, en lecture seule (étape 1m).
await until("retour au bilan du match", () =>
/\/bilan$/.test(location.hash) &&
document.getElementById("summary")?.dataset.ready === "true");
await page.goBack();
await until("retour au résultat du match", () => location.hash === "#/" &&
!document.getElementById("again").hidden);
// Paysage : le score dans la colonne de commandes.
await page.setViewportSize(LANDSCAPE);
await sleep(200);
@@ -362,20 +376,6 @@ for (;;) {
`score en paysage : « ${box} »`);
await page.setViewportSize(PORTRAIT);
await sleep(200);
// Après le match, « Changer les réglages » mène à l'écran des
// choix ; le fermer ramène au résultat, où « Rejouer » relance
// tout de suite un match de même longueur.
await page.click("#summary-settings");
await until("écran « Nouvelle partie » après le match", () =>
location.hash === "#/nouvelle-partie" && document.getElementById("panel-veil").hidden);
await page.click("#new-game-close");
// Retour au bilan ; le fermer laisse le résultat sur le plateau.
await until("retour au bilan du match", () =>
/\/bilan$/.test(location.hash) &&
document.getElementById("summary")?.dataset.ready === "true");
await page.click("#summary-close");
await until("retour au résultat du match", () => location.hash === "#/" &&
!document.getElementById("again").hidden);
check((await page.textContent("#again > span")) === "Rejouer",
`après le match, barre d'actions : « ${await page.textContent("#again > span")} »`);
log(`match ${matches} fini : ${games} parties, ${crawfordGames} Crawford au total`);
+1 -1
View File
@@ -198,7 +198,7 @@ async function checkNewGame(entry, oldId, choice) {
for (let waited = 0; waited < 2000; waited += 100) {
const s = await page.evaluate(() => ({
hash: location.hash,
summary: !document.getElementById("summary-veil").hidden,
summary: !document.getElementById("summary").hidden,
panel: !document.getElementById("panel-veil").hidden,
board: !document.getElementById("game").hidden,
newGame: !document.getElementById("new-game").hidden,
+25 -27
View File
@@ -269,8 +269,8 @@ async function waitForPlayer() {
if (!panel.hidden) {
return panel.dataset.kind;
}
// Le bilan remplace le panneau de fin de partie (étape 1e).
if (!document.getElementById("summary-veil").hidden) {
// Le bilan, une page, arrive à la fin de la partie (étape 1m).
if (!document.getElementById("summary").hidden) {
return "over";
}
const usable = (id) => {
@@ -1619,8 +1619,8 @@ for (let actions = 0; ; actions++) {
// --------------------------------------------------------- Fin de partie
// Le panneau de fin de partie, puis le bilan à sa place une fois
// l'analyse prête (étape 1e, testé en détail par bilan.mjs).
// Le bilan arrive en page à la fin de la partie, puis se remplit avec
// l'analyse (étape 1m, testé en détail par bilan.mjs et fin-de-partie.mjs).
await page.waitForSelector('#summary[data-ready="true"]', { timeout: 120_000 });
// Le bilan posé : son mini-plateau dessiné (ou « Aucun coup à revoir »).
await page.waitForSelector("#summary-board .board-frame, #summary .summary-none", { state: "attached" });
@@ -1628,17 +1628,16 @@ const journal = await savedJournal();
/** Le titre du bilan et la phrase du résultat. */
async function summaryResult() {
const title = await page.textContent("#summary-title");
const reading = await page.textContent("#summary-reading");
const detail = /^(Vous avez passé son double : |L'ordinateur a passé votre double : )?\d+ points? pour (vous|lui)(, videau à \d+)?\./.exec(reading)?.[0] ?? reading;
const detail = await page.textContent("#summary-detail");
return `${title}, ${detail}`;
}
const result = await summaryResult();
check((await page.textContent("#summary .overline")) === "Fin de partie" &&
/^(Vous gagnez|L'ordinateur gagne)/.test(await page.textContent("#summary-title")) &&
/^(Vous avez passé son double : |L'ordinateur a passé votre double : )?\d+ points? pour (vous|lui)(, videau à \d+)?\. /.test(
await page.textContent("#summary-reading")),
/^(Vous avez passé son double : |L'ordinateur a passé votre double : )?\d+ points? pour (vous|lui)(, videau à \d+)?\.$/.test(
await page.textContent("#summary-detail")) &&
(await page.textContent("#summary-reading")).startsWith("D'après mon analyse"),
`bilan de fin de partie : ${result}`);
check((await page.textContent("#prompt")) === "", "fin de partie : la consigne répète le panneau");
log(
`partie finie : ${result} (${countMoves(journal, "player")} coups du joueur, ` +
`${countMoves(journal, "computer")} de l'ordinateur, ${journal.events.length} événements)`,
@@ -1651,12 +1650,6 @@ check((await page.textContent("#summary-analysis")) === "Voir l'analyse" &&
(await page.textContent("#summary-settings")) === "Changer les réglages" &&
(await page.getAttribute("#summary-settings", "href")) === "#/nouvelle-partie",
"fin de partie : bilan sans « Voir l'analyse », « Rejouer » et « Changer les réglages »");
await review("6-fin-de-partie");
await page.setViewportSize({ width: 844, height: 320 });
await sleep(150);
check((await page.locator("#band-text").count()) === 0, "fin de partie : consigne sous le panneau en paysage");
await page.setViewportSize(PORTRAIT);
await sleep(150);
check(countMoves(journal, "player") >= 3 && countMoves(journal, "computer") >= 3, "trop peu de coups");
check(reloaded && resumed, "rechargement ou reprise de l'ancienne partie non essayés");
check(replays === 2, "le coup de l'ordinateur n'a pas été revu");
@@ -1681,13 +1674,17 @@ log(skips > 0 ? `aucun coup possible ${skips} fois (${skipsByDice} en touchant l
log(`vibrations demandées : ${(await vibrations()).length}`);
await shot("4-fin-de-partie");
// Fermer le bilan laisse voir la partie finie, sans panneau ; « Rejouer »
// reste dans la barre d'actions.
await page.click("#summary-close");
await page.waitForSelector("#summary-veil", { state: "hidden" });
// Le retour du téléphone ramène au plateau final, sans panneau, avec
// « Partie terminée · Voir le bilan » ; « Rejouer » reste dans la barre
// d'actions.
await page.goBack();
await page.waitForSelector("#summary", { state: "hidden" });
check(!(await page.isVisible("#panel")) && (await page.textContent("#again > span")) === "Rejouer" &&
(await page.isVisible("#again")),
"bilan fermé : panneau toujours là, ou pas de « Rejouer »");
(await page.isVisible("#again")) &&
(await page.textContent("#over-line")) === "Partie terminée · Voir le bilan",
"retour du bilan : panneau toujours là, pas de « Rejouer » ou pas de ligne de fin");
// La recette sur le plateau final, en lecture seule.
await review("6-fin-de-partie");
step("mes parties");
// Mes parties (IndexedDB), depuis le menu : une deuxième partie commencée,
@@ -1752,7 +1749,8 @@ step("mes parties");
check(shown === result, `écran différent après la reprise : ${shown}`);
check((await page.evaluate(() => performance.getEntriesByType("navigation").length)) === loads,
"la page a été rechargée");
await page.click("#summary-close");
await page.goBack();
await page.waitForSelector("#summary", { state: "hidden" });
log(
`mes parties : ${listed} parties listées (${branchCount} branche(s) pour la première), ` +
`SGF exporté (${sgf.length} octets), première partie reprise sans rechargement`,
@@ -1828,11 +1826,11 @@ if (offline === "roll") {
await page.click("#roll");
await waitForPlayer();
}
// Si la partie reprise est finie, son bilan se rouvre au rechargement et
// couvre l'écran (c'est voulu) : on le ferme avant d'ouvrir l'aide.
if (await page.locator("#summary-veil").isVisible()) {
await page.click("#summary-close");
await page.waitForSelector("#summary-veil", { state: "hidden" });
// Si la page rechargée est le bilan, on revient au plateau avant d'ouvrir
// l'aide.
if (await page.locator("#summary").isVisible()) {
await page.goBack();
await page.waitForSelector("#summary", { state: "hidden" });
}
await page.click("#help-button");
await page.waitForSelector(".glossary dt", { state: "attached" });
+3 -3
View File
@@ -351,7 +351,7 @@ check(
await capture("2-trois-parties");
log(`courbe : ${shown.dots.map((d) => d.rate).join(", ")} ; « ${shown.summary} » ; résultats : ${shown.items.map((i) => i.result).join(" | ")}`);
// Une ligne ouvre le bilan ; le fermer ramène à la progression.
// Une ligne ouvre le bilan, une page ; le retour ramène à la progression.
await page.click(`#progression-list .progression-item[data-id="${games[0].id}"] .progression-game`);
await until(
"bilan depuis la progression",
@@ -360,9 +360,9 @@ await until(
document.getElementById("summary")?.dataset.ready === "true",
[games[0].id],
);
await page.click("#summary-close");
await page.goBack();
await progressionReady();
log("une ligne ouvre le bilan, la croix ramène à la progression");
log("une ligne ouvre le bilan, le retour ramène à la progression");
// « Demander des exercices à une IA » : la feuille du prompt.
await page.click("#progression-exercises");
+2 -1
View File
@@ -419,7 +419,8 @@ const summaryHash = await page.evaluate(() => location.hash);
const id = summaryHash.split("/")[2];
await capture("4-bouton-bilan", () => page.locator("#summary-ask-ai").scrollIntoViewIfNeeded());
const summaryText = await openPrompt("#summary-ask-ai", "/bilan/ia");
await checkOneSheet("summary", "Bilan", "bilan");
// Le bilan est une page (étape 1m) : le prompt monte dans sa propre feuille.
await checkOneSheet(null, "Bilan", "bilan");
checkPrompt(summaryText, "prompt du bilan");
check(summaryText.includes("Résultat : l'ordinateur a gagné"), "prompt du bilan : résultat");
check(
+6 -1
View File
@@ -57,7 +57,12 @@ export async function hiddenUnderActionBar(target) {
};
const bars = [...document.querySelectorAll("body *")].filter((el) => {
const style = getComputedStyle(el);
return style.position === "sticky" && style.bottom !== "auto" && shown(el);
// Une barre collée en bas : sticky, ou fixe et marquée
// .action-bar (la barre du bilan, étape 1m).
const stuck =
style.position === "sticky" ||
(style.position === "fixed" && el.classList.contains("action-bar"));
return stuck && style.bottom !== "auto" && shown(el);
});
const describe = (el) =>
el.id
+8 -11
View File
@@ -276,21 +276,18 @@ await capture("3b-feuille-apres-refus", async () => {
check((await resignState()).sheet, "la feuille s'est fermée en changeant de taille");
});
await page.click("#resign-confirm");
// Le panneau de fin, puis le bilan à sa place dès que l'analyse est prête :
// entre les deux, ni l'un ni l'autre un court instant.
// Le bilan, une page, arrive après le plateau final (étape 1m).
await until("fin de partie", (title) =>
(!document.getElementById("panel-veil").hidden &&
document.getElementById("panel-text").textContent === title) ||
(!document.getElementById("summary-veil").hidden &&
document.getElementById("summary-title")?.textContent === title),
!document.getElementById("summary").hidden &&
document.getElementById("summary-title")?.textContent === title,
"Perdue par abandon, gammon, 4 points");
check(await page.isHidden("#resign"), "drapeau après la fin");
// Le bilan, une fois l'analyse prête : aucun coup, une seule phrase.
await until("bilan prêt", () => !document.getElementById("summary-veil").hidden &&
await until("bilan prêt", () => !document.getElementById("summary").hidden &&
document.getElementById("summary")?.dataset.ready === "true", null, 120_000);
const bilan = await page.evaluate(() => ({
title: document.getElementById("summary-title")?.textContent,
reading: document.getElementById("summary-reading")?.textContent,
reading: document.getElementById("summary-detail")?.textContent,
counts: document.getElementById("summary-counts") !== null,
gauges: document.querySelector("#summary .summary-gauges") !== null,
}));
@@ -306,11 +303,11 @@ const bilanActions = await page.evaluate(() => ({
check(!bilanActions.analysis && bilanActions.primary === "Rejouer" &&
bilanActions.settings === "Changer les réglages", `actions du bilan sans coup : ${JSON.stringify(bilanActions)}`);
await capture("5-bilan-abandon");
// Le bilan fermé laisse la partie finie à l'écran : une seule phrase, celle
// Le retour du téléphone ramène à la partie finie : une seule phrase, celle
// du maître, dans le style de l'état de la partie.
await page.click("#summary-close");
await page.goBack();
await until("partie finie à l'écran", () => location.hash === "#/" &&
document.getElementById("summary-veil").hidden &&
document.getElementById("summary").hidden &&
document.getElementById("prompt").textContent === "L'ordinateur accepte : vous perdez un gammon, 4 points.");
const ending = await page.evaluate(() => ({
neutral: document.getElementById("prompt").classList.contains("neutral"),