import { getQueueToken } from '@nestjs/bullmq'; import { Test, TestingModule } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import { FEATURE_SCHEMA_VERSION, type PlayerAnalysisDto, } from '@persona-lenz/shared'; import request from 'supertest'; import { App } from 'supertest/types'; import { configureApp } from './../src/app.setup'; import { AppModule } from './../src/app.module'; import { AnalysisQueueService } from './../src/modules/analysis/analysis-queue.service'; import { ANALYSIS_QUEUE_NAME } from './../src/modules/analysis/analysis.constants'; import { ConnectionService } from './../src/modules/global/database/connection.service'; import { REDIS_CLIENT } from './../src/modules/global/redis/redis.constants'; import { SecretService } from './../src/modules/global/secret/secret.service'; describe('AppController (e2e)', () => { let app: INestApplication; let analysisQueueService: { enqueueUserAnalysis: jest.Mock; }; let connectionService: { getModel: jest.Mock; }; function createLeanExec(value: T) { return { lean: jest.fn(() => ({ exec: jest.fn().mockResolvedValue(value), })), }; } beforeEach(async () => { analysisQueueService = { enqueueUserAnalysis: jest.fn(), }; connectionService = { getModel: jest.fn(), }; const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }) .overrideProvider(ConnectionService) .useValue(connectionService) .overrideProvider(AnalysisQueueService) .useValue(analysisQueueService) .overrideProvider(SecretService) .useValue({ get: jest.fn((key: string) => { if (key === 'REDIS_URL') { return Promise.resolve('redis://localhost:6379/0'); } return Promise.resolve(''); }), ready: jest.fn().mockResolvedValue(undefined), }) .overrideProvider(REDIS_CLIENT) .useValue({ destroy: jest.fn(), quit: jest.fn().mockResolvedValue(undefined), }) .overrideProvider(getQueueToken(ANALYSIS_QUEUE_NAME)) .useValue({ add: jest.fn(), }) .compile(); app = moduleFixture.createNestApplication(); configureApp(app); await app.init(); }); it('/api/health (GET)', () => { return request(app.getHttpServer()) .get('/api/health') .expect(200) .expect({ status: 'ok' }); }); it('/api/analysis/request (POST) validates and enqueues analysis requests', async () => { analysisQueueService.enqueueUserAnalysis.mockResolvedValue({ jobId: 'analysis-job-1', status: 'queued', }); await request(app.getHttpServer()) .post('/api/analysis/request') .send({ gameName: ' Hide on bush ', ignored: 'field', matchCount: 999, tagLine: ' KR1 ', }) .expect(202) .expect({ jobId: 'analysis-job-1', status: 'queued', }); expect(analysisQueueService.enqueueUserAnalysis).toHaveBeenCalledWith({ gameName: 'Hide on bush', tagLine: 'KR1', platformRoute: 'kr', regionalRoute: 'asia', queueId: 420, requestedMatchCount: 50, }); }); it('/api/analysis/request (POST) maps non-default platforms to regional routes', async () => { analysisQueueService.enqueueUserAnalysis.mockResolvedValue({ jobId: 'analysis-job-1', status: 'queued', }); await request(app.getHttpServer()) .post('/api/analysis/request') .send({ gameName: 'Hide on bush', matchCount: 0, platform: 'ph2', tagLine: 'KR1', }) .expect(202); expect(analysisQueueService.enqueueUserAnalysis).toHaveBeenCalledWith({ gameName: 'Hide on bush', tagLine: 'KR1', platformRoute: 'ph2', regionalRoute: 'sea', queueId: 420, requestedMatchCount: 1, }); }); it.each([ ['short gameName', { gameName: 'x', tagLine: 'KR1' }], ['missing tagLine', { gameName: 'Hide on bush' }], ['long tagLine', { gameName: 'Hide on bush', tagLine: 'TOOLONG' }], [ 'unsupported platform', { gameName: 'Hide on bush', platform: 'bad', tagLine: 'KR1' }, ], [ 'non-number matchCount', { gameName: 'Hide on bush', matchCount: '20', tagLine: 'KR1' }, ], ])('/api/analysis/request (POST) rejects %s', async (_label, body) => { await request(app.getHttpServer()) .post('/api/analysis/request') .send(body) .expect(400); expect(analysisQueueService.enqueueUserAnalysis).not.toHaveBeenCalled(); }); it('/api/analysis/request (POST) throttles repeated accepted requests', async () => { analysisQueueService.enqueueUserAnalysis.mockResolvedValue({ jobId: 'analysis-job-1', status: 'queued', }); for (let index = 0; index < 10; index += 1) { await request(app.getHttpServer()) .post('/api/analysis/request') .send({ gameName: 'Hide on bush', tagLine: 'KR1', }) .expect(202); } await request(app.getHttpServer()) .post('/api/analysis/request') .send({ gameName: 'Hide on bush', tagLine: 'KR1', }) .expect(429); }); it('/api/analysis/jobs/:jobId (GET) returns job statuses', async () => { const records = new Map([ [ 'queued-job', { error: undefined, jobId: 'queued-job', progress: { fetchedMatches: 0, totalMatches: 0 }, status: 'queued', }, ], [ 'completed-job', { error: undefined, jobId: 'completed-job', progress: { fetchedMatches: 20, totalMatches: 20 }, puuid: 'target-puuid', stage: 'completed', status: 'completed', }, ], [ 'failed-job', { error: 'internal redis hostname leaked', jobId: 'failed-job', progress: { fetchedMatches: 4, totalMatches: 20 }, stage: 'fetch-match-details', status: 'failed', }, ], ]); const findOne = jest.fn(({ jobId }: { jobId: string }) => createLeanExec(records.get(jobId) ?? null), ); connectionService.getModel.mockResolvedValue({ findOne, }); await request(app.getHttpServer()) .get('/api/analysis/jobs/queued-job') .expect(200) .expect({ error: null, jobId: 'queued-job', progress: { fetchedMatches: 0, totalMatches: 0 }, status: 'queued', }); await request(app.getHttpServer()) .get('/api/analysis/jobs/completed-job') .expect(200) .expect({ error: null, jobId: 'completed-job', progress: { fetchedMatches: 20, totalMatches: 20 }, puuid: 'target-puuid', stage: 'completed', status: 'completed', }); await request(app.getHttpServer()) .get('/api/analysis/jobs/failed-job') .expect(200) .expect({ error: 'Analysis failed during processing.', jobId: 'failed-job', progress: { fetchedMatches: 4, totalMatches: 20 }, stage: 'fetch-match-details', status: 'failed', }); expect(findOne).toHaveBeenCalledWith({ jobId: 'queued-job' }); expect(findOne).toHaveBeenCalledWith({ jobId: 'completed-job' }); expect(findOne).toHaveBeenCalledWith({ jobId: 'failed-job' }); }); it('/api/analysis/jobs/:jobId (GET) returns 404 for missing jobs', async () => { connectionService.getModel.mockResolvedValue({ findOne: jest.fn(() => createLeanExec(null)), }); await request(app.getHttpServer()) .get('/api/analysis/jobs/missing-job') .expect(404); }); it('/api/players/:puuid/analysis/latest (GET) returns latest analysis', async () => { const accountFindOne = jest.fn(() => createLeanExec({ gameName: 'Hide on bush', profileIconId: 1, tagLine: 'KR1', tiers: [ { fetchedAt: new Date('2026-07-01T00:00:00.000Z'), leaguePoints: 100, losses: 5, queueType: 'RANKED_SOLO_5x5', rank: 'I', tier: 'MASTER', wins: 10, }, ], }), ); const profileFindOne = jest.fn(() => createLeanExec({ championPool: [{ championId: 103, games: 4, wins: 3 }], confidence: 0.9, featureSchemaVersion: FEATURE_SCHEMA_VERSION, mainRole: 'MIDDLE', profile: { kda: 0.8, killParticipation: 0.7, damageShare: 0.6, damagePerMin: 0.5, goldPerMin: 0.4, csPerMin: 0.3, visionScorePerMin: 0.2, wardsKilledPerMin: 0.1, controlWardsPlaced: 0.2, deathsPerMin: 0.1, objectiveParticipation: 0.6, soloKills: 0.4, }, queueId: 420, sampleGameCount: 12, updatedAt: new Date('2026-07-02T00:00:00.000Z'), }), ); connectionService.getModel.mockImplementation((modelKey: string) => { if (modelKey === 'account') { return Promise.resolve({ findOne: accountFindOne, }); } if (modelKey !== 'playerProfile') { throw new Error(`Unexpected model ${modelKey}`); } return Promise.resolve({ findOne: profileFindOne, }); }); const response = await request(app.getHttpServer()) .get('/api/players/target-puuid/analysis/latest') .expect(200); const responseBody = response.body as PlayerAnalysisDto; expect(accountFindOne).toHaveBeenCalledWith({ puuid: 'target-puuid' }); expect(profileFindOne).toHaveBeenCalledWith({ puuid: 'target-puuid', queueId: 420, }); expect(responseBody).toEqual({ account: { gameName: 'Hide on bush', profileIconId: 1, tagLine: 'KR1', tiers: [ { fetchedAt: '2026-07-01T00:00:00.000Z', leaguePoints: 100, losses: 5, queueType: 'RANKED_SOLO_5x5', rank: 'I', tier: 'MASTER', wins: 10, }, ], }, profile: { championPool: [{ championId: 103, games: 4, wins: 3 }], confidence: 0.9, featureSchemaVersion: FEATURE_SCHEMA_VERSION, mainRole: 'MIDDLE', playstyle: { kda: 0.8, killParticipation: 0.7, damageShare: 0.6, damagePerMin: 0.5, goldPerMin: 0.4, csPerMin: 0.3, visionScorePerMin: 0.2, wardsKilledPerMin: 0.1, controlWardsPlaced: 0.2, deathsPerMin: 0.1, objectiveParticipation: 0.6, soloKills: 0.4, }, queueId: 420, sampleGameCount: 12, }, strengths: [ { metricId: 'deathsPerMin', value: 0.1 }, { metricId: 'kda', value: 0.8 }, { metricId: 'killParticipation', value: 0.7 }, ], weaknesses: [ { metricId: 'wardsKilledPerMin', value: 0.1 }, { metricId: 'visionScorePerMin', value: 0.2 }, { metricId: 'controlWardsPlaced', value: 0.2 }, ], updatedAt: '2026-07-02T00:00:00.000Z', }); }); it('/api/players/:puuid/analysis/latest (GET) returns 404 without a profile', async () => { connectionService.getModel.mockImplementation((modelKey: string) => { if (modelKey === 'playerProfile') { return Promise.resolve({ findOne: jest.fn(() => createLeanExec(null)), }); } return Promise.resolve({ findOne: jest.fn(() => createLeanExec({})), }); }); await request(app.getHttpServer()) .get('/api/players/target-puuid/analysis/latest') .expect(404) .expect((response) => { expect(response.body).toMatchObject({ message: '분석할 랭크 게임이 없음', }); }); }); afterEach(async () => { await app.close(); }); });