Files
Dune/tests/ambassador-marker-sandmaster-controls.test.tsx
T
Quintine 1a65e69932
Verify and publish checkpoint container / container (push) Successful in 11m9s
Preserve cache promises and support concealed Ambassador collection
2026-11-16 20:15:36 +11:00

157 lines
9.1 KiB
TypeScript

import assert from 'node:assert/strict';
import test from 'node:test';
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import * as jsxRuntime from 'react/jsx-runtime';
import ts from 'typescript';
import { AmbassadorMovement } from '../components/ambassador-movement';
import { applyAction, viewGame, type Action, type Game, type GameView } from '../game/engine';
import * as board from '../game/board';
import * as sandmaster from '../game/sandmaster-movement';
import * as matching from '../game/advisor-ambassador-matching';
import { placeAmbassador, validateAmbassadors } from '../game/ecaz-ambassadors';
import { deployRicheseNoField } from '../game/richese-no-field';
import { validateEcazLoyalty } from '../game/ecaz-loyalty';
import { createSelectedDeckSkillsSetup, assertSelectedDeckSkillsInventory } from './fixture-selected-deck-skills';
const seat = (game: Game, id: string) => {
const player = game.players.find(row => row.id === id); assert.ok(player); return player;
};
/** The shared inventory fixture predates Advanced Ecaz Loyalty. Validate its
* real custody, then include that unique card in the fixture's traitor count. */
function assertInventory(game: Game) {
validateEcazLoyalty(game);
const inventory = structuredClone(game);
if (inventory.ecazLoyalty?.card) {
(inventory.traitorReserve ??= []).push(inventory.ecazLoyalty.card);
delete inventory.ecazLoyalty;
}
assertSelectedDeckSkillsInventory(inventory);
}
/** Public setup and original Sandmaster assignment. The original marker,
* Ambassador, forces and destination Spice piles are staged at a controlled
* movement boundary; the actual trigger and beneficiary choice are played. */
function fixture(advanced: boolean) {
const setup = createSelectedDeckSkillsSetup({advanced, factions:['richese','ecaz','atreides'],
expansions:['choam','ecaz'],skill:'sandmaster'});
let game = structuredClone(setup.afterSetup);
for (const player of game.players) {
player.reserves += Object.values(player.forces).reduce((sum,n) => sum+n,0);
player.forces = {}; player.shipped = false; player.moved = 0;
}
const entrant = seat(game,'atreides'), richese = seat(game,'richese'), ecaz = seat(game,'ecaz');
entrant.reserves--; entrant.forces = {'imperial_basin:10':1}; entrant.shipped = true;
richese.ally = 'ecaz'; ecaz.ally = 'richese';
assert.ok(richese.noField);
const marker = richese.noField.tokens.find(token => token.value === 3); assert.ok(marker);
richese.noField = deployRicheseNoField(richese.noField, {tokenId:marker.id,controller:richese.id,
location:{territory:'red_chasm',sector:7}});
richese.noFieldEvent = 'ui-marker-event';
assert.ok(game.ecazAmbassadors);
const ambassadors = structuredClone(game.ecazAmbassadors);
const token = ambassadors.tokens.find(row => row.effect === 'fremen'); assert.ok(token);
if (!ambassadors.cohort.includes(token.id)) {
const replaced = ambassadors.tokens.find(row => row.id === ambassadors.cohort[0]); assert.ok(replaced);
replaced.zone = 'pool'; token.zone = 'supply'; ambassadors.cohort[0] = token.id;
}
game.ecazAmbassadors = placeAmbassador(ambassadors,token.id,{turn:1,availableSpice:ecaz.spice,
destination:{id:'arrakeen',stronghold:true,inStorm:false,allowed:true}}).state;
validateAmbassadors(game.ecazAmbassadors);
Object.assign(game,{turn:2,phase:5,storm:18,active:'atreides',ready:[],response:null,decision:null,
phaseOpening:null,stormResolution:null,stormPending:null,movementRemaining:['atreides','richese','ecaz'],
spice:{'south_mesa:4':4,'south_mesa:5':2}});
delete game.stormMovementSource;
assertInventory(game);
game = applyAction(game,'atreides',{type:'move',forces:{'imperial_basin:10':1},territory:'arrakeen',sector:10});
assert.equal(game.pendingAmbassador?.stage,'offer');
game = applyAction(game,'ecaz',{type:'decision',event:game.pendingAmbassador!.event,
trigger:true,beneficiary:'richese'});
assert.equal(game.pendingAmbassador?.stage,'move');
return {game,marker:marker.id};
}
type Element = ReactElement<{children?:ReactNode;[key:string]:unknown}>;
function elements(node: ReactNode): Element[] {
if (Array.isArray(node)) return node.flatMap(elements);
if (!isValidElement<{children?:ReactNode;[key:string]:unknown}>(node)) return [];
return [node,...elements(node.props.children)];
}
/** Run the real component with persistent deterministic hooks so the real
* select, checkbox and submit callbacks can be exercised without a DOM. */
function controller(game: GameView, busy = false) {
const states: unknown[] = [], sent: Action[] = [];
let cursor = 0;
const exports: {AmbassadorMovement?: typeof AmbassadorMovement} = {};
const code = ts.transpileModule(readFileSync(new URL('../components/ambassador-movement.tsx',import.meta.url),'utf8'), {
compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX},
}).outputText;
runInNewContext(code,{exports,require(name:string) {
if (name === 'react/jsx-runtime') return jsxRuntime;
if (name === 'react') return {useId:() => 'ambassador-fixture',useState(initial:unknown) {
const index = cursor++; if (!(index in states)) states[index] = initial;
return [states[index],(next:unknown) => {
states[index] = typeof next === 'function' ? (next as (value:unknown) => unknown)(states[index]) : next;
}];
}};
if (name === '@/game/board') return board;
if (name === '@/game/sandmaster-movement') return sandmaster;
if (name === '@/game/advisor-ambassador-matching') return matching;
if (name === './ui/button') return {Button:'button'};
if (name === './ui/input') return {Input:'input'};
throw Error(`Unexpected component import ${name}`);
}});
assert.ok(exports.AmbassadorMovement);
const render = () => { cursor=0; return elements(exports.AmbassadorMovement!({game,busy,act:action=>sent.push(action)})); };
const select = (suffix:string,value:string) => {
const node = render().find(element => element.props.id === `ambassador-fixture-${suffix}`); assert.ok(node);
assert.ok(elements(node).some(option => option.type === 'option' && option.props.value === value));
(node.props.onChange as (event:{target:{value:string}})=>void)({target:{value}});
};
return {render,sent,select};
}
for (const advanced of [false,true]) void test(
`${advanced ? 'Advanced' : 'Basic'} marker-only Ambassador owner selects an actual Sandmaster pile`, () => {
const {game,marker} = fixture(advanced), view = viewGame(game,'richese');
const html = renderToStaticMarkup(createElement(AmbassadorMovement,{game:view,busy:false,act() {}}));
assert.match(html,/Ambassador force relocation/);
assert.match(html,/Include concealed No-Field/);
assert.match(html,/Choose physical forces or the concealed No-Field/);
assert.equal(renderToStaticMarkup(createElement(AmbassadorMovement,
{game:viewGame(game,'atreides'),busy:false,act() {}})), '');
const ui = controller(view);
ui.select('destination','south_mesa'); ui.select('sector','south_mesa:4');
const checkbox = ui.render().find(element => element.type === 'input' && element.props.type === 'checkbox' &&
element.props.checked === false); assert.ok(checkbox);
(checkbox.props.onChange as (event:{target:{checked:boolean}})=>void)({target:{checked:true}});
ui.select('sandmaster-pile','south_mesa:5');
const button = ui.render().find(element => element.type === 'button' &&
element.props.children === 'Relocate selected forces'); assert.ok(button);
assert.equal(button.props.disabled,false); (button.props.onClick as ()=>void)();
assert.deepEqual(JSON.parse(JSON.stringify(ui.sent)),[{type:'decision',event:game.pendingAmbassador!.event,
forces:{},eliteForces:{},territory:'south_mesa',sector:4,
noField:{tokenId:marker,event:'ui-marker-event'},sandmasterCollect:true,sandmasterPile:'south_mesa:5'}]);
const before = seat(game,'richese').spice, done = applyAction(game,'richese',ui.sent[0]);
assert.equal(seat(done,'richese').spice,before+1);
assert.equal(done.spice['south_mesa:5'],1);
assert.deepEqual(seat(done,'richese').noField?.deployed?.location,{territory:'south_mesa',sector:4});
assert.throws(() => applyAction(done,'richese',ui.sent[0]),'The spent event cannot repeat');
assertInventory(done);
const blocked = controller(view,true);
blocked.select('destination','south_mesa'); blocked.select('sector','south_mesa:4');
const busyCheckbox = blocked.render().find(element => element.type === 'input' && element.props.type === 'checkbox' &&
element.props.checked === false); assert.ok(busyCheckbox);
(busyCheckbox.props.onChange as (event:{target:{checked:boolean}})=>void)({target:{checked:true}});
const busyButton = blocked.render().find(element => element.type === 'button' &&
element.props.children === 'Relocate selected forces'); assert.ok(busyButton);
assert.equal(busyButton.props.disabled,true); (busyButton.props.onClick as ()=>void)();
assert.deepEqual(blocked.sent,[]);
},
);