From 26fa7c701d76ea686c000a45099b9db28f9d6ac0 Mon Sep 17 00:00:00 2001 From: Kirill Ivlev Date: Sun, 24 Nov 2024 20:36:25 +0400 Subject: [PATCH] TGD-55 --- src/mocks/commandbus.mock.ts | 2 +- src/mocks/guests-service.mock.ts | 2 +- src/quiz/quiz.service.spec.ts | 134 ++++++++++++++++++++++++++++++- src/quiz/quiz.service.ts | 15 ++-- 4 files changed, 143 insertions(+), 10 deletions(-) diff --git a/src/mocks/commandbus.mock.ts b/src/mocks/commandbus.mock.ts index 60ad82e..b3dbd30 100644 --- a/src/mocks/commandbus.mock.ts +++ b/src/mocks/commandbus.mock.ts @@ -1,3 +1,3 @@ export const CommandbusMock = { - + execute: jest.fn(), } \ No newline at end of file diff --git a/src/mocks/guests-service.mock.ts b/src/mocks/guests-service.mock.ts index f70f872..cc01ec0 100644 --- a/src/mocks/guests-service.mock.ts +++ b/src/mocks/guests-service.mock.ts @@ -1,3 +1,3 @@ export const GuestsServiceMock = { - + updatePenaltiesCount: jest.fn(), } \ No newline at end of file diff --git a/src/quiz/quiz.service.spec.ts b/src/quiz/quiz.service.spec.ts index bc3e406..bf168b7 100644 --- a/src/quiz/quiz.service.spec.ts +++ b/src/quiz/quiz.service.spec.ts @@ -1,5 +1,5 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { QuizService } from './quiz.service'; +import {Test, TestingModule} from '@nestjs/testing'; +import {QuizService} from './quiz.service'; import {getModelToken} from "@nestjs/mongoose"; import {Question} from "../schemas/question.schema"; import {Model} from "mongoose"; @@ -13,9 +13,18 @@ import {EventbusMock} from "../mocks/eventbus.mock"; import {CommandbusMock} from "../mocks/commandbus.mock"; import {FeatureflagService} from "../featureflag/featureflag.service"; import {FeatureflagServiceMock} from "../mocks/featureflag-service.mock"; +import {IncreasePlayerWinningRateCommand} from "../game/commands/increase-player-winning-rate.command"; +import {IncreasePlayerScoreCommand} from "../guests/command/increase-player-score.command"; +import {getRandomInt} from "../helpers/rand-number"; +import {CreateNewQueueItemCommand} from "../game/commands/create-new-queue-item.command"; +import {GameQueueTypes} from "../schemas/game-queue.schema"; + +jest.mock('../../src/helpers/rand-number'); describe('QuizService', () => { let service: QuizService; + let cmdBus: CommandBus; + let guestService: GuestsService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -32,9 +41,130 @@ describe('QuizService', () => { }).compile(); service = await module.resolve(QuizService); + cmdBus = await module.resolve(CommandBus); + guestService = await module.resolve(GuestsService); }); it('should be defined', () => { expect(service).toBeDefined(); }); + + describe('calculateScore()', () => { + const questionDocumentMock = { + text: 'test question', + answered: false, + valid: 'option1', + answers: ['option1', 'option2', 'option3', 'option4'], + answeredBy: 1, + note: '', + qId: 'xx-xxx-xxx', + userAnswers: [{ + user: 1, + time: new Date(), + valid: false, + }, { + user: 2, + time: new Date(new Date().setSeconds((new Date).getSeconds() - 5)), + valid: false, + }, { + user: 3, + time: new Date(), + valid: true, + }], + scoreCalculated: false, + save: jest.fn(), + }; + + it('should not calculate score if it is already calculated', async () => { + // setup + questionDocumentMock.scoreCalculated = true; + const getSpy = jest.spyOn(service,'get').mockResolvedValue(questionDocumentMock as any); + const cmdBusExecSpy = jest.spyOn(cmdBus, 'execute').mockResolvedValue(null); + + // act + await service.calculateScore(); + + // validate + expect(getSpy).toHaveBeenCalled(); + expect(cmdBusExecSpy).not.toHaveBeenCalled(); + }) + + it('should assign points to winner', async () => { + //setup + questionDocumentMock.scoreCalculated = false; + const getSpy = jest.spyOn(service, 'get').mockResolvedValue(questionDocumentMock as any); + const cmdBusExecSpy = jest.spyOn(cmdBus, 'execute'); + + // act + await service.calculateScore(); + + // validate + const validUser = questionDocumentMock.userAnswers.find(user => user.valid) + expect(cmdBusExecSpy).toHaveBeenNthCalledWith(1,new IncreasePlayerWinningRateCommand(validUser.user, expect.anything())); + expect(cmdBusExecSpy).toHaveBeenNthCalledWith(2, new IncreasePlayerScoreCommand(validUser.user, 1)); + expect(cmdBusExecSpy).toHaveBeenNthCalledWith(4, new IncreasePlayerScoreCommand(validUser.user, 1)); + }) + + + it('should randomly add penalty to last answer if rnd > 50', async () => { + // setup + (getRandomInt as jest.Mock).mockReturnValue(65); + questionDocumentMock.scoreCalculated = false; + const getSpy = jest.spyOn(service, 'get').mockResolvedValue(questionDocumentMock as any); + const cmdBusExecSpy = jest.spyOn(cmdBus, 'execute'); + const whoShouldGetPenalty = questionDocumentMock.userAnswers.find(x => x.user == 2); + + //act + await service.calculateScore(); + + //validate + expect(getRandomInt).toHaveBeenCalledWith(0,100); + expect(cmdBusExecSpy).toHaveBeenCalledWith(new CreateNewQueueItemCommand(whoShouldGetPenalty.user, GameQueueTypes.penalty)); + }); + + it('should not add penalty to last answer if rnd < 50', async () => { + // setup + jest.clearAllMocks(); + (getRandomInt as jest.Mock).mockReturnValue(10); + questionDocumentMock.scoreCalculated = false; + jest.spyOn(service, 'get').mockResolvedValue(questionDocumentMock as any); + const cmdBusExecSpy = jest.spyOn(cmdBus, 'execute'); + const whoShouldGetPenalty = questionDocumentMock.userAnswers.find(x => x.user == 2); + + //act + await service.calculateScore(); + + //validate + expect(getRandomInt).toHaveBeenCalledWith(0,100); + expect(cmdBusExecSpy).not.toHaveBeenCalledWith(new CreateNewQueueItemCommand(whoShouldGetPenalty.user, GameQueueTypes.penalty)); + + }) + + it('should set score calculated after calculation', async () => { + questionDocumentMock.scoreCalculated = false; + const saveSpy = jest.spyOn(questionDocumentMock,'save').mockResolvedValue(true); + jest.spyOn(service, 'get').mockResolvedValue(questionDocumentMock as any); + + // act + await service.calculateScore(); + + //validate + expect(saveSpy).toHaveBeenCalled(); + }) + + it('should add show results in queue', async () => { + // setup + questionDocumentMock.scoreCalculated = false; + const cmdBusExecSpy = jest.spyOn(cmdBus, 'execute'); + const validUser = questionDocumentMock.userAnswers.find(user => user.valid) + jest.spyOn(service, 'get').mockResolvedValue(questionDocumentMock as any); + + + // act + await service.calculateScore(); + + // validate + expect(cmdBusExecSpy).toHaveBeenCalledWith(new CreateNewQueueItemCommand(expect.anything(), GameQueueTypes.showresults)); + }) + }); }); diff --git a/src/quiz/quiz.service.ts b/src/quiz/quiz.service.ts index b744bba..3a06f55 100644 --- a/src/quiz/quiz.service.ts +++ b/src/quiz/quiz.service.ts @@ -120,7 +120,7 @@ export class QuizService { return Promise.resolve(true); } - private async calculateScore() { + async calculateScore() { const question = await this.get(); if(question.scoreCalculated) { return; @@ -128,7 +128,6 @@ export class QuizService { if(!await this.featureFlagService.getFeatureFlag(FeatureFlagsConsts.DontMarkQuestionsAsCompleted)) { this.logger.verbose(`[proceedWithGame]: DontMarkQuestionsAsCompleted disabled, marking as complete`); question.answered = true; - } this.logger.verbose(`[calculateScore] enter `); const playerAnswers = question.userAnswers.map((answer) => { @@ -157,13 +156,17 @@ export class QuizService { const invalidAnswers = sortedAnswers.filter((answer) => !answer.valid) if(invalidAnswers.length > 0) { - const lastInvalidAnswer = invalidAnswers[invalidAnswers.length - 1]; + //const lastInvalidAnswer = invalidAnswers[invalidAnswers.length - 1]; + const lastInvalidAnswer = invalidAnswers.sort((a,b) => a.time - b.time)[0]; if(!lastInvalidAnswer) { return; } - targetUser = lastInvalidAnswer.user; - await this.guestService.updatePenaltiesCount(lastInvalidAnswer.user); - await this.commandBus.execute(new CreateNewQueueItemCommand(lastInvalidAnswer.user, GameQueueTypes.penalty)); + const random = getRandomInt(0,100); + if(random > 50) { + await this.guestService.updatePenaltiesCount(lastInvalidAnswer.user); + await this.commandBus.execute(new CreateNewQueueItemCommand(lastInvalidAnswer.user, GameQueueTypes.penalty)); + targetUser = lastInvalidAnswer.user; + } } await this.commandBus.execute(new CreateNewQueueItemCommand(targetUser, GameQueueTypes.showresults)); question.scoreCalculated = true; -- 2.45.2