Files
wikideck/tests/ui-pvp-recap.test.ts

106 lines
6.6 KiB
TypeScript
Raw Permalink 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.
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { renderToStaticMarkup } from 'react-dom/server';
import { createElement } from 'react';
import { RecapArticle, loadRecap, matchIdFromPath } from '../src/game/recap/BattleRecap.tsx';
import { fallbackRecap, parseMatchRecord, runs } from '../src/game/recap/model.ts';
// Real cards from the sample pool (no network).
const sample = JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8'));
const pool: { pageId: number; title: string; revisionId?: number }[] = (Array.isArray(sample) ? sample : sample.cards ?? []).map((c: Record<string, unknown>) => {
const a = (c.article ?? c) as Record<string, unknown>;
return { pageId: a.pageId as number, title: a.title as string, revisionId: a.revisionId as number | undefined };
}).filter((c: { pageId: unknown; title: unknown }) => typeof c.pageId === 'number' && typeof c.title === 'string');
const record = {
matchId: 'm_7f3a', modeName: 'Classic', players: [{ name: 'alice' }, { name: 'bob' }],
startedAt: Date.UTC(2026, 10, 17, 23, 40), endedAt: Date.UTC(2026, 10, 18, 0, 2), turns: 9,
result: { winner: 0, reason: 'notability' }, strength: [40, 40],
played: [pool.slice(0, 4).map(c => ({ ...c, type: 'Figure' })).concat([{ ...pool[4], type: 'Doctrine' }]), pool.slice(5, 8).map(c => ({ ...c, type: 'Figure' }))],
lost: [[pool[1]], [pool[5], pool[6]]],
};
test('recap: deterministic, named after the winner’s decisive non-Figure card, with an infobox', () => {
assert.ok(pool.length >= 8, 'card-sample.json has cards');
const a = fallbackRecap(parseMatchRecord(record));
const b = fallbackRecap(parseMatchRecord(structuredClone(record)));
assert.deepEqual(a, b);
assert.equal(a.title, `Battle of ${pool[4].title} (2026)`);
assert.equal(a.infobox.date, '18 November 2026');
assert.deepEqual(a.infobox.belligerents, ['alice', 'bob']);
assert.deepEqual(a.infobox.casualties, [`1 card destroyed: ${pool[1].title}`, `2 cards destroyed: ${pool[5].title}, ${pool[6].title}`]);
assert.deepEqual(a.infobox.commanders, [pool[0].title, pool[5].title]);
assert.equal(a.masthead, 'WikiDeck');
assert.match(a.footer, /game events/);
assert.equal(a.infobox.result, 'Victory for alice');
assert.equal(a.url, '/recap/m_7f3a');
});
test('recap: References cite every card played, once each, with revision ids', () => {
const doc = fallbackRecap(parseMatchRecord(record));
const played = [...record.played[0], ...record.played[1]];
assert.equal(doc.references.length, new Set(played.map(c => `${c.pageId}:${c.revisionId ?? ''}`)).size);
for (const c of played) assert.ok(doc.references.some(r => r.title === c.title));
const html = renderToStaticMarkup(createElement(RecapArticle, { doc }));
assert.match(html, /WikiDeck/);
assert.match(html, /Casualties/);
assert.match(html, /Course of the battle/);
assert.doesNotMatch(html, /\*\*/, 'markup is rendered, not shown');
assert.match(html, /href="#ref-1"/);
if (pool[0].revisionId) assert.match(html, new RegExp(`oldid=${pool[0].revisionId}`));
});
test('recap text: fixed templates only, no adjectives about the outcome or winks', () => {
const doc = fallbackRecap(parseMatchRecord(record));
const text = [doc.lead, ...doc.sections.flatMap(s => s.paragraphs)].join(' ');
assert.doesNotMatch(text, /!|lol|brutal|humiliat|heroic|surprising|twist|killed|decisive|pyrrhic/i);
assert.match(text, /\*\*Battle of [^*]+\*\* was a WikiDeck engagement fought on 18 November 2026 between the forces of alice and bob/);
assert.match(text, /nine turns/);
assert.match(text, /bob was reduced to zero Notability\./);
});
test('recap falls back to "Match of <date>" when nothing was played, and tolerates junk', () => {
const doc = fallbackRecap(parseMatchRecord({ matchId: 'x', endedAt: Date.UTC(2026, 10, 17), players: ['a', 'b'], result: { winner: null } }));
assert.equal(doc.title, 'Match of 17 November 2026');
assert.equal(doc.infobox.result, 'Draw');
const junk = fallbackRecap(parseMatchRecord({ players: 7, played: [[{ title: 3 }], 'x'], url: 'javascript:1' }));
assert.equal(junk.references.length, 0);
});
test('only https Wikipedia links reach the References', () => {
const doc = fallbackRecap(parseMatchRecord({ ...record, played: [[{ pageId: 1, title: 'A', url: 'https://evil.example/a' }], []] }));
assert.match(doc.references[0].url, /^https:\/\/en\.wikipedia\.org\/wiki\/A$/);
});
test('/battle/<id> routing and loading from GET /api/game/matches/:id (stubbed fetch)', async () => {
assert.equal(matchIdFromPath('/battle/m_7f3a'), 'm_7f3a');
assert.equal(matchIdFromPath('/battle/../x'), '');
assert.equal(matchIdFromPath('/recap/m_7f3a'), 'm_7f3a');
let asked = '';
const fake = (async (url: string) => { asked = url; return new Response(JSON.stringify(record), { headers: { 'content-type': 'application/json' } }); }) as typeof fetch;
const doc = await loadRecap('m_7f3a', fake);
assert.equal(asked, '/api/game/matches/m_7f3a');
assert.match(doc.title, /^Battle of /);
const missing = (async () => new Response('{}', { status: 404 })) as unknown as typeof fetch;
await assert.rejects(loadRecap('nope', missing), /No battle/);
});
test('story markup becomes text runs; card titles cannot inject markup', () => {
assert.deepEqual(runs('The **Battle of X** saw *Moon*[2].'), [{ text: 'The ' }, { text: 'Battle of X', bold: true }, { text: ' saw ' },
{ text: 'Moon', italic: true }, { text: '[2]', cite: 2 }, { text: '.' }]);
const doc = fallbackRecap(parseMatchRecord({ matchId: 'z', players: ['a', 'b'], result: { winner: 0 }, played: [[{ pageId: 1, title: '**Evil** [9]', type: 'Event' }], []] }));
assert.equal(doc.title, 'Battle of Evil 9');
const seen = [doc.lead, ...doc.sections.flatMap(s => s.paragraphs)].flatMap(runs);
assert.ok(!seen.some(r => r.cite === 9));
});
test('a host-pvp match record (winner/reason at top level, decks, no replay yet) still yields a plain recap', () => {
const doc = fallbackRecap(parseMatchRecord({ matchId: 'a'.repeat(32), modeId: 'classic', seed: 's', rules: {}, players: [{ id: 'x', name: 'alice' }, { id: 'y', name: 'bob' }],
winner: 1, reason: 'concede', startedAt: Date.UTC(2026, 10, 18, 1), endedAt: Date.UTC(2026, 10, 18, 1, 20), decks: [new Array(40).fill({}), new Array(40).fill({})], actions: [] }));
assert.equal(doc.title, 'Match of 18 November 2026');
assert.equal(doc.infobox.result, 'Victory for bob');
assert.deepEqual(doc.infobox.strength, ['40 cards', '40 cards']);
assert.match(doc.sections.flatMap(s => s.paragraphs).join(' '), /alice withdrew from the engagement\./);
});