Merge branch 'main' into feature/dynasty-list-parity
# Conflicts: # tools/frontend-legacy-parity/playwright.config.mjs
This commit is contained in:
@@ -75,6 +75,82 @@ export const canonicalFrontendFixture = {
|
||||
[2, '진', '#1976d2', 2],
|
||||
],
|
||||
},
|
||||
bestGeneral: {
|
||||
isUnited: true,
|
||||
sections: [
|
||||
{
|
||||
title: '명 성',
|
||||
valueType: 'int',
|
||||
entries: [
|
||||
{
|
||||
id: 1,
|
||||
name: '유비',
|
||||
ownerName: '시각검증',
|
||||
nationName: '촉',
|
||||
bgColor: '#006400',
|
||||
fgColor: '#ffffff',
|
||||
picture: 'default.jpg',
|
||||
imageServer: 0,
|
||||
value: 12000,
|
||||
printValue: '12,000',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: '조조',
|
||||
ownerName: '검증계정',
|
||||
nationName: '위',
|
||||
bgColor: '#8b0000',
|
||||
fgColor: '#ffffff',
|
||||
picture: 'default.jpg',
|
||||
imageServer: 0,
|
||||
value: 11000,
|
||||
printValue: '11,000',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: '계 급',
|
||||
valueType: 'int',
|
||||
entries: [],
|
||||
},
|
||||
],
|
||||
uniqueItems: [
|
||||
{
|
||||
title: '명 마',
|
||||
slot: 'horse',
|
||||
entries: [
|
||||
{
|
||||
itemKey: 'che_명마_15_적토마',
|
||||
itemName: '적토마',
|
||||
itemInfo: '최고의 명마',
|
||||
owner: {
|
||||
id: 1,
|
||||
name: '유비',
|
||||
nationName: '촉',
|
||||
bgColor: '#006400',
|
||||
fgColor: '#ffffff',
|
||||
picture: 'default.jpg',
|
||||
imageServer: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
itemKey: 'che_명마_15_적토마',
|
||||
itemName: '적토마',
|
||||
itemInfo: '최고의 명마',
|
||||
owner: {
|
||||
id: 0,
|
||||
name: '경매중',
|
||||
nationName: '-',
|
||||
bgColor: '#00582c',
|
||||
fgColor: '#ffffff',
|
||||
picture: null,
|
||||
imageServer: 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
hallOptions: [
|
||||
{
|
||||
season: 1,
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
import { expect, test, type Page, type Route } from '@playwright/test';
|
||||
|
||||
import { canonicalFrontendFixture as fixture } from './fixtures/canonical';
|
||||
|
||||
const gamePort = process.env.FRONTEND_PARITY_GAME_PORT ?? '15102';
|
||||
const response = (data: unknown) => ({ result: { data } });
|
||||
const errorResponse = (path: string, message: string) => ({
|
||||
error: {
|
||||
message,
|
||||
code: -32000,
|
||||
data: { code: 'BAD_REQUEST', httpStatus: 400, path },
|
||||
},
|
||||
});
|
||||
|
||||
const operationNames = (route: Route): string[] => {
|
||||
const pathname = new URL(route.request().url()).pathname;
|
||||
return decodeURIComponent(pathname.slice(pathname.lastIndexOf('/trpc/') + 6)).split(',');
|
||||
};
|
||||
|
||||
const general = {
|
||||
id: 1,
|
||||
name: '테스트장수',
|
||||
npcState: 0,
|
||||
nationId: 1,
|
||||
cityId: 1,
|
||||
troopId: 0,
|
||||
picture: 'default.jpg',
|
||||
imageServer: 0,
|
||||
officerLevel: 1,
|
||||
stats: { leadership: 80, strength: 70, intelligence: 90 },
|
||||
gold: 1000,
|
||||
rice: 1000,
|
||||
crew: 500,
|
||||
train: 100,
|
||||
atmos: 100,
|
||||
injury: 0,
|
||||
experience: 1200,
|
||||
dedication: 900,
|
||||
items: { horse: null, weapon: null, book: null, item: null },
|
||||
};
|
||||
|
||||
const generalContext = {
|
||||
general,
|
||||
city: {
|
||||
id: 1,
|
||||
name: '낙양',
|
||||
level: 7,
|
||||
nationId: 1,
|
||||
population: 50000,
|
||||
agriculture: 5000,
|
||||
commerce: 5000,
|
||||
security: 5000,
|
||||
defence: 5000,
|
||||
wall: 5000,
|
||||
supplyState: 1,
|
||||
frontState: 2,
|
||||
},
|
||||
nation: {
|
||||
id: 1,
|
||||
name: '테스트국',
|
||||
color: '#d32f2f',
|
||||
level: 5,
|
||||
gold: 10000,
|
||||
rice: 10000,
|
||||
tech: 1200,
|
||||
typeCode: 'che_군벌',
|
||||
capitalCityId: 1,
|
||||
},
|
||||
settings: {},
|
||||
penalties: {},
|
||||
};
|
||||
|
||||
const target = (generalId: number, generalName: string, nationId: number, nationName: string, color: string) => ({
|
||||
generalId,
|
||||
generalName,
|
||||
nationId,
|
||||
nationName,
|
||||
color,
|
||||
icon: '/image/icons/default.jpg',
|
||||
});
|
||||
|
||||
const ownTarget = target(1, '테스트장수', 1, '테스트국', '#d32f2f');
|
||||
const foreignTarget = target(8, '상대장수', 2, '상대국', '#2457a6');
|
||||
const messageTime = new Date().toISOString().replace('T', ' ').slice(0, 19);
|
||||
|
||||
const buildMessages = (permission: number) => ({
|
||||
result: true,
|
||||
public: [
|
||||
{
|
||||
id: 101,
|
||||
msgType: 'public',
|
||||
src: ownTarget,
|
||||
dest: null,
|
||||
text: '전체 메시지 본문',
|
||||
option: {},
|
||||
time: messageTime,
|
||||
},
|
||||
],
|
||||
national: [
|
||||
{
|
||||
id: 102,
|
||||
msgType: 'national',
|
||||
src: ownTarget,
|
||||
dest: target(0, '', 1, '테스트국', '#d32f2f'),
|
||||
text: '국가 메시지 본문',
|
||||
option: {},
|
||||
time: messageTime,
|
||||
},
|
||||
],
|
||||
private: [
|
||||
{
|
||||
id: 103,
|
||||
msgType: 'private',
|
||||
src: foreignTarget,
|
||||
dest: ownTarget,
|
||||
text: '개인 메시지 본문',
|
||||
option: {},
|
||||
time: messageTime,
|
||||
},
|
||||
],
|
||||
diplomacy: [
|
||||
{
|
||||
id: 104,
|
||||
msgType: 'diplomacy',
|
||||
src: foreignTarget,
|
||||
dest: target(0, '', 1, '테스트국', '#d32f2f'),
|
||||
text: permission >= 3 ? '외교 메시지 본문' : '(외교 메시지입니다)',
|
||||
option:
|
||||
permission >= 3
|
||||
? { action: 'noAggression', deletable: false }
|
||||
: { action: 'noAggression', deletable: false, invalid: true },
|
||||
time: messageTime,
|
||||
},
|
||||
],
|
||||
sequence: 104,
|
||||
nationId: 1,
|
||||
generalName: general.name,
|
||||
permission,
|
||||
canRespondDiplomacy: permission >= 4 && general.officerLevel > 4,
|
||||
latestRead: { private: 0, diplomacy: 0 },
|
||||
});
|
||||
|
||||
const contacts = {
|
||||
nation: [
|
||||
{
|
||||
nationId: 0,
|
||||
mailbox: 9000,
|
||||
name: '재야',
|
||||
color: '#000000',
|
||||
general: [],
|
||||
},
|
||||
{
|
||||
nationId: 1,
|
||||
mailbox: 9001,
|
||||
name: '테스트국',
|
||||
color: '#d32f2f',
|
||||
general: [
|
||||
[1, '테스트장수', 4],
|
||||
[2, '아군군주', 1],
|
||||
],
|
||||
},
|
||||
{
|
||||
nationId: 2,
|
||||
mailbox: 9002,
|
||||
name: '상대국',
|
||||
color: '#2457a6',
|
||||
general: [
|
||||
[8, '상대외교관', 4],
|
||||
[9, '상대일반', 0],
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const installFixture = async (
|
||||
page: Page,
|
||||
options: { permission: number; sendError?: string }
|
||||
): Promise<Array<{ operation: string; body: unknown }>> => {
|
||||
const mutations: Array<{ operation: string; body: unknown }> = [];
|
||||
await page.addInitScript(
|
||||
({ gameToken, profile }) => {
|
||||
window.localStorage.setItem('sammo-game-token', gameToken);
|
||||
window.localStorage.setItem('sammo-game-profile', profile);
|
||||
},
|
||||
{
|
||||
gameToken: fixture.game.session.gameToken,
|
||||
profile: fixture.game.session.profile,
|
||||
}
|
||||
);
|
||||
await page.route('**/image/**', (route) => route.fulfill({ status: 204, body: '' }));
|
||||
await page.route('**/che/api/events**', (route) => route.abort());
|
||||
await page.route('**/che/api/trpc/**', async (route) => {
|
||||
const body = route.request().postDataJSON();
|
||||
const results = operationNames(route).map((operation) => {
|
||||
if (operation === 'lobby.info') {
|
||||
return response({ ...fixture.game.lobby, myGeneral: general });
|
||||
}
|
||||
if (operation === 'general.me') return response(generalContext);
|
||||
if (operation === 'world.getMapLayout') return response(fixture.game.mapLayout);
|
||||
if (operation === 'world.getMap') {
|
||||
return response({ ...fixture.game.map, myCity: 1, myNation: 1 });
|
||||
}
|
||||
if (operation === 'turns.getCommandTable') return response({ general: [], nation: [] });
|
||||
if (operation === 'turns.reserved.getGeneral' || operation === 'turns.reserved.getNation') {
|
||||
return response([]);
|
||||
}
|
||||
if (operation === 'messages.getRecent') return response(buildMessages(options.permission));
|
||||
if (operation === 'messages.getContacts') return response(contacts);
|
||||
if (operation === 'board.getAccess') return response({ canMeeting: true, canSecret: true });
|
||||
if (operation === 'tournament.getState') return response({ stage: 0 });
|
||||
if (
|
||||
operation === 'messages.send' ||
|
||||
operation === 'messages.readLatest' ||
|
||||
operation === 'messages.delete' ||
|
||||
operation === 'messages.respond'
|
||||
) {
|
||||
mutations.push({ operation, body });
|
||||
if (operation === 'messages.send' && options.sendError) {
|
||||
return errorResponse(operation, options.sendError);
|
||||
}
|
||||
return response(operation === 'messages.respond' ? { result: true, reason: 'success' } : { ok: true });
|
||||
}
|
||||
return errorResponse(operation, `Unhandled message fixture operation: ${operation}`);
|
||||
});
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(results),
|
||||
});
|
||||
});
|
||||
return mutations;
|
||||
};
|
||||
|
||||
const openMessages = async (page: Page, viewport: { width: number; height: number }) => {
|
||||
await page.setViewportSize(viewport);
|
||||
await page.goto(`http://127.0.0.1:${gamePort}/che/`);
|
||||
await expect(page.getByRole('heading', { name: '전장 현황' })).toBeVisible();
|
||||
if (viewport.width <= 1024) {
|
||||
await page.getByRole('button', { name: '메시지', exact: true }).click();
|
||||
}
|
||||
await expect(page.locator('.MessagePanel')).toBeVisible();
|
||||
};
|
||||
|
||||
for (const viewport of [
|
||||
{ width: 1000, height: 900 },
|
||||
{ width: 500, height: 900 },
|
||||
]) {
|
||||
test(`matches the reference message computed DOM at ${viewport.width}px Chromium viewport`, async ({ page }) => {
|
||||
await installFixture(page, { permission: 4 });
|
||||
await openMessages(page, viewport);
|
||||
const geometry = await page.locator('.MessagePanel').evaluate((panel) => {
|
||||
const required = (selector: string) => panel.querySelector<HTMLElement>(selector)!;
|
||||
const rect = (element: Element) => {
|
||||
const box = element.getBoundingClientRect();
|
||||
return { x: box.x, y: box.y, width: box.width, height: box.height };
|
||||
};
|
||||
const panelStyle = getComputedStyle(panel);
|
||||
const header = required('.BoardHeader');
|
||||
const plate = required('.msg-plate');
|
||||
const icon = required('.general-icon');
|
||||
return {
|
||||
panel: rect(panel),
|
||||
inputForm: rect(required('.MessageInputForm')),
|
||||
select: rect(required('.message-select')),
|
||||
input: rect(required('.message-text')),
|
||||
submit: rect(required('.message-send')),
|
||||
publicSection: rect(required('.PublicTalk')),
|
||||
nationalSection: rect(required('.NationalTalk')),
|
||||
firstHeader: rect(header),
|
||||
firstPlate: rect(plate),
|
||||
firstIcon: rect(icon),
|
||||
computed: {
|
||||
panelDisplay: panelStyle.display,
|
||||
panelColumns: panelStyle.gridTemplateColumns,
|
||||
panelFontSize: panelStyle.fontSize,
|
||||
headerColor: getComputedStyle(header).color,
|
||||
headerOutlineWidth: getComputedStyle(header).outlineWidth,
|
||||
plateBackgroundColor: getComputedStyle(plate).backgroundColor,
|
||||
plateFontSize: getComputedStyle(plate).fontSize,
|
||||
plateMinHeight: getComputedStyle(plate).minHeight,
|
||||
iconObjectFit: getComputedStyle(icon).objectFit,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
expect(geometry.panel.x).toBeCloseTo(0, 0);
|
||||
expect(geometry.panel.width).toBeCloseTo(viewport.width, 0);
|
||||
expect(geometry.inputForm.width).toBeCloseTo(viewport.width, 0);
|
||||
expect(geometry.select.height).toBeCloseTo(35.5, 0);
|
||||
expect(geometry.submit.height).toBeCloseTo(35.5, 0);
|
||||
expect(geometry.firstHeader.height).toBeCloseTo(25, 0);
|
||||
expect(geometry.firstPlate.height).toBeGreaterThanOrEqual(64);
|
||||
expect(geometry.firstIcon).toMatchObject({ width: 64, height: 64 });
|
||||
expect(geometry.computed).toMatchObject({
|
||||
panelFontSize: '14px',
|
||||
headerColor: 'rgb(255, 255, 255)',
|
||||
headerOutlineWidth: '1px',
|
||||
plateBackgroundColor: 'rgb(20, 28, 101)',
|
||||
plateFontSize: '12.5px',
|
||||
plateMinHeight: '64px',
|
||||
iconObjectFit: 'fill',
|
||||
});
|
||||
|
||||
if (viewport.width === 1000) {
|
||||
expect(geometry.computed.panelDisplay).toBe('grid');
|
||||
expect(geometry.computed.panelColumns).toBe('500px 500px');
|
||||
expect(geometry.select.width).toBeCloseTo(166.66, 0);
|
||||
expect(geometry.input.width).toBeCloseTo(666.66, 0);
|
||||
expect(geometry.submit.width).toBeCloseTo(166.66, 0);
|
||||
expect(geometry.publicSection.width).toBeCloseTo(500, 0);
|
||||
expect(geometry.nationalSection.x).toBeCloseTo(500, 0);
|
||||
} else {
|
||||
expect(geometry.computed.panelDisplay).toBe('block');
|
||||
expect(geometry.select.width).toBeCloseTo(250, 0);
|
||||
expect(geometry.input.width).toBeCloseTo(500, 0);
|
||||
expect(geometry.input.height).toBeCloseTo(33.5, 0);
|
||||
expect(geometry.submit.width).toBeCloseTo(250, 0);
|
||||
}
|
||||
|
||||
const submit = page.locator('.message-send');
|
||||
await submit.hover();
|
||||
expect(
|
||||
await submit.evaluate((element) => ({
|
||||
cursor: getComputedStyle(element).cursor,
|
||||
backgroundColor: getComputedStyle(element).backgroundColor,
|
||||
}))
|
||||
).toEqual({ cursor: 'pointer', backgroundColor: 'rgb(55, 90, 127)' });
|
||||
await submit.focus();
|
||||
expect(
|
||||
await submit.evaluate((element) => ({
|
||||
outlineWidth: getComputedStyle(element).outlineWidth,
|
||||
boxShadow: getComputedStyle(element).boxShadow,
|
||||
}))
|
||||
).toEqual({ outlineWidth: '0px', boxShadow: 'none' });
|
||||
});
|
||||
}
|
||||
|
||||
test('exposes ambassador targets, reply, read, delete, and successful send interactions', async ({ page }) => {
|
||||
const mutations = await installFixture(page, { permission: 4 });
|
||||
await openMessages(page, { width: 500, height: 900 });
|
||||
|
||||
const select = page.getByLabel('메시지 수신 대상');
|
||||
await expect(select.locator('option[value="9002"]')).toHaveCount(1);
|
||||
await expect(select.locator('option[value="8"]')).toBeDisabled();
|
||||
await expect(select.locator('option[value="9"]')).toBeEnabled();
|
||||
|
||||
await page.locator('.PrivateTalk .msg-target').filter({ hasText: '상대장수' }).click();
|
||||
await expect(select).toHaveValue('8');
|
||||
|
||||
await page.locator('.PrivateTalk').getByRole('button', { name: '모두 읽음' }).click();
|
||||
await expect.poll(() => mutations.filter((entry) => entry.operation === 'messages.readLatest').length).toBe(1);
|
||||
|
||||
const deleteButton = page.locator('.PublicTalk .delete-message');
|
||||
page.once('dialog', (dialog) => dialog.accept());
|
||||
await deleteButton.click();
|
||||
await expect.poll(() => mutations.filter((entry) => entry.operation === 'messages.delete').length).toBe(1);
|
||||
|
||||
await select.selectOption('9999');
|
||||
await page.getByLabel('메시지 입력').fill('전송 성공');
|
||||
await page.getByRole('button', { name: '서신전달&갱신' }).click();
|
||||
await expect(page.getByLabel('메시지 입력')).toHaveValue('');
|
||||
await expect.poll(() => mutations.filter((entry) => entry.operation === 'messages.send').length).toBe(1);
|
||||
});
|
||||
|
||||
test('redacts diplomacy for a low-permission general and preserves the failed-send error flow', async ({ page }) => {
|
||||
const mutations = await installFixture(page, {
|
||||
permission: 2,
|
||||
sendError: '공개 메세지를 보낼 수 없습니다.',
|
||||
});
|
||||
await openMessages(page, { width: 500, height: 900 });
|
||||
|
||||
const select = page.getByLabel('메시지 수신 대상');
|
||||
await expect(select.locator('option[value="9002"]')).toHaveCount(0);
|
||||
await expect(page.locator('.DiplomacyTalk')).toContainText('삭제된 메시지입니다');
|
||||
await expect(page.locator('.DiplomacyTalk')).not.toContainText('외교 메시지 본문');
|
||||
await expect(page.locator('.DiplomacyTalk .message-response button').first()).toBeDisabled();
|
||||
|
||||
await select.selectOption('9999');
|
||||
await page.getByLabel('메시지 입력').fill('차단될 메시지');
|
||||
await page.getByRole('button', { name: '서신전달&갱신' }).click();
|
||||
await expect(page.getByLabel('메시지 입력')).toHaveValue('');
|
||||
await expect(page.locator('.error')).toHaveText('공개 메세지를 보낼 수 없습니다.');
|
||||
await expect.poll(() => mutations.filter((entry) => entry.operation === 'messages.send').length).toBe(1);
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
import { expect, test, type Page, type Route } from '@playwright/test';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { dirname, extname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
|
||||
const imageRoot = resolve(repositoryRoot, '../../image');
|
||||
const artifactRoot = process.env.FRONTEND_PARITY_ARTIFACT_DIR;
|
||||
const gameUrl = `http://127.0.0.1:${process.env.FRONTEND_PARITY_GAME_PORT ?? '15102'}/che/inherit`;
|
||||
|
||||
const response = (data: unknown) => ({ result: { data } });
|
||||
|
||||
const operations = (route: Route): string[] => {
|
||||
const pathname = new URL(route.request().url()).pathname;
|
||||
return decodeURIComponent(pathname.slice(pathname.lastIndexOf('/trpc/') + 6)).split(',');
|
||||
};
|
||||
|
||||
const installImages = async (page: Page): Promise<void> => {
|
||||
await page.route('**/image/**', async (route) => {
|
||||
const relative = decodeURIComponent(new URL(route.request().url()).pathname).replace(/^\/image\//, '');
|
||||
for (const candidate of [
|
||||
resolve(imageRoot, relative),
|
||||
resolve(imageRoot, 'game', relative),
|
||||
resolve(imageRoot, 'icons', '22.jpg'),
|
||||
]) {
|
||||
try {
|
||||
const body = await readFile(candidate);
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: extname(candidate).toLowerCase() === '.png' ? 'image/png' : 'image/jpeg',
|
||||
body,
|
||||
});
|
||||
return;
|
||||
} catch {
|
||||
// 다음 공개 image root 후보를 확인한다.
|
||||
}
|
||||
}
|
||||
await route.abort('failed');
|
||||
});
|
||||
};
|
||||
|
||||
const statusFixture = {
|
||||
items: {
|
||||
previous: 12_000,
|
||||
lived_month: 240,
|
||||
max_domestic_critical: 80,
|
||||
active_action: 35,
|
||||
combat: 150,
|
||||
sabotage: 60,
|
||||
dex: 42,
|
||||
unifier: 0,
|
||||
tournament: 30,
|
||||
betting: 20,
|
||||
max_belong: 8,
|
||||
},
|
||||
totalPoint: 12_665,
|
||||
inheritConst: {
|
||||
minMonthToAllowInheritItem: 4,
|
||||
inheritBornSpecialPoint: 6000,
|
||||
inheritBornTurntimePoint: 2500,
|
||||
inheritBornCityPoint: 1000,
|
||||
inheritBornStatPoint: 1000,
|
||||
inheritItemUniqueMinPoint: 5000,
|
||||
inheritItemRandomPoint: 3000,
|
||||
inheritBuffPoints: [0, 200, 600, 1200, 2000, 3000],
|
||||
inheritSpecificSpecialPoint: 4000,
|
||||
inheritResetAttrPointBase: [1000, 1000, 2000, 3000],
|
||||
inheritCheckOwnerPoint: 1000,
|
||||
},
|
||||
buffLevels: {
|
||||
warAvoidRatio: 0,
|
||||
warCriticalRatio: 1,
|
||||
warMagicTrialProb: 0,
|
||||
domesticSuccessProb: 0,
|
||||
domesticFailProb: 0,
|
||||
warAvoidRatioOppose: 0,
|
||||
warCriticalRatioOppose: 0,
|
||||
warMagicTrialProbOppose: 0,
|
||||
},
|
||||
resetCosts: { resetSpecialWar: 1000, resetTurnTime: 1000 },
|
||||
resetLevels: { resetSpecialWar: 0, resetTurnTime: 0 },
|
||||
availableSpecialWar: [{ key: 'che_선봉', name: '선봉', info: '공격에 유리합니다.' }],
|
||||
availableUnique: [
|
||||
{
|
||||
key: 'che_무기_12_칠성검',
|
||||
name: '칠성검(+12)',
|
||||
rawName: '칠성검',
|
||||
info: '무력을 올려주는 유니크 무기입니다.',
|
||||
},
|
||||
],
|
||||
availableTargetGenerals: [{ id: 8, name: '조조' }],
|
||||
turnTimeZones: ['00:00'],
|
||||
isUnited: false,
|
||||
currentSpecialWar: 'che_선봉',
|
||||
currentStat: { leadership: 70, strength: 45, intel: 85 },
|
||||
};
|
||||
|
||||
const installFixture = async (page: Page, options: { failBuff?: boolean } = {}) => {
|
||||
let buffMutationCount = 0;
|
||||
await installImages(page);
|
||||
await page.addInitScript(() => {
|
||||
window.localStorage.setItem('sammo-game-token', 'ga_inherit-visual-token');
|
||||
window.localStorage.setItem('sammo-game-profile', 'che');
|
||||
});
|
||||
await page.route('**/che/api/trpc/**', async (route) => {
|
||||
const names = operations(route);
|
||||
if (options.failBuff && names.includes('inherit.buyHiddenBuff')) {
|
||||
await route.fulfill({
|
||||
status: 500,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { message: '의도한 유산 구입 오류' } }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const result = names.map((name) => {
|
||||
if (name === 'inherit.getStatus') return response(statusFixture);
|
||||
if (name === 'lobby.info') {
|
||||
return response({
|
||||
profile: { id: 'che', scenario: 'default', name: '체섭' },
|
||||
world: { year: 200, month: 4 },
|
||||
myGeneral: { id: 7, name: '유비', nationId: 1 },
|
||||
});
|
||||
}
|
||||
if (name === 'inherit.getLogs') {
|
||||
return response([
|
||||
{
|
||||
id: 2,
|
||||
year: 200,
|
||||
month: 4,
|
||||
text: '1000 포인트로 장수 소유자 확인',
|
||||
createdAt: '2026-07-26T00:00:00.000Z',
|
||||
},
|
||||
]);
|
||||
}
|
||||
if (name === 'join.getConfig') {
|
||||
return response({ rules: { stat: { total: 200, min: 10, max: 100 } } });
|
||||
}
|
||||
if (name === 'inherit.buyHiddenBuff') {
|
||||
buffMutationCount += 1;
|
||||
return response({ ok: true, remainPoint: 11_800 });
|
||||
}
|
||||
throw new Error(`Unhandled inheritance fixture operation: ${name}`);
|
||||
});
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(result),
|
||||
});
|
||||
});
|
||||
return { buffMutationCount: () => buffMutationCount };
|
||||
};
|
||||
|
||||
test.describe('inheritance management legacy parity', () => {
|
||||
test('matches the ref 1000px grid and computed styles on desktop and mobile', async ({ page }) => {
|
||||
await installFixture(page);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.goto(gameUrl);
|
||||
await expect(page.locator('#container')).toBeVisible();
|
||||
await expect(page.locator('#specific-unique')).toHaveValue('che_무기_12_칠성검');
|
||||
|
||||
const desktop = await page.evaluate(() => {
|
||||
const rect = (selector: string) => {
|
||||
const box = document.querySelector<HTMLElement>(selector)!.getBoundingClientRect();
|
||||
return { x: box.x, width: box.width };
|
||||
};
|
||||
const container = getComputedStyle(document.querySelector<HTMLElement>('#container')!);
|
||||
const title = getComputedStyle(document.querySelector<HTMLElement>('.section-title')!);
|
||||
const button = getComputedStyle(document.querySelector<HTMLElement>('.buy-button')!);
|
||||
return {
|
||||
container: rect('#container'),
|
||||
firstPoint: rect('#inherit_sum'),
|
||||
fontFamily: container.fontFamily,
|
||||
fontSize: container.fontSize,
|
||||
backgroundImage: container.backgroundImage,
|
||||
titleBackgroundImage: title.backgroundImage,
|
||||
buttonBackground: button.backgroundColor,
|
||||
};
|
||||
});
|
||||
|
||||
expect(desktop.container.width).toBe(1000);
|
||||
expect(desktop.container.x).toBe(140);
|
||||
expect(desktop.firstPoint.width).toBeCloseTo(327.3, 0);
|
||||
expect(desktop.fontFamily).toContain('Pretendard');
|
||||
expect(desktop.fontSize).toBe('14px');
|
||||
expect(desktop.backgroundImage).toContain('back_walnut.jpg');
|
||||
expect(desktop.titleBackgroundImage).toContain('back_green.jpg');
|
||||
|
||||
const buyButton = page.locator('.buy-button').first();
|
||||
const beforeHover = await buyButton.evaluate((element) => getComputedStyle(element).backgroundColor);
|
||||
await buyButton.hover();
|
||||
const afterHover = await buyButton.evaluate((element) => getComputedStyle(element).backgroundColor);
|
||||
expect(afterHover).not.toBe(beforeHover);
|
||||
await buyButton.focus();
|
||||
await expect(buyButton).toBeFocused();
|
||||
|
||||
if (artifactRoot) {
|
||||
await page.screenshot({ path: resolve(artifactRoot, 'inherit-core-desktop.png'), fullPage: true });
|
||||
}
|
||||
|
||||
await page.setViewportSize({ width: 500, height: 900 });
|
||||
await page.reload();
|
||||
await expect(page.locator('#container')).toBeVisible();
|
||||
const mobile = await page.evaluate(() => {
|
||||
const container = document.querySelector<HTMLElement>('#container')!.getBoundingClientRect();
|
||||
const first = document.querySelector<HTMLElement>('#inherit_sum')!.getBoundingClientRect();
|
||||
const second = document.querySelector<HTMLElement>('#inherit_previous')!.getBoundingClientRect();
|
||||
return {
|
||||
containerWidth: container.width,
|
||||
firstWidth: first.width,
|
||||
stacked: second.y > first.y,
|
||||
};
|
||||
});
|
||||
expect(mobile.containerWidth).toBe(500);
|
||||
expect(mobile.firstWidth).toBeCloseTo(482, 0);
|
||||
expect(mobile.stacked).toBe(true);
|
||||
});
|
||||
|
||||
test('submits a legacy buff purchase and refreshes status and logs', async ({ page }) => {
|
||||
const fixture = await installFixture(page);
|
||||
page.on('dialog', (dialog) => dialog.accept());
|
||||
await page.goto(gameUrl);
|
||||
await page.locator('#buff-warAvoidRatio').fill('1');
|
||||
await page.locator('#buff-warAvoidRatio').locator('xpath=../..').getByRole('button', { name: '구입' }).click();
|
||||
await expect.poll(fixture.buffMutationCount).toBe(1);
|
||||
await expect(page.locator('#inherit_previous_value')).toHaveValue('12,000');
|
||||
});
|
||||
|
||||
test('keeps controls usable and renders an API mutation error', async ({ page }) => {
|
||||
await installFixture(page, { failBuff: true });
|
||||
page.on('dialog', (dialog) => dialog.accept());
|
||||
await page.goto(gameUrl);
|
||||
await page.locator('#buff-warAvoidRatio').fill('1');
|
||||
await page.locator('#buff-warAvoidRatio').locator('xpath=../..').getByRole('button', { name: '구입' }).click();
|
||||
await expect(page.locator('[role="alert"]')).toBeVisible();
|
||||
await expect(page.locator('#buff-warAvoidRatio')).toHaveValue('1');
|
||||
await expect(page.locator('#buff-warAvoidRatio')).toBeEnabled();
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { resolve } from 'node:path';
|
||||
import { canonicalFrontendFixture as fixture } from './fixtures/canonical';
|
||||
|
||||
const artifactRoot = process.env.FRONTEND_PARITY_ARTIFACT_DIR;
|
||||
const gamePort = process.env.FRONTEND_PARITY_GAME_PORT ?? '15102';
|
||||
const response = (data: unknown) => ({ result: { data } });
|
||||
|
||||
const operationNames = (route: Route): string[] => {
|
||||
@@ -90,6 +91,7 @@ const messageBundle = (visible: boolean, canRespondDiplomacy = true) => ({
|
||||
sequence: visible ? diplomacyMessage.id : -1,
|
||||
nationId: 1,
|
||||
generalName: general.name,
|
||||
permission: canRespondDiplomacy ? 4 : 2,
|
||||
canRespondDiplomacy,
|
||||
latestRead: { diplomacy: 0, private: 0 },
|
||||
});
|
||||
@@ -131,6 +133,9 @@ const installFixture = async (
|
||||
if (operation === 'messages.getRecent') {
|
||||
return response(messageBundle(visible, options.canRespondDiplomacy));
|
||||
}
|
||||
if (operation === 'messages.getContacts') return response({ nation: [] });
|
||||
if (operation === 'board.getAccess') return response({ canMeeting: true, canSecret: true });
|
||||
if (operation === 'tournament.getState') return response({ stage: 0 });
|
||||
if (operation === 'messages.respond') {
|
||||
mutations.push({ operation, body: requestBody });
|
||||
if (options.acceptResponse) {
|
||||
@@ -151,9 +156,9 @@ const installFixture = async (
|
||||
};
|
||||
|
||||
const openDiplomacyTab = async (page: Page) => {
|
||||
await page.goto('http://127.0.0.1:15102/che/');
|
||||
await page.goto(`http://127.0.0.1:${gamePort}/che/`);
|
||||
await expect(page.getByRole('heading', { name: '전장 현황' })).toBeVisible();
|
||||
await page.getByRole('button', { name: '외교', exact: true }).last().click();
|
||||
await expect(page.locator('.DiplomacyTalk')).toBeVisible();
|
||||
await expect(page.getByText(diplomacyMessage.text)).toBeVisible();
|
||||
};
|
||||
|
||||
@@ -186,16 +191,16 @@ test.describe('instant diplomacy response UI', () => {
|
||||
});
|
||||
|
||||
expect(geometry.buttons).toHaveLength(2);
|
||||
expect(geometry.buttons[1]!.x - (geometry.buttons[0]!.x + geometry.buttons[0]!.width)).toBeCloseTo(4, 0);
|
||||
expect(geometry.buttons[1]!.x - (geometry.buttons[0]!.x + geometry.buttons[0]!.width)).toBeCloseTo(0, 0);
|
||||
expect(geometry.buttons[0]).toMatchObject({
|
||||
color: 'rgb(143, 209, 143)',
|
||||
fontSize: '11.2px',
|
||||
color: 'rgb(255, 255, 255)',
|
||||
fontSize: '12.5px',
|
||||
borderWidth: '1px',
|
||||
cursor: 'pointer',
|
||||
});
|
||||
expect(geometry.buttons[1]).toMatchObject({
|
||||
color: 'rgb(224, 154, 154)',
|
||||
fontSize: '11.2px',
|
||||
color: 'rgb(255, 255, 255)',
|
||||
fontSize: '12.5px',
|
||||
borderWidth: '1px',
|
||||
cursor: 'pointer',
|
||||
});
|
||||
@@ -234,18 +239,17 @@ test.describe('instant diplomacy response UI', () => {
|
||||
test('keeps the message and exposes a rejected response on mobile Chromium', async ({ page }) => {
|
||||
const mutations = await installFixture(page, { acceptResponse: false });
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.goto('http://127.0.0.1:15102/che/');
|
||||
await page.goto(`http://127.0.0.1:${gamePort}/che/`);
|
||||
await expect(page.getByRole('heading', { name: '전장 현황' })).toBeVisible();
|
||||
await page.getByRole('button', { name: '메시지', exact: true }).click();
|
||||
await page.getByRole('button', { name: '외교', exact: true }).click();
|
||||
|
||||
const responseRow = page.locator('.message-response');
|
||||
await expect(responseRow).toBeVisible();
|
||||
const itemWidth = await page
|
||||
.locator('.message-item')
|
||||
.locator('.DiplomacyTalk .msg-plate')
|
||||
.evaluate((element) => element.getBoundingClientRect().width);
|
||||
expect(itemWidth).toBeGreaterThan(320);
|
||||
expect(itemWidth).toBeLessThanOrEqual(342);
|
||||
expect(itemWidth).toBeGreaterThanOrEqual(389);
|
||||
expect(itemWidth).toBeLessThanOrEqual(390);
|
||||
|
||||
page.once('dialog', async (dialog) => {
|
||||
expect(dialog.message()).toBe('거절하시겠습니까?');
|
||||
@@ -272,10 +276,9 @@ test.describe('instant diplomacy response UI', () => {
|
||||
canRespondDiplomacy: false,
|
||||
});
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.goto('http://127.0.0.1:15102/che/');
|
||||
await page.goto(`http://127.0.0.1:${gamePort}/che/`);
|
||||
await expect(page.getByRole('heading', { name: '전장 현황' })).toBeVisible();
|
||||
await page.getByRole('button', { name: '메시지', exact: true }).click();
|
||||
await page.getByRole('button', { name: '외교', exact: true }).click();
|
||||
|
||||
const accept = page.locator('.message-response').getByRole('button', { name: '수락' });
|
||||
await expect(accept).toBeDisabled();
|
||||
@@ -284,7 +287,7 @@ test.describe('instant diplomacy response UI', () => {
|
||||
const style = getComputedStyle(element);
|
||||
return { cursor: style.cursor, opacity: style.opacity };
|
||||
})
|
||||
).toEqual({ cursor: 'not-allowed', opacity: '0.5' });
|
||||
).toEqual({ cursor: 'not-allowed', opacity: '0.65' });
|
||||
await accept.click({ force: true });
|
||||
expect(mutations).toHaveLength(0);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
import { chromium } from '@playwright/test';
|
||||
|
||||
const baseUrl = process.env.REF_NATION_BETTING_URL ?? 'https://dev-sam-ref.hided.net/sam/';
|
||||
const staticBaseUrl = process.env.REF_NATION_BETTING_STATIC_BASE_URL;
|
||||
const username = process.env.REF_NATION_BETTING_USER ?? 'refuser1';
|
||||
const passwordFile = process.env.REF_NATION_BETTING_PASSWORD_FILE;
|
||||
const artifactRoot = resolve(process.env.REF_NATION_BETTING_ARTIFACT_DIR ?? 'test-results/reference-nation-betting');
|
||||
|
||||
if (!staticBaseUrl && !passwordFile) {
|
||||
throw new Error('REF_NATION_BETTING_PASSWORD_FILE is required.');
|
||||
}
|
||||
|
||||
const password = passwordFile ? (await readFile(passwordFile, 'utf8')).trim() : '';
|
||||
|
||||
const bettingList = {
|
||||
result: true,
|
||||
bettingList: {
|
||||
7: {
|
||||
id: 7,
|
||||
type: 'bettingNation',
|
||||
name: '천통국 예상',
|
||||
finished: false,
|
||||
selectCnt: 2,
|
||||
isExclusive: false,
|
||||
reqInheritancePoint: true,
|
||||
openYearMonth: 2316,
|
||||
closeYearMonth: 2340,
|
||||
winner: null,
|
||||
totalAmount: 800,
|
||||
},
|
||||
},
|
||||
year: 193,
|
||||
month: 1,
|
||||
};
|
||||
|
||||
const bettingDetail = {
|
||||
result: true,
|
||||
bettingInfo: {
|
||||
id: 7,
|
||||
type: 'bettingNation',
|
||||
name: '천통국 예상',
|
||||
finished: false,
|
||||
selectCnt: 2,
|
||||
isExclusive: false,
|
||||
reqInheritancePoint: true,
|
||||
openYearMonth: 2316,
|
||||
closeYearMonth: 2340,
|
||||
candidates: [
|
||||
{ title: '촉', info: '국력: 1200<br>장수 수: 8<br>도시 수: 5', isHtml: true },
|
||||
{ title: '위', info: '국력: 1100<br>장수 수: 7<br>도시 수: 4', isHtml: true },
|
||||
{ title: '오', info: '국력: 900<br>장수 수: 6<br>도시 수: 3', isHtml: true },
|
||||
{ title: '연', info: '국력: 700<br>장수 수: 5<br>도시 수: 2', isHtml: true },
|
||||
{ title: '양', info: '국력: 650<br>장수 수: 4<br>도시 수: 2', isHtml: true },
|
||||
{ title: '형', info: '국력: 600<br>장수 수: 3<br>도시 수: 1', isHtml: true },
|
||||
],
|
||||
winner: null,
|
||||
},
|
||||
bettingDetail: [
|
||||
['[-1]', 500],
|
||||
['[0,1]', 200],
|
||||
['[1,2]', 100],
|
||||
],
|
||||
myBetting: [['[0,1]', 50]],
|
||||
remainPoint: 1200,
|
||||
year: 193,
|
||||
month: 1,
|
||||
};
|
||||
|
||||
const login = async (context, page) => {
|
||||
await page.goto(baseUrl, { waitUntil: 'networkidle', timeout: 60_000 });
|
||||
const globalSalt = await page.locator('#global_salt').inputValue();
|
||||
// The reference entrance polls install status and can keep the PHP session
|
||||
// occupied. Leave it before the login request so the session lock is free.
|
||||
await page.goto('about:blank');
|
||||
await context.clearCookies();
|
||||
const passwordHash = createHash('sha512')
|
||||
.update(globalSalt + password + globalSalt)
|
||||
.digest('hex');
|
||||
const response = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), {
|
||||
data: { username, password: passwordHash },
|
||||
timeout: 60_000,
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok() || result.result !== true) {
|
||||
throw new Error('Reference login failed.');
|
||||
}
|
||||
};
|
||||
|
||||
const installBettingFixture = async (page) => {
|
||||
await page.route('**/api.php*', async (route) => {
|
||||
const path = new URL(route.request().url()).searchParams.get('path');
|
||||
if (path === 'Betting/GetBettingList') {
|
||||
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(bettingList) });
|
||||
return;
|
||||
}
|
||||
if (path === 'Betting/GetBettingDetail') {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(bettingDetail),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await route.continue();
|
||||
});
|
||||
};
|
||||
|
||||
const mountStaticReference = async (page) => {
|
||||
const hweUrl = new URL('hwe/', staticBaseUrl);
|
||||
const assetUrl = new URL('dist_js/hwe_dynamic/vue/', staticBaseUrl);
|
||||
await page.setContent(
|
||||
`<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=500">
|
||||
<base href="${hweUrl}">
|
||||
<link rel="stylesheet" href="${new URL('d_shared/common.css', hweUrl)}">
|
||||
<link rel="stylesheet" href="${new URL('vendors.css', assetUrl)}">
|
||||
<link rel="stylesheet" href="${new URL('common_ts.css', assetUrl)}">
|
||||
<link rel="stylesheet" href="${new URL('bootstrap.css', assetUrl)}">
|
||||
<link rel="stylesheet" href="${new URL('v_nationBetting.css', assetUrl)}">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script src="${new URL('d_shared/common_path.js', hweUrl)}"></script>
|
||||
<script src="${new URL('vendors.js', assetUrl)}"></script>
|
||||
<script src="${new URL('common_ts.js', assetUrl)}"></script>
|
||||
<script src="${new URL('bootstrap.js', assetUrl)}"></script>
|
||||
<script src="${new URL('v_nationBetting.js', assetUrl)}"></script>
|
||||
</body>
|
||||
</html>`,
|
||||
{ waitUntil: 'networkidle' }
|
||||
);
|
||||
};
|
||||
|
||||
const measure = async (browser, viewport) => {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: viewport.width, height: viewport.height },
|
||||
deviceScaleFactor: 1,
|
||||
colorScheme: 'dark',
|
||||
locale: 'ko-KR',
|
||||
timezoneId: 'UTC',
|
||||
ignoreHTTPSErrors: true,
|
||||
});
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
await installBettingFixture(page);
|
||||
if (staticBaseUrl) {
|
||||
await mountStaticReference(page);
|
||||
} else {
|
||||
await login(context, page);
|
||||
await page.goto(new URL('hwe/v_nationBetting.php', baseUrl).toString(), {
|
||||
waitUntil: 'networkidle',
|
||||
timeout: 60_000,
|
||||
});
|
||||
}
|
||||
await page.locator('.bettingItem').click();
|
||||
await page.locator('.bettingCandidate').first().waitFor({ state: 'visible' });
|
||||
|
||||
const geometry = await page.locator('#container').evaluate((container) => {
|
||||
const rect = (element) => {
|
||||
const value = element.getBoundingClientRect();
|
||||
return { x: value.x, y: value.y, width: value.width, height: value.height };
|
||||
};
|
||||
const cards = Array.from(container.querySelectorAll('.bettingCandidate'));
|
||||
const firstCard = cards[0];
|
||||
const cardStyle = getComputedStyle(firstCard);
|
||||
const titleStyle = getComputedStyle(firstCard.querySelector('.title'));
|
||||
const optionalRect = (selector) => {
|
||||
const element = container.querySelector(selector);
|
||||
return element ? rect(element) : null;
|
||||
};
|
||||
return {
|
||||
container: rect(container),
|
||||
topBar: rect(container.querySelector('.back_bar')),
|
||||
candidateCells: Array.from(container.querySelectorAll('.bettingCandidates > div')).map(rect),
|
||||
candidates: cards.map(rect),
|
||||
bettingForm: optionalRect('.bettingCandidates + .row'),
|
||||
payoutTable: optionalRect('.bettingCandidates + .row + div'),
|
||||
bettingList: optionalRect('.bettingList'),
|
||||
bottomBar: optionalRect('.bottom_bar, .bg0[style]'),
|
||||
cardStyle: {
|
||||
borderWidth: cardStyle.borderWidth,
|
||||
borderRadius: cardStyle.borderRadius,
|
||||
cursor: cardStyle.cursor,
|
||||
fontSize: cardStyle.fontSize,
|
||||
lineHeight: cardStyle.lineHeight,
|
||||
},
|
||||
titleStyle: {
|
||||
fontWeight: titleStyle.fontWeight,
|
||||
textAlign: titleStyle.textAlign,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
await page.locator('.bettingCandidate').first().click();
|
||||
const pickedStyle = await page
|
||||
.locator('.bettingCandidate')
|
||||
.first()
|
||||
.evaluate((candidate) => {
|
||||
const style = getComputedStyle(candidate);
|
||||
return {
|
||||
borderColor: style.borderColor,
|
||||
outlineWidth: style.outlineWidth,
|
||||
titleWeight: getComputedStyle(candidate.querySelector('.title')).fontWeight,
|
||||
};
|
||||
});
|
||||
|
||||
const screenshotPath = resolve(artifactRoot, `nation-betting-ref-${viewport.name}.png`);
|
||||
await page.screenshot({ path: screenshotPath, fullPage: true, animations: 'disabled' });
|
||||
return { geometry, pickedStyle, screenshotPath };
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
};
|
||||
|
||||
await mkdir(artifactRoot, { recursive: true });
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
try {
|
||||
const result = {};
|
||||
for (const viewport of [
|
||||
{ name: 'desktop', width: 1280, height: 900 },
|
||||
{ name: 'mobile', width: 500, height: 900 },
|
||||
]) {
|
||||
result[viewport.name] = await measure(browser, viewport);
|
||||
}
|
||||
const outputPath = resolve(artifactRoot, 'computed-dom.json');
|
||||
await writeFile(outputPath, `${JSON.stringify(result, null, 2)}\n`);
|
||||
process.stdout.write(`${JSON.stringify({ ok: true, artifactRoot, outputPath })}\n`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -13,8 +13,10 @@ export default defineConfig({
|
||||
'visual-parity.spec.ts',
|
||||
'public-gaps.spec.ts',
|
||||
'instant-diplomacy-message.spec.ts',
|
||||
'ingame-message-parity.spec.ts',
|
||||
'tournament-betting.spec.ts',
|
||||
'dynasty-parity.spec.ts',
|
||||
'inheritance-management.spec.ts',
|
||||
],
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
|
||||
@@ -4,10 +4,7 @@ import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
|
||||
const imageRoots = [
|
||||
resolve(repositoryRoot, '../image/game'),
|
||||
resolve(repositoryRoot, '../../image/game'),
|
||||
];
|
||||
const imageRoots = [resolve(repositoryRoot, '../image/game'), resolve(repositoryRoot, '../../image/game')];
|
||||
const artifactRoot = process.env.FRONTEND_PARITY_ARTIFACT_DIR;
|
||||
|
||||
const response = (data: unknown) => ({ result: { data } });
|
||||
@@ -214,12 +211,39 @@ test('nation betting matches the legacy desktop geometry and preserves a failed
|
||||
const geometry = await page.locator('#nation-betting-container').evaluate((container) => {
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const bar = container.querySelector<HTMLElement>('.legacy-top-bar')!.getBoundingClientRect();
|
||||
const detail = container.querySelector<HTMLElement>('.betting-detail')!;
|
||||
const detailRect = detail.getBoundingClientRect();
|
||||
const candidateRowElement = container.querySelector<HTMLElement>('.betting-candidates')!;
|
||||
const candidateRow = candidateRowElement.getBoundingClientRect();
|
||||
const candidateCells = Array.from(container.querySelectorAll<HTMLElement>('.betting-candidate-cell'));
|
||||
const cards = Array.from(container.querySelectorAll<HTMLElement>('.betting-candidate'));
|
||||
const cardStyle = getComputedStyle(cards[0]!);
|
||||
const optionalRect = (selector: string) => {
|
||||
const element = container.querySelector<HTMLElement>(selector);
|
||||
if (!element) return null;
|
||||
const rect = element.getBoundingClientRect();
|
||||
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
|
||||
};
|
||||
return {
|
||||
container: { x: containerRect.x, width: containerRect.width },
|
||||
container: { x: containerRect.x, width: containerRect.width, height: containerRect.height },
|
||||
bar: { width: bar.width, height: bar.height },
|
||||
cardWidths: cards.map((card) => card.getBoundingClientRect().width),
|
||||
detail: { x: detailRect.x, width: detailRect.width },
|
||||
candidateRow: {
|
||||
x: candidateRow.x,
|
||||
width: candidateRow.width,
|
||||
},
|
||||
candidateCells: candidateCells.map((cell) => {
|
||||
const rect = cell.getBoundingClientRect();
|
||||
return { x: rect.x, width: rect.width };
|
||||
}),
|
||||
cards: cards.map((card) => {
|
||||
const rect = card.getBoundingClientRect();
|
||||
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
|
||||
}),
|
||||
bettingForm: optionalRect('.betting-form'),
|
||||
payoutTable: optionalRect('.payout-table'),
|
||||
bettingList: optionalRect('.betting-list'),
|
||||
bottomBar: optionalRect('.betting-footer'),
|
||||
cardStyle: {
|
||||
borderWidth: cardStyle.borderWidth,
|
||||
borderRadius: cardStyle.borderRadius,
|
||||
@@ -229,24 +253,43 @@ test('nation betting matches the legacy desktop geometry and preserves a failed
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
expect(geometry.container).toEqual({ x: 140, width: 1000 });
|
||||
expect(geometry.container).toEqual({ x: 140, width: 1000, height: 435 });
|
||||
expect(geometry.bar).toEqual({ width: 1000, height: 32 });
|
||||
expect(geometry.cardWidths.every((width) => Math.abs(width - 162) < 1)).toBe(true);
|
||||
expect(geometry.detail).toEqual({ x: 140, width: 1000 });
|
||||
expect(geometry.candidateRow).toEqual({ x: 138.25, width: 1003.5 });
|
||||
expect(geometry.candidateCells.map(({ width }) => width)).toEqual(Array(6).fill(167.25));
|
||||
expect(geometry.cards.map(({ width }) => width)).toEqual(Array(6).fill(163.75));
|
||||
expect(geometry.cards.map(({ height }) => height)).toEqual(Array(6).fill(143));
|
||||
expect(geometry.cards.map(({ y }) => y)).toEqual(Array(6).fill(53));
|
||||
expect(geometry.bettingForm).toEqual({ x: 140, y: 196, width: 1000, height: 35.5 });
|
||||
expect(geometry.payoutTable).toEqual({ x: 140, y: 231.5, width: 1000, height: 85 });
|
||||
expect(geometry.bettingList).toEqual({ x: 140, y: 330.5, width: 1000, height: 45.5 });
|
||||
expect(geometry.bottomBar).toEqual({ x: 140, y: 379.5, width: 1000, height: 55.5 });
|
||||
expect(geometry.cardStyle).toEqual({
|
||||
borderWidth: '1px',
|
||||
borderRadius: '7px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
lineHeight: '18.2px',
|
||||
lineHeight: '21px',
|
||||
});
|
||||
await expect(page.locator('.legacy-top-bar .legacy-nav-button')).toHaveCount(1);
|
||||
await expect(page.locator('.payout-row:not(.payout-head)').first().locator('div').nth(2)).toHaveText(
|
||||
'(50 -> 100.0)'
|
||||
);
|
||||
|
||||
await page.locator('.betting-candidate').nth(0).click();
|
||||
await page.locator('.betting-candidate').nth(1).click();
|
||||
const pickedStyle = await page.locator('.betting-candidate').first().evaluate((candidate) => {
|
||||
const style = getComputedStyle(candidate);
|
||||
return { borderColor: style.borderColor, outlineWidth: style.outlineWidth, titleWeight: getComputedStyle(candidate.querySelector('.candidate-title')!).fontWeight };
|
||||
});
|
||||
const pickedStyle = await page
|
||||
.locator('.betting-candidate')
|
||||
.first()
|
||||
.evaluate((candidate) => {
|
||||
const style = getComputedStyle(candidate);
|
||||
return {
|
||||
borderColor: style.borderColor,
|
||||
outlineWidth: style.outlineWidth,
|
||||
titleWeight: getComputedStyle(candidate.querySelector('.candidate-title')!).fontWeight,
|
||||
};
|
||||
});
|
||||
expect(pickedStyle.borderColor).toBe('rgb(255, 255, 255)');
|
||||
// Chromium snaps the legacy 1.5px CSS outline to one device pixel at DSF 1.
|
||||
expect(pickedStyle.outlineWidth).toBe('1px');
|
||||
@@ -281,6 +324,7 @@ test('nation betting keeps the legacy 500px three-column mobile contract', async
|
||||
return {
|
||||
x: rect.x,
|
||||
width: rect.width,
|
||||
firstX: cards[0]!.getBoundingClientRect().x,
|
||||
firstWidth: cards[0]!.getBoundingClientRect().width,
|
||||
fourthY: cards[3]!.getBoundingClientRect().y,
|
||||
firstY: cards[0]!.getBoundingClientRect().y,
|
||||
@@ -288,7 +332,8 @@ test('nation betting keeps the legacy 500px three-column mobile contract', async
|
||||
});
|
||||
expect(geometry.x).toBe(0);
|
||||
expect(geometry.width).toBe(500);
|
||||
expect(geometry.firstWidth).toBeCloseTo(161.328125, 3);
|
||||
expect(geometry.firstX).toBe(0);
|
||||
expect(geometry.firstWidth).toBe(164.328125);
|
||||
expect(geometry.fourthY).toBeGreaterThan(geometry.firstY);
|
||||
|
||||
if (artifactRoot) {
|
||||
@@ -325,17 +370,7 @@ test('NPC list matches the legacy table geometry, sorting and error retention',
|
||||
expect(geometry.tableWidth).toBe(1000);
|
||||
// The legacy width attributes total 974px; Chromium proportionally expands them into the 1000px table.
|
||||
expect(geometry.headerWidths).toEqual([
|
||||
104.609375,
|
||||
104.609375,
|
||||
69.734375,
|
||||
121.015625,
|
||||
69.734375,
|
||||
90.25,
|
||||
69.734375,
|
||||
69.734375,
|
||||
69.734375,
|
||||
69.734375,
|
||||
80,
|
||||
104.609375, 104.609375, 69.734375, 121.015625, 69.734375, 90.25, 69.734375, 69.734375, 69.734375, 69.734375, 80,
|
||||
80.109375,
|
||||
]);
|
||||
expect(geometry.headerStyle).toEqual({
|
||||
@@ -346,7 +381,10 @@ test('NPC list matches the legacy table geometry, sorting and error retention',
|
||||
lineHeight: '18.2px',
|
||||
});
|
||||
await expect(page.locator('.npc-table tbody tr').first()).toContainText('관우');
|
||||
await expect(page.locator('.npc-table tbody tr').first().locator('td').first()).toHaveCSS('color', 'rgb(135, 206, 235)');
|
||||
await expect(page.locator('.npc-table tbody tr').first().locator('td').first()).toHaveCSS(
|
||||
'color',
|
||||
'rgb(135, 206, 235)'
|
||||
);
|
||||
const personality = page.locator('.npc-table tbody tr').first().locator('.trait-tooltip').first();
|
||||
await personality.hover();
|
||||
await expect(personality.getByRole('tooltip')).toBeVisible();
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { chromium } from '@playwright/test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const baseUrl = process.env.REF_PARITY_URL ?? 'http://127.0.0.1:3400/sam/';
|
||||
const username = process.env.REF_PARITY_USER ?? 'refadmin';
|
||||
const passwordFile = process.env.REF_PARITY_PASSWORD_FILE;
|
||||
const artifactRoot = resolve(process.env.REF_PARITY_ARTIFACT_DIR ?? 'test-results/reference-current-city');
|
||||
|
||||
if (!passwordFile) {
|
||||
throw new Error('REF_PARITY_PASSWORD_FILE is required.');
|
||||
}
|
||||
|
||||
const password = (await readFile(passwordFile, 'utf8')).trim();
|
||||
await mkdir(artifactRoot, { recursive: true });
|
||||
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
try {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 1200, height: 900 },
|
||||
deviceScaleFactor: 1,
|
||||
locale: 'ko-KR',
|
||||
timezoneId: 'Asia/Seoul',
|
||||
colorScheme: 'dark',
|
||||
});
|
||||
const page = await context.newPage();
|
||||
await page.goto(baseUrl, { waitUntil: 'networkidle' });
|
||||
const globalSalt = await page.locator('#global_salt').inputValue();
|
||||
const passwordHash = createHash('sha512')
|
||||
.update(globalSalt + password + globalSalt)
|
||||
.digest('hex');
|
||||
const loginResponse = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), {
|
||||
data: { username, password: passwordHash },
|
||||
});
|
||||
const loginResult = await loginResponse.json();
|
||||
if (!loginResponse.ok() || loginResult.result !== true) {
|
||||
throw new Error('Reference login failed.');
|
||||
}
|
||||
|
||||
await page.goto(new URL('hwe/', baseUrl).toString(), { waitUntil: 'networkidle' });
|
||||
const mapCity = page.locator('a[href*="b_currentCity.php?citylist="]').first();
|
||||
const hasMapCity = await mapCity.isVisible({ timeout: 8_000 }).catch(() => false);
|
||||
let mapInteraction;
|
||||
if (hasMapCity) {
|
||||
mapInteraction = await mapCity.evaluate((element) => ({
|
||||
available: true,
|
||||
href: element.getAttribute('href'),
|
||||
cursor: getComputedStyle(element).cursor,
|
||||
rect: (() => {
|
||||
const box = element.getBoundingClientRect();
|
||||
return { x: box.x, y: box.y, width: box.width, height: box.height };
|
||||
})(),
|
||||
}));
|
||||
await mapCity.click();
|
||||
await page.waitForLoadState('networkidle');
|
||||
if (!page.url().includes('b_currentCity.php?citylist=')) {
|
||||
throw new Error(`Reference map click did not open current city: ${page.url()}`);
|
||||
}
|
||||
} else {
|
||||
mapInteraction = {
|
||||
available: false,
|
||||
pageUrl: page.url(),
|
||||
pageTitle: await page.title(),
|
||||
};
|
||||
await page.goto(new URL('hwe/b_currentCity.php', baseUrl).toString(), { waitUntil: 'networkidle' });
|
||||
}
|
||||
|
||||
const measurements = await page.evaluate(() => {
|
||||
const measure = (element) => {
|
||||
const box = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
rect: { x: box.x, y: box.y, width: box.width, height: box.height },
|
||||
style: {
|
||||
fontFamily: style.fontFamily,
|
||||
fontSize: style.fontSize,
|
||||
lineHeight: style.lineHeight,
|
||||
color: style.color,
|
||||
backgroundColor: style.backgroundColor,
|
||||
backgroundImage: style.backgroundImage,
|
||||
borderCollapse: style.borderCollapse,
|
||||
padding: style.padding,
|
||||
textAlign: style.textAlign,
|
||||
},
|
||||
};
|
||||
};
|
||||
const tables = [...document.querySelectorAll('table')];
|
||||
const selector = document.querySelector('#citySelector');
|
||||
const stats = tables.find((table) => table.textContent?.includes('90병장'));
|
||||
const generals = document.querySelector('#general_list')?.closest('table');
|
||||
const firstIcon = document.querySelector('.generalIcon');
|
||||
const title = stats?.querySelector('tr:first-child td');
|
||||
return {
|
||||
body: measure(document.body),
|
||||
tables: tables.map(measure),
|
||||
selector: selector ? measure(selector) : null,
|
||||
stats: stats ? measure(stats) : null,
|
||||
generals: generals ? measure(generals) : null,
|
||||
firstIcon: firstIcon
|
||||
? {
|
||||
...measure(firstIcon),
|
||||
naturalWidth: firstIcon.naturalWidth,
|
||||
naturalHeight: firstIcon.naturalHeight,
|
||||
}
|
||||
: null,
|
||||
title: title ? measure(title) : null,
|
||||
document: {
|
||||
width: document.documentElement.scrollWidth,
|
||||
height: document.documentElement.scrollHeight,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
await page.screenshot({
|
||||
path: resolve(artifactRoot, 'reference-current-city-desktop.png'),
|
||||
fullPage: true,
|
||||
animations: 'disabled',
|
||||
});
|
||||
await writeFile(
|
||||
resolve(artifactRoot, 'reference-current-city-computed-dom.json'),
|
||||
`${JSON.stringify({ mapInteraction, currentCity: measurements }, null, 2)}\n`
|
||||
);
|
||||
process.stdout.write(`${JSON.stringify({ ok: true, artifactRoot })}\n`);
|
||||
await context.close();
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { chromium } from '@playwright/test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const baseUrl = process.env.REF_GENERAL_URL ?? 'http://127.0.0.1:3400/sam/';
|
||||
const username = process.env.REF_GENERAL_USER ?? 'refuser1';
|
||||
const passwordFile = process.env.REF_GENERAL_PASSWORD_FILE;
|
||||
const artifactRoot = resolve(process.env.REF_GENERAL_ARTIFACT_DIR ?? 'test-results/reference-general-lists');
|
||||
if (!passwordFile) throw new Error('REF_GENERAL_PASSWORD_FILE is required.');
|
||||
const password = (await readFile(passwordFile, 'utf8')).trim();
|
||||
await mkdir(artifactRoot, { recursive: true });
|
||||
|
||||
const measure = async (page, selectors) =>
|
||||
page.evaluate((items) => {
|
||||
const result = {};
|
||||
for (const [name, selector] of Object.entries(items)) {
|
||||
const element = document.querySelector(selector);
|
||||
if (!element) {
|
||||
result[name] = null;
|
||||
continue;
|
||||
}
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
result[name] = {
|
||||
rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
||||
style: {
|
||||
fontFamily: style.fontFamily,
|
||||
fontSize: style.fontSize,
|
||||
borderCollapse: style.borderCollapse,
|
||||
backgroundImage: style.backgroundImage,
|
||||
color: style.color,
|
||||
},
|
||||
};
|
||||
}
|
||||
return { elements: result, documentWidth: document.documentElement.scrollWidth };
|
||||
}, selectors);
|
||||
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
try {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 1200, height: 900 },
|
||||
deviceScaleFactor: 1,
|
||||
locale: 'ko-KR',
|
||||
colorScheme: 'dark',
|
||||
});
|
||||
const page = await context.newPage();
|
||||
await page.goto(baseUrl, { waitUntil: 'networkidle' });
|
||||
const salt = await page.locator('#global_salt').inputValue();
|
||||
const passwordHash = createHash('sha512')
|
||||
.update(salt + password + salt)
|
||||
.digest('hex');
|
||||
const login = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), {
|
||||
data: { username, password: passwordHash },
|
||||
});
|
||||
const loginResult = await login.json();
|
||||
if (!login.ok() || loginResult.result !== true) throw new Error('Reference login failed.');
|
||||
|
||||
const output = {};
|
||||
for (const [name, path, selectors] of [
|
||||
[
|
||||
'generals',
|
||||
'hwe/b_myGenInfo.php',
|
||||
{
|
||||
body: 'body',
|
||||
title: 'body > table:first-of-type',
|
||||
list: 'body > table:nth-of-type(2)',
|
||||
firstRow: 'body > table:nth-of-type(2) tr:nth-child(2)',
|
||||
},
|
||||
],
|
||||
[
|
||||
'secret',
|
||||
'hwe/b_genList.php',
|
||||
{
|
||||
body: 'body',
|
||||
title: 'body > table:first-of-type',
|
||||
summary: 'body > table:nth-of-type(2)',
|
||||
list: '#general_list',
|
||||
firstRow: '#general_list tbody tr:first-child',
|
||||
},
|
||||
],
|
||||
]) {
|
||||
await page.goto(new URL(path, baseUrl).toString(), { waitUntil: 'networkidle' });
|
||||
output[name] = await measure(page, selectors);
|
||||
await page.screenshot({ path: resolve(artifactRoot, `ref-${name}.png`), fullPage: true });
|
||||
}
|
||||
await writeFile(resolve(artifactRoot, 'computed-dom.json'), `${JSON.stringify(output, null, 2)}\n`);
|
||||
process.stdout.write(`${JSON.stringify({ ok: true, artifactRoot, output })}\n`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { chromium } from '@playwright/test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const baseUrl = process.env.REF_MENU_URL ?? 'http://127.0.0.1:3400/sam/';
|
||||
const username = process.env.REF_MENU_USER ?? 'refuser1';
|
||||
const passwordFile = process.env.REF_MENU_PASSWORD_FILE;
|
||||
const artifactRoot = resolve(process.env.REF_MENU_ARTIFACT_DIR ?? 'test-results/reference-ingame-menus');
|
||||
|
||||
if (!passwordFile) {
|
||||
throw new Error('REF_MENU_PASSWORD_FILE is required.');
|
||||
}
|
||||
|
||||
const password = (await readFile(passwordFile, 'utf8')).trim();
|
||||
await mkdir(artifactRoot, { recursive: true });
|
||||
|
||||
const login = async (context, page) => {
|
||||
await page.goto(baseUrl, { waitUntil: 'networkidle' });
|
||||
const globalSalt = await page.locator('#global_salt').inputValue();
|
||||
const passwordHash = createHash('sha512')
|
||||
.update(globalSalt + password + globalSalt)
|
||||
.digest('hex');
|
||||
const response = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), {
|
||||
data: { username, password: passwordHash },
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok() || result.result !== true) {
|
||||
throw new Error('Reference login failed.');
|
||||
}
|
||||
};
|
||||
|
||||
const rectAndStyle = (element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
||||
style: {
|
||||
display: style.display,
|
||||
gridTemplateColumns: style.gridTemplateColumns,
|
||||
fontFamily: style.fontFamily,
|
||||
fontSize: style.fontSize,
|
||||
lineHeight: style.lineHeight,
|
||||
color: style.color,
|
||||
backgroundColor: style.backgroundColor,
|
||||
backgroundImage: style.backgroundImage,
|
||||
borderTopColor: style.borderTopColor,
|
||||
borderTopWidth: style.borderTopWidth,
|
||||
padding: style.padding,
|
||||
margin: style.margin,
|
||||
cursor: style.cursor,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const measure = async (page, selectors) =>
|
||||
page.evaluate(
|
||||
({ selectors, measureSource }) => {
|
||||
const measureElement = new Function(`return (${measureSource})`)();
|
||||
const result = {};
|
||||
for (const [name, selector] of Object.entries(selectors)) {
|
||||
const element = document.querySelector(selector);
|
||||
result[name] = element ? measureElement(element) : null;
|
||||
}
|
||||
return {
|
||||
elements: result,
|
||||
document: {
|
||||
width: document.documentElement.scrollWidth,
|
||||
height: document.documentElement.scrollHeight,
|
||||
},
|
||||
};
|
||||
},
|
||||
{ selectors, measureSource: rectAndStyle.toString() }
|
||||
);
|
||||
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
try {
|
||||
const output = {};
|
||||
for (const viewport of [
|
||||
{ name: 'desktop', width: 1000, height: 900 },
|
||||
{ name: 'mobile', width: 500, height: 900 },
|
||||
]) {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: viewport.width, height: viewport.height },
|
||||
deviceScaleFactor: 1,
|
||||
locale: 'ko-KR',
|
||||
timezoneId: 'Asia/Seoul',
|
||||
colorScheme: 'dark',
|
||||
});
|
||||
const page = await context.newPage();
|
||||
const consoleErrors = [];
|
||||
const failedResources = [];
|
||||
page.on('console', (message) => {
|
||||
if (message.type() === 'error') consoleErrors.push(message.text());
|
||||
});
|
||||
page.on('response', (response) => {
|
||||
if (response.status() >= 400) failedResources.push(`${response.status()} ${response.url()}`);
|
||||
});
|
||||
await login(context, page);
|
||||
await page.goto(new URL('hwe/', baseUrl).toString(), { waitUntil: 'networkidle' });
|
||||
|
||||
await page.goto(new URL('hwe/b_myPage.php', baseUrl).toString(), { waitUntil: 'networkidle' });
|
||||
await page.locator('#container').waitFor();
|
||||
const myPage = await measure(page, {
|
||||
body: 'body',
|
||||
container: '#container',
|
||||
title: '#container > .row:first-child',
|
||||
infoColumn: '#container > .row:nth-child(2) > .col:first-child',
|
||||
settingsColumn: '#container > .row:nth-child(2) > .col:nth-child(2)',
|
||||
saveButton: '#set_my_setting',
|
||||
firstSelect: 'select',
|
||||
customCss: '#custom_css',
|
||||
firstLogTitle: '#generalActionPlate',
|
||||
});
|
||||
await page.screenshot({ path: resolve(artifactRoot, `ref-my-page-${viewport.name}.png`), fullPage: true });
|
||||
|
||||
await page.goto(new URL('hwe/a_traffic.php', baseUrl).toString(), { waitUntil: 'networkidle' });
|
||||
const traffic = await measure(page, {
|
||||
body: 'body',
|
||||
title: 'body > table:first-of-type',
|
||||
chartLayout: 'body > table:nth-of-type(2)',
|
||||
refreshChart: 'body > table:nth-of-type(2) > tbody > tr > td:first-child > table',
|
||||
onlineChart: 'body > table:nth-of-type(2) > tbody > tr > td:nth-child(2) > table',
|
||||
firstBigBar: '.big_bar',
|
||||
suspectTable: 'body > table:nth-of-type(3)',
|
||||
});
|
||||
await page.screenshot({ path: resolve(artifactRoot, `ref-traffic-${viewport.name}.png`), fullPage: true });
|
||||
|
||||
await page.goto(new URL('hwe/a_npcList.php', baseUrl).toString(), { waitUntil: 'networkidle' });
|
||||
const npcList = await measure(page, {
|
||||
body: 'body',
|
||||
title: 'body > table:first-of-type',
|
||||
sortSelect: 'select[name="type"]',
|
||||
list: 'body > table:nth-of-type(2)',
|
||||
header: 'body > table:nth-of-type(2) tr:first-child',
|
||||
footer: 'body > table:nth-of-type(3)',
|
||||
});
|
||||
await page.screenshot({ path: resolve(artifactRoot, `ref-npc-list-${viewport.name}.png`), fullPage: true });
|
||||
|
||||
await page.goto(new URL('hwe/v_battleCenter.php', baseUrl).toString(), { waitUntil: 'networkidle' });
|
||||
try {
|
||||
await page.locator('#container').waitFor({ timeout: 10_000 });
|
||||
} catch {
|
||||
throw new Error(
|
||||
`Reference battle center failed to mount: ${JSON.stringify({
|
||||
url: page.url(),
|
||||
text: (await page.locator('body').innerText()).slice(0, 500),
|
||||
html: (await page.content()).slice(-1_000),
|
||||
consoleErrors,
|
||||
failedResources,
|
||||
})}`
|
||||
);
|
||||
}
|
||||
const battleCenter = await measure(page, {
|
||||
body: 'body',
|
||||
container: '#container',
|
||||
topBar: '#container > :first-child',
|
||||
selectorRow: '#container > .row:nth-child(2)',
|
||||
previousButton: '#container > .row:nth-child(2) button:first-child',
|
||||
firstSelect: '#container > .row:nth-child(2) select:first-of-type',
|
||||
generalCard: '.header-cell',
|
||||
firstLogHeader: '.header-cell:nth-of-type(1)',
|
||||
});
|
||||
await page.screenshot({
|
||||
path: resolve(artifactRoot, `ref-battle-center-${viewport.name}.png`),
|
||||
fullPage: true,
|
||||
});
|
||||
output[viewport.name] = { myPage, traffic, npcList, battleCenter };
|
||||
await context.close();
|
||||
}
|
||||
await writeFile(resolve(artifactRoot, 'computed-dom.json'), `${JSON.stringify(output, null, 2)}\n`);
|
||||
process.stdout.write(`${JSON.stringify({ ok: true, artifactRoot, viewports: Object.keys(output) })}\n`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile } from 'node:fs/promises';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
|
||||
import { chromium } from '@playwright/test';
|
||||
|
||||
const baseUrl = process.env.REF_MESSAGE_URL ?? 'http://127.0.0.1:3400/sam/';
|
||||
const username = process.env.REF_MESSAGE_USER ?? 'refuser1';
|
||||
const passwordFile = process.env.REF_MESSAGE_PASSWORD_FILE;
|
||||
const artifactRoot = process.env.REF_MESSAGE_ARTIFACT_DIR;
|
||||
|
||||
if (!passwordFile) {
|
||||
throw new Error('REF_MESSAGE_PASSWORD_FILE is required.');
|
||||
}
|
||||
|
||||
const password = (await readFile(passwordFile, 'utf8')).trim();
|
||||
|
||||
const login = async (context, page) => {
|
||||
await page.goto(baseUrl, { waitUntil: 'networkidle', timeout: 60_000 });
|
||||
const globalSalt = await page.locator('#global_salt').inputValue();
|
||||
const passwordHash = createHash('sha512')
|
||||
.update(globalSalt + password + globalSalt)
|
||||
.digest('hex');
|
||||
const response = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), {
|
||||
data: { username, password: passwordHash },
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok() || result.result !== true) {
|
||||
throw new Error('Reference login failed.');
|
||||
}
|
||||
};
|
||||
|
||||
const ensureGeneral = async (page) => {
|
||||
await page.goto(new URL('hwe/index.php', baseUrl).toString(), {
|
||||
waitUntil: 'networkidle',
|
||||
timeout: 60_000,
|
||||
});
|
||||
if (await page.locator('.MessagePanel').isVisible()) {
|
||||
return;
|
||||
}
|
||||
|
||||
await page.goto(new URL('hwe/v_join.php', baseUrl).toString(), {
|
||||
waitUntil: 'networkidle',
|
||||
timeout: 60_000,
|
||||
});
|
||||
const create = page.getByRole('button', { name: '장수 생성', exact: true });
|
||||
await create.waitFor({ state: 'visible', timeout: 30_000 });
|
||||
page.once('dialog', (dialog) => dialog.accept());
|
||||
await create.click();
|
||||
await page.locator('.MessagePanel').waitFor({ state: 'visible', timeout: 60_000 });
|
||||
};
|
||||
|
||||
const measure = async (browser, name, viewport) => {
|
||||
const context = await browser.newContext({
|
||||
viewport,
|
||||
deviceScaleFactor: 1,
|
||||
colorScheme: 'dark',
|
||||
locale: 'ko-KR',
|
||||
timezoneId: 'UTC',
|
||||
ignoreHTTPSErrors: true,
|
||||
});
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
await login(context, page);
|
||||
await ensureGeneral(page);
|
||||
await page.locator('.MessagePanel').waitFor({ state: 'visible', timeout: 30_000 });
|
||||
await page.locator('.BoardHeader').first().waitFor({ state: 'visible' });
|
||||
const marker = `computed-dom-${name}-${Date.now()}`;
|
||||
await page.locator('.MessageInputForm select').selectOption('9999');
|
||||
await page.locator('.MessageInputForm input').fill(marker);
|
||||
await page.getByRole('button', { name: '서신전달&갱신' }).click();
|
||||
await page.getByText(marker, { exact: true }).waitFor({ state: 'visible', timeout: 30_000 });
|
||||
|
||||
if (artifactRoot) {
|
||||
const path = resolve(artifactRoot, `message-ref-${name}.png`);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await page.locator('.MessagePanel').screenshot({
|
||||
path,
|
||||
animations: 'disabled',
|
||||
});
|
||||
}
|
||||
|
||||
const result = await page.evaluate(() => {
|
||||
const rect = (element) => {
|
||||
const box = element.getBoundingClientRect();
|
||||
return {
|
||||
x: box.x,
|
||||
y: box.y,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
};
|
||||
};
|
||||
const required = (selector) => {
|
||||
const element = document.querySelector(selector);
|
||||
if (!element) throw new Error(`Missing reference selector: ${selector}`);
|
||||
return element;
|
||||
};
|
||||
const optionalRect = (selector) => {
|
||||
const element = document.querySelector(selector);
|
||||
return element ? rect(element) : null;
|
||||
};
|
||||
const style = (selector) => getComputedStyle(required(selector));
|
||||
const input = required('.MessageInputForm input');
|
||||
const select = required('.MessageInputForm select');
|
||||
const submit = required('#msg_submit-col button');
|
||||
const firstPlate = document.querySelector('.msg_plate');
|
||||
const firstIcon = document.querySelector('.msg_plate .generalIcon');
|
||||
const panelStyle = style('.MessagePanel');
|
||||
const headerStyle = style('.BoardHeader');
|
||||
const plateStyle = firstPlate ? getComputedStyle(firstPlate) : null;
|
||||
const iconStyle = firstIcon ? getComputedStyle(firstIcon) : null;
|
||||
return {
|
||||
panel: rect(required('.MessagePanel')),
|
||||
inputForm: rect(required('.MessageInputForm')),
|
||||
select: rect(select),
|
||||
input: rect(input),
|
||||
submit: rect(submit),
|
||||
publicSection: rect(required('.PublicTalk')),
|
||||
nationalSection: rect(required('.NationalTalk')),
|
||||
privateSection: rect(required('.PrivateTalk')),
|
||||
diplomacySection: rect(required('.DiplomacyTalk')),
|
||||
firstHeader: rect(required('.BoardHeader')),
|
||||
firstPlate: optionalRect('.msg_plate'),
|
||||
firstIcon: optionalRect('.msg_plate .generalIcon'),
|
||||
computed: {
|
||||
panelDisplay: panelStyle.display,
|
||||
panelColumns: panelStyle.gridTemplateColumns,
|
||||
panelFontSize: panelStyle.fontSize,
|
||||
headerColor: headerStyle.color,
|
||||
headerOutlineWidth: headerStyle.outlineWidth,
|
||||
headerBackgroundImage: headerStyle.backgroundImage,
|
||||
plateBackgroundColor: plateStyle?.backgroundColor ?? null,
|
||||
plateFontSize: plateStyle?.fontSize ?? null,
|
||||
plateMinHeight: plateStyle?.minHeight ?? null,
|
||||
iconObjectFit: iconStyle?.objectFit ?? null,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const submit = page.locator('#msg_submit-col button');
|
||||
await submit.hover();
|
||||
const hover = await submit.evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
cursor: style.cursor,
|
||||
backgroundColor: style.backgroundColor,
|
||||
};
|
||||
});
|
||||
await submit.focus();
|
||||
const focus = await submit.evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
outline: style.outline,
|
||||
boxShadow: style.boxShadow,
|
||||
};
|
||||
});
|
||||
const markerPlate = page.locator('.msg_plate').filter({ hasText: marker });
|
||||
const deleteButton = markerPlate.locator('.btn-delete-msg');
|
||||
if (await deleteButton.isVisible()) {
|
||||
page.once('dialog', (dialog) => dialog.accept());
|
||||
await deleteButton.click();
|
||||
}
|
||||
return { ...result, interaction: { hover, focus } };
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
};
|
||||
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
try {
|
||||
const measurements = {
|
||||
desktop: await measure(browser, 'desktop', { width: 1000, height: 900 }),
|
||||
mobile: await measure(browser, 'mobile', { width: 500, height: 900 }),
|
||||
};
|
||||
process.stdout.write(`${JSON.stringify(measurements, null, 2)}\n`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { chromium } from '@playwright/test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const baseUrl = process.env.REF_PARITY_URL ?? 'http://127.0.0.1:3400/sam/';
|
||||
const username = process.env.REF_PARITY_USER ?? 'refadmin';
|
||||
const passwordFile = process.env.REF_PARITY_PASSWORD_FILE;
|
||||
const artifactRoot = resolve(process.env.REF_PARITY_ARTIFACT_DIR ?? 'test-results/reference-npc-policy');
|
||||
|
||||
if (!passwordFile) {
|
||||
throw new Error('REF_PARITY_PASSWORD_FILE is required.');
|
||||
}
|
||||
|
||||
const password = (await readFile(passwordFile, 'utf8')).trim();
|
||||
await mkdir(artifactRoot, { recursive: true });
|
||||
|
||||
const login = async (context, page) => {
|
||||
await page.goto(baseUrl, { waitUntil: 'networkidle' });
|
||||
const globalSalt = await page.locator('#global_salt').inputValue();
|
||||
const passwordHash = createHash('sha512')
|
||||
.update(globalSalt + password + globalSalt)
|
||||
.digest('hex');
|
||||
const response = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), {
|
||||
data: { username, password: passwordHash },
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok() || result.result !== true) {
|
||||
throw new Error('Reference login failed.');
|
||||
}
|
||||
};
|
||||
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
try {
|
||||
const result = {};
|
||||
for (const viewport of [
|
||||
{ name: 'desktop', width: 1000, height: 900 },
|
||||
{ name: 'mobile', width: 500, height: 900 },
|
||||
]) {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: viewport.width, height: viewport.height },
|
||||
deviceScaleFactor: 1,
|
||||
locale: 'ko-KR',
|
||||
timezoneId: 'Asia/Seoul',
|
||||
colorScheme: 'dark',
|
||||
});
|
||||
const page = await context.newPage();
|
||||
await login(context, page);
|
||||
await page.goto(new URL('hwe/', baseUrl).toString(), { waitUntil: 'networkidle' });
|
||||
await page.goto(new URL('hwe/v_NPCControl.php', baseUrl).toString(), { waitUntil: 'networkidle' });
|
||||
try {
|
||||
await page.locator('#container').waitFor({ timeout: 10_000 });
|
||||
} catch {
|
||||
throw new Error(
|
||||
`Reference NPC policy failed to mount: ${JSON.stringify({
|
||||
url: page.url(),
|
||||
text: (await page.locator('body').innerText()).slice(0, 500),
|
||||
})}`
|
||||
);
|
||||
}
|
||||
result[viewport.name] = await page.evaluate(() => {
|
||||
const measure = (selector) => {
|
||||
const element = document.querySelector(selector);
|
||||
if (!element) return null;
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
||||
style: {
|
||||
display: style.display,
|
||||
gridTemplateColumns: style.gridTemplateColumns,
|
||||
fontFamily: style.fontFamily,
|
||||
fontSize: style.fontSize,
|
||||
lineHeight: style.lineHeight,
|
||||
color: style.color,
|
||||
backgroundColor: style.backgroundColor,
|
||||
backgroundImage: style.backgroundImage,
|
||||
borderColor: style.borderColor,
|
||||
padding: style.padding,
|
||||
margin: style.margin,
|
||||
cursor: style.cursor,
|
||||
},
|
||||
};
|
||||
};
|
||||
return {
|
||||
body: measure('body'),
|
||||
container: measure('#container'),
|
||||
topBackBar: measure('body > :first-child'),
|
||||
sectionBar: measure('.section_bar'),
|
||||
formList: measure('.form_list'),
|
||||
firstField: measure('.form_list > .col'),
|
||||
firstInput: measure('input[type="number"]'),
|
||||
firstInfoButton: measure('.form_list button'),
|
||||
controlBar: measure('.control_bar'),
|
||||
resetButton: measure('.reset_btn'),
|
||||
submitButton: measure('.submit_btn'),
|
||||
priorityGrid: measure('.half_section_left'),
|
||||
priorityColumn: measure('.priority-list'),
|
||||
priorityItem: measure('.priority-list .list-group-item'),
|
||||
helpButton: measure('.priority_info button'),
|
||||
document: {
|
||||
width: document.documentElement.scrollWidth,
|
||||
height: document.documentElement.scrollHeight,
|
||||
},
|
||||
};
|
||||
});
|
||||
await page.screenshot({
|
||||
path: resolve(artifactRoot, `ref-npc-policy-${viewport.name}.png`),
|
||||
fullPage: true,
|
||||
});
|
||||
await context.close();
|
||||
}
|
||||
await writeFile(resolve(artifactRoot, 'computed-dom.json'), `${JSON.stringify(result, null, 2)}\n`);
|
||||
process.stdout.write(`${JSON.stringify({ ok: true, artifactRoot, viewports: Object.keys(result) })}\n`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { chromium } from '@playwright/test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const baseUrl = process.env.REF_RANKING_URL ?? 'https://dev-sam-ref.hided.net/sam/';
|
||||
const username = process.env.REF_RANKING_USER ?? 'refuser1';
|
||||
const passwordFile = process.env.REF_RANKING_PASSWORD_FILE;
|
||||
const artifactRoot = resolve(process.env.REF_RANKING_ARTIFACT_DIR ?? 'test-results/reference-rankings');
|
||||
|
||||
if (!passwordFile) {
|
||||
throw new Error('REF_RANKING_PASSWORD_FILE is required.');
|
||||
}
|
||||
|
||||
const password = (await readFile(passwordFile, 'utf8')).trim();
|
||||
await mkdir(artifactRoot, { recursive: true });
|
||||
|
||||
const login = async (context, page) => {
|
||||
await page.goto(baseUrl, { waitUntil: 'networkidle', timeout: 60_000 });
|
||||
const globalSalt = await page.locator('#global_salt').inputValue();
|
||||
const passwordHash = createHash('sha512')
|
||||
.update(globalSalt + password + globalSalt)
|
||||
.digest('hex');
|
||||
const response = await context.request.post(new URL('api.php?path=Login/LoginByID', baseUrl).toString(), {
|
||||
data: { username, password: passwordHash },
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok() || result.result !== true) {
|
||||
throw new Error('Reference login failed.');
|
||||
}
|
||||
};
|
||||
|
||||
const measureRanking = async (page) =>
|
||||
page.evaluate(() => {
|
||||
const pick = (selector) => {
|
||||
const element = document.querySelector(selector);
|
||||
if (!element) {
|
||||
return null;
|
||||
}
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
||||
style: {
|
||||
fontFamily: style.fontFamily,
|
||||
fontSize: style.fontSize,
|
||||
lineHeight: style.lineHeight,
|
||||
backgroundImage: style.backgroundImage,
|
||||
backgroundColor: style.backgroundColor,
|
||||
color: style.color,
|
||||
borderTopColor: style.borderTopColor,
|
||||
borderTopWidth: style.borderTopWidth,
|
||||
borderRadius: style.borderRadius,
|
||||
padding: style.padding,
|
||||
fontWeight: style.fontWeight,
|
||||
cursor: style.cursor,
|
||||
minHeight: style.minHeight,
|
||||
objectFit: style.objectFit,
|
||||
},
|
||||
};
|
||||
};
|
||||
const image = document.querySelector('.generalIcon');
|
||||
return {
|
||||
title: document.title,
|
||||
container: pick('#container'),
|
||||
rankType: pick('.rankType'),
|
||||
rankCell: pick('.rankView li'),
|
||||
uniqueCell: pick('.rankView li.no_value'),
|
||||
image: image
|
||||
? {
|
||||
...pick('.generalIcon'),
|
||||
naturalWidth: image.naturalWidth,
|
||||
naturalHeight: image.naturalHeight,
|
||||
}
|
||||
: null,
|
||||
firstButton: pick('button, input[type="submit"], input[type="button"]'),
|
||||
rankSectionCount: document.querySelectorAll('.rankView').length,
|
||||
document: {
|
||||
width: document.documentElement.scrollWidth,
|
||||
height: document.documentElement.scrollHeight,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
try {
|
||||
const result = {};
|
||||
for (const viewport of [
|
||||
{ name: 'desktop', width: 1365, height: 768 },
|
||||
{ name: 'mobile', width: 390, height: 844 },
|
||||
]) {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: viewport.width, height: viewport.height },
|
||||
deviceScaleFactor: 1,
|
||||
locale: 'ko-KR',
|
||||
timezoneId: 'UTC',
|
||||
colorScheme: 'dark',
|
||||
ignoreHTTPSErrors: true,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
await login(context, page);
|
||||
await page.goto(new URL('hwe/', baseUrl).toString(), { waitUntil: 'networkidle', timeout: 60_000 });
|
||||
|
||||
await page.goto(new URL('hwe/a_bestGeneral.php', baseUrl).toString(), {
|
||||
waitUntil: 'networkidle',
|
||||
timeout: 60_000,
|
||||
});
|
||||
await page.locator('#container').waitFor();
|
||||
const bestGeneral = await measureRanking(page);
|
||||
const userButton = page.getByRole('button', { name: '유저 보기' });
|
||||
await userButton.hover();
|
||||
bestGeneral.userButtonHover = await userButton.evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return { backgroundColor: style.backgroundColor, cursor: style.cursor };
|
||||
});
|
||||
await userButton.focus();
|
||||
bestGeneral.userButtonFocus = await userButton.evaluate((element) => getComputedStyle(element).outline);
|
||||
await page.screenshot({
|
||||
path: resolve(artifactRoot, `ref-best-general-${viewport.name}.png`),
|
||||
fullPage: true,
|
||||
animations: 'disabled',
|
||||
});
|
||||
|
||||
await page.goto(new URL('hwe/a_hallOfFame.php', baseUrl).toString(), {
|
||||
waitUntil: 'networkidle',
|
||||
timeout: 60_000,
|
||||
});
|
||||
await page.locator('#container').waitFor();
|
||||
const hallOfFame = await measureRanking(page);
|
||||
const scenario = page.locator('#by_scenario');
|
||||
hallOfFame.scenario = await scenario.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
rect: { width: rect.width, height: rect.height },
|
||||
fontFamily: style.fontFamily,
|
||||
fontSize: style.fontSize,
|
||||
};
|
||||
});
|
||||
await scenario.focus();
|
||||
hallOfFame.scenarioFocus = await scenario.evaluate((element) => getComputedStyle(element).outline);
|
||||
await page.screenshot({
|
||||
path: resolve(artifactRoot, `ref-hall-of-fame-${viewport.name}.png`),
|
||||
fullPage: true,
|
||||
animations: 'disabled',
|
||||
});
|
||||
|
||||
result[viewport.name] = { bestGeneral, hallOfFame };
|
||||
await context.close();
|
||||
}
|
||||
await writeFile(resolve(artifactRoot, 'computed-dom.json'), `${JSON.stringify(result, null, 2)}\n`);
|
||||
process.stdout.write(`${JSON.stringify({ ok: true, artifactRoot, viewports: Object.keys(result) })}\n`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { canonicalFrontendFixture as fixture } from './fixtures/canonical';
|
||||
|
||||
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
|
||||
const imageRoot = resolve(repositoryRoot, '../../image');
|
||||
const imageRoots = [resolve(repositoryRoot, '../image'), resolve(repositoryRoot, '../../image')];
|
||||
const artifactRoot = process.env.FRONTEND_PARITY_ARTIFACT_DIR;
|
||||
|
||||
const response = (data: unknown) => ({ result: { data } });
|
||||
@@ -28,11 +28,11 @@ const installImages = async (page: Page): Promise<void> => {
|
||||
await page.route('**/image/**', async (route) => {
|
||||
const pathname = decodeURIComponent(new URL(route.request().url()).pathname);
|
||||
const relative = pathname.replace(/^\/image\//, '');
|
||||
const candidates = [
|
||||
const candidates = imageRoots.flatMap((imageRoot) => [
|
||||
resolve(imageRoot, relative),
|
||||
resolve(imageRoot, 'game', relative),
|
||||
resolve(imageRoot, 'icons', '22.jpg'),
|
||||
];
|
||||
]);
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const body = await readFile(candidate);
|
||||
@@ -139,6 +139,7 @@ const installAuthenticatedGameFixture = async (page: Page): Promise<void> => {
|
||||
};
|
||||
}
|
||||
if (operation === 'public.getMapLayout') return fixture.game.mapLayout;
|
||||
if (operation === 'ranking.getBestGeneral') return fixture.game.bestGeneral;
|
||||
if (operation === 'yearbook.getRange') return fixture.game.yearbookRange;
|
||||
if (operation === 'yearbook.getHistory') return fixture.game.yearbook;
|
||||
if (operation === 'vote.getVoteList') return fixture.game.surveyList;
|
||||
@@ -387,6 +388,117 @@ test.describe('gateway legacy parity', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('best general legacy parity', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await installAuthenticatedGameFixture(page);
|
||||
});
|
||||
|
||||
for (const viewport of [
|
||||
{ name: 'desktop', width: 1365, height: 768, expectedWidth: 1000 },
|
||||
{ name: 'mobile', width: 390, height: 844, expectedWidth: 500 },
|
||||
]) {
|
||||
test(`matches the ref fixed ranking grid on ${viewport.name}`, async ({ page }) => {
|
||||
await page.setViewportSize(viewport);
|
||||
await page.goto('http://127.0.0.1:15102/che/best-general');
|
||||
await expect(page.getByText('유비').first()).toBeVisible();
|
||||
await expect(page.locator('.rankView')).toHaveCount(3);
|
||||
if (artifactRoot) {
|
||||
await page.screenshot({
|
||||
path: resolve(artifactRoot, `best-general-core-${viewport.name}.png`),
|
||||
fullPage: true,
|
||||
animations: 'disabled',
|
||||
});
|
||||
}
|
||||
|
||||
const geometry = await page.evaluate(() => {
|
||||
const container = document.querySelector<HTMLElement>('#best-general-container')!;
|
||||
const item = document.querySelector<HTMLElement>('.rankView li')!;
|
||||
const uniqueItem = document.querySelector<HTMLElement>('.rankView li.no-value')!;
|
||||
const title = document.querySelector<HTMLElement>('.rankType')!;
|
||||
const image = document.querySelector<HTMLImageElement>('.generalIcon')!;
|
||||
return {
|
||||
container: {
|
||||
x: container.getBoundingClientRect().x,
|
||||
width: container.getBoundingClientRect().width,
|
||||
fontFamily: getComputedStyle(container).fontFamily,
|
||||
fontSize: getComputedStyle(container).fontSize,
|
||||
backgroundImage: getComputedStyle(container).backgroundImage,
|
||||
},
|
||||
item: {
|
||||
width: item.getBoundingClientRect().width,
|
||||
minHeight: getComputedStyle(item).minHeight,
|
||||
},
|
||||
uniqueItem: {
|
||||
minHeight: getComputedStyle(uniqueItem).minHeight,
|
||||
},
|
||||
title: {
|
||||
fontSize: getComputedStyle(title).fontSize,
|
||||
lineHeight: getComputedStyle(title).lineHeight,
|
||||
backgroundImage: getComputedStyle(title).backgroundImage,
|
||||
},
|
||||
image: {
|
||||
width: image.getBoundingClientRect().width,
|
||||
height: image.getBoundingClientRect().height,
|
||||
naturalWidth: image.naturalWidth,
|
||||
objectFit: getComputedStyle(image).objectFit,
|
||||
},
|
||||
closeX: document
|
||||
.querySelector<HTMLElement>('.legacy-ranking-title .legacy-button')!
|
||||
.getBoundingClientRect().x,
|
||||
};
|
||||
});
|
||||
|
||||
expect(geometry.container.width).toBe(viewport.expectedWidth);
|
||||
expect(geometry.container.fontFamily).toContain('Pretendard');
|
||||
expect(geometry.container.fontSize).toBe('14px');
|
||||
expect(geometry.container.backgroundImage).toContain('back_walnut.jpg');
|
||||
expect(geometry.closeX).toBe(geometry.container.x);
|
||||
expect(geometry.item).toEqual({ width: 100, minHeight: '149px' });
|
||||
expect(geometry.uniqueItem.minHeight).toBe('128px');
|
||||
expect(geometry.title).toMatchObject({
|
||||
fontSize: viewport.name === 'desktop' ? '28px' : '22.06px',
|
||||
lineHeight: viewport.name === 'desktop' ? '33.6px' : '26.472px',
|
||||
});
|
||||
expect(geometry.title.backgroundImage).toContain('back_green.jpg');
|
||||
expect(geometry.image).toMatchObject({ width: 64, height: 64, objectFit: 'fill' });
|
||||
expect(geometry.image.naturalWidth).toBeGreaterThan(0);
|
||||
|
||||
const npcButton = page.getByRole('button', { name: 'NPC 보기' });
|
||||
await npcButton.hover();
|
||||
await expect(npcButton).toHaveCSS('background-color', 'rgb(107, 107, 107)');
|
||||
await npcButton.focus();
|
||||
await expect(npcButton).toBeFocused();
|
||||
await npcButton.click();
|
||||
await expect(npcButton).toHaveAttribute('aria-pressed', 'true');
|
||||
|
||||
const itemName = page.locator('.item-name').first();
|
||||
await itemName.hover();
|
||||
await expect(itemName).toHaveAttribute('title', '최고의 명마');
|
||||
});
|
||||
}
|
||||
|
||||
test('keeps the current ranking and selected user type after an API error', async ({ page }) => {
|
||||
await page.goto('http://127.0.0.1:15102/che/best-general');
|
||||
await expect(page.getByText('유비').first()).toBeVisible();
|
||||
await page.route('**/che/api/trpc/**', async (route) => {
|
||||
if (operationNames(route).includes('ranking.getBestGeneral')) {
|
||||
await route.fulfill({
|
||||
status: 500,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { message: '명장일람 조회에 실패했습니다.' } }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await route.fallback();
|
||||
});
|
||||
const npcButton = page.getByRole('button', { name: 'NPC 보기' });
|
||||
await npcButton.click();
|
||||
await expect(page.getByRole('alert')).toBeVisible();
|
||||
await expect(page.getByText('유비').first()).toBeVisible();
|
||||
await expect(npcButton).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('hall of fame legacy parity', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await installHallFixture(page);
|
||||
@@ -401,6 +513,13 @@ test.describe('hall of fame legacy parity', () => {
|
||||
await page.goto('http://127.0.0.1:15102/che/hall-of-fame');
|
||||
await expect(page.getByText('유비')).toBeVisible();
|
||||
await expect(page.locator('.rankView')).toHaveCount(2);
|
||||
if (artifactRoot) {
|
||||
await page.screenshot({
|
||||
path: resolve(artifactRoot, `hall-of-fame-core-${viewport.name}.png`),
|
||||
fullPage: true,
|
||||
animations: 'disabled',
|
||||
});
|
||||
}
|
||||
|
||||
const geometry = await page.evaluate(() => {
|
||||
const container = document.querySelector<HTMLElement>('#container')!;
|
||||
@@ -409,7 +528,10 @@ test.describe('hall of fame legacy parity', () => {
|
||||
const titleStyle = getComputedStyle(document.querySelector<HTMLElement>('.rankType')!);
|
||||
const image = document.querySelector<HTMLImageElement>('.generalIcon')!;
|
||||
return {
|
||||
container: container.getBoundingClientRect().width,
|
||||
container: {
|
||||
x: container.getBoundingClientRect().x,
|
||||
width: container.getBoundingClientRect().width,
|
||||
},
|
||||
containerBackgroundImage: getComputedStyle(container).backgroundImage,
|
||||
item: {
|
||||
width: item.getBoundingClientRect().width,
|
||||
@@ -427,23 +549,57 @@ test.describe('hall of fame legacy parity', () => {
|
||||
naturalHeight: image.naturalHeight,
|
||||
objectFit: getComputedStyle(image).objectFit,
|
||||
},
|
||||
closeX: document
|
||||
.querySelector<HTMLElement>('.legacy-hall-title .legacy-button')!
|
||||
.getBoundingClientRect().x,
|
||||
};
|
||||
});
|
||||
|
||||
expect(geometry.container).toBe(viewport.expectedWidth);
|
||||
expect(geometry.container.width).toBe(viewport.expectedWidth);
|
||||
expect(geometry.closeX).toBe(geometry.container.x);
|
||||
expect(geometry.containerBackgroundImage).toContain('back_walnut.jpg');
|
||||
expect(geometry.item.width).toBe(100);
|
||||
expect(geometry.title.fontFamily).toContain('Pretendard');
|
||||
expect(geometry.title.fontSize).toBe(viewport.name === 'desktop' ? '28px' : '22.06px');
|
||||
expect(geometry.title.backgroundImage).toContain('back_green.jpg');
|
||||
expect(geometry.image).toMatchObject({ width: 64, height: 64, objectFit: 'cover' });
|
||||
expect(geometry.image).toMatchObject({ width: 64, height: 64, objectFit: 'fill' });
|
||||
expect(geometry.image.naturalWidth).toBeGreaterThan(0);
|
||||
|
||||
const close = page.getByRole('button', { name: '창 닫기' }).first();
|
||||
await close.hover();
|
||||
await expect(close).toHaveCSS('background-color', 'rgb(107, 107, 107)');
|
||||
await close.focus();
|
||||
await expect(close).toBeFocused();
|
||||
|
||||
const scenario = page.getByLabel('시나리오 검색');
|
||||
await expect(scenario).toHaveCSS('width', '189px');
|
||||
await scenario.focus();
|
||||
await expect(scenario).toBeFocused();
|
||||
await scenario.selectOption('scenario:1:22');
|
||||
await expect(scenario).toHaveValue('scenario:1:22');
|
||||
});
|
||||
}
|
||||
|
||||
test('keeps the selected scenario after a hall API error', async ({ page }) => {
|
||||
await page.goto('http://127.0.0.1:15102/che/hall-of-fame');
|
||||
await expect(page.getByText('유비')).toBeVisible();
|
||||
await page.route('**/che/api/trpc/**', async (route) => {
|
||||
if (operationNames(route).includes('ranking.getHallOfFame')) {
|
||||
await route.fulfill({
|
||||
status: 500,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { message: '명예의 전당 조회에 실패했습니다.' } }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await route.fallback();
|
||||
});
|
||||
const scenario = page.getByLabel('시나리오 검색');
|
||||
await scenario.selectOption('scenario:1:22');
|
||||
await expect(page.getByRole('alert')).toBeVisible();
|
||||
await expect(scenario).toHaveValue('scenario:1:22');
|
||||
await expect(page.getByText('유비')).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test('game login delegates to the gateway like the ref entry point', async ({ page }) => {
|
||||
|
||||
@@ -348,6 +348,8 @@ const buildWorldInput = (
|
||||
maxGeneral: 500,
|
||||
baseGold: 0,
|
||||
baseRice: 2_000,
|
||||
generalMinimumGold: 0,
|
||||
generalMinimumRice: 500,
|
||||
maxResourceActionAmount: 10_000,
|
||||
maxTechLevel: 12,
|
||||
maxLevel: 255,
|
||||
|
||||
@@ -0,0 +1,468 @@
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs/promises';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
|
||||
|
||||
import type { AppRouter as GatewayAppRouter } from '@sammo-ts/gateway-api';
|
||||
import { createGatewayApiServer } from '@sammo-ts/gateway-api';
|
||||
import type { AppRouter as GameAppRouter } from '@sammo-ts/game-api';
|
||||
import {
|
||||
buildTournamentKeys,
|
||||
createGameApiServer,
|
||||
DatabaseTurnDaemonTransport,
|
||||
processTournamentTick,
|
||||
TournamentStore,
|
||||
} from '@sammo-ts/game-api';
|
||||
import { createTurnDaemonRuntime } from '@sammo-ts/game-engine';
|
||||
import {
|
||||
createGamePostgresConnector,
|
||||
createGatewayPostgresConnector,
|
||||
createRedisConnector,
|
||||
resolvePostgresConfigFromEnv,
|
||||
resolveRedisConfigFromEnv,
|
||||
type GamePrisma,
|
||||
} from '@sammo-ts/infra';
|
||||
|
||||
const workspaceRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
|
||||
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const parseEnvFile = (rawText: string): Record<string, string> => {
|
||||
const env: Record<string, string> = {};
|
||||
for (const line of rawText.split(/\r?\n/)) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) {
|
||||
continue;
|
||||
}
|
||||
const separator = trimmed.indexOf('=');
|
||||
if (separator < 0) {
|
||||
continue;
|
||||
}
|
||||
const key = trimmed.slice(0, separator).trim();
|
||||
let value = trimmed.slice(separator + 1).trim();
|
||||
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
env[key] = value;
|
||||
}
|
||||
return env;
|
||||
};
|
||||
|
||||
const loadEnv = async (): Promise<void> => {
|
||||
const values = parseEnvFile(await fs.readFile(path.join(workspaceRoot, '.env.ci'), 'utf8'));
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (process.env[key] === undefined) {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
process.env.INTEGRATION_JOIN_ALLOW_CITY ??= 'true';
|
||||
process.env.INTEGRATION_WORLD_SEED ??= 'tournament-lifecycle-seed';
|
||||
};
|
||||
|
||||
const execCommand = (command: string, args: string[], env?: NodeJS.ProcessEnv): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
execFile(command, args, { env, cwd: workspaceRoot }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
reject(new Error(`${command} ${args.join(' ')} failed:\n${stdout}\n${stderr}`));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
const ensureSchema = async (schema: string): Promise<void> => {
|
||||
const connector = createGatewayPostgresConnector({
|
||||
url: resolvePostgresConfigFromEnv({ schema: 'public' }).url,
|
||||
});
|
||||
await connector.connect();
|
||||
try {
|
||||
await connector.prisma.$executeRawUnsafe(`CREATE SCHEMA IF NOT EXISTS "${schema}"`);
|
||||
} finally {
|
||||
await connector.disconnect();
|
||||
}
|
||||
};
|
||||
|
||||
const truncateSchema = async (schema: string): Promise<void> => {
|
||||
const connector = createGatewayPostgresConnector({
|
||||
url: resolvePostgresConfigFromEnv({ schema: 'public' }).url,
|
||||
});
|
||||
await connector.connect();
|
||||
try {
|
||||
const rows = (await connector.prisma.$queryRawUnsafe(
|
||||
`SELECT tablename FROM pg_tables WHERE schemaname = '${schema}'`
|
||||
)) as Array<{ tablename: string }>;
|
||||
if (rows.length === 0) {
|
||||
return;
|
||||
}
|
||||
const tableList = rows.map((row) => `"${schema}"."${row.tablename}"`).join(', ');
|
||||
await connector.prisma.$executeRawUnsafe(`TRUNCATE TABLE ${tableList} RESTART IDENTITY CASCADE`);
|
||||
} finally {
|
||||
await connector.disconnect();
|
||||
}
|
||||
};
|
||||
|
||||
const resetServices = async (): Promise<void> => {
|
||||
await ensureSchema('public');
|
||||
await ensureSchema('che');
|
||||
await execCommand('pnpm', ['--filter', '@sammo-ts/infra', 'prisma:db:push:gateway', '--accept-data-loss'], {
|
||||
...process.env,
|
||||
POSTGRES_SCHEMA: 'public',
|
||||
});
|
||||
await execCommand('pnpm', ['--filter', '@sammo-ts/infra', 'prisma:db:push:game', '--accept-data-loss'], {
|
||||
...process.env,
|
||||
POSTGRES_SCHEMA: 'che',
|
||||
});
|
||||
await truncateSchema('public');
|
||||
await truncateSchema('che');
|
||||
|
||||
const redis = createRedisConnector(resolveRedisConfigFromEnv());
|
||||
await redis.connect();
|
||||
try {
|
||||
await redis.client.flushDb();
|
||||
} finally {
|
||||
await redis.disconnect();
|
||||
}
|
||||
};
|
||||
|
||||
const createGatewayClient = (baseUrl: string, pathName: string, token: { value?: string }) =>
|
||||
createTRPCProxyClient<GatewayAppRouter>({
|
||||
links: [
|
||||
httpBatchLink({
|
||||
url: `${baseUrl}${pathName}`,
|
||||
headers: () => (token.value ? { 'x-session-token': token.value } : {}),
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const createGameClient = (baseUrl: string, pathName: string, token: { value?: string }) =>
|
||||
createTRPCProxyClient<GameAppRouter>({
|
||||
links: [
|
||||
httpBatchLink({
|
||||
url: `${baseUrl}${pathName}`,
|
||||
headers: () => (token.value ? { authorization: `Bearer ${token.value}` } : {}),
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
describe('actual tournament lifecycle', () => {
|
||||
let gatewayServer: Awaited<ReturnType<typeof createGatewayApiServer>> | null = null;
|
||||
let gameServer: Awaited<ReturnType<typeof createGameApiServer>> | null = null;
|
||||
let turnDaemon: Awaited<ReturnType<typeof createTurnDaemonRuntime>> | null = null;
|
||||
let turnDaemonLoop: Promise<void> | null = null;
|
||||
let gameConnector: Awaited<ReturnType<typeof createGamePostgresConnector>> | null = null;
|
||||
let redisConnector: Awaited<ReturnType<typeof createRedisConnector>> | null = null;
|
||||
let store: TournamentStore | null = null;
|
||||
let transport: DatabaseTurnDaemonTransport | null = null;
|
||||
|
||||
const clients = new Map<string, ReturnType<typeof createGameClient>>();
|
||||
const generalIds = new Map<string, number>();
|
||||
|
||||
beforeAll(async () => {
|
||||
await loadEnv();
|
||||
process.env.SCENARIO = '908';
|
||||
process.chdir(workspaceRoot);
|
||||
await resetServices();
|
||||
|
||||
gatewayServer = await createGatewayApiServer();
|
||||
await gatewayServer.app.listen({ host: gatewayServer.config.host, port: gatewayServer.config.port });
|
||||
gameServer = await createGameApiServer();
|
||||
await gameServer.app.listen({ host: gameServer.config.host, port: gameServer.config.port });
|
||||
|
||||
const gatewayUrl = `http://localhost:${gatewayServer.config.port}`;
|
||||
const gameUrl = `http://localhost:${gameServer.config.port}`;
|
||||
const adminSession = { value: undefined as string | undefined };
|
||||
const gatewayClient = createGatewayClient(gatewayUrl, gatewayServer.config.trpcPath, adminSession);
|
||||
|
||||
const bootstrap = await gatewayClient.auth.bootstrapLocal.mutate({
|
||||
token: process.env.GATEWAY_BOOTSTRAP_TOKEN ?? '',
|
||||
username: 'admin',
|
||||
password: 'admin-pass-123',
|
||||
displayName: '관리자',
|
||||
});
|
||||
adminSession.value = bootstrap.sessionToken;
|
||||
|
||||
const users = [
|
||||
['participant', '대회참가자'],
|
||||
['bettor-a', '베팅유저A'],
|
||||
['bettor-b', '베팅유저B'],
|
||||
['no-general', '무장수유저'],
|
||||
] as const;
|
||||
for (const [username, displayName] of users) {
|
||||
await gatewayClient.admin.users.createLocal.mutate({
|
||||
username,
|
||||
password: `${username}-pass`,
|
||||
displayName,
|
||||
});
|
||||
}
|
||||
|
||||
await gatewayClient.admin.profiles.upsert.mutate({
|
||||
profile: 'che',
|
||||
scenario: '908',
|
||||
apiPort: Number(process.env.GAME_API_PORT ?? 14000),
|
||||
status: 'RUNNING',
|
||||
});
|
||||
await gatewayClient.admin.profiles.installNow.mutate({
|
||||
profileName: 'che:908',
|
||||
install: {
|
||||
scenarioId: 908,
|
||||
turnTermMinutes: 1,
|
||||
sync: false,
|
||||
fiction: 0,
|
||||
extend: true,
|
||||
blockGeneralCreate: 0,
|
||||
npcMode: 0,
|
||||
showImgLevel: 0,
|
||||
tournamentTrig: true,
|
||||
joinMode: 'full',
|
||||
autorunUser: null,
|
||||
},
|
||||
});
|
||||
|
||||
for (const [username, displayName] of users) {
|
||||
const login = await gatewayClient.auth.login.mutate({
|
||||
username,
|
||||
password: `${username}-pass`,
|
||||
});
|
||||
const gatewayToken = await gatewayClient.auth.issueGameSession.mutate({
|
||||
sessionToken: login.sessionToken,
|
||||
profile: 'che:908',
|
||||
});
|
||||
const accessRef = { value: undefined as string | undefined };
|
||||
const client = createGameClient(gameUrl, gameServer.config.trpcPath, accessRef);
|
||||
const access = await client.auth.exchangeGatewayToken.mutate({ gatewayToken: gatewayToken.gameToken });
|
||||
accessRef.value = access.accessToken;
|
||||
clients.set(username, client);
|
||||
|
||||
if (username !== 'no-general') {
|
||||
const created = await client.join.createGeneral.mutate({
|
||||
name: displayName,
|
||||
leadership: 55,
|
||||
strength: 55,
|
||||
intel: 55,
|
||||
character: 'Random',
|
||||
});
|
||||
generalIds.set(username, created.generalId);
|
||||
}
|
||||
}
|
||||
|
||||
const gameDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'che' }).url;
|
||||
const gatewayDatabaseUrl = resolvePostgresConfigFromEnv({ schema: 'public' }).url;
|
||||
gameConnector = createGamePostgresConnector({ url: gameDatabaseUrl });
|
||||
await gameConnector.connect();
|
||||
await gameConnector.prisma.general.updateMany({
|
||||
where: { id: { in: [...generalIds.values()] } },
|
||||
data: { gold: 10_000 },
|
||||
});
|
||||
const maxGeneralId = (await gameConnector.prisma.general.aggregate({ _max: { id: true } }))._max.id ?? 0;
|
||||
const npcTemplate = await gameConnector.prisma.general.findFirstOrThrow({
|
||||
where: { id: { in: [...generalIds.values()] } },
|
||||
});
|
||||
const {
|
||||
id: _templateId,
|
||||
userId: _templateUserId,
|
||||
name: _templateName,
|
||||
createdAt: _templateCreatedAt,
|
||||
updatedAt: _templateUpdatedAt,
|
||||
...npcTemplateData
|
||||
} = npcTemplate;
|
||||
const templateMeta =
|
||||
typeof npcTemplate.meta === 'object' && npcTemplate.meta !== null && !Array.isArray(npcTemplate.meta)
|
||||
? npcTemplate.meta
|
||||
: {};
|
||||
await gameConnector.prisma.general.createMany({
|
||||
data: Array.from({ length: 48 }, (_, index): GamePrisma.GeneralCreateManyInput => ({
|
||||
...npcTemplateData,
|
||||
id: maxGeneralId + index + 1,
|
||||
userId: null,
|
||||
name: `대회NPC${index + 1}`,
|
||||
npcState: 2,
|
||||
leadership: 40 + (index % 31),
|
||||
strength: 40 + ((index * 3) % 31),
|
||||
intel: 40 + ((index * 7) % 31),
|
||||
gold: 10_000,
|
||||
lastTurn: npcTemplate.lastTurn as GamePrisma.InputJsonValue,
|
||||
meta: { ...templateMeta, explevel: 20 },
|
||||
penalty: npcTemplate.penalty as GamePrisma.InputJsonValue,
|
||||
})),
|
||||
});
|
||||
|
||||
redisConnector = createRedisConnector(resolveRedisConfigFromEnv());
|
||||
await redisConnector.connect();
|
||||
store = new TournamentStore(redisConnector.client, buildTournamentKeys('che:908'));
|
||||
transport = new DatabaseTurnDaemonTransport(gameConnector.prisma, 30_000);
|
||||
|
||||
turnDaemon = await createTurnDaemonRuntime({
|
||||
profile: 'che',
|
||||
profileName: 'che:908',
|
||||
databaseUrl: gameDatabaseUrl,
|
||||
gatewayDatabaseUrl,
|
||||
redisUrl: resolveRedisConfigFromEnv().url,
|
||||
});
|
||||
|
||||
for (let attempt = 0; attempt < 36; attempt += 1) {
|
||||
const current = turnDaemon.world.getState().lastTurnTime;
|
||||
const next = new Date(current.getTime());
|
||||
next.setUTCMonth(next.getUTCMonth() + 1);
|
||||
await turnDaemon.world.advanceMonth(next);
|
||||
if ((await store.getState())?.stage === 1) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
expect(await store.getState()).toMatchObject({ stage: 1, auto: true });
|
||||
|
||||
turnDaemonLoop = turnDaemon.lifecycle.start();
|
||||
const status = await transport.requestStatus(10_000);
|
||||
expect(status).not.toBeNull();
|
||||
}, 120_000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (turnDaemon) {
|
||||
await turnDaemon.lifecycle.stop('tournament-lifecycle-test');
|
||||
await turnDaemon.close();
|
||||
await turnDaemonLoop;
|
||||
}
|
||||
await redisConnector?.disconnect();
|
||||
await gameConnector?.disconnect();
|
||||
await gameServer?.app.close();
|
||||
await gatewayServer?.app.close();
|
||||
}, 30_000);
|
||||
|
||||
it('runs auto-open, enrollment, betting, finals, rewards, and payout through the real daemon', async () => {
|
||||
if (!store || !transport || !gameConnector) {
|
||||
throw new Error('integration runtime is not ready');
|
||||
}
|
||||
const participant = clients.get('participant')!;
|
||||
const bettorA = clients.get('bettor-a')!;
|
||||
const bettorB = clients.get('bettor-b')!;
|
||||
const noGeneral = clients.get('no-general')!;
|
||||
|
||||
await expect(noGeneral.tournament.getState.query()).rejects.toThrow();
|
||||
await expect(participant.tournament.join.mutate()).resolves.toMatchObject({ ok: true });
|
||||
await expect(participant.tournament.join.mutate()).resolves.toMatchObject({ ok: true });
|
||||
|
||||
for (let steps = 0; steps < 2000; steps += 1) {
|
||||
const state = await store.getState();
|
||||
if (!state) {
|
||||
throw new Error('tournament state disappeared');
|
||||
}
|
||||
if (state.stage === 6) {
|
||||
break;
|
||||
}
|
||||
await store.setState({
|
||||
...state,
|
||||
nextAt: new Date(Date.now() - 1_000).toISOString(),
|
||||
});
|
||||
await processTournamentTick({
|
||||
store,
|
||||
prisma: gameConnector.prisma,
|
||||
daemonTransport: transport,
|
||||
});
|
||||
}
|
||||
|
||||
const bettingState = await store.getState();
|
||||
expect(bettingState).toMatchObject({ stage: 6, auto: true });
|
||||
const matches = await store.getMatches();
|
||||
const candidates = Array.from(
|
||||
new Set(
|
||||
matches.filter((match) => match.stage === 7).flatMap((match) => [match.attackerId, match.defenderId])
|
||||
)
|
||||
);
|
||||
expect(candidates).toHaveLength(16);
|
||||
|
||||
const idleDeadline = Date.now() + 60_000;
|
||||
while (Date.now() < idleDeadline) {
|
||||
const pending = await gameConnector.prisma.inputEvent.count({
|
||||
where: { status: { in: ['PENDING', 'PROCESSING'] } },
|
||||
});
|
||||
if (pending === 0) {
|
||||
break;
|
||||
}
|
||||
await sleep(100);
|
||||
}
|
||||
expect(
|
||||
await gameConnector.prisma.inputEvent.count({
|
||||
where: { status: { in: ['PENDING', 'PROCESSING'] } },
|
||||
})
|
||||
).toBe(0);
|
||||
|
||||
for (const targetId of candidates) {
|
||||
await bettorA.tournament.placeBet.mutate({ targetId, amount: 10 });
|
||||
}
|
||||
await bettorB.tournament.placeBet.mutate({ targetId: candidates[0]!, amount: 100 });
|
||||
|
||||
const bets = await store.getBettingEntries();
|
||||
const bettorAId = generalIds.get('bettor-a')!;
|
||||
const bettorBId = generalIds.get('bettor-b')!;
|
||||
expect(bets.filter((entry) => entry.generalId === bettorAId)).toHaveLength(16);
|
||||
expect(bets.some((entry) => entry.generalId === bettorBId && entry.targetId === candidates[0])).toBe(true);
|
||||
expect(bets.every((entry) => entry.generalId !== generalIds.get('participant'))).toBe(true);
|
||||
|
||||
const bettorBeforeSettlement = await gameConnector.prisma.general.findUniqueOrThrow({
|
||||
where: { id: bettorAId },
|
||||
select: { gold: true, meta: true },
|
||||
});
|
||||
|
||||
await store.setState({
|
||||
...bettingState!,
|
||||
bettingCloseAt: new Date(Date.now() - 1_000).toISOString(),
|
||||
nextAt: new Date(Date.now() - 1_000).toISOString(),
|
||||
});
|
||||
|
||||
for (let steps = 0; steps < 100; steps += 1) {
|
||||
const state = await store.getState();
|
||||
if (!state) {
|
||||
throw new Error('tournament state disappeared');
|
||||
}
|
||||
if (state.stage === 0 && state.rewardSettled && state.bettingSettled) {
|
||||
break;
|
||||
}
|
||||
if (state.stage > 0) {
|
||||
await store.setState({
|
||||
...state,
|
||||
bettingCloseAt:
|
||||
state.stage === 6 ? new Date(Date.now() - 1_000).toISOString() : state.bettingCloseAt,
|
||||
nextAt: new Date(Date.now() - 1_000).toISOString(),
|
||||
});
|
||||
}
|
||||
await processTournamentTick({
|
||||
store,
|
||||
prisma: gameConnector.prisma,
|
||||
daemonTransport: transport,
|
||||
});
|
||||
}
|
||||
|
||||
const finalState = await store.getState();
|
||||
expect(finalState).toMatchObject({
|
||||
stage: 0,
|
||||
auto: false,
|
||||
rewardSettled: true,
|
||||
bettingSettled: true,
|
||||
});
|
||||
expect(finalState?.winnerId).toBeTypeOf('number');
|
||||
|
||||
const bettorAfterSettlement = await gameConnector.prisma.general.findUniqueOrThrow({
|
||||
where: { id: bettorAId },
|
||||
select: { gold: true, meta: true },
|
||||
});
|
||||
expect(bettorAfterSettlement.gold).toBeGreaterThan(bettorBeforeSettlement.gold);
|
||||
expect(bettorAfterSettlement.meta).toMatchObject({
|
||||
betgold: 160,
|
||||
betwin: 1,
|
||||
});
|
||||
expect(Number((bettorAfterSettlement.meta as Record<string, unknown>).betwingold)).toBeGreaterThan(0);
|
||||
|
||||
const settlementEvents = await gameConnector.prisma.inputEvent.findMany({
|
||||
where: { eventType: { in: ['tournamentReward', 'tournamentBettingPayout'] } },
|
||||
select: { eventType: true, status: true, result: true },
|
||||
});
|
||||
expect(settlementEvents).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ eventType: 'tournamentReward', status: 'SUCCEEDED' }),
|
||||
expect.objectContaining({ eventType: 'tournamentBettingPayout', status: 'SUCCEEDED' }),
|
||||
])
|
||||
);
|
||||
expect(settlementEvents.every((event) => (event.result as { ok?: boolean } | null)?.ok === true)).toBe(true);
|
||||
}, 120_000);
|
||||
});
|
||||
@@ -1058,6 +1058,245 @@ integration('general command post-required cooldown boundary matrix', () => {
|
||||
}, 120_000);
|
||||
});
|
||||
|
||||
const missingTargetCases: Array<{ name: string; action: string; args: Record<string, unknown> }> = [
|
||||
{
|
||||
name: 'gift to a missing general',
|
||||
action: 'che_증여',
|
||||
args: { isGold: true, amount: 100, destGeneralID: 999 },
|
||||
},
|
||||
{
|
||||
name: 'spy on a missing city',
|
||||
action: 'che_첩보',
|
||||
args: { destCityID: 999 },
|
||||
},
|
||||
{
|
||||
name: 'move to a missing city',
|
||||
action: 'che_이동',
|
||||
args: { destCityID: 999 },
|
||||
},
|
||||
{
|
||||
name: 'employ a missing general',
|
||||
action: 'che_등용',
|
||||
args: { destGeneralID: 999 },
|
||||
},
|
||||
];
|
||||
|
||||
integration('general command missing-target fallback matrix', () => {
|
||||
it.each(missingTargetCases)(
|
||||
'$name rejects the missing target and falls back without command RNG',
|
||||
async ({ action, args }) => {
|
||||
const request = buildRequest(action, args);
|
||||
const reference = runReferenceTurnCommandTraceRequest(
|
||||
workspaceRoot!,
|
||||
request as unknown as Record<string, unknown>
|
||||
);
|
||||
const core = await runCoreTurnCommandTrace(request, reference.before);
|
||||
|
||||
expect(reference.execution.outcome).toMatchObject({ completed: false });
|
||||
expect(core.execution.outcome).toMatchObject({
|
||||
requestedAction: action,
|
||||
actionKey: '휴식',
|
||||
usedFallback: true,
|
||||
});
|
||||
expect(core.rng).toEqual(reference.rng);
|
||||
expect(
|
||||
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
|
||||
ignoredPathPatterns: ignoredLifecyclePaths,
|
||||
})
|
||||
).toEqual([]);
|
||||
},
|
||||
120_000
|
||||
);
|
||||
});
|
||||
|
||||
const resourceAmountCases: Array<{
|
||||
name: string;
|
||||
action: string;
|
||||
args: Record<string, unknown>;
|
||||
expectedAmount: number;
|
||||
}> = [
|
||||
{
|
||||
name: 'gift rounds a half unit up',
|
||||
action: 'che_증여',
|
||||
args: { isGold: true, amount: 150, destGeneralID: 3 },
|
||||
expectedAmount: 200,
|
||||
},
|
||||
{
|
||||
name: 'gift clamps below the minimum',
|
||||
action: 'che_증여',
|
||||
args: { isGold: true, amount: 1, destGeneralID: 3 },
|
||||
expectedAmount: 100,
|
||||
},
|
||||
{
|
||||
name: 'gift clamps above the maximum',
|
||||
action: 'che_증여',
|
||||
args: { isGold: true, amount: 10_050, destGeneralID: 3 },
|
||||
expectedAmount: 10_000,
|
||||
},
|
||||
{
|
||||
name: 'donation rounds a half unit up',
|
||||
action: 'che_헌납',
|
||||
args: { isGold: true, amount: 150 },
|
||||
expectedAmount: 200,
|
||||
},
|
||||
{
|
||||
name: 'donation clamps below the minimum',
|
||||
action: 'che_헌납',
|
||||
args: { isGold: true, amount: 1 },
|
||||
expectedAmount: 100,
|
||||
},
|
||||
{
|
||||
name: 'donation clamps above the maximum',
|
||||
action: 'che_헌납',
|
||||
args: { isGold: true, amount: 10_050 },
|
||||
expectedAmount: 10_000,
|
||||
},
|
||||
{
|
||||
name: 'trade rounds a half unit up',
|
||||
action: 'che_군량매매',
|
||||
args: { buyRice: true, amount: 150 },
|
||||
expectedAmount: 200,
|
||||
},
|
||||
{
|
||||
name: 'trade clamps below the minimum',
|
||||
action: 'che_군량매매',
|
||||
args: { buyRice: true, amount: 1 },
|
||||
expectedAmount: 100,
|
||||
},
|
||||
{
|
||||
name: 'trade clamps above the maximum',
|
||||
action: 'che_군량매매',
|
||||
args: { buyRice: true, amount: 10_050 },
|
||||
expectedAmount: 10_000,
|
||||
},
|
||||
];
|
||||
|
||||
integration('general command resource amount normalization matrix', () => {
|
||||
it.each(resourceAmountCases)(
|
||||
'$name matches legacy rounding and clamp semantics',
|
||||
async ({ action, args, expectedAmount }) => {
|
||||
const request = buildRequest(action, args);
|
||||
const reference = runReferenceTurnCommandTraceRequest(
|
||||
workspaceRoot!,
|
||||
request as unknown as Record<string, unknown>
|
||||
);
|
||||
const core = await runCoreTurnCommandTrace(request, reference.before);
|
||||
const referenceActor = reference.after.generals.find((entry) => entry.id === 1);
|
||||
const coreActor = core.after.generals.find((entry) => entry.id === 1);
|
||||
const referenceLastTurn = referenceActor?.lastTurn as { arg?: Record<string, unknown> } | null | undefined;
|
||||
const coreLastTurn = coreActor?.lastTurn as { arg?: Record<string, unknown> } | null | undefined;
|
||||
|
||||
expect(reference.execution.outcome).toMatchObject({ completed: true });
|
||||
expect(core.execution.outcome).toMatchObject({
|
||||
requestedAction: action,
|
||||
actionKey: action,
|
||||
usedFallback: false,
|
||||
});
|
||||
expect(referenceLastTurn?.arg).toMatchObject({ amount: expectedAmount });
|
||||
expect(coreLastTurn?.arg).toMatchObject({ amount: expectedAmount });
|
||||
expect(core.rng).toEqual(reference.rng);
|
||||
expect(
|
||||
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
|
||||
ignoredPathPatterns: ignoredLifecyclePaths,
|
||||
})
|
||||
).toEqual([]);
|
||||
},
|
||||
120_000
|
||||
);
|
||||
});
|
||||
|
||||
integration('general command donation resource boundaries', () => {
|
||||
it('donates the available resource when the normalized request exceeds the current amount', async () => {
|
||||
const request = buildRequest('che_헌납', { isGold: true, amount: 10_000 }, { gold: 5_000 });
|
||||
const reference = runReferenceTurnCommandTraceRequest(
|
||||
workspaceRoot!,
|
||||
request as unknown as Record<string, unknown>
|
||||
);
|
||||
const core = await runCoreTurnCommandTrace(request, reference.before);
|
||||
|
||||
expect(reference.execution.outcome).toMatchObject({ completed: true });
|
||||
expect(core.execution.outcome).toMatchObject({
|
||||
requestedAction: 'che_헌납',
|
||||
actionKey: 'che_헌납',
|
||||
usedFallback: false,
|
||||
});
|
||||
expect(core.rng).toEqual(reference.rng);
|
||||
expect(
|
||||
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
|
||||
ignoredPathPatterns: ignoredLifecyclePaths,
|
||||
})
|
||||
).toEqual([]);
|
||||
}, 120_000);
|
||||
|
||||
it('falls back when current rice is below the legacy minimum even for a small request', async () => {
|
||||
const request = buildRequest('che_헌납', { isGold: false, amount: 100 }, { rice: 499 });
|
||||
const reference = runReferenceTurnCommandTraceRequest(
|
||||
workspaceRoot!,
|
||||
request as unknown as Record<string, unknown>
|
||||
);
|
||||
const core = await runCoreTurnCommandTrace(request, reference.before);
|
||||
|
||||
expect(reference.execution.outcome).toMatchObject({ completed: false });
|
||||
expect(core.execution.outcome).toMatchObject({
|
||||
requestedAction: 'che_헌납',
|
||||
actionKey: '휴식',
|
||||
usedFallback: true,
|
||||
});
|
||||
expect(core.rng).toEqual(reference.rng);
|
||||
expect(
|
||||
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
|
||||
ignoredPathPatterns: ignoredLifecyclePaths,
|
||||
})
|
||||
).toEqual([]);
|
||||
}, 120_000);
|
||||
});
|
||||
|
||||
integration('general command gift resource and target boundaries', () => {
|
||||
it('keeps the legacy minimum rice reserve while gifting the available amount', async () => {
|
||||
const request = buildRequest('che_증여', { isGold: false, amount: 10_000, destGeneralID: 3 }, { rice: 600 });
|
||||
const reference = runReferenceTurnCommandTraceRequest(
|
||||
workspaceRoot!,
|
||||
request as unknown as Record<string, unknown>
|
||||
);
|
||||
const core = await runCoreTurnCommandTrace(request, reference.before);
|
||||
|
||||
expect(reference.execution.outcome).toMatchObject({ completed: true });
|
||||
expect(core.execution.outcome).toMatchObject({
|
||||
requestedAction: 'che_증여',
|
||||
actionKey: 'che_증여',
|
||||
usedFallback: false,
|
||||
});
|
||||
expect(core.rng).toEqual(reference.rng);
|
||||
expect(
|
||||
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
|
||||
ignoredPathPatterns: ignoredLifecyclePaths,
|
||||
})
|
||||
).toEqual([]);
|
||||
}, 120_000);
|
||||
|
||||
it('rejects gifting to the actor and falls back without command RNG', async () => {
|
||||
const request = buildRequest('che_증여', { isGold: true, amount: 100, destGeneralID: 1 });
|
||||
const reference = runReferenceTurnCommandTraceRequest(
|
||||
workspaceRoot!,
|
||||
request as unknown as Record<string, unknown>
|
||||
);
|
||||
const core = await runCoreTurnCommandTrace(request, reference.before);
|
||||
|
||||
expect(reference.execution.outcome).toMatchObject({ completed: false });
|
||||
expect(core.execution.outcome).toMatchObject({
|
||||
requestedAction: 'che_증여',
|
||||
actionKey: '휴식',
|
||||
usedFallback: true,
|
||||
});
|
||||
expect(core.rng).toEqual(reference.rng);
|
||||
expect(
|
||||
compareTurnSnapshotDeltas(reference.before, reference.after, core.before, core.after, {
|
||||
ignoredPathPatterns: ignoredLifecyclePaths,
|
||||
})
|
||||
).toEqual([]);
|
||||
}, 120_000);
|
||||
});
|
||||
|
||||
type GeneralConstraintCase = {
|
||||
name: string;
|
||||
action: string;
|
||||
|
||||
Reference in New Issue
Block a user