Files
gridpilot.gg/core/racing/application/use-cases/GetLeagueDriverSeasonStatsUseCase.test.ts
2025-12-21 00:43:42 +01:00

232 lines
8.3 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
GetLeagueDriverSeasonStatsUseCase,
type GetLeagueDriverSeasonStatsResult,
type GetLeagueDriverSeasonStatsInput,
type GetLeagueDriverSeasonStatsErrorCode,
} from './GetLeagueDriverSeasonStatsUseCase';
import type { IStandingRepository } from '../../domain/repositories/IStandingRepository';
import type { IResultRepository } from '../../domain/repositories/IResultRepository';
import type { IPenaltyRepository } from '../../domain/repositories/IPenaltyRepository';
import type { IRaceRepository } from '../../domain/repositories/IRaceRepository';
import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import type { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import type { DriverRatingPort } from '../ports/DriverRatingPort';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
describe('GetLeagueDriverSeasonStatsUseCase', () => {
const mockStandingFindByLeagueId = vi.fn();
const mockResultFindByDriverIdAndLeagueId = vi.fn();
const mockPenaltyFindByRaceId = vi.fn();
const mockRaceFindByLeagueId = vi.fn();
const mockDriverRatingGetRating = vi.fn();
const mockDriverFindById = vi.fn();
const mockTeamFindById = vi.fn();
let useCase: GetLeagueDriverSeasonStatsUseCase;
let standingRepository: IStandingRepository;
let resultRepository: IResultRepository;
let penaltyRepository: IPenaltyRepository;
let raceRepository: IRaceRepository;
let driverRepository: IDriverRepository;
let teamRepository: ITeamRepository;
let driverRatingPort: DriverRatingPort;
let output: UseCaseOutputPort<GetLeagueDriverSeasonStatsResult> & { present: ReturnType<typeof vi.fn> };
beforeEach(() => {
mockStandingFindByLeagueId.mockReset();
mockResultFindByDriverIdAndLeagueId.mockReset();
mockPenaltyFindByRaceId.mockReset();
mockRaceFindByLeagueId.mockReset();
mockDriverRatingGetRating.mockReset();
mockDriverFindById.mockReset();
mockTeamFindById.mockReset();
standingRepository = {
findByLeagueId: mockStandingFindByLeagueId,
findByDriverIdAndLeagueId: vi.fn(),
findAll: vi.fn(),
save: vi.fn(),
saveMany: vi.fn(),
delete: vi.fn(),
deleteByLeagueId: vi.fn(),
exists: vi.fn(),
recalculate: vi.fn(),
};
resultRepository = {
findByDriverIdAndLeagueId: mockResultFindByDriverIdAndLeagueId,
};
penaltyRepository = {
findByRaceId: mockPenaltyFindByRaceId,
};
raceRepository = {
findById: vi.fn(),
findAll: vi.fn(),
findByLeagueId: mockRaceFindByLeagueId,
findUpcomingByLeagueId: vi.fn(),
findCompletedByLeagueId: vi.fn(),
findByStatus: vi.fn(),
findByDateRange: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
exists: vi.fn(),
};
driverRepository = {
findById: mockDriverFindById,
};
teamRepository = {
findById: mockTeamFindById,
};
driverRatingPort = {
getRating: mockDriverRatingGetRating,
};
output = {
present: vi.fn(),
} as unknown as UseCaseOutputPort<GetLeagueDriverSeasonStatsResult> & {
present: ReturnType<typeof vi.fn>;
};
useCase = new GetLeagueDriverSeasonStatsUseCase(
standingRepository,
resultRepository,
penaltyRepository,
raceRepository,
driverRepository,
teamRepository,
driverRatingPort,
output,
);
});
it('should return league driver season stats for given league id', async () => {
const input: GetLeagueDriverSeasonStatsInput = { leagueId: 'league-1' };
const mockStandings = [
{ driverId: 'driver-1', position: 1, points: 100, racesCompleted: 5 },
{ driverId: 'driver-2', position: 2, points: 80, racesCompleted: 5 },
];
const mockRaces = [{ id: 'race-1' }, { id: 'race-2' }];
const mockPenalties = [
{ driverId: 'driver-1', status: 'applied', type: 'points_deduction', value: 10 },
];
const mockResults = [{ position: 1 }];
const mockRating = { rating: 1500, ratingChange: 50 };
const mockDriver = { id: 'driver-1', name: 'Driver One', teamId: 'team-1' };
const mockTeam = { id: 'team-1', name: 'Team One' };
mockStandingFindByLeagueId.mockResolvedValue(mockStandings);
mockRaceFindByLeagueId.mockResolvedValue(mockRaces);
mockPenaltyFindByRaceId.mockImplementation((raceId: string) => {
if (raceId === 'race-1') return Promise.resolve(mockPenalties);
return Promise.resolve([]);
});
mockDriverRatingGetRating.mockReturnValue(mockRating);
mockResultFindByDriverIdAndLeagueId.mockResolvedValue(mockResults);
mockDriverFindById.mockImplementation((id: string) => {
if (id === 'driver-1') return Promise.resolve(mockDriver);
if (id === 'driver-2') return Promise.resolve({ id: 'driver-2', name: 'Driver Two' });
return Promise.resolve(null);
});
mockTeamFindById.mockResolvedValue(mockTeam);
const result = await useCase.execute(input);
expect(result.isOk()).toBe(true);
expect(result.unwrap()).toBeUndefined();
expect(output.present).toHaveBeenCalledTimes(1);
const presented = output.present.mock.calls[0][0] as GetLeagueDriverSeasonStatsResult;
expect(presented.leagueId).toBe('league-1');
expect(presented.stats).toHaveLength(2);
expect(presented.stats[0]).toEqual({
leagueId: 'league-1',
driverId: 'driver-1',
position: 1,
driverName: 'Driver One',
teamId: 'team-1',
teamName: 'Team One',
totalPoints: 100,
basePoints: 90,
penaltyPoints: -10,
bonusPoints: 0,
pointsPerRace: 20,
racesStarted: 1,
racesFinished: 1,
dnfs: 0,
noShows: 1,
avgFinish: 1,
rating: 1500,
ratingChange: 50,
});
});
it('should handle no penalties', async () => {
const input: GetLeagueDriverSeasonStatsInput = { leagueId: 'league-1' };
const mockStandings = [
{ driverId: 'driver-1', position: 1, points: 100, racesCompleted: 5 },
];
const mockRaces = [{ id: 'race-1' }];
const mockResults = [{ position: 1 }];
const mockRating = { rating: null, ratingChange: null };
const mockDriver = { id: 'driver-1', name: 'Driver One' };
mockStandingFindByLeagueId.mockResolvedValue(mockStandings);
mockRaceFindByLeagueId.mockResolvedValue(mockRaces);
mockPenaltyFindByRaceId.mockResolvedValue([]);
mockDriverRatingGetRating.mockReturnValue(mockRating);
mockResultFindByDriverIdAndLeagueId.mockResolvedValue(mockResults);
mockDriverFindById.mockResolvedValue(mockDriver);
mockTeamFindById.mockResolvedValue(null);
const result = await useCase.execute(input);
expect(result.isOk()).toBe(true);
expect(result.unwrap()).toBeUndefined();
expect(output.present).toHaveBeenCalledTimes(1);
const presented = output.present.mock.calls[0][0] as GetLeagueDriverSeasonStatsResult;
expect(presented.stats[0].penaltyPoints).toBe(0);
});
it('should return LEAGUE_NOT_FOUND when no standings are found', async () => {
const input: GetLeagueDriverSeasonStatsInput = { leagueId: 'missing-league' };
mockStandingFindByLeagueId.mockResolvedValue([]);
mockRaceFindByLeagueId.mockResolvedValue([]);
const result = await useCase.execute(input);
expect(result.isErr()).toBe(true);
const err = result.unwrapErr() as ApplicationErrorCode<
GetLeagueDriverSeasonStatsErrorCode,
{ message: string }
>;
expect(err.code).toBe('LEAGUE_NOT_FOUND');
expect(err.details.message).toBe('League not found');
expect(output.present).not.toHaveBeenCalled();
});
it('should return REPOSITORY_ERROR when an unexpected error occurs', async () => {
const input: GetLeagueDriverSeasonStatsInput = { leagueId: 'league-1' };
const thrown = new Error('repository failure');
mockStandingFindByLeagueId.mockRejectedValue(thrown);
const result = await useCase.execute(input);
expect(result.isErr()).toBe(true);
const err = result.unwrapErr() as ApplicationErrorCode<
GetLeagueDriverSeasonStatsErrorCode,
{ message: string }
>;
expect(err.code).toBe('REPOSITORY_ERROR');
expect(err.details.message).toBe('repository failure');
expect(output.present).not.toHaveBeenCalled();
});
});