Files

217 lines
12 KiB
TypeScript

import { test, expect } from '@playwright/test';
async function enter(page, name = 'Wayfarer') {
await page.goto('/game?world=e2e');
await expect(page.locator('#connection-status')).toHaveText('World online');
await page.getByLabel('Character name').fill(name);
await page.getByRole('button', { name: 'Enter world' }).click();
await expectWorldReady(page);
await expect(page.locator('#game-controls')).toBeVisible();
}
async function expectWorldReady(page, characterId?: string) {
// Software-rendered CI can take longer than the default 5s to process the
// initial snapshot. test.slow() extends the test, not this assertion's budget.
// Keep the nine-chunk requirement and include both sides in failure output.
await expect.poll(() => page.evaluate(expectedId => {
const game = (window as any).__aeternalis;
return {
connection: document.getElementById('connection-status')?.textContent,
subscribedChunks: game?.snapshot?.chunkKeys.length ?? 0,
renderedChunks: game?.diagnostics().chunks ?? 0,
characterMatches: expectedId ? game?.snapshot?.self.entity.id === expectedId : !!game?.snapshot?.self.entity.id,
};
}, characterId), { timeout: 20000, message: 'World readiness requires the expected character and all nine subscribed/rendered chunks' })
.toEqual({ connection: 'Connected', subscribedChunks: 9, renderedChunks: 9, characterMatches: true });
}
test('desktop renders models, moves authoritatively, gathers, and reconnects', async ({ page }) => {
// Same reasoning as the boss test's test.slow(): this is the most elaborate test here
// (WebGL pixel readback, model diagnostics, a full reload/reconnect cycle), so it's the
// most likely to hit the config's 45s per-test deadline before its own poll timeouts do
// on a slow CI run.
test.slow();
const errors: string[] = [];
page.on('pageerror', error => errors.push(error.message));
await page.setViewportSize({ width: 1440, height: 900 });
// Regression: sparse input plus stale snapshots used to overshoot the tree,
// send gathering intents from outside server range, then abandon the action.
// Keep the real simulation and input handlers; delay only delivery/cadence.
await page.routeWebSocket('**/ws', socket => {
const server = socket.connectToServer();
server.onMessage(message => { setTimeout(() => socket.send(message), 1500); });
});
await page.addInitScript(() => {
const interval = window.setInterval.bind(window);
window.setInterval = ((handler, delay, ...args) => interval(handler, delay === 50 ? 1500 : delay, ...args)) as typeof window.setInterval;
});
await enter(page);
// Gather from the spawn clearing before testing keyboard movement. A delayed
// key release can otherwise change the nearest resource (including its risk
// and required confirmation), coupling gathering success to the walk's length.
await page.getByRole('button', { name: 'Gather', exact: true }).click();
let gatherDiagnostics: unknown;
try {
await expect.poll(async () => {
gatherDiagnostics = await page.evaluate(() => {
const game = (window as any).__aeternalis, s = game.snapshot;
return {
gainedXP: Object.values(s.self.gathering).some((skill: any) => skill.xp > 0),
attempt: s.self.gatherAttempt,
position: s.self.entity.position,
movementFactor: s.self.movementFactor,
ack: s.self.ack,
tick: s.tick,
connection: document.querySelector('#connection-status')?.textContent,
message: s.message,
target: document.querySelector('#target')?.textContent,
notice: document.querySelector('#notice')?.textContent,
walkTo: game.walkTo,
pendingAction: game.pendingAction,
keys: game.keys,
};
});
return (gatherDiagnostics as { gainedXP: boolean }).gainedXP;
}, { timeout: 30000, message: 'Gather must award profession XP despite delayed stop acknowledgement' }).toBe(true);
} catch (error) {
// toMatchObject omits unmatched properties from its diff. Put the complete
// last sample in the error so CI's text log actually includes diagnostics.
throw new Error(`${String(error)}\nGather diagnostics: ${JSON.stringify(gatherDiagnostics, null, 2)}`);
}
const before = await page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.position);
await page.keyboard.down('d');
try {
await expect.poll(() => page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.position.x), { timeout: 15000 }).toBeGreaterThan(before.x + 3);
} finally {
await page.keyboard.up('d');
}
await page.getByRole('button', { name: 'Inventory and crafting' }).click();
await expect(page.locator('#inventory')).toBeVisible();
await expect(page.locator('#inventory-items')).toContainText('Knife');
await page.getByRole('button', { name: 'Close inventory', exact: true }).click();
const id = await page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.id);
await page.screenshot({ path: 'test-results/desktop.png' });
const pixels = await page.evaluate(async () => {
const canvas = document.getElementById('world') as HTMLCanvasElement;
// Read in the animation frame immediately after rendering; avoid a cleared backbuffer.
return new Promise<number>(resolve => requestAnimationFrame(() => {
const gl = canvas.getContext('webgl2')!;
const data = new Uint8Array(64 * 64 * 4);
gl.readPixels(Math.floor(canvas.width / 2) - 32, Math.floor(canvas.height / 2) - 32, 64, 64, gl.RGBA, gl.UNSIGNED_BYTE, data);
const colors = new Set<string>(); for (let i = 0; i < data.length; i += 4) colors.add(`${data[i]},${data[i+1]},${data[i+2]}`);
resolve(colors.size);
}));
});
expect(pixels).toBeGreaterThan(8);
const diagnostics = await page.evaluate(() => (window as any).__aeternalis.diagnostics());
expect(diagnostics.models).toBe(6); expect(diagnostics.frames).toBeGreaterThan(10); expect(diagnostics.triangles).toBeGreaterThan(1000);
// Keep the real server connection, but hold incoming snapshots until we have
// checked that an open socket alone does not claim the world is synchronized.
let releaseSnapshots: (() => void) | undefined;
await page.routeWebSocket('**/ws', socket => {
const server = socket.connectToServer();
let held = true;
const buffered: (string | Buffer)[] = [];
server.onMessage(message => { if (held) buffered.push(message); else socket.send(message); });
releaseSnapshots = () => { held = false; for (const message of buffered) socket.send(message); buffered.length = 0; };
});
await page.reload();
await expect(page.locator('#connection-status')).toHaveText('Synchronizing world', { timeout: 20000 });
expect(await page.evaluate(() => (window as any).__aeternalis?.snapshot)).toBeUndefined();
releaseSnapshots!();
await expectWorldReady(page, id);
expect(errors).toEqual([]);
});
test('mobile controls fit and move the character', async ({ page }) => {
// Entry, authoritative movement and screenshots each need time on software
// rendering; allow their bounded waits to finish on the CI worker.
test.slow();
const errors: string[] = [];
page.on('pageerror', error => errors.push(error.message));
await page.setViewportSize({ width: 390, height: 844 });
// Hold authentication at the network boundary: entry must stay unavailable
// until it completes, even when the world preview has already loaded.
await page.route('**/api/me', async route => {
await expect(page.getByRole('button', { name: 'Enter world' })).toBeDisabled();
await expect(page.locator('#connection-status')).not.toHaveText('World online');
await route.continue();
}, { times: 1 });
await enter(page, 'Mobile');
await expect(page.getByRole('button', { name: 'Move north' })).toBeVisible();
const before = await page.evaluate(() => (window as any).__aeternalis.snapshot.self.entity.position.z);
const button = page.getByRole('button', { name: 'Move north' });
// Pointer capture needs an active browser pointer, not a synthetic pointer ID.
// Hold until the server confirms movement rather than releasing after 650ms
// and assuming the CI browser sent enough movement intents during that time.
await button.hover();
await page.mouse.down();
try {
await expect.poll(() => page.evaluate(startZ => {
const s = (window as any).__aeternalis.snapshot;
return {
movedNorth: s.self.entity.position.z < startZ - 2,
position: s.self.entity.position,
movementFactor: s.self.movementFactor,
ack: s.self.ack,
tick: s.tick,
connection: document.querySelector('#connection-status')?.textContent,
message: s.message,
};
}, before), { timeout: 15000, message: 'Holding Move north must produce authoritative movement' }).toMatchObject({ movedNorth: true });
} finally {
await page.mouse.up();
}
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
await page.getByRole('button', { name: 'Inventory and crafting' }).click();
const box = await page.locator('#inventory').boundingBox();
expect(box!.x).toBeGreaterThanOrEqual(0); expect(box!.x + box!.width).toBeLessThanOrEqual(390);
await page.screenshot({ path: 'test-results/mobile.png' });
await page.getByRole('button', { name: 'Close inventory', exact: true }).click();
await page.setViewportSize({ width: 844, height: 390 });
await page.screenshot({ path: 'test-results/mobile-landscape.png' });
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
expect(errors).toEqual([]);
});
test('unauthenticated API and hostile origins cannot mutate state', async ({ request }) => {
expect((await request.post('/api/join', { data: { name: 'Intruder' }, headers: { Origin: 'https://evil.example' } })).status()).toBe(403);
expect((await request.get('/api/me')).status()).toBe(401);
const response = await request.get('/api/config');
expect(response.headers()['content-security-policy']).toContain("frame-ancestors 'none'");
expect(response.headers()['x-content-type-options']).toBe('nosniff');
});
test('boss event is visible and accepts server-authoritative combat', async ({ page }) => {
// The 20s poll below has its own budget, but on slow CI hardware the cumulative time
// for enter() + awakening the boss + closing settings can eat far enough into the
// config's 45s per-test timeout that the whole test gets killed before that poll's own
// timeout ever gets to fire and report cleanly. slow() triples this test's budget.
test.slow();
await page.setViewportSize({ width: 1440, height: 900 });
// Hold rendering after the target click. Input and server combat must keep
// progressing even when requestAnimationFrame is stalled on a slow GPU.
await page.addInitScript(() => {
const raf = window.requestAnimationFrame.bind(window);
window.requestAnimationFrame = callback => raf(time => {
const deliver = () => {
if ((window as any).__holdGameFrames) setTimeout(deliver, 50);
else callback(time);
};
deliver();
});
});
await enter(page, 'Boss witness');
await page.getByRole('button', { name: 'Display settings' }).click();
await page.getByRole('button', { name: 'Awaken Harbinger' }).click();
await expect(page.locator('#phase-label')).toHaveText('THE UNRAVELING');
await page.getByRole('button', { name: 'Close display settings' }).click();
const hp = await page.evaluate(() => (window as any).__aeternalis.snapshot.world.bossHp);
await page.locator('#target-boss').evaluate(button => button.addEventListener('click', () => { (window as any).__holdGameFrames = true; }, { once: true }));
await page.getByRole('button', { name: 'Target Harbinger', exact: true }).click();
await expect.poll(() => page.evaluate(() => (window as any).__aeternalis.snapshot.world.bossHp), { timeout: 20000 }).toBeLessThan(hp);
await page.evaluate(() => { (window as any).__holdGameFrames = false; });
await expect(page.locator('#boss-bar')).toBeVisible();
await page.screenshot({ path: 'test-results/boss.png' });
});