243 lines
16 KiB
TypeScript
243 lines
16 KiB
TypeScript
import { test } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import type { CulpritInput, CulpritMatchInfo, CulpritMatchItem } from '@gvr/shared';
|
|
import { SettingsStore, DEFAULT_TTS_TEXT } from '../src/core/settings.ts';
|
|
import { kastRound } from '../src/core/games/valorant.ts';
|
|
import { makeDemoLol } from './fixtures/demo-matches.ts';
|
|
import { culpritApi, MIN, seedValorant, setup } from './fixtures/culprit-seed.ts';
|
|
|
|
test('범인찾기: 발로란트 추가 지표 저장 (피해량 · 첫킬 · 설치 · 역할 · 라운드별 장비)', () => {
|
|
const ctx = setup();
|
|
const { id } = seedValorant(ctx);
|
|
const det = JSON.parse(ctx.store.getMatch(id)!.detail!);
|
|
const jett = det.players.find((p: any) => p.puuid === 'p-sh');
|
|
assert.equal(jett.stats.role, '타격대');
|
|
assert.ok(jett.stats.damage > 0, '피해량');
|
|
assert.equal(typeof jett.stats.firstKills, 'number');
|
|
assert.ok(det.players.reduce((n: number, p: any) => n + p.stats.firstKills, 0) > 0, '첫킬 합 > 0');
|
|
const plants = det.players.reduce((n: number, p: any) => n + p.stats.plants, 0);
|
|
assert.ok(plants > 0, '설치 기록');
|
|
const r = det.roundsDetail[1];
|
|
assert.equal(typeof r.allyAttack, 'boolean');
|
|
assert.ok(r.players['p-sh'] !== undefined, '라운드별 선수 지표');
|
|
assert.ok(Object.values<any>(r.economy).every((e) => typeof e.loadout === 'number'), '라운드 장비 값');
|
|
// 전반(1~12)과 후반(13~)은 공수가 바뀐다
|
|
assert.notEqual(det.roundsDetail[0].allyAttack, det.roundsDetail[12].allyAttack);
|
|
// KAST · 받은 피해 (OP.GG 발로란트 OP스코어 입력)
|
|
assert.ok(det.players.every((p: any) => p.stats.kastRounds >= 0 && p.stats.kastRounds <= det.roundsDetail.length && p.stats.damageTaken > 0));
|
|
});
|
|
|
|
test('범인찾기: KAST 라운드 판정 (킬 · 어시 · 생존 · 5초 안 트레이드)', () => {
|
|
const players = { a1: { teamId: 'Red' }, a2: { teamId: 'Red' }, a3: { teamId: 'Red' }, b1: { teamId: 'Blue' }, b2: { teamId: 'Blue' } };
|
|
const r = { playerStats: Object.keys(players).map((subject) => ({ subject })) };
|
|
const kills = [
|
|
{ killer: 'b1', victim: 'a1', gameTime: 10000, assistants: [] }, // a1 죽음 → 3초 뒤 a2 가 b1 을 잡아 트레이드
|
|
{ killer: 'a2', victim: 'b1', gameTime: 13000, assistants: ['a3'] },
|
|
{ killer: 'b2', victim: 'a2', gameTime: 20000, assistants: [] }, // a2 는 킬이 있어 KAST
|
|
{ killer: 'b2', victim: 'a3', gameTime: 30000, assistants: [] }, // a3 는 어시가 있어 KAST
|
|
];
|
|
assert.deepEqual(kastRound(r, kills, players).sort(), ['a1', 'a2', 'a3', 'b1', 'b2']); // b1 은 킬이 있다
|
|
// 트레이드가 5초를 넘기면 KAST 아님
|
|
const late = [{ ...kills[0] }, { ...kills[1], gameTime: 16000 }];
|
|
assert.ok(!kastRound(r, late, players).includes('a1'));
|
|
});
|
|
|
|
test('범인찾기: 분석 가능 판정과 AI 자료', () => {
|
|
const ctx = setup();
|
|
const { id } = seedValorant(ctx);
|
|
const m = ctx.store.getMatch(id)!;
|
|
assert.deepEqual(ctx.culprit.eligibility(m), { state: 'ready', reasons: [], notes: [] });
|
|
const input = ctx.culprit.buildInput(m);
|
|
assert.ok(!input.text.includes('녹음'), '녹음이 경기를 다 덮으면 녹음 안내 줄 없음');
|
|
const lines = input.text.split('\n');
|
|
assert.match(lines[0], /^# 경기 발로란트 .* 13:9 \(우리 팀 승리\) · 22라운드/);
|
|
// 우리 팀이 P1~P5, 하늘은 음성O, 디스코드 계정이 없는 상대는 음성X
|
|
const p1 = lines.find((l) => l.startsWith('P1 '))!;
|
|
assert.match(p1, /^P1 하늘 우리 제트\(타격대\) \d+\/\d+\/\d+ ACS\d+ ADR\d+ KAST\d+% 피해격차[+-]\d+ 첫킬\d+\/첫데스\d+ HS\d+% 설치\d+\/해체\d+ .*음성O$/);
|
|
// 기록 점수 (OP.GG OP스코어 계산법): 10명 모두, 이긴 팀 1등 MVP · 진 팀 1등 ACE
|
|
const head = lines.findIndex((l) => l.startsWith('# 기록 점수 (0~10, OP.GG OP스코어 계산법'));
|
|
assert.ok(head > 0, '기록 점수 칸');
|
|
const rl = lines.slice(head + 1, head + 11);
|
|
assert.ok(rl.every((l, i) => new RegExp(`^P${i + 1} \\d+\\.\\d점 \\d+위/팀\\d위`).test(l)), rl.join('\n'));
|
|
assert.equal(rl.filter((l) => / MVP( |$)/.test(l)).length, 1);
|
|
assert.equal(rl.filter((l) => / ACE( |$)/.test(l)).length, 1);
|
|
assert.ok(rl.slice(0, 5).some((l) => / MVP( |$)/.test(l)), 'MVP 는 이긴 우리 팀');
|
|
const rp = input.players.map((p) => p.rating!);
|
|
assert.ok(rp.every((r) => r && r.score >= 0 && r.score <= 10 && !r.basic));
|
|
assert.deepEqual(rp.map((r) => r.rank).sort((a, b) => a - b), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
|
|
assert.equal(rp.find((r) => r.rank === 1)!.score, Math.max(...rp.map((r) => r.score)));
|
|
assert.match(lines.find((l) => l.startsWith('P6 '))!, /상대 .*음성X$/);
|
|
assert.equal(input.players.find((p) => p.id === 'P2')!.voice, true, '민수는 대화가 있다');
|
|
assert.equal(input.players.find((p) => p.id === 'P3')!.voice, false);
|
|
// 게임 계정이 없는 화자는 디스코드 이름으로
|
|
assert.ok(lines.some((l) => l.includes('도윤(게임 계정 모름)')));
|
|
// 근거 번호: 대화 · 이벤트 · 라운드 · 스탯
|
|
const u1 = lines.find((l) => l.startsWith('[u1] '))!;
|
|
assert.match(u1, /^\[u1\] R3 0:05 P1: 현우야 같이 가 기다려 둘 있어$/);
|
|
assert.equal(input.refs.u1.kind, 'utterance');
|
|
assert.ok(lines.some((l) => /^\[e\d+\] R\d+ \d+:\d+ 킬 P\d+ → P\d+/.test(l)), '킬 줄');
|
|
assert.ok(lines.some((l) => /^\[r1\] R1 우리 (공격|수비) 라운드 끝 · (승리|패배)\(.+\) \d+:\d+ · 평균 장비 우리 [\d,]+ \/ 상대 [\d,]+ · 선수 장비\/피해: P1 /.test(l)), '라운드 줄');
|
|
assert.deepEqual(input.refs['s:P4'], { kind: 'stat', pid: 'P4' });
|
|
assert.equal(input.stats.utterances, 4);
|
|
assert.equal(input.stats.basic, false);
|
|
// 줄은 시간 순서
|
|
const u2Index = lines.findIndex((l) => l.startsWith('[u2] '));
|
|
assert.ok(lines.findIndex((l) => l.startsWith('[r2] ')) < lines.findIndex((l) => l.startsWith('[u1] ')));
|
|
assert.ok(u2Index > lines.findIndex((l) => l.startsWith('[u1] ')));
|
|
});
|
|
|
|
test('범인찾기: 녹음이 늦게 시작 · 녹음 없음 · 음성 변환 중 · 녹음 제외', () => {
|
|
// 녹음이 끊긴 경기도 분석한다 (v1.11.0): 녹음된 대화만 쓰고 AI 에 알린다
|
|
const late = setup();
|
|
const a = seedValorant(late, { sessionStartOffsetMs: 17 * MIN });
|
|
const e = late.culprit.eligibility(late.store.getMatch(a.id)!);
|
|
assert.deepEqual(e, { state: 'ready', reasons: [], notes: ['녹음이 경기 시작 12분 뒤에 시작됐습니다: 녹음된 대화만 씁니다'] });
|
|
assert.ok(late.culprit.buildInput(late.store.getMatch(a.id)!).text.includes('\n# 녹음이 경기 시작 12분 뒤에 시작됐습니다. 녹음이 빠진 구간의 대화는 없다\n'));
|
|
|
|
// 앱을 켜지 않고 한 경기 (녹음 · 대화 없음): 플레이 기록 · 채팅으로만
|
|
const none = setup();
|
|
const n = seedValorant(none);
|
|
none.store.db.prepare('DELETE FROM utterances').run();
|
|
none.store.db.prepare('DELETE FROM sessions').run();
|
|
const nm = none.store.getMatch(n.id)!;
|
|
assert.deepEqual(none.culprit.eligibility(nm), { state: 'ready', reasons: [], notes: ['녹음 없음: 플레이 기록 · 채팅으로만 분석합니다'] });
|
|
const ni = none.culprit.buildInput(nm);
|
|
assert.ok(ni.text.includes('\n# 이 경기는 음성 녹음이 없다. 모두 음성X 로 보고 플레이 기록과 채팅으로만 평가한다\n'));
|
|
assert.ok(ni.players.every((p) => !p.voice));
|
|
assert.equal(ni.stats.utterances, 0);
|
|
assert.ok(ni.stats.events > 0 && ni.stats.rounds > 0);
|
|
|
|
const pend = setup();
|
|
const b = seedValorant(pend, { pending: true });
|
|
assert.deepEqual(pend.culprit.eligibility(pend.store.getMatch(b.id)!), { state: 'pending', reasons: ['음성 변환 중 (1문장 남음)'], notes: [] });
|
|
|
|
// 녹음 제외한 사람의 대화는 보내지 않는다
|
|
const ex = setup();
|
|
const c = seedValorant(ex);
|
|
ex.store.setExcluded('u2', true);
|
|
const input = ex.culprit.buildInput(ex.store.getMatch(c.id)!);
|
|
assert.ok(!input.text.includes('내가 뚫을게'));
|
|
assert.equal(input.players.find((p) => p.id === 'P2')!.voice, false);
|
|
|
|
// 경기 결과를 못 받은 경기
|
|
const nd = setup();
|
|
nd.store.upsertMatch({ id: 'val-x', game: 'valorant', started_at: Date.now() - 50 * MIN, ended_at: Date.now() - 10 * MIN, status: 'complete', detail: JSON.stringify({ live: true }) });
|
|
nd.store.startSession('s', 'g', 'c', null, Date.now() - 60 * MIN);
|
|
assert.deepEqual(nd.culprit.eligibility(nd.store.getMatch('val-x')!), { state: 'blocked', reasons: ['경기 결과를 받지 못했습니다'] });
|
|
});
|
|
|
|
test('범인찾기: 롤 포지션 · 시야 · 10/15분 지표와 골드 차', () => {
|
|
const ctx = setup();
|
|
const LS = Date.now() - 80 * MIN;
|
|
const lol = makeDemoLol();
|
|
ctx.store.setMeta('riot_self_puuid', 'l-sh');
|
|
ctx.store.startSession('s', 'g', 'c', null, LS - MIN);
|
|
ctx.store.endSession('s', LS + lol.durationMs + MIN);
|
|
ctx.games.matchStarted({ id: 'lol-1', game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } });
|
|
ctx.games.matchEnded('lol-1', LS + lol.durationMs);
|
|
(ctx.games.adapters[1] as any).applyHistory('lol-1', lol.game, lol.timeline, LS);
|
|
const m = ctx.store.getMatch('lol-1')!;
|
|
const det = JSON.parse(m.detail!);
|
|
assert.deepEqual(
|
|
det.players.map((p: any) => p.stats.role),
|
|
['미드', '정글', '탑', '원딜', '서폿', '미드', '정글', '탑', '원딜', '서폿'],
|
|
);
|
|
assert.deepEqual(det.players[1].stats.at10, { cs: 60, gold: det.players[1].stats.at10.gold, xp: 4220 });
|
|
assert.equal(ctx.culprit.eligibility(m).state, 'ready');
|
|
const input = ctx.culprit.buildInput(m);
|
|
assert.match(input.text, /\nP5 Duck 우리 [^ ]+\(서폿\) \d+\/\d+\/\d+ CS\d+ 골드\d+ 딜17500 받은\d+ 시야62 와드48\/4\/9 10분\d+·\d+ 15분\d+·\d+ 음성X\n/);
|
|
assert.match(input.text, /\n# 골드 차\(우리-상대\): 5분 [+-][\d,]+ · 10분/);
|
|
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 킬 P\d+ → P\d+/);
|
|
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 내셔 남작 처치 우리 팀 · P2\n/);
|
|
// 기록 점수 + LOL.PS 라인전 점수의 입력 (10 · 15분 맞라이너와 차)
|
|
assert.match(input.text, /\n# 기록 점수 \(0~10, OP\.GG OP스코어 계산법/);
|
|
assert.match(input.text, /\nP1 \d+\.\d점 \d+위\/팀\d위.* · 라인전\(vs P6\) 10분 CS[+-][\d,]+ 골드[+-][\d,]+ 경험치[+-][\d,]+ 15분 CS[+-][\d,]+ 골드[+-][\d,]+ 경험치[+-][\d,]+\n/);
|
|
const p1 = input.players.find((p) => p.id === 'P1')!;
|
|
const p6 = input.players.find((p) => p.id === 'P6')!;
|
|
assert.equal(p1.rating!.lane!.at15!.cs, -p6.rating!.lane!.at15!.cs, '맞라인 차는 서로 반대');
|
|
assert.equal(p1.rating!.lane!.at10!.xp, -p6.rating!.lane!.at10!.xp);
|
|
assert.ok(p1.rating!.lane!.at10!.cs !== undefined && p1.rating!.lane!.at15!.gold !== undefined);
|
|
assert.equal(input.players.filter((p) => p.rating?.badge).length, 2);
|
|
});
|
|
|
|
test('범인찾기 API: 목록 · 상세 · 내부 전용 경로', async () => {
|
|
const ctx = setup();
|
|
const { id } = seedValorant(ctx);
|
|
const api = await culpritApi(ctx);
|
|
const list = (await api.inject({ url: '/api/culprit/matches' })).json() as CulpritMatchItem[];
|
|
assert.equal(list.length, 1);
|
|
assert.equal(list[0].eligibility.state, 'ready');
|
|
// 브라우저(사이트 중계)는 내부 경로를 쓸 수 없다
|
|
assert.equal((await api.inject({ url: `/api/culprit/internal/${id}/input` })).statusCode, 403);
|
|
assert.equal((await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, payload: {} })).statusCode, 403);
|
|
const r = await api.inject({ url: `/api/culprit/internal/${id}/input`, headers: { 'x-gvr-internal': '1' } });
|
|
assert.equal(r.statusCode, 200);
|
|
const input = r.json().input as CulpritInput;
|
|
assert.ok(input.text.length > 1000);
|
|
const result = {
|
|
summary: '요약',
|
|
confidence: 'high',
|
|
confidence_note: '',
|
|
teams: [
|
|
{ team: 'ally', culprit: 'P2', reason: '이유', evidence: [{ ref: 'u2', note: '"아 그냥 간다"', target: input.refs.u2 }] },
|
|
{ team: 'enemy', culprit: 'P8', reason: '이유', evidence: [] },
|
|
],
|
|
players: input.players.map((p) => ({ id: p.id, score: p.id === 'P2' || p.id === 'P8' ? 3 : 7, tag: p.id === 'P2' || p.id === 'P8' ? '범인' : '무난', comment: '평', evidence: [] })),
|
|
};
|
|
const put = await api.inject({
|
|
method: 'PUT',
|
|
url: `/api/culprit/internal/${id}/result`,
|
|
headers: { 'x-gvr-internal': '1' },
|
|
payload: { result, players: input.players, model: 'claude-opus-5-5', createdBy: { id: 'u1', name: '하늘' }, meta: { costUsd: 0.41 } },
|
|
});
|
|
assert.equal(put.statusCode, 200);
|
|
const info = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
|
|
assert.equal(info.eligibility.state, 'done');
|
|
assert.equal(info.analysis!.result.teams[0].culprit, 'P2');
|
|
assert.equal(info.analysis!.meta.costUsd, 0.41);
|
|
assert.equal(info.history.length, 1);
|
|
assert.equal(info.sources.utterances, 4);
|
|
const list2 = (await api.inject({ url: '/api/culprit/matches' })).json() as CulpritMatchItem[];
|
|
assert.deepEqual(
|
|
list2[0].culprits.map((c) => [c.team, c.name]),
|
|
[
|
|
['ally', '민수'],
|
|
['enemy', 'Kiwi'],
|
|
],
|
|
);
|
|
// 다시 분석하면 이전 결과는 기록으로 남는다
|
|
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result, players: input.players, model: 'm2', createdBy: { id: 'u1', name: '하늘' }, meta: {} } });
|
|
const info2 = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
|
|
assert.equal(info2.history.length, 2);
|
|
assert.equal(info2.analysis!.model, 'm2');
|
|
assert.equal(info2.history.filter((h) => h.current).length, 1);
|
|
|
|
// 표시 이름(실명 숨기기): 이름을 바꾸기 전에 시작한 분석(자료 · 요약에 예전 이름)이 바꾼 뒤에 도착해도 예전 이름이 남지 않는다
|
|
ctx.store.setDisplayNames({ u1: '별명' });
|
|
assert.equal(ctx.store.getUser('u1')?.name, '별명');
|
|
const late = { ...result, summary: '하늘이 캐리했다' };
|
|
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result: late, players: input.players, model: 'm3', createdBy: { id: 'u1', name: '하늘' }, meta: {} } });
|
|
const raw = () => JSON.stringify(ctx.store.db.prepare('SELECT created_by, result FROM culprit_analyses').all());
|
|
assert.ok(!raw().includes('하늘'), raw());
|
|
const info3 = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
|
|
assert.equal(info3.analysis!.result.summary, '별명이 캐리했다');
|
|
assert.equal(info3.analysis!.createdBy.name, '별명');
|
|
assert.ok(info3.analysis!.players.some((p) => p.name === '별명'));
|
|
// 같은 이름으로 다시 받아도(이미 바뀐 유저는 건너뛰는 경우) 그대로 깨끗하다
|
|
ctx.store.setDisplayNames({ u1: '별명' });
|
|
assert.ok(!raw().includes('하늘'));
|
|
await api.close();
|
|
});
|
|
|
|
test('녹음 안내 문구: 예전 기본 문구는 AI 분석 안내가 들어간 새 기본 문구로, 직접 고친 문구는 그대로', () => {
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-tts-'));
|
|
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify({ discord: { ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.' } }));
|
|
assert.equal(new SettingsStore(dir).get().discord.ttsText, DEFAULT_TTS_TEXT);
|
|
assert.match(DEFAULT_TTS_TEXT, /AI 경기 분석에 쓰일 수 있어요/);
|
|
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify({ discord: { ttsText: '녹음 중입니다' } }));
|
|
assert.equal(new SettingsStore(dir).get().discord.ttsText, '녹음 중입니다');
|
|
});
|