Files
lolympus-tournament-support/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts
T

295 lines
8.8 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types';
import { TournamentResultService } from './tournament-result.service';
describe('TournamentResultService Competition cutover', () => {
it('accepts a manually collected Riot game through Competition without mutating legacy result state', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const seriesId = new mongoose.Types.ObjectId();
const earlierGameSlotId = new mongoose.Types.ObjectId();
const gameSlotId = new mongoose.Types.ObjectId();
const tournamentCodeId = new mongoose.Types.ObjectId();
const teamAId = new mongoose.Types.ObjectId();
const teamBId = new mongoose.Types.ObjectId();
const users = Array.from({ length: 10 }, (_, index) => ({
userId: new mongoose.Types.ObjectId(),
puuid: `cutover-puuid-${index + 1}`,
}));
const legacyResult = {
winnerTeamIndex: 2,
riotMatchIds: ['legacy'],
games: [],
seriesResults: [],
};
const legacyBracket = { marker: 'must-not-change' };
const match = {
_id: matchId,
communityId,
status: 'team-built',
gameCount: 1,
gameMode: 'pair',
teamBuiltAt: new Date('2026-07-12T09:00:00.000Z'),
tournamentCodeIds: [tournamentCodeId],
participants: users.map(({ userId, puuid }) => ({
userId,
puuid,
excluded: false,
})),
teams: [
{
teamIndex: 1,
name: 'Team A',
members: users.slice(0, 5).map(({ userId }) => ({ userId })),
},
{
teamIndex: 2,
name: 'Team B',
members: users.slice(5).map(({ userId }) => ({ userId })),
},
],
result: legacyResult,
doubleElimination: legacyBracket,
save: jest.fn().mockResolvedValue(undefined),
} as unknown as MatchDocument & { save: jest.Mock };
const readyCompetition = {
_id: competitionId,
revision: 0,
phase: 'ready',
teams: [
{
teamId: teamAId,
members: users.slice(0, 5).map(({ userId }) => ({ userId })),
},
{
teamId: teamBId,
members: users.slice(5).map(({ userId }) => ({ userId })),
},
],
projection: {
phase: 'ready',
series: [
{
seriesId: seriesId.toString(),
status: 'ready',
entries: [
{ slot: 'A', teamId: teamAId.toString(), gameWins: 0 },
{ slot: 'B', teamId: teamBId.toString(), gameWins: 0 },
],
},
],
gameSlots: [
{
id: earlierGameSlotId.toString(),
seriesId: seriesId.toString(),
ordinal: 1,
displayNumber: 16,
status: 'ready',
},
{
id: gameSlotId.toString(),
seriesId: seriesId.toString(),
ordinal: 2,
displayNumber: 17,
status: 'ready',
},
],
games: [],
},
};
const completedCompetition = {
...readyCompetition,
revision: 1,
phase: 'completed',
projection: {
...readyCompetition.projection,
phase: 'completed',
games: [
{
evidence: { type: 'riot', riotMatchId: 'KR_CUTOVER_1' },
},
],
},
};
const detail = riotDetail(users.map(({ puuid }) => puuid));
const connectionService = {
getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'match') {
return Promise.resolve({
findById: jest.fn().mockResolvedValue(match),
});
}
if (name === 'community') {
return Promise.resolve({
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ riotRegion: 'asia' }),
}),
}),
}),
});
}
if (name === 'riotMatch') {
return Promise.resolve({
findOne: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
}),
updateOne: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(undefined),
}),
});
}
if (name === 'competition') {
return Promise.resolve({
findById: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(readyCompetition),
}),
}),
});
}
if (name === 'tournamentCode') {
return Promise.resolve({
findOne: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
_id: tournamentCodeId,
code: 'CUTOVER-CODE',
state: 'reserved',
gameNumber: 17,
}),
}),
});
}
if (name === 'tournamentCodeAssignment') {
return Promise.resolve({
findOne: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
competitionId,
seriesId,
gameSlotId,
tournamentCodeId,
state: 'reserved',
}),
}),
}),
updateOne: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(undefined),
}),
});
}
throw new Error(`Unexpected model ${name}`);
}),
};
const commandService = {
acceptGame: jest.fn().mockResolvedValue({
competition: completedCompetition,
commandId: 'cmpcmd-result',
revision: 1,
replayed: false,
}),
};
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
};
const service = new TournamentResultService(
connectionService as never,
{ getMatch: jest.fn().mockResolvedValue(detail) } as never,
{} as never,
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
matchStatsService as never,
{
runWithLock: jest.fn(),
runWithRenewedLock: jest.fn(),
} as never,
{ bootstrap: jest.fn().mockResolvedValue(readyCompetition) } as never,
commandService as never,
{
provisionReadyAssignments: jest.fn().mockResolvedValue({
requested: 1,
reserved: 0,
existing: 1,
unavailable: 0,
}),
} as never,
);
const response = await service.collectManualByRiotMatch({
matchId,
communityId,
riotMatchId: ' KR_CUTOVER_1 ',
});
expect(response).toMatchObject({
scanned: 1,
matched: 1,
skipped: 0,
riotMatchIds: ['KR_CUTOVER_1'],
gameNumbers: [17],
});
expect(commandService.acceptGame).toHaveBeenCalledWith(
expect.objectContaining({
competitionId,
expectedRevision: 0,
idempotencyKey: 'riot-result:KR_CUTOVER_1',
seriesId,
gameSlotId,
ordinal: 2,
mapping: expect.objectContaining({
blueTeamId: teamAId.toString(),
redTeamId: teamBId.toString(),
winnerTeamId: teamAId.toString(),
}),
startedAt: new Date('2026-07-12T10:00:00.000Z'),
durationSeconds: 1800,
participants: expect.any(Array),
tournamentCode: {
tournamentCodeId,
riotMatchId: 'KR_CUTOVER_1',
},
}),
);
expect(match.result).toBe(legacyResult);
expect(match.doubleElimination).toBe(legacyBracket);
expect(match.status).toBe('finished');
expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith(matchId, {
sourceRevision: 1,
});
});
});
function riotDetail(puuids: string[]): RiotMatchDto {
const participants = puuids.map((puuid, index) => ({
puuid,
participantId: index + 1,
teamId: index < 5 ? 100 : 200,
championId: index + 1,
kills: 1,
deaths: 1,
assists: 1,
win: index < 5,
}));
return {
metadata: {
dataVersion: '2',
matchId: 'KR_CUTOVER_1',
participants: puuids,
},
info: {
tournamentCode: 'CUTOVER-CODE',
gameCreation: Date.parse('2026-07-12T10:00:00.000Z'),
gameEndTimestamp: Date.parse('2026-07-12T10:30:00.000Z'),
gameDuration: 1800,
participants,
teams: [
{ teamId: 100, win: true },
{ teamId: 200, win: false },
],
},
} as unknown as RiotMatchDto;
}