From a436d7418757e6102623516f725b38d6463756da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9C=E5=A6=82?= <77052266+JiangRu1@users.noreply.github.com> Date: Thu, 1 Feb 2024 13:39:03 +0800 Subject: [PATCH 1/3] ADM-762: [frontend] feat: clear cache in pipeline (#1017) * ADM-762: [frontend] feat: clear cache in pipeline * ADM-762: [frontend] refactor: delete useless interface --- .../PipelineMetricSelection.test.tsx | 6 +++--- .../containers/ReportStep/ReportStep.test.tsx | 6 +++--- frontend/__tests__/context/metricsSlice.test.ts | 4 ++-- frontend/src/context/Metrics/metricsSlice.ts | 14 +++++++------- frontend/src/context/interface/index.tsx | 7 ------- .../hooks/useMetricsStepValidationCheckContext.tsx | 6 +++--- 6 files changed, 18 insertions(+), 25 deletions(-) delete mode 100644 frontend/src/context/interface/index.tsx diff --git a/frontend/__tests__/containers/MetricsStep/DeploymentFrequencySettings/PipelineMetricSelection.test.tsx b/frontend/__tests__/containers/MetricsStep/DeploymentFrequencySettings/PipelineMetricSelection.test.tsx index 9a8bd5202e..712b3bdd92 100644 --- a/frontend/__tests__/containers/MetricsStep/DeploymentFrequencySettings/PipelineMetricSelection.test.tsx +++ b/frontend/__tests__/containers/MetricsStep/DeploymentFrequencySettings/PipelineMetricSelection.test.tsx @@ -11,9 +11,9 @@ import { } from '@test/fixtures'; import { PipelineMetricSelection } from '@src/containers/MetricsStep/DeploymentFrequencySettings/PipelineMetricSelection'; import { updatePipelineToolVerifyResponseSteps } from '@src/context/config/configSlice'; -import { act, render, waitFor, within, screen } from '@testing-library/react'; +import { act, render, screen, waitFor, within } from '@testing-library/react'; +import { IPipelineConfig } from '@src/context/Metrics/metricsSlice'; import { metricsClient } from '@src/clients/MetricsClient'; -import { PipelineSetting } from '@src/context/interface'; import { setupStore } from '@test/utils/setupStoreUtil'; import userEvent from '@testing-library/user-event'; import { Provider } from 'react-redux'; @@ -70,7 +70,7 @@ describe('PipelineMetricSelection', () => { const mockUpdatePipeline = jest.fn(); const setup = async ( - deploymentFrequencySetting: PipelineSetting, + deploymentFrequencySetting: IPipelineConfig, isShowRemoveButton: boolean, isDuplicated: boolean, ) => { diff --git a/frontend/__tests__/containers/ReportStep/ReportStep.test.tsx b/frontend/__tests__/containers/ReportStep/ReportStep.test.tsx index d120d12c54..a3a305bbd4 100644 --- a/frontend/__tests__/containers/ReportStep/ReportStep.test.tsx +++ b/frontend/__tests__/containers/ReportStep/ReportStep.test.tsx @@ -101,12 +101,12 @@ describe('Report Step', () => { store.dispatch(updateMetrics(params)); store.dispatch(addADeploymentFrequencySetting()); store.dispatch( - updateDeploymentFrequencySettings({ updateId: 0, label: 'organization', value: 'mock organization' }), + updateDeploymentFrequencySettings({ updateId: 1, label: 'organization', value: 'mock organization' }), ); store.dispatch( - updateDeploymentFrequencySettings({ updateId: 0, label: 'pipelineName', value: 'mock pipeline name' }), + updateDeploymentFrequencySettings({ updateId: 1, label: 'pipelineName', value: 'mock pipeline name' }), ); - store.dispatch(updateDeploymentFrequencySettings({ updateId: 0, label: 'step', value: 'mock step1' })); + store.dispatch(updateDeploymentFrequencySettings({ updateId: 1, label: 'step', value: 'mock step1' })); store.dispatch( updatePipelineToolVerifyResponse({ pipelineList: [ diff --git a/frontend/__tests__/context/metricsSlice.test.ts b/frontend/__tests__/context/metricsSlice.test.ts index 29b009a564..50e4f77dcb 100644 --- a/frontend/__tests__/context/metricsSlice.test.ts +++ b/frontend/__tests__/context/metricsSlice.test.ts @@ -341,7 +341,7 @@ describe('saveMetricsSetting reducer', () => { }); it('should add a deploymentFrequencySetting when handle addADeploymentFrequencySettings given initial state', () => { - const addedDeploymentFrequencySettings = [{ id: 0, organization: '', pipelineName: '', step: '', branches: [] }]; + const addedDeploymentFrequencySettings = [{ id: 1, organization: '', pipelineName: '', step: '', branches: [] }]; const savedMetricsSetting = saveMetricsSettingReducer(initState, addADeploymentFrequencySetting()); @@ -349,7 +349,7 @@ describe('saveMetricsSetting reducer', () => { }); it('should add a deploymentFrequencySetting when handle addADeploymentFrequencySettings but initState dont have DeploymentFrequencySettings', () => { - const addedDeploymentFrequencySettings = [{ id: 0, organization: '', pipelineName: '', step: '', branches: [] }]; + const addedDeploymentFrequencySettings = [{ id: 1, organization: '', pipelineName: '', step: '', branches: [] }]; const initStateWithoutDeploymentFrequencySettings = { ...initState, diff --git a/frontend/src/context/Metrics/metricsSlice.ts b/frontend/src/context/Metrics/metricsSlice.ts index 582d457947..4d8451a42e 100644 --- a/frontend/src/context/Metrics/metricsSlice.ts +++ b/frontend/src/context/Metrics/metricsSlice.ts @@ -7,7 +7,6 @@ import { METRICS_CONSTANTS, } from '@src/constants/resources'; import { pipeline } from '@src/context/config/pipelineTool/verifyResponseSlice'; -import { initialBasicConfigState } from '@src/context/config/configSlice'; import { createSlice } from '@reduxjs/toolkit'; import camelCase from 'lodash.camelcase'; import { RootState } from '@src/store'; @@ -212,12 +211,14 @@ export const metricsSlice = createSlice({ state.cycleTimeSettingsType = action.payload; }, addADeploymentFrequencySetting: (state) => { + const { deploymentFrequencySettings, importedData } = state; const newId = - state.deploymentFrequencySettings.length >= 1 - ? state.deploymentFrequencySettings[state.deploymentFrequencySettings.length - 1].id + 1 - : 0; + Math.max( + deploymentFrequencySettings[deploymentFrequencySettings.length - 1]?.id ?? 0, + importedData.importedDeployment[importedData.importedDeployment.length - 1]?.id ?? 0, + ) + 1; state.deploymentFrequencySettings = [ - ...state.deploymentFrequencySettings, + ...deploymentFrequencySettings, { id: newId, organization: '', pipelineName: '', step: '', branches: [] }, ]; }, @@ -488,8 +489,7 @@ export const selectOrganizationWarningMessage = (state: RootState, id: number) = export const selectPipelineNameWarningMessage = (state: RootState, id: number) => { const { deploymentWarningMessage } = state.metrics; - const warningMessage = deploymentWarningMessage; - return warningMessage.find((item) => item.id === id)?.pipelineName; + return deploymentWarningMessage.find((item) => item.id === id)?.pipelineName; }; export const selectStepWarningMessage = (state: RootState, id: number) => { diff --git a/frontend/src/context/interface/index.tsx b/frontend/src/context/interface/index.tsx deleted file mode 100644 index 4c9e832e23..0000000000 --- a/frontend/src/context/interface/index.tsx +++ /dev/null @@ -1,7 +0,0 @@ -export interface PipelineSetting { - id: number; - organization: string; - pipelineName: string; - step: string; - branches: string[]; -} diff --git a/frontend/src/hooks/useMetricsStepValidationCheckContext.tsx b/frontend/src/hooks/useMetricsStepValidationCheckContext.tsx index 6e92394581..1fdcd3ad6d 100644 --- a/frontend/src/hooks/useMetricsStepValidationCheckContext.tsx +++ b/frontend/src/hooks/useMetricsStepValidationCheckContext.tsx @@ -1,8 +1,8 @@ -import { PipelineSetting } from '@src/context/interface'; +import { IPipelineConfig } from '@src/context/Metrics/metricsSlice'; import React, { createContext, useContext } from 'react'; interface ProviderContextType { - getDuplicatedPipeLineIds: (pipelineSettings: PipelineSetting[]) => number[]; + getDuplicatedPipeLineIds: (pipelineSettings: IPipelineConfig[]) => number[]; } interface ContextProviderProps { @@ -13,7 +13,7 @@ export const ValidationContext = createContext({ getDuplicatedPipeLineIds: () => [], }); -const getDuplicatedPipeLineIds = (pipelineSettings: PipelineSetting[]) => { +const getDuplicatedPipeLineIds = (pipelineSettings: IPipelineConfig[]) => { const errors: { [key: string]: number[] } = {}; pipelineSettings.forEach(({ id, organization, pipelineName, step }) => { if (organization && pipelineName && step) { From 9197e13caf360a4dd29c23a5635fc2794e8f9639 Mon Sep 17 00:00:00 2001 From: yulongcai <141199398+yulongcai@users.noreply.github.com> Date: Thu, 1 Feb 2024 14:16:06 +0800 Subject: [PATCH 2/3] ADM-794:[backend]fix: add test for pipeline (#1014) * ADM-794:[backend]fix: add test for generate report * ADM-794:[backend]fix: repair test for pipeline * ADM-794:[backend]fix: add test for pipeline * ADM-794:[backend]fix: refactor code * ADM-794:[backend]fix: refactor for report service test --------- Co-authored-by: yunsong.yang <52806477+mikeyangyun@users.noreply.github.com> --- .../report/GenerateReporterServiceTest.java | 14 ++--- .../service/report/KanbanFixture.java | 41 +++++++++++++ .../service/report/KanbanServiceTest.java | 13 +++- .../service/report/PipelineServiceTest.java | 60 +++++++------------ .../service/report/ReportServiceTest.java | 47 +++++++++++---- 5 files changed, 117 insertions(+), 58 deletions(-) create mode 100644 backend/src/test/java/heartbeat/service/report/KanbanFixture.java diff --git a/backend/src/test/java/heartbeat/service/report/GenerateReporterServiceTest.java b/backend/src/test/java/heartbeat/service/report/GenerateReporterServiceTest.java index 5243a82a54..d7311c9a64 100644 --- a/backend/src/test/java/heartbeat/service/report/GenerateReporterServiceTest.java +++ b/backend/src/test/java/heartbeat/service/report/GenerateReporterServiceTest.java @@ -641,7 +641,7 @@ void shouldGetDataFromCache() { assertEquals(EXPORT_CSV_VALIDITY_TIME, res.getExportValidityTime()); assertEquals(true, res.getAllMetricsCompleted()); - assertEquals(null, res.getReportMetricsError().getBoardMetricsError()); + assertNull(res.getReportMetricsError().getBoardMetricsError()); } @Test @@ -662,7 +662,7 @@ void shouldReturnCompletedFalseGivenResponseNullMetricsDataCompletedFalseWhenGet assertEquals(false, res.getBoardMetricsCompleted()); assertEquals(false, res.getPipelineMetricsCompleted()); assertEquals(false, res.getSourceControlMetricsCompleted()); - assertEquals(null, res.getReportMetricsError().getBoardMetricsError()); + assertNull(res.getReportMetricsError().getBoardMetricsError()); } @Test @@ -683,7 +683,7 @@ void shouldReturnCompletedTrueGivenResponseNonNullMetricsDataCompletedFalseWhenG assertEquals(true, res.getBoardMetricsCompleted()); assertEquals(true, res.getPipelineMetricsCompleted()); assertEquals(true, res.getSourceControlMetricsCompleted()); - assertEquals(null, res.getReportMetricsError().getBoardMetricsError()); + assertNull(res.getReportMetricsError().getBoardMetricsError()); } @Test @@ -697,10 +697,10 @@ void shouldReturnMetricsCompletedStatusIsNullWhenAsyncMetricsStatusIsNull() { assertEquals(EXPORT_CSV_VALIDITY_TIME, res.getExportValidityTime()); assertEquals(false, res.getAllMetricsCompleted()); - assertEquals(null, res.getBoardMetricsCompleted()); - assertEquals(null, res.getPipelineMetricsCompleted()); - assertEquals(null, res.getSourceControlMetricsCompleted()); - assertEquals(null, res.getReportMetricsError().getBoardMetricsError()); + assertNull(res.getBoardMetricsCompleted()); + assertNull(res.getPipelineMetricsCompleted()); + assertNull(res.getSourceControlMetricsCompleted()); + assertNull(res.getReportMetricsError().getBoardMetricsError()); } @Test diff --git a/backend/src/test/java/heartbeat/service/report/KanbanFixture.java b/backend/src/test/java/heartbeat/service/report/KanbanFixture.java new file mode 100644 index 0000000000..f508a58c67 --- /dev/null +++ b/backend/src/test/java/heartbeat/service/report/KanbanFixture.java @@ -0,0 +1,41 @@ +package heartbeat.service.report; + +import heartbeat.controller.board.dto.request.RequestJiraBoardColumnSetting; +import heartbeat.controller.board.dto.request.StoryPointsAndCycleTimeRequest; +import heartbeat.controller.board.dto.response.TargetField; +import heartbeat.controller.report.dto.request.JiraBoardSetting; + +import java.util.List; + +public class KanbanFixture { + + public static JiraBoardSetting MOCK_JIRA_BOARD_SETTING() { + return JiraBoardSetting.builder() + .users(List.of("user1")) + .token("token") + .type("jira") + .site("site") + .projectKey("ADM") + .boardId("2") + .boardColumns(List.of(RequestJiraBoardColumnSetting.builder().value("DONE").name("DONE").build())) + .targetFields(List.of(TargetField.builder().key("customer").build())) + .treatFlagCardAsBlock(true) + .assigneeFilter("assignee") + .build(); + } + + public static StoryPointsAndCycleTimeRequest MOCK_EXPECT_STORY_POINT_AND_CYCLE_TIME_REQUEST() { + return StoryPointsAndCycleTimeRequest.builder() + .token("token") + .type("jira") + .site("site") + .project("ADM") + .boardId("2") + .targetFields(List.of(TargetField.builder().key("customer").build())) + .treatFlagCardAsBlock(true) + .startTime("startTime") + .endTime("endTime") + .build(); + } + +} diff --git a/backend/src/test/java/heartbeat/service/report/KanbanServiceTest.java b/backend/src/test/java/heartbeat/service/report/KanbanServiceTest.java index 2e7b376cf0..a71c692b7a 100644 --- a/backend/src/test/java/heartbeat/service/report/KanbanServiceTest.java +++ b/backend/src/test/java/heartbeat/service/report/KanbanServiceTest.java @@ -32,9 +32,12 @@ class KanbanServiceTest { private KanbanCsvService kanbanCsvService; @Test - void shouldCallCsvServiceToGenerateScvInfo() { + void shouldCallCsvServiceToGenerateCSVInfoWhenJiraBoardSettingIsNotNull() { + JiraBoardSetting mockJiraBoardSetting = KanbanFixture.MOCK_JIRA_BOARD_SETTING(); GenerateReportRequest request = GenerateReportRequest.builder() - .jiraBoardSetting(JiraBoardSetting.builder().treatFlagCardAsBlock(true).build()) + .jiraBoardSetting(mockJiraBoardSetting) + .startTime("startTime") + .endTime("endTime") .build(); CardCollection realDoneCardCollection = CardCollection.builder().build(); CardCollection nonDoneCardCollection = CardCollection.builder().build(); @@ -49,6 +52,12 @@ void shouldCallCsvServiceToGenerateScvInfo() { assertEquals(realDoneCardCollection, result.getRealDoneCardCollection()); assertEquals(nonDoneCardCollection, result.getNonDoneCardCollection()); verify(kanbanCsvService).generateCsvInfo(request, realDoneCardCollection, nonDoneCardCollection); + verify(jiraService).getStoryPointsAndCycleTimeForNonDoneCards( + KanbanFixture.MOCK_EXPECT_STORY_POINT_AND_CYCLE_TIME_REQUEST(), mockJiraBoardSetting.getBoardColumns(), + mockJiraBoardSetting.getUsers()); + verify(jiraService).getStoryPointsAndCycleTimeForDoneCards( + KanbanFixture.MOCK_EXPECT_STORY_POINT_AND_CYCLE_TIME_REQUEST(), mockJiraBoardSetting.getBoardColumns(), + mockJiraBoardSetting.getUsers(), mockJiraBoardSetting.getAssigneeFilter()); } } diff --git a/backend/src/test/java/heartbeat/service/report/PipelineServiceTest.java b/backend/src/test/java/heartbeat/service/report/PipelineServiceTest.java index 38a4b53497..556def51e7 100644 --- a/backend/src/test/java/heartbeat/service/report/PipelineServiceTest.java +++ b/backend/src/test/java/heartbeat/service/report/PipelineServiceTest.java @@ -16,6 +16,7 @@ import heartbeat.service.report.calculator.model.FetchedData; import heartbeat.service.source.github.GitHubService; import org.assertj.core.util.Lists; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -28,6 +29,7 @@ import org.mockito.quality.Strictness; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -56,25 +58,40 @@ public class PipelineServiceTest { @Captor ArgumentCaptor> roadMapArgumentCaptor; + private String token; + + private String startTime; + + private String endTime; + + @BeforeEach + public void setup() { + startTime = "startTime"; + endTime = "endTime"; + token = "token"; + } + @Nested class FetchGithubData { @Test void shouldReturnEmptyBuildInfosListAndEmptyLeadTimeWhenDeploymentEnvironmentsIsEmpty() { GenerateReportRequest request = GenerateReportRequest.builder() - .buildKiteSetting(BuildKiteSetting.builder().deploymentEnvList(new ArrayList()).build()) + .buildKiteSetting(BuildKiteSetting.builder().deploymentEnvList(new ArrayList<>()).build()) .metrics(new ArrayList<>()) + .codebaseSetting(CodebaseSetting.builder().token(token).build()) .build(); FetchedData.BuildKiteData result = pipelineService.fetchGithubData(request); assertEquals(0, result.getBuildInfosList().size()); verify(buildKiteService, never()).countDeployTimes(any(), any(), any(), any()); + verify(gitHubService).fetchPipelinesLeadTime(List.of(), new HashMap<>(), token); } @Test void shouldReturnEmptyPipelineLeadTimeWhenCodebaseSettingIsEmpty() { GenerateReportRequest request = GenerateReportRequest.builder() - .buildKiteSetting(BuildKiteSetting.builder().deploymentEnvList(new ArrayList()).build()) + .buildKiteSetting(BuildKiteSetting.builder().deploymentEnvList(new ArrayList<>()).build()) .metrics(new ArrayList<>()) .build(); FetchedData.BuildKiteData result = pipelineService.fetchGithubData(request); @@ -84,11 +101,8 @@ void shouldReturnEmptyPipelineLeadTimeWhenCodebaseSettingIsEmpty() { } @Test - void shouldGetPipelineLeadTimeFromGithubServiceAndBuildkiteServiceWhenCodebaseSettingIsNotEmpty() { + void shouldGetPipelineLeadTimeFromGithubServiceAndBuildKiteServiceWhenCodebaseSettingIsNotEmpty() { List fakeBuildKiteBuildInfos = new ArrayList<>(); - String startTime = "startTime"; - String endTime = "endTime"; - String token = "token"; GenerateReportRequest request = GenerateReportRequest.builder() .buildKiteSetting(BuildKiteSetting.builder() .deploymentEnvList(List.of(DeploymentEnvironment.builder().id("env1").repository("repo1").build(), @@ -120,9 +134,6 @@ void shouldGetPipelineLeadTimeFromGithubServiceAndBuildkiteServiceWhenCodebaseSe @Test void shouldGetSecondValueInRoadMapWhenDeployEnvironmentListHasTwoElementWithSameKey() { List fakeBuildKiteBuildInfos = new ArrayList<>(); - String startTime = "startTime"; - String endTime = "endTime"; - String token = "token"; GenerateReportRequest request = GenerateReportRequest.builder() .buildKiteSetting(BuildKiteSetting.builder() .deploymentEnvList(List.of(DeploymentEnvironment.builder().id("env1").repository("repo1").build(), @@ -157,9 +168,6 @@ void shouldFilterAuthorByInputCrews() { BuildKiteBuildInfo.builder() .author(BuildKiteBuildInfo.Author.builder().name("test-author2").build()) .build()); - String startTime = "startTime"; - String endTime = "endTime"; - String token = "token"; GenerateReportRequest request = GenerateReportRequest.builder() .buildKiteSetting(BuildKiteSetting.builder() .deploymentEnvList(List.of(DeploymentEnvironment.builder().id("env1").repository("repo1").build())) @@ -197,7 +205,7 @@ class FetchBuildKiteInfo { @Test void shouldReturnEmptyWhenDeploymentEnvListIsEmpty() { GenerateReportRequest request = GenerateReportRequest.builder() - .buildKiteSetting(BuildKiteSetting.builder().deploymentEnvList(new ArrayList()).build()) + .buildKiteSetting(BuildKiteSetting.builder().deploymentEnvList(new ArrayList<>()).build()) .metrics(new ArrayList<>()) .build(); FetchedData.BuildKiteData result = pipelineService.fetchBuildKiteInfo(request); @@ -213,9 +221,6 @@ void shouldReturnValueWhenDeploymentEnvListIsNotEmpty() { List fakeBuildKiteBuildInfos = List.of(BuildKiteBuildInfo.builder() .creator(BuildKiteBuildInfo.Creator.builder().name("someone").build()) .build()); - String startTime = "startTime"; - String endTime = "endTime"; - String token = "token"; GenerateReportRequest request = GenerateReportRequest.builder() .buildKiteSetting(BuildKiteSetting.builder() .token(token) @@ -250,9 +255,6 @@ void shouldFilterCreatorByInputCrews() { .creator(BuildKiteBuildInfo.Creator.builder().name("test-creator2").build()) .build(), BuildKiteBuildInfo.builder().creator(null).build()); - String startTime = "startTime"; - String endTime = "endTime"; - String token = "token"; GenerateReportRequest request = GenerateReportRequest.builder() .buildKiteSetting(BuildKiteSetting.builder() .deploymentEnvList(List.of(DeploymentEnvironment.builder().id("env1").repository("repo1").build())) @@ -284,8 +286,6 @@ class GenerateCSVForPipelineWithCodebase { @Test void shouldReturnEmptyWhenDeploymentEnvironmentsIsEmpty() { - String startTime = "startTime"; - String endTime = "endTime"; List result = pipelineService.generateCSVForPipelineWithCodebase( CodebaseSetting.builder().build(), startTime, endTime, FetchedData.BuildKiteData.builder().build(), Lists.list()); @@ -296,8 +296,6 @@ void shouldReturnEmptyWhenDeploymentEnvironmentsIsEmpty() { @Test void shouldReturnEmptyWhenNoBuildInfoFoundForDeploymentEnvironment() { - String startTime = "startTime"; - String endTime = "endTime"; List result = pipelineService.generateCSVForPipelineWithCodebase( CodebaseSetting.builder().build(), startTime, endTime, FetchedData.BuildKiteData.builder().buildInfosList(List.of(Map.entry("env1", List.of()))).build(), @@ -309,8 +307,6 @@ void shouldReturnEmptyWhenNoBuildInfoFoundForDeploymentEnvironment() { @Test void shouldReturnEmptyWhenPipelineStepsIsEmpty() { - String startTime = "startTime"; - String endTime = "endTime"; List kiteBuildInfos = List.of(BuildKiteBuildInfo.builder().build()); when(buildKiteService.getPipelineStepNames(eq(kiteBuildInfos))).thenReturn(List.of()); @@ -327,8 +323,6 @@ void shouldReturnEmptyWhenPipelineStepsIsEmpty() { @Test void shouldReturnEmptyWhenBuildJobIsEmpty() { - String startTime = "startTime"; - String endTime = "endTime"; List kiteBuildInfos = List.of(BuildKiteBuildInfo.builder().build()); when(buildKiteService.getPipelineStepNames(eq(kiteBuildInfos))).thenReturn(List.of("check")); when(buildKiteService.getBuildKiteJob(any(), any(), any(), eq(startTime), eq(endTime))).thenReturn(null); @@ -347,8 +341,6 @@ void shouldReturnEmptyWhenBuildJobIsEmpty() { @Test void shouldFilterOutInvalidBuildOfCommentIsEmtpy() { - String startTime = "startTime"; - String endTime = "endTime"; List kiteBuildInfos = List.of(BuildKiteBuildInfo.builder().commit("").build()); when(buildKiteService.getPipelineStepNames(eq(kiteBuildInfos))).thenReturn(List.of("check")); when(buildKiteService.getStepsBeforeEndStep(any(), any())).thenReturn(List.of("check")); @@ -369,8 +361,6 @@ void shouldFilterOutInvalidBuildOfCommentIsEmtpy() { @Test void shouldGenerateValueWithoutCommitWhenCodebaseSettingIsEmpty() { - String startTime = "startTime"; - String endTime = "endTime"; List kiteBuildInfos = List.of(BuildKiteBuildInfo.builder().commit("commit").build()); when(buildKiteService.getPipelineStepNames(eq(kiteBuildInfos))).thenReturn(List.of("check")); when(buildKiteService.getStepsBeforeEndStep(any(), any())).thenReturn(List.of("check")); @@ -393,8 +383,6 @@ void shouldGenerateValueWithoutCommitWhenCodebaseSettingIsEmpty() { @Test void shouldGenerateValueWithoutCommitWhenCodebaseSettingTokenIsEmpty() { - String startTime = "startTime"; - String endTime = "endTime"; List kiteBuildInfos = List.of(BuildKiteBuildInfo.builder().commit("commit").build()); when(buildKiteService.getPipelineStepNames(eq(kiteBuildInfos))).thenReturn(List.of("check")); when(buildKiteService.getStepsBeforeEndStep(any(), any())).thenReturn(List.of("check")); @@ -418,8 +406,6 @@ void shouldGenerateValueWithoutCommitWhenCodebaseSettingTokenIsEmpty() { @Test void shouldGenerateValueWithoutCommitWhenCommitIdIsEmpty() { - String startTime = "startTime"; - String endTime = "endTime"; List kiteBuildInfos = List.of(BuildKiteBuildInfo.builder().commit("commit").build()); when(buildKiteService.getPipelineStepNames(eq(kiteBuildInfos))).thenReturn(List.of("check")); when(buildKiteService.getStepsBeforeEndStep(any(), any())).thenReturn(List.of("check")); @@ -443,8 +429,6 @@ void shouldGenerateValueWithoutCommitWhenCommitIdIsEmpty() { @Test void shouldGenerateValueHasCommit() { - String startTime = "startTime"; - String endTime = "endTime"; List kiteBuildInfos = List.of(BuildKiteBuildInfo.builder().commit("commit").build()); CommitInfo fakeCommitInfo = CommitInfo.builder().build(); when(buildKiteService.getPipelineStepNames(eq(kiteBuildInfos))).thenReturn(List.of("check")); @@ -473,8 +457,6 @@ void shouldGenerateValueHasCommit() { @Test void shouldGenerateValueWithLeadTimeWhenLeadTimeExisting() { - String startTime = "startTime"; - String endTime = "endTime"; List kiteBuildInfos = List.of(BuildKiteBuildInfo.builder().commit("commit").build()); CommitInfo fakeCommitInfo = CommitInfo.builder().build(); when(buildKiteService.getPipelineStepNames(eq(kiteBuildInfos))).thenReturn(List.of("check")); diff --git a/backend/src/test/java/heartbeat/service/report/ReportServiceTest.java b/backend/src/test/java/heartbeat/service/report/ReportServiceTest.java index 332be16bcd..f00fb67047 100644 --- a/backend/src/test/java/heartbeat/service/report/ReportServiceTest.java +++ b/backend/src/test/java/heartbeat/service/report/ReportServiceTest.java @@ -1,40 +1,39 @@ package heartbeat.service.report; import heartbeat.controller.report.dto.request.GenerateReportRequest; -import heartbeat.controller.report.dto.request.ReportType; import heartbeat.controller.report.dto.request.MetricType; +import heartbeat.controller.report.dto.request.ReportType; import heartbeat.controller.report.dto.response.MetricsDataCompleted; +import heartbeat.exception.NotFoundException; import heartbeat.handler.AsyncMetricsDataHandler; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; -import org.mockito.stubbing.Answer; import org.springframework.core.io.InputStreamResource; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; -import java.io.InputStreamReader; import java.io.InputStream; +import java.io.InputStreamReader; import java.util.ArrayList; +import java.util.List; import java.util.stream.Collectors; +import static heartbeat.controller.report.dto.request.MetricEnum.LEAD_TIME_FOR_CHANGES; +import static heartbeat.controller.report.dto.request.MetricEnum.VELOCITY; +import static heartbeat.service.report.scheduler.DeleteExpireCSVScheduler.EXPORT_CSV_VALIDITY_TIME; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; - -import heartbeat.exception.NotFoundException; - -import static heartbeat.service.report.scheduler.DeleteExpireCSVScheduler.EXPORT_CSV_VALIDITY_TIME; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.STRICT_STUBS) @@ -77,8 +76,10 @@ void exportCsvShouldThrowNotFoundExceptionWhenTimestampIsValid() { void generateBoardReportByTypeShouldCallGenerateBoardReport() throws InterruptedException { GenerateReportRequest request = GenerateReportRequest.builder().metrics(new ArrayList<>()).build(); doAnswer(invocation -> null).when(generateReporterService).generateBoardReport(request); + reportService.generateReportByType(request, MetricType.BOARD); Thread.sleep(100); + verify(generateReporterService).generateBoardReport(request); verify(generateReporterService, never()).generateDoraReport(request); } @@ -87,8 +88,10 @@ void generateBoardReportByTypeShouldCallGenerateBoardReport() throws Interrupted void generateDoraReportByTypeShouldCallGenerateDoraReport() throws InterruptedException { GenerateReportRequest request = GenerateReportRequest.builder().metrics(new ArrayList<>()).build(); doAnswer(invocation -> null).when(generateReporterService).generateDoraReport(request); + reportService.generateReportByType(request, MetricType.DORA); Thread.sleep(100); + verify(generateReporterService).generateDoraReport(request); verify(generateReporterService, never()).generateBoardReport(request); } @@ -98,8 +101,32 @@ void ShouldInitializeMetricsDataCompletedInHandlerWithPreOneWhenPreOneExisted() GenerateReportRequest request = GenerateReportRequest.builder().metrics(new ArrayList<>()).build(); when(asyncMetricsDataHandler.getMetricsDataCompleted(any())).thenReturn(MetricsDataCompleted.builder().build()); doAnswer(invocation -> null).when(generateReporterService).generateBoardReport(request); + reportService.generateReportByType(request, MetricType.BOARD); Thread.sleep(100); + + verify(generateReporterService).generateBoardReport(request); + verify(generateReporterService, never()).generateDoraReport(request); + } + + @Test + void ShouldInitializeMetricsDataCompletedInHandlerWhenRequestMetricsExist() { + MetricsDataCompleted expectMetricsDataResult = MetricsDataCompleted.builder() + .boardMetricsCompleted(false) + .pipelineMetricsCompleted(true) + .sourceControlMetricsCompleted(false) + .build(); + GenerateReportRequest request = GenerateReportRequest.builder() + .csvTimeStamp("csvTimeStamp") + .metrics(List.of(VELOCITY.getValue(), LEAD_TIME_FOR_CHANGES.getValue())) + .build(); + when(asyncMetricsDataHandler.getMetricsDataCompleted(any())) + .thenReturn(MetricsDataCompleted.builder().pipelineMetricsCompleted(true).build()); + doAnswer(invocation -> null).when(generateReporterService).generateBoardReport(request); + + reportService.generateReportByType(request, MetricType.BOARD); + + verify(asyncMetricsDataHandler).putMetricsDataCompleted("csvTimeStamp", expectMetricsDataResult); verify(generateReporterService).generateBoardReport(request); verify(generateReporterService, never()).generateDoraReport(request); } From e41ff49ac0747e02d903af18aa900fa1a5ea7d49 Mon Sep 17 00:00:00 2001 From: yulongcai <141199398+yulongcai@users.noreply.github.com> Date: Thu, 1 Feb 2024 15:22:01 +0800 Subject: [PATCH 3/3] ADM-794:[backend]fix: repair test to add sleep (#1018) * ADM-794:[backend]fix: add test for generate report * ADM-794:[backend]fix: repair test for pipeline * ADM-794:[backend]fix: add test for pipeline * ADM-794:[backend]fix: refactor code * ADM-794:[backend]fix: refactor for report service test * ADM-794:[backend]fix: repair test to add sleep --- .../test/java/heartbeat/service/report/ReportServiceTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backend/src/test/java/heartbeat/service/report/ReportServiceTest.java b/backend/src/test/java/heartbeat/service/report/ReportServiceTest.java index f00fb67047..563045ea5d 100644 --- a/backend/src/test/java/heartbeat/service/report/ReportServiceTest.java +++ b/backend/src/test/java/heartbeat/service/report/ReportServiceTest.java @@ -110,7 +110,7 @@ void ShouldInitializeMetricsDataCompletedInHandlerWithPreOneWhenPreOneExisted() } @Test - void ShouldInitializeMetricsDataCompletedInHandlerWhenRequestMetricsExist() { + void ShouldInitializeMetricsDataCompletedInHandlerWhenRequestMetricsExist() throws InterruptedException { MetricsDataCompleted expectMetricsDataResult = MetricsDataCompleted.builder() .boardMetricsCompleted(false) .pipelineMetricsCompleted(true) @@ -124,6 +124,7 @@ void ShouldInitializeMetricsDataCompletedInHandlerWhenRequestMetricsExist() { .thenReturn(MetricsDataCompleted.builder().pipelineMetricsCompleted(true).build()); doAnswer(invocation -> null).when(generateReporterService).generateBoardReport(request); + Thread.sleep(100); reportService.generateReportByType(request, MetricType.BOARD); verify(asyncMetricsDataHandler).putMetricsDataCompleted("csvTimeStamp", expectMetricsDataResult);