571 lines
16 KiB
TypeScript
571 lines
16 KiB
TypeScript
import { getQueueToken } from '@nestjs/bullmq';
|
|
import { Test, TestingModule } from '@nestjs/testing';
|
|
import { INestApplication } from '@nestjs/common';
|
|
import {
|
|
FEATURE_SCHEMA_VERSION,
|
|
type PlayerAnalysisDto,
|
|
type SimilarPlayersDto,
|
|
} 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,
|
|
SEED_COLLECTION_QUEUE_NAME,
|
|
} from './../src/modules/analysis/analysis.constants';
|
|
import { SimilarPlayerService } from './../src/modules/analysis/similar-player.service';
|
|
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<App>;
|
|
let analysisQueueService: {
|
|
enqueueUserAnalysis: jest.Mock;
|
|
};
|
|
let similarPlayerService: {
|
|
findSimilarPlayers: jest.Mock;
|
|
};
|
|
let connectionService: {
|
|
getModel: jest.Mock;
|
|
};
|
|
|
|
function createLeanExec<T>(value: T) {
|
|
return {
|
|
lean: jest.fn(() => ({
|
|
exec: jest.fn().mockResolvedValue(value),
|
|
})),
|
|
};
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
analysisQueueService = {
|
|
enqueueUserAnalysis: jest.fn(),
|
|
};
|
|
similarPlayerService = {
|
|
findSimilarPlayers: jest.fn(),
|
|
};
|
|
connectionService = {
|
|
getModel: jest.fn(),
|
|
};
|
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
|
imports: [AppModule],
|
|
})
|
|
.overrideProvider(ConnectionService)
|
|
.useValue(connectionService)
|
|
.overrideProvider(AnalysisQueueService)
|
|
.useValue(analysisQueueService)
|
|
.overrideProvider(SimilarPlayerService)
|
|
.useValue(similarPlayerService)
|
|
.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(),
|
|
})
|
|
.overrideProvider(getQueueToken(SEED_COLLECTION_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,
|
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
|
});
|
|
expect(responseBody).toMatchObject({
|
|
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,
|
|
},
|
|
updatedAt: '2026-07-02T00:00:00.000Z',
|
|
});
|
|
expect(responseBody.strengths).toHaveLength(12);
|
|
expect(responseBody.weaknesses).toHaveLength(12);
|
|
expect(responseBody.strengths).toEqual(
|
|
expect.arrayContaining([
|
|
{ metricId: 'deathsPerMin', value: 0.1 },
|
|
{ metricId: 'kda', value: 0.8 },
|
|
{ metricId: 'killParticipation', value: 0.7 },
|
|
{ metricId: 'wardsKilledPerMin', value: 0.1 },
|
|
]),
|
|
);
|
|
expect(responseBody.weaknesses).toEqual(
|
|
expect.arrayContaining([
|
|
{ metricId: 'wardsKilledPerMin', value: 0.1 },
|
|
{ metricId: 'visionScorePerMin', value: 0.2 },
|
|
{ metricId: 'controlWardsPlaced', value: 0.2 },
|
|
{ metricId: 'deathsPerMin', value: 0.1 },
|
|
]),
|
|
);
|
|
expect(responseBody.strengths.slice(0, 3)).toEqual([
|
|
{ metricId: 'deathsPerMin', value: 0.1 },
|
|
{ metricId: 'kda', value: 0.8 },
|
|
{ metricId: 'killParticipation', value: 0.7 },
|
|
]);
|
|
expect(responseBody.weaknesses.slice(0, 3)).toEqual([
|
|
{ metricId: 'wardsKilledPerMin', value: 0.1 },
|
|
{ metricId: 'visionScorePerMin', value: 0.2 },
|
|
{ metricId: 'controlWardsPlaced', value: 0.2 },
|
|
]);
|
|
});
|
|
|
|
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: '분석할 랭크 게임이 없음',
|
|
});
|
|
});
|
|
});
|
|
|
|
it('/api/players/:puuid/similar-players (GET) returns similar players with display Riot IDs', async () => {
|
|
similarPlayerService.findSimilarPlayers.mockResolvedValue({
|
|
puuid: 'target-puuid',
|
|
queueId: 420,
|
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
|
matches: [
|
|
{
|
|
puuid: 'similar-player-puuid',
|
|
similarityScore: 0.87,
|
|
finalScore: 0.81,
|
|
tier: 'CHALLENGER',
|
|
leaguePoints: 900,
|
|
tierComparison: 'higher',
|
|
mainRole: 'MIDDLE',
|
|
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
|
|
sampleGameCount: 40,
|
|
similarMetrics: [
|
|
{
|
|
metricId: 'kda',
|
|
currentValue: 0.3,
|
|
otherValue: 0.31,
|
|
absoluteGap: 0.01,
|
|
},
|
|
],
|
|
strongerMetrics: [
|
|
{
|
|
metricId: 'goldPerMin',
|
|
currentValue: 0.5,
|
|
otherValue: 0.8,
|
|
lead: 0.3,
|
|
},
|
|
],
|
|
weakerMetrics: [
|
|
{
|
|
metricId: 'visionScorePerMin',
|
|
currentValue: 0.6,
|
|
otherValue: 0.4,
|
|
lead: 0.2,
|
|
},
|
|
],
|
|
},
|
|
],
|
|
});
|
|
const accountFind = jest.fn(() =>
|
|
createLeanExec([
|
|
{
|
|
puuid: 'similar-player-puuid',
|
|
gameName: '프리리',
|
|
tagLine: 'KR1',
|
|
},
|
|
]),
|
|
);
|
|
connectionService.getModel.mockResolvedValue({
|
|
find: accountFind,
|
|
});
|
|
|
|
const response = await request(app.getHttpServer())
|
|
.get('/api/players/target-puuid/similar-players?limit=3')
|
|
.expect(200);
|
|
const responseBody = response.body as SimilarPlayersDto;
|
|
|
|
expect(similarPlayerService.findSimilarPlayers).toHaveBeenCalledWith(
|
|
'target-puuid',
|
|
420,
|
|
3,
|
|
);
|
|
expect(accountFind).toHaveBeenCalledWith({
|
|
puuid: { $in: ['similar-player-puuid'] },
|
|
});
|
|
expect(responseBody).toEqual({
|
|
puuid: 'target-puuid',
|
|
queueId: 420,
|
|
profileUpdatedAt: '2026-07-02T00:00:00.000Z',
|
|
matches: [
|
|
{
|
|
displayId: 'similar-1',
|
|
riotId: {
|
|
gameName: '프리리',
|
|
tagLine: 'KR1',
|
|
},
|
|
similarityScore: 0.87,
|
|
finalScore: 0.81,
|
|
tier: 'CHALLENGER',
|
|
leaguePoints: 900,
|
|
tierComparison: 'higher',
|
|
mainRole: 'MIDDLE',
|
|
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
|
|
sampleGameCount: 40,
|
|
similarMetrics: [
|
|
{
|
|
metricId: 'kda',
|
|
currentValue: 0.3,
|
|
otherValue: 0.31,
|
|
absoluteGap: 0.01,
|
|
},
|
|
],
|
|
strongerMetrics: [
|
|
{
|
|
metricId: 'goldPerMin',
|
|
currentValue: 0.5,
|
|
otherValue: 0.8,
|
|
lead: 0.3,
|
|
},
|
|
],
|
|
weakerMetrics: [
|
|
{
|
|
metricId: 'visionScorePerMin',
|
|
currentValue: 0.6,
|
|
otherValue: 0.4,
|
|
lead: 0.2,
|
|
},
|
|
],
|
|
},
|
|
],
|
|
});
|
|
expect(responseBody.matches[0]).not.toHaveProperty('puuid');
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await app.close();
|
|
});
|
|
});
|