import { test } from 'node:test'; import assert from 'node:assert/strict'; import { EventEmitter } from 'node:events'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { startMockRiot, lolLiveData } from './mock/riot.ts'; const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-games-')); const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); async function until(fn: () => boolean, ms = 8000, label = 'condition') { const t = Date.now(); while (!fn()) { if (Date.now() - t > ms) throw new Error(`timeout: ${label}`); await sleep(50); } } test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅→라운드→종료→상세', async () => { const dir = tmp(); const mock = await startMockRiot(path.join(dir, 'mock')); process.env.GVR_RIOT_LOCKFILE = mock.lockfile; process.env.GVR_LCU_LOCKFILE = mock.lockfile; process.env.GVR_VAL_GLZ = mock.base; process.env.GVR_VAL_PD = mock.base; process.env.GVR_LOL_LIVE_URL = mock.base; process.env.GVR_POLL_MS = '150'; process.env.GVR_DETAIL_RETRY_MS = '100'; const { Store } = await import('../src/core/db/db.ts'); const { Timeline } = await import('../src/core/timeline.ts'); const { GameAssets } = await import('../src/core/games/assets.ts'); const { GameManager } = await import('../src/core/games/manager.ts'); const { Bus } = await import('../src/core/util/events.ts'); const { defaultSettings } = await import('../src/core/settings.ts'); const store = new Store(path.join(dir, 'db.sqlite')); const bus = new Bus(); const live: any[] = []; bus.on('live', (e) => live.push(e)); const tl = new Timeline(store); const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) }); const sttCalls: string[] = []; const stt: any = { onMatchStart: async () => sttCalls.push('start'), onMatchEnd: async () => sttCalls.push('end') }; const assets = new GameAssets(path.join(dir, 'cache')); (assets as any).refresh = async () => undefined; // 네트워크 없이 assets.lol = { at: Date.now(), version: '16.20.1', champions: { ahri: { id: 'Ahri', key: '103', name: '아리', icon: '/game-assets/ddragon/cdn/16.20.1/img/champion/Ahri.png' }, 'key:103': { id: 'Ahri', key: '103', name: '아리', icon: '/game-assets/ddragon/cdn/16.20.1/img/champion/Ahri.png' } }, items: {}, }; const s = defaultSettings(); store.upsertUser({ id: 'owner', name: '하늘', avatar: null }); const gm = new GameManager(store, assets, worker, stt, tl, bus, () => s, () => 'owner'); gm.start(); try { // ---- 발로란트 await until(() => gm.status().valorant.connected, 5000, 'val connected'); mock.st.valStart = Date.now() - 2000; mock.st.valState = 'INGAME'; await until(() => !!store.getMatch('val-m-0001'), 5000, 'val match start'); assert.equal(store.getMatch('val-m-0001')!.status, 'live'); mock.st.valMessages.push({ mid: 'c1', cid: 'm-0001-blue@ares-coregame.kr1.pvp.net', body: '스모크 깔게', game_name: '민수', puuid: 'ally-2', time: String(Date.now()) }); mock.st.valMessages.push({ mid: 'c2', cid: 'm-0001-all@ares-coregame.kr1.pvp.net', body: 'gg', game_name: '상대1', puuid: 'enemy-1', time: String(Date.now()) }); await until(() => store.events('val-m-0001').filter((e) => e.type === 'chat').length === 2, 5000, 'chat'); mock.st.ally = 1; await until(() => store.events('val-m-0001').some((e) => e.type === 'round_end'), 5000, 'live round'); // 지금 게임 상태 (앱 게임 연동 탭 · 사이트) const lv = gm.live().find((g) => g.game === 'valorant')!; assert.equal(lv.phase, '경기 중'); assert.equal(lv.mode, '경쟁전'); assert.equal(lv.round, 2); assert.deepEqual(lv.score, { ally: 1, enemy: 0 }); assert.equal(lv.self?.name, '하늘#KR1'); await until(() => live.some((e) => e.type === 'games.state' && e.data[0].inMatch), 5000, 'games.state'); // 발화 하나 (경기 중) store.insertUtterance({ id: 'u-val', session_id: null, user_id: 'owner', started_at: Date.now(), ended_at: Date.now() + 500, audio_path: null, match_id: gm.liveMatchAt(Date.now()) }); assert.equal(store.getUtterance('u-val')!.match_id, 'val-m-0001'); mock.st.valState = 'MENUS'; await until(() => store.getMatch('val-m-0001')!.status === 'complete', 8000, 'val details'); const ev = store.events('val-m-0001'); assert.equal(ev.filter((e) => e.type === 'kill').length, 4); assert.equal(ev.filter((e) => e.type === 'chat').length, 2, '채팅은 상세 적용 뒤에도 남는다'); assert.ok(!ev.some((e) => e.id.includes('live-round')), '실시간 라운드는 상세로 교체'); assert.equal(store.rounds('val-m-0001').length, 3); assert.ok(sttCalls.includes('start') && sttCalls.includes('end')); assert.ok(store.listAccounts().some((a) => a.user_id === 'owner' && a.puuid === 'self-puuid-0001'), '주인 계정 자동 연결'); const sum = gm.summary(store.getMatch('val-m-0001')!); assert.deepEqual(sum.score, { ally: 2, enemy: 1 }); assert.equal(sum.win, true); // ---- 롤 mock.st.lolPhase = 'ChampSelect'; await until(() => (gm as any).adapters[1].pendingChat.length === 1, 5000, 'champ select chat'); mock.st.lolPhase = 'InProgress'; mock.st.lolLive = lolLiveData(120, [ { EventID: 0, EventName: 'GameStart', EventTime: 0.05 }, { EventID: 1, EventName: 'ChampionKill', EventTime: 75.2, KillerName: '하늘', VictimName: '적1', Assisters: ['민수'] }, { EventID: 2, EventName: 'DragonKill', EventTime: 90.0, KillerName: '민수', DragonType: 'Fire', Stolen: 'False' }, { EventID: 3, EventName: 'TurretKilled', EventTime: 95.0, KillerName: '하늘', TurretKilled: 'Turret_T2_R_03_A' }, ]); await until(() => !!store.getMatch('lol-7001'), 5000, 'lol start'); await until(() => store.events('lol-7001').length >= 4, 5000, 'lol events'); const ll = gm.live().find((g) => g.game === 'lol')!; assert.equal(ll.phase, '경기 중'); assert.equal(ll.mode, '솔로 랭크'); assert.equal(ll.self?.character, '아리'); assert.equal(ll.self?.kda, '3/1/2'); assert.deepEqual(ll.teamKills, { ally: 4, enemy: 2 }); assert.equal(ll.gameTimeSec, 120); const lev = store.events('lol-7001'); const chat = lev.find((e) => e.type === 'chat')!; assert.equal(JSON.parse(chat.data).text, '정글 갱 갈게요'); assert.equal(JSON.parse(chat.data).source, 'lcu'); const drag = JSON.parse(lev.find((e) => e.type === 'object' && e.data.includes('dragon'))!.data); assert.equal(drag.label, '화염의 용'); assert.equal(drag.ally, true); const tower = JSON.parse(lev.find((e) => e.data.includes('"tower"'))!.data); assert.equal(tower.team, 'ORDER'); // 게임 시간 표시 const k = lev.find((e) => e.type === 'kill')!; assert.equal(tl.eventItem(k).time.primary, '1:15'); mock.st.lolLive = null; mock.st.lolPhase = 'EndOfGame'; mock.st.lolHistoryReady = true; await until(() => store.getMatch('lol-7001')!.status === 'complete', 8000, 'lol history'); const det = JSON.parse(store.getMatch('lol-7001')!.detail!); assert.equal(det.goldDiff.length, 2); assert.equal(det.goldDiff[1].diff, 1700); assert.equal(det.players[0].character.id, 'Ahri'); const kill = store.events('lol-7001').find((e) => e.type === 'kill')!; assert.deepEqual(JSON.parse(kill.data).location, { x: 7000, y: 7200 }); } finally { gm.stop(); await mock.close(); store.close(); } }); test('발로란트 데스매치: 경기 전체가 라운드 1개로 와도 라운드 · 에이스를 만들지 않는다', async () => { const { processMatchDetails } = await import('../src/core/games/valorant.ts'); const { GameAssets } = await import('../src/core/games/assets.ts'); const { makeValDetails, SELF } = await import('./fixtures/make-val-details.ts'); const md = makeValDetails(1_000_000); md.matchInfo.queueID = 'deathmatch'; // 한 "라운드"에 한 사람이 5킬 (데스매치에서는 흔함) const r0 = md.roundResults[0]; const ps = r0.playerStats.find((p: any) => p.subject === SELF)!; const k = ps.kills[0]; ps.kills = Array.from({ length: 6 }, (_, i) => ({ ...k, gameTime: k.gameTime + i * 1000, victim: `enemy-${i}` })); md.roundResults = [r0]; const res = processMatchDetails(md, SELF, new GameAssets(tmp()), 'val-dm', 1_000_000); assert.equal(res.rounds.length, 0); assert.equal(res.roundsDetail.length, 0); assert.ok(!res.events.some((e) => e.type === 'round_end' || e.type === 'ace' || e.type === 'multikill')); assert.ok(res.events.filter((e) => e.type === 'kill').length >= 6); assert.equal(res.result.score, null); });