repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/BranchWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.branch.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class BranchWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new BranchWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(5); } }
1,262
35.085714
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/BranchesWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.branch.ws; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; public class BranchesWsTest { @Test public void define_ws() { BranchesWs underTest = new BranchesWs(new BranchWsAction() { @Override public void define(WebService.NewController context) { context.createAction("foo").setHandler(this); } @Override public void handle(Request request, Response response) { } }); WebService.Context context = new WebService.Context(); underTest.define(context); assertThat(context.controller("api/project_branches").action("foo")).isNotNull(); } }
1,640
30.557692
85
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/queue/BranchSupportTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ce.queue; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import java.util.Collections; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.server.ce.queue.BranchSupport.ComponentKey; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class BranchSupportTest { private static final Map<String, String> NO_CHARACTERISTICS = Collections.emptyMap(); private final BranchSupportDelegate branchSupportDelegate = mock(BranchSupportDelegate.class); private final BranchSupport underTestNoBranch = new BranchSupport(null); private final BranchSupport underTestWithBranch = new BranchSupport(branchSupportDelegate); @Test public void createComponentKey_of_main_branch() { String projectKey = randomAlphanumeric(12); ComponentKey componentKey = underTestNoBranch.createComponentKey(projectKey, NO_CHARACTERISTICS); assertThat(componentKey) .isEqualTo(underTestWithBranch.createComponentKey(projectKey, NO_CHARACTERISTICS)); assertThat(componentKey.getKey()).isEqualTo(projectKey); assertThat(componentKey.getBranchName()).isEmpty(); assertThat(componentKey.getPullRequestKey()).isEmpty(); } @Test public void createComponentKey_delegates_to_delegate_if_characteristics_is_not_empty() { String projectKey = randomAlphanumeric(12); Map<String, String> nonEmptyMap = newRandomNonEmptyMap(); ComponentKey expected = mock(ComponentKey.class); when(branchSupportDelegate.createComponentKey(projectKey, nonEmptyMap)).thenReturn(expected); ComponentKey componentKey = underTestWithBranch.createComponentKey(projectKey, nonEmptyMap); assertThat(componentKey).isSameAs(expected); } @Test public void createBranchComponent_fails_with_ISE_if_delegate_is_null() { DbSession dbSession = mock(DbSession.class); ComponentKey componentKey = mock(ComponentKey.class); ComponentDto mainComponentDto = new ComponentDto(); BranchDto mainComponentBranchDto = new BranchDto(); assertThatThrownBy(() -> underTestNoBranch.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto)) .isInstanceOf(IllegalStateException.class) .hasMessage("Current edition does not support branch feature"); } @Test public void createBranchComponent_delegates_to_delegate() { DbSession dbSession = mock(DbSession.class); ComponentKey componentKey = mock(ComponentKey.class); ComponentDto mainComponentDto = new ComponentDto(); ComponentDto expected = new ComponentDto(); BranchDto mainComponentBranchDto = new BranchDto(); when(branchSupportDelegate.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto)) .thenReturn(expected); ComponentDto dto = underTestWithBranch.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto); assertThat(dto).isSameAs(expected); } @DataProvider public static Object[][] nullOrNonEmpty() { return new Object[][] { {null}, {randomAlphabetic(5)}, }; } private static Map<String, String> newRandomNonEmptyMap() { return IntStream.range(0, 1 + new Random().nextInt(10)).boxed().collect(Collectors.toMap(i -> "key_" + i, i1 -> "val_" + i1)); } }
4,762
40.417391
136
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/CeWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ce.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class CeWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new CeWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(20); } }
1,252
33.805556
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/CeWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ce.ws; import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.server.ws.WebService; import org.sonar.server.ce.queue.ReportSubmitter; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class CeWsTest { @Test public void define() { CeWsAction wsAction = new SubmitAction(mock(ReportSubmitter.class)); CeWs ws = new CeWs(wsAction); WebService.Context context = mock(WebService.Context.class, Mockito.RETURNS_DEEP_STUBS); ws.define(context); assertThat(context.controller("api/ce")).isNotNull(); } }
1,468
33.162791
92
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/InfoActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ce.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.ce.queue.CeQueue; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.SystemPasscode; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Ce; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class InfoActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private SystemPasscode passcode = mock(SystemPasscode.class); private CeQueue ceQueue = mock(CeQueue.class); private InfoAction underTest = new InfoAction(userSession, passcode, ceQueue); private WsActionTester ws = new WsActionTester(underTest); @Test public void test_definition() { WebService.Action def = ws.getDef(); assertThat(def.key()).isEqualTo("info"); assertThat(def.isInternal()).isTrue(); assertThat(def.isPost()).isFalse(); assertThat(def.params()).isEmpty(); } @Test public void test_example_of_response() { userSession.logIn().setSystemAdministrator(); when(ceQueue.getWorkersPauseStatus()).thenReturn(CeQueue.WorkersPauseStatus.PAUSING); ws.newRequest().execute().assertJson(ws.getDef().responseExampleAsString()); } @Test public void test_workers_in_pausing_state() { userSession.logIn().setSystemAdministrator(); when(ceQueue.getWorkersPauseStatus()).thenReturn(CeQueue.WorkersPauseStatus.PAUSING); Ce.InfoWsResponse response = ws.newRequest().executeProtobuf(Ce.InfoWsResponse.class); assertThat(response.getWorkersPauseStatus()).isEqualTo(Ce.WorkersPauseStatus.PAUSING); } @Test public void test_workers_in_paused_state() { userSession.logIn().setSystemAdministrator(); when(ceQueue.getWorkersPauseStatus()).thenReturn(CeQueue.WorkersPauseStatus.PAUSED); Ce.InfoWsResponse response = ws.newRequest().executeProtobuf(Ce.InfoWsResponse.class); assertThat(response.getWorkersPauseStatus()).isEqualTo(Ce.WorkersPauseStatus.PAUSED); } @Test public void test_workers_in_resumed_state() { userSession.logIn().setSystemAdministrator(); when(ceQueue.getWorkersPauseStatus()).thenReturn(CeQueue.WorkersPauseStatus.RESUMED); Ce.InfoWsResponse response = ws.newRequest().executeProtobuf(Ce.InfoWsResponse.class); assertThat(response.getWorkersPauseStatus()).isEqualTo(Ce.WorkersPauseStatus.RESUMED); } @Test public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void throw_ForbiddenException_if_invalid_passcode() { userSession.anonymous(); when(passcode.isValid(any())).thenReturn(false); assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void authenticate_with_passcode() { userSession.anonymous(); when(passcode.isValid(any())).thenReturn(true); when(ceQueue.getWorkersPauseStatus()).thenReturn(CeQueue.WorkersPauseStatus.RESUMED); Ce.InfoWsResponse response = ws.newRequest().executeProtobuf(Ce.InfoWsResponse.class); assertThat(response.getWorkersPauseStatus()).isEqualTo(Ce.WorkersPauseStatus.RESUMED); } }
4,527
36.421488
90
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/PauseActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ce.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.ce.queue.CeQueue; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.SystemPasscode; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class PauseActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private SystemPasscode passcode = mock(SystemPasscode.class); private CeQueue ceQueue = mock(CeQueue.class); private PauseAction underTest = new PauseAction(userSession, passcode, ceQueue); private WsActionTester ws = new WsActionTester(underTest); @Test public void test_definition() { WebService.Action def = ws.getDef(); assertThat(def.key()).isEqualTo("pause"); assertThat(def.isInternal()).isTrue(); assertThat(def.isPost()).isTrue(); assertThat(def.params()).isEmpty(); assertThat(def.responseExampleAsString()).isNull(); } @Test public void pause_workers() { userSession.logIn().setSystemAdministrator(); ws.newRequest().execute(); verify(ceQueue).pauseWorkers(); } @Test public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void throw_ForbiddenException_if_invalid_passcode() { userSession.anonymous(); when(passcode.isValid(any())).thenReturn(false); assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void authenticate_with_passcode() { userSession.anonymous(); when(passcode.isValid(any())).thenReturn(true); ws.newRequest().execute(); verify(ceQueue).pauseWorkers(); } }
3,133
31.645833
82
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/ResumeActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ce.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.ce.queue.CeQueue; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.SystemPasscode; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ResumeActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private SystemPasscode passcode = mock(SystemPasscode.class); private CeQueue ceQueue = mock(CeQueue.class); private ResumeAction underTest = new ResumeAction(userSession, passcode, ceQueue); private WsActionTester ws = new WsActionTester(underTest); @Test public void test_definition() { WebService.Action def = ws.getDef(); assertThat(def.key()).isEqualTo("resume"); assertThat(def.isInternal()).isTrue(); assertThat(def.isPost()).isTrue(); assertThat(def.params()).isEmpty(); assertThat(def.responseExampleAsString()).isNull(); } @Test public void resume_workers() { userSession.logIn().setSystemAdministrator(); ws.newRequest().execute(); verify(ceQueue).resumeWorkers(); } @Test public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void throw_ForbiddenException_if_invalid_passcode() { userSession.anonymous(); when(passcode.isValid(any())).thenReturn(false); assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void authenticate_with_passcode() { userSession.anonymous(); when(passcode.isValid(any())).thenReturn(true); ws.newRequest().execute(); verify(ceQueue).resumeWorkers(); } }
3,140
31.71875
84
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/SubmitActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ce.ws; import com.google.common.base.Strings; import java.io.ByteArrayInputStream; import java.util.Map; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.ce.task.CeTask; import org.sonar.db.ce.CeTaskTypes; import org.sonar.server.ce.queue.ReportSubmitter; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import org.sonar.test.JsonAssert; import org.sonarqube.ws.Ce; import org.sonarqube.ws.MediaTypes; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class SubmitActionTest { private static final String PROJECT_UUID = "PROJECT_1"; private static final String BRANCH_UUID = "BRANCH_1"; private static final CeTask.Component ENTITY = new CeTask.Component(PROJECT_UUID, "KEY_1", "NAME_1"); private static final CeTask.Component COMPONENT = new CeTask.Component(BRANCH_UUID, "KEY_1", "NAME_1"); private static final CeTask A_CE_TASK = new CeTask.Builder() .setUuid("TASK_1") .setType(CeTaskTypes.REPORT) .setComponent(COMPONENT) .setEntity(ENTITY) .setSubmitter(new CeTask.User("UUID_1", "LOGIN_1")) .build(); private final ArgumentCaptor<Map<String, String>> map = ArgumentCaptor.forClass(Map.class); private final ReportSubmitter reportSubmitter = mock(ReportSubmitter.class); private final SubmitAction underTest = new SubmitAction(reportSubmitter); private final WsActionTester tester = new WsActionTester(underTest); @Test public void submit_task_to_the_queue_and_ask_for_immediate_processing() { when(reportSubmitter.submit(eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK); Ce.SubmitResponse submitResponse = tester.newRequest() .setParam("projectKey", "my_project") .setParam("projectName", "My Project") .setPart("report", new ByteArrayInputStream("{binary}".getBytes()), "foo.bar") .setMethod("POST") .executeProtobuf(Ce.SubmitResponse.class); verify(reportSubmitter).submit(eq("my_project"), eq("My Project"), anyMap(), any()); assertThat(submitResponse.getTaskId()).isEqualTo("TASK_1"); assertThat(submitResponse.getProjectId()).isEqualTo(BRANCH_UUID); } @Test public void submit_task_with_characteristics() { when(reportSubmitter.submit(eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK); String[] characteristics = {"branch=foo", "pullRequest=123", "unsupported=bar"}; Ce.SubmitResponse submitResponse = tester.newRequest() .setParam("projectKey", "my_project") .setParam("projectName", "My Project") .setMultiParam("characteristic", asList(characteristics)) .setPart("report", new ByteArrayInputStream("{binary}".getBytes()), "foo.bar") .setMethod("POST") .executeProtobuf(Ce.SubmitResponse.class); assertThat(submitResponse.getTaskId()).isEqualTo("TASK_1"); verify(reportSubmitter).submit(eq("my_project"), eq("My Project"), map.capture(), any()); // unsupported characteristics are ignored assertThat(map.getValue()).containsExactly(entry("branch", "foo"), entry("pullRequest", "123")); } @Test public void abbreviate_long_name() { String longName = Strings.repeat("a", 1_000); String expectedName = Strings.repeat("a", 497) + "..."; when(reportSubmitter.submit(eq("my_project"), eq(expectedName), anyMap(), any())).thenReturn(A_CE_TASK); Ce.SubmitResponse submitResponse = tester.newRequest() .setParam("projectKey", "my_project") .setParam("projectName", longName) .setPart("report", new ByteArrayInputStream("{binary}".getBytes()), "foo.bar") .setMethod("POST") .executeProtobuf(Ce.SubmitResponse.class); verify(reportSubmitter).submit(eq("my_project"), eq(expectedName), anyMap(), any()); assertThat(submitResponse.getTaskId()).isEqualTo("TASK_1"); assertThat(submitResponse.getProjectId()).isEqualTo(BRANCH_UUID); } @Test public void test_example_json_response() { when(reportSubmitter.submit(eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK); TestResponse wsResponse = tester.newRequest() .setParam("projectKey", "my_project") .setParam("projectName", "My Project") .setPart("report", new ByteArrayInputStream("{binary}".getBytes()), "foo.bar") .setMediaType(MediaTypes.JSON) .setMethod("POST") .execute(); JsonAssert.assertJson(tester.getDef().responseExampleAsString()).isSimilarTo(wsResponse.getInput()); } /** * If project name is not specified, then name is the project key */ @Test public void project_name_is_optional() { when(reportSubmitter.submit(eq("my_project"), eq("my_project"), anyMap(), any())).thenReturn(A_CE_TASK); tester.newRequest() .setParam("projectKey", "my_project") .setPart("report", new ByteArrayInputStream("{binary}".getBytes()), "foo.bar") .setMediaType(MediaTypes.PROTOBUF) .setMethod("POST") .execute(); verify(reportSubmitter).submit(eq("my_project"), eq("my_project"), anyMap(), any()); } }
6,295
39.883117
108
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/TaskFormatterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ce.ws; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.ce.CeTaskMessageDto; import org.sonar.db.ce.CeTaskMessageType; import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.user.UserDto; import org.sonarqube.ws.Ce; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.ce.CeQueueTesting.makeInProgress; import static org.sonar.db.ce.CeTaskMessageType.INFO; public class TaskFormatterTest { private static final String NODE_NAME = "nodeName1"; private static final int WARNING_COUNT = 5; @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final System2 system2 = mock(System2.class); private final TaskFormatter underTest = new TaskFormatter(db.getDbClient(), system2); @Test public void formatQueue_without_component() { CeQueueDto dto = new CeQueueDto(); dto.setUuid("UUID"); dto.setTaskType("TYPE"); dto.setStatus(CeQueueDto.Status.PENDING); dto.setCreatedAt(1_450_000_000_000L); Ce.Task wsTask = underTest.formatQueue(db.getSession(), dto); assertThat(wsTask.getType()).isEqualTo("TYPE"); assertThat(wsTask.getId()).isEqualTo("UUID"); assertThat(wsTask.getStatus()).isEqualTo(Ce.TaskStatus.PENDING); assertThat(wsTask.getSubmittedAt()).isEqualTo(DateUtils.formatDateTime(new Date(1_450_000_000_000L))); assertThat(wsTask.hasScannerContext()).isFalse(); assertThat(wsTask.hasExecutionTimeMs()).isFalse(); assertThat(wsTask.hasSubmitterLogin()).isFalse(); assertThat(wsTask.hasComponentId()).isFalse(); assertThat(wsTask.hasComponentKey()).isFalse(); assertThat(wsTask.hasComponentName()).isFalse(); assertThat(wsTask.hasExecutedAt()).isFalse(); assertThat(wsTask.hasStartedAt()).isFalse(); assertThat(wsTask.hasExecutionTimeMs()).isFalse(); } @Test public void formatQueue_with_component_and_other_fields() { String uuid = "COMPONENT_UUID"; db.components().insertPrivateProject((t) -> t.setUuid(uuid).setKey("COMPONENT_KEY").setName("Component Name")).getMainBranchComponent(); UserDto user = db.users().insertUser(); CeQueueDto dto = new CeQueueDto(); dto.setUuid("UUID"); dto.setTaskType("TYPE"); dto.setStatus(CeQueueDto.Status.PENDING); dto.setCreatedAt(1_450_000_000_000L); dto.setComponentUuid(uuid); dto.setSubmitterUuid(user.getUuid()); db.getDbClient().ceQueueDao().insert(db.getSession(), dto); makeInProgress(db.getSession(), "workerUuid", 1_958_000_000_000L, dto); CeQueueDto inProgress = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), dto.getUuid()).get(); Ce.Task wsTask = underTest.formatQueue(db.getSession(), inProgress); assertThat(wsTask.getType()).isEqualTo("TYPE"); assertThat(wsTask.getId()).isEqualTo("UUID"); assertThat(wsTask.getComponentId()).isEqualTo(uuid); assertThat(wsTask.getComponentKey()).isEqualTo("COMPONENT_KEY"); assertThat(wsTask.getComponentName()).isEqualTo("Component Name"); assertThat(wsTask.getComponentQualifier()).isEqualTo("TRK"); assertThat(wsTask.getStatus()).isEqualTo(Ce.TaskStatus.IN_PROGRESS); assertThat(wsTask.getSubmitterLogin()).isEqualTo(user.getLogin()); assertThat(wsTask.hasExecutionTimeMs()).isTrue(); assertThat(wsTask.hasExecutedAt()).isFalse(); assertThat(wsTask.hasScannerContext()).isFalse(); } @Test public void formatQueue_do_not_fail_if_component_not_found() { CeQueueDto dto = new CeQueueDto(); dto.setUuid("UUID"); dto.setTaskType("TYPE"); dto.setStatus(CeQueueDto.Status.IN_PROGRESS); dto.setCreatedAt(1_450_000_000_000L); dto.setComponentUuid("DOES_NOT_EXIST"); Ce.Task wsTask = underTest.formatQueue(db.getSession(), dto); assertThat(wsTask.getComponentId()).isEqualTo("DOES_NOT_EXIST"); assertThat(wsTask.hasComponentKey()).isFalse(); assertThat(wsTask.hasComponentName()).isFalse(); } @Test public void formatQueue_compute_execute_time_if_in_progress() { long startedAt = 1_450_000_001_000L; long now = 1_450_000_003_000L; CeQueueDto dto = new CeQueueDto(); dto.setUuid("UUID"); dto.setTaskType("TYPE"); dto.setStatus(CeQueueDto.Status.PENDING); dto.setCreatedAt(1_450_000_000_000L); db.getDbClient().ceQueueDao().insert(db.getSession(), dto); makeInProgress(db.getSession(), "workerUuid", startedAt, dto); CeQueueDto inProgress = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), dto.getUuid()).get(); when(system2.now()).thenReturn(now); Ce.Task wsTask = underTest.formatQueue(db.getSession(), inProgress); assertThat(wsTask.getExecutionTimeMs()).isEqualTo(now - startedAt); } @Test public void formatQueues() { CeQueueDto dto1 = new CeQueueDto(); dto1.setUuid("UUID1"); dto1.setTaskType("TYPE1"); dto1.setStatus(CeQueueDto.Status.IN_PROGRESS); dto1.setCreatedAt(1_450_000_000_000L); CeQueueDto dto2 = new CeQueueDto(); dto2.setUuid("UUID2"); dto2.setTaskType("TYPE2"); dto2.setStatus(CeQueueDto.Status.PENDING); dto2.setCreatedAt(1_451_000_000_000L); Iterable<Ce.Task> wsTasks = underTest.formatQueue(db.getSession(), asList(dto1, dto2)); assertThat(wsTasks).extracting("id").containsExactly("UUID1", "UUID2"); } @Test public void formatActivity() { UserDto user = db.users().insertUser(); CeActivityDto dto = newActivity("UUID", "COMPONENT_UUID", CeActivityDto.Status.FAILED, user); Ce.Task wsTask = underTest.formatActivity(db.getSession(), dto, null); assertThat(wsTask.getType()).isEqualTo(CeTaskTypes.REPORT); assertThat(wsTask.getId()).isEqualTo("UUID"); assertThat(wsTask.getNodeName()).isEqualTo(NODE_NAME); assertThat(wsTask.getStatus()).isEqualTo(Ce.TaskStatus.FAILED); assertThat(wsTask.getSubmittedAt()).isEqualTo(DateUtils.formatDateTime(new Date(1_450_000_000_000L))); assertThat(wsTask.getSubmitterLogin()).isEqualTo(user.getLogin()); assertThat(wsTask.getExecutionTimeMs()).isEqualTo(500L); assertThat(wsTask.getAnalysisId()).isEqualTo("U1"); assertThat(wsTask.hasScannerContext()).isFalse(); assertThat(wsTask.getWarningCount()).isZero(); assertThat(wsTask.getWarningsList()).isEmpty(); } @Test public void formatActivity_set_scanner_context_if_argument_is_non_null() { CeActivityDto dto = newActivity("UUID", "COMPONENT_UUID", CeActivityDto.Status.FAILED, null); String expected = "scanner context baby!"; Ce.Task wsTask = underTest.formatActivity(db.getSession(), dto, expected); assertThat(wsTask.hasScannerContext()).isTrue(); assertThat(wsTask.getScannerContext()).isEqualTo(expected); } @Test public void formatActivity_filterNonWarnings_andSetMessagesAndCount() { TestActivityDto dto = newActivity("UUID", "COMPONENT_UUID", CeActivityDto.Status.FAILED, null); CeTaskMessageDto warning1 = createCeTaskMessageDto(1998, CeTaskMessageType.GENERIC); CeTaskMessageDto warning2 = createCeTaskMessageDto(1999, CeTaskMessageType.GENERIC); List<CeTaskMessageDto> ceTaskMessageDtos = new ArrayList<>(dto.getCeTaskMessageDtos()); ceTaskMessageDtos.add(warning1); ceTaskMessageDtos.add(warning2); dto.setCeTaskMessageDtos(ceTaskMessageDtos); Ce.Task wsTask = underTest.formatActivity(db.getSession(), dto, null); assertThat(wsTask.getWarningCount()).isEqualTo(2); assertThat(wsTask.getWarningsList()).hasSameElementsAs(getMessagesText(List.of(warning1, warning2))); } private static List<String> getMessagesText(List<CeTaskMessageDto> ceTaskMessageDtos) { return ceTaskMessageDtos.stream().map(CeTaskMessageDto::getMessage).toList(); } @Test public void formatActivities() { UserDto user1 = db.users().insertUser(); UserDto user2 = db.users().insertUser(); CeActivityDto dto1 = newActivity("UUID1", "COMPONENT_UUID", CeActivityDto.Status.FAILED, user1); CeActivityDto dto2 = newActivity("UUID2", "COMPONENT_UUID", CeActivityDto.Status.SUCCESS, user2); Iterable<Ce.Task> wsTasks = underTest.formatActivity(db.getSession(), asList(dto1, dto2)); assertThat(wsTasks) .extracting(Ce.Task::getId, Ce.Task::getSubmitterLogin) .containsExactlyInAnyOrder( tuple("UUID1", user1.getLogin()), tuple("UUID2", user2.getLogin())); } @Test public void formatActivity_with_both_error_message_and_stacktrace() { CeActivityDto dto = newActivity("UUID", "COMPONENT_UUID", CeActivityDto.Status.FAILED, null) .setErrorMessage("error msg") .setErrorStacktrace("error stacktrace") .setErrorType("anErrorType"); Ce.Task task = underTest.formatActivity(db.getSession(), Collections.singletonList(dto)).iterator().next(); assertThat(task.getErrorMessage()).isEqualTo(dto.getErrorMessage()); assertThat(task.getErrorStacktrace()).isEqualTo(dto.getErrorStacktrace()); assertThat(task.getErrorType()).isEqualTo(dto.getErrorType()); } @Test public void formatActivity_with_both_error_message_only() { CeActivityDto dto = newActivity("UUID", "COMPONENT_UUID", CeActivityDto.Status.FAILED, null) .setErrorMessage("error msg"); Ce.Task task = underTest.formatActivity(db.getSession(), Collections.singletonList(dto)).iterator().next(); assertThat(task.getErrorMessage()).isEqualTo(dto.getErrorMessage()); assertThat(task.hasErrorStacktrace()).isFalse(); } @Test public void formatActivity_with_both_error_message_and_only_stacktrace_flag() { CeActivityDto dto = newActivity("UUID", "COMPONENT_UUID", CeActivityDto.Status.FAILED, null) .setErrorMessage("error msg"); Ce.Task task = underTest.formatActivity(db.getSession(), Collections.singletonList(dto)).iterator().next(); assertThat(task.getErrorMessage()).isEqualTo(dto.getErrorMessage()); assertThat(task.hasErrorStacktrace()).isFalse(); } private TestActivityDto newActivity(String taskUuid, String componentUuid, CeActivityDto.Status status, @Nullable UserDto user) { CeQueueDto queueDto = new CeQueueDto() .setCreatedAt(1_450_000_000_000L) .setTaskType(CeTaskTypes.REPORT) .setComponentUuid(componentUuid) .setSubmitterUuid(user == null ? null : user.getUuid()) .setUuid(taskUuid); TestActivityDto testActivityDto = new TestActivityDto(queueDto); List<CeTaskMessageDto> ceTaskMessageDtos = IntStream.range(0, WARNING_COUNT) .mapToObj(i -> createCeTaskMessageDto(i, INFO)) .toList(); testActivityDto.setCeTaskMessageDtos(ceTaskMessageDtos); return (TestActivityDto) testActivityDto .setStatus(status) .setNodeName(NODE_NAME) .setExecutionTimeMs(500L) .setAnalysisUuid("U1"); } private CeTaskMessageDto createCeTaskMessageDto(int i, CeTaskMessageType ceTaskMessageType) { CeTaskMessageDto ceTaskMessageDto = new CeTaskMessageDto(); ceTaskMessageDto.setMessage("message_" + i); ceTaskMessageDto.setCreatedAt(system2.now()); ceTaskMessageDto.setTaskUuid("uuid_" + i); ceTaskMessageDto.setType(ceTaskMessageType); return ceTaskMessageDto; } private static class TestActivityDto extends CeActivityDto { public TestActivityDto(CeQueueDto queueDto) { super(queueDto); } @Override public CeActivityDto setHasScannerContext(boolean hasScannerContext) { return super.setHasScannerContext(hasScannerContext); } @Override public CeActivityDto setCeTaskMessageDtos(List<CeTaskMessageDto> ceTaskMessageDtos) { return super.setCeTaskMessageDtos(ceTaskMessageDtos); } } }
12,937
39.305296
140
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/TaskTypesActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ce.ws; import com.google.common.collect.ImmutableSet; import java.util.Set; import org.junit.Test; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.CeTaskResult; import org.sonar.ce.task.taskprocessor.CeTaskProcessor; import org.sonar.server.ws.WsActionTester; import static org.sonar.test.JsonAssert.assertJson; public class TaskTypesActionTest { WsActionTester ws = new WsActionTester(new TaskTypesAction(new CeTaskProcessor[] { new FakeCeTaskProcessor("REPORT"), new FakeCeTaskProcessor("DEV_REFRESH", "DEV_PURGE"), new FakeCeTaskProcessor("VIEW_REFRESH") })); @Test public void json_example() { String response = ws.newRequest().execute().getInput(); assertJson(response).isSimilarTo(getClass().getResource("task_types-example.json")); } private static class FakeCeTaskProcessor implements CeTaskProcessor { private final Set<String> taskTypes; private FakeCeTaskProcessor(String... taskTypes) { this.taskTypes = ImmutableSet.copyOf(taskTypes); } @Override public Set<String> getHandledCeTaskTypes() { return taskTypes; } @Override public CeTaskResult process(CeTask task) { throw new UnsupportedOperationException(); } } }
2,104
30.893939
88
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/WorkerCountActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ce.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.ce.configuration.WorkerCountProvider; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Ce.WorkerCountResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.test.JsonAssert.assertJson; public class WorkerCountActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private WorkerCountProvider workerCountProvider = mock(WorkerCountProvider.class); @Test public void return_value_and_can_set_worker_count_to_true_when_provider_exists() { userSession.logIn().setSystemAdministrator(); when(workerCountProvider.get()).thenReturn(5); WsActionTester ws = new WsActionTester(new WorkerCountAction(userSession, workerCountProvider)); WorkerCountResponse response = ws.newRequest().executeProtobuf(WorkerCountResponse.class); assertThat(response.getValue()).isEqualTo(5); assertThat(response.getCanSetWorkerCount()).isTrue(); } @Test public void return_1_and_can_set_worker_count_to_false_when_provider_does_not_exist() { userSession.logIn().setSystemAdministrator(); WsActionTester ws = new WsActionTester(new WorkerCountAction(userSession)); WorkerCountResponse response = ws.newRequest().executeProtobuf(WorkerCountResponse.class); assertThat(response.getValue()).isOne(); assertThat(response.getCanSetWorkerCount()).isFalse(); } @Test public void fail_when_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); WsActionTester ws = new WsActionTester(new WorkerCountAction(userSession)); assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(ForbiddenException.class); } @Test public void test_definition() { WsActionTester ws = new WsActionTester(new WorkerCountAction(userSession, workerCountProvider)); WebService.Action action = ws.getDef(); assertThat(action.key()).isEqualTo("worker_count"); assertThat(action.since()).isEqualTo("6.5"); assertThat(action.responseExampleAsString()).isNotEmpty(); assertThat(action.params()).isEmpty(); } @Test public void test_example() { userSession.logIn().setSystemAdministrator(); when(workerCountProvider.get()).thenReturn(5); WsActionTester ws = new WsActionTester(new WorkerCountAction(userSession, workerCountProvider)); String response = ws.newRequest().execute().getInput(); assertJson(response).isSimilarTo(ws.getDef().responseExample()); } }
3,698
36.744898
100
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/NewComponentTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component; import org.junit.Test; import static com.google.common.base.Strings.repeat; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.server.component.NewComponent.newComponentBuilder; public class NewComponentTest { private static final String KEY = "key"; private static final String NAME = "name"; private final NewComponent.Builder underTest = newComponentBuilder(); @Test public void build_throws_IAE_when_key_is_null() { underTest.setKey(null); expectBuildException(IllegalArgumentException.class, "Component key can't be empty"); } @Test public void build_throws_IAE_when_key_is_empty() { underTest .setKey(""); expectBuildException(IllegalArgumentException.class, "Component key can't be empty"); } @Test public void build_throws_IAE_when_key_is_longer_than_400_characters() { underTest.setKey(repeat("a", 400 + 1)); expectBuildException( IllegalArgumentException.class, "Component key length (401) is longer than the maximum authorized (400)"); } @Test public void build_fails_with_IAE_when_name_is_null() { underTest.setKey(KEY); expectBuildException(IllegalArgumentException.class, "Component name can't be empty"); } @Test public void build_fails_with_IAE_when_name_is_empty() { underTest.setKey(KEY) .setName(""); expectBuildException(IllegalArgumentException.class, "Component name can't be empty"); } @Test public void build_fails_with_IAE_when_name_is_longer_than_2000_characters() { underTest.setKey(KEY) .setName(repeat("a", 501)); expectBuildException( IllegalArgumentException.class, "Component name length (501) is longer than the maximum authorized (500)"); } @Test public void build_fails_with_IAE_when_qualifier_is_null() { underTest.setKey(KEY) .setName(NAME) .setQualifier(null); expectBuildException(IllegalArgumentException.class, "Component qualifier can't be empty"); } @Test public void build_fails_with_IAE_when_qualifier_is_empty() { underTest.setKey(KEY) .setName(NAME) .setQualifier(""); expectBuildException(IllegalArgumentException.class, "Component qualifier can't be empty"); } @Test public void build_fails_with_IAE_when_qualifier_is_longer_than_10_characters() { underTest.setKey(KEY) .setName(NAME) .setQualifier(repeat("a", 10 + 1)); expectBuildException( IllegalArgumentException.class, "Component qualifier length (11) is longer than the maximum authorized (10)"); } @Test public void getQualifier_returns_PROJECT_when_no_set_in_builder() { NewComponent newComponent = underTest.setKey(KEY) .setName(NAME) .build(); assertThat(newComponent.qualifier()).isEqualTo(PROJECT); } @Test public void isProject_shouldReturnTrue_whenQualifierIsProject() { NewComponent newComponent = underTest.setKey(KEY) .setName(NAME) .setQualifier(PROJECT) .build(); assertThat(newComponent.isProject()).isTrue(); } @Test public void isProject_shouldReturnFalse_whenQualifierIsNotProject() { NewComponent newComponent = underTest.setKey(KEY) .setName(NAME) .setQualifier(randomAlphabetic(4)) .build(); assertThat(newComponent.isProject()).isFalse(); } private void expectBuildException(Class<? extends Exception> expectedExceptionType, String expectedMessage) { assertThatThrownBy(underTest::build) .isInstanceOf(expectedExceptionType) .hasMessageContaining(expectedMessage); } }
4,665
30.106667
111
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ProjectKeyChangedEventTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ProjectKeyChangedEventTest { @Test public void gettersAndSettersWorkCorrectly() { ProjectKeyChangedEvent underTest = new ProjectKeyChangedEvent("oldKey", "newKey"); assertThat(underTest.getEvent()).isEqualTo("ProjectKeyChanged"); assertThat(underTest.getOldProjectKey()).isEqualTo("oldKey"); assertThat(underTest.getNewProjectKey()).isEqualTo("newKey"); } }
1,358
35.72973
86
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ComponentsWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class ComponentsWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new ComponentsWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(7); } }
1,273
35.4
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ComponentsWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.ws; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.sonarqube.ws.client.component.ComponentsWsParameters.CONTROLLER_COMPONENTS; public class ComponentsWsTest { private final String actionKey = randomAlphanumeric(10); private final ComponentsWsAction action = new ComponentsWsAction() { @Override public void handle(Request request, Response response) { } @Override public void define(WebService.NewController context) { context.createAction(actionKey).setHandler(this); } }; @Test public void define_controller() { WebService.Context context = new WebService.Context(); new ComponentsWs(action).define(context); WebService.Controller controller = context.controller(CONTROLLER_COMPONENTS); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.since()).isEqualTo("4.2"); assertThat(controller.actions()).extracting(WebService.Action::key).containsExactly(actionKey); } }
2,133
35.793103
99
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/FilterParserTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.ws; import java.util.Collections; import java.util.List; import org.junit.Test; import org.sonar.server.component.ws.FilterParser.Criterion; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.EQ; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.GT; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.GTE; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.IN; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.LT; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.LTE; public class FilterParserTest { @Test public void parse_filter_having_operator_and_value() { List<Criterion> criterion = FilterParser.parse("ncloc > 10 and coverage <= 80"); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("ncloc", GT, "10"), tuple("coverage", LTE, "80")); } @Test public void parse_filter_having_operator_and_value_ignores_white_spaces() { List<Criterion> criterion = FilterParser.parse(" ncloc > 10 "); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("ncloc", GT, "10")); } @Test public void parse_filter_having_in_operator() { List<Criterion> criterion = FilterParser.parse("ncloc in (80,90)"); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValues, Criterion::getValue) .containsOnly( tuple("ncloc", IN, asList("80", "90"), null)); } @Test public void parse_filter_having_in_operator_ignores_white_spaces() { List<Criterion> criterion = FilterParser.parse(" ncloc in ( 80 , 90 ) "); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValues, Criterion::getValue) .containsOnly( tuple("ncloc", IN, asList("80", "90"), null)); } @Test public void parse_filter_having_value_containing_operator_characters() { List<Criterion> criterion = FilterParser.parse("languages IN (java, python, <null>)"); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValues, Criterion::getValue) .containsOnly( tuple("languages", IN, asList("java", "python", "<null>"), null)); } @Test public void parse_filter_having_value_containing_non_alphanumeric_characters() { List<Criterion> criterion = FilterParser.parse("q = \"+*ç%&/()\""); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("q", EQ, "+*ç%&/()")); } @Test public void parse_filter_having_in_empty_list() { List<Criterion> criterion = FilterParser.parse("languages IN ()"); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValues, Criterion::getValue) .containsOnly( tuple("languages", IN, Collections.emptyList(), null)); } @Test public void parse_filter_having_only_key() { List<Criterion> criterion = FilterParser.parse("isFavorite"); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("isFavorite", null, null)); } @Test public void parse_filter_having_only_key_ignores_white_spaces() { List<Criterion> criterion = FilterParser.parse(" isFavorite "); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("isFavorite", null, null)); } @Test public void parse_filter_having_different_criterion_types() { List<Criterion> criterion = FilterParser.parse(" ncloc > 10 and coverage <= 80 and isFavorite "); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("ncloc", GT, "10"), tuple("coverage", LTE, "80"), tuple("isFavorite", null, null)); } @Test public void parse_filter_with_key_having_underscore() { List<Criterion> criterion = FilterParser.parse(" alert_status = OK"); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("alert_status", EQ, "OK")); } @Test public void parse_filter_without_any_space_in_criteria() { List<Criterion> criterion = FilterParser.parse("ncloc>10 and coverage<=80 and tags in (java,platform)"); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue, Criterion::getValues) .containsOnly( tuple("ncloc", GT, "10", emptyList()), tuple("coverage", LTE, "80", emptyList()), tuple("tags", IN, null, asList("java", "platform"))); } @Test public void parse_filter_having_all_operators() { List<Criterion> criterion = FilterParser.parse("ncloc < 10 and coverage <= 80 and debt > 50 and duplication >= 56.5 and security_rating = 1 and language in (java,js)"); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue, Criterion::getValues) .containsOnly( tuple("ncloc", LT, "10", emptyList()), tuple("coverage", LTE, "80", emptyList()), tuple("debt", GT, "50", emptyList()), tuple("duplication", GTE, "56.5", emptyList()), tuple("security_rating", EQ, "1", emptyList()), tuple("language", IN, null, asList("java", "js"))); } @Test public void parse_filter_starting_and_ending_with_double_quotes() { assertThat(FilterParser.parse("q = \"Sonar Qube\"")) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("q", EQ, "Sonar Qube")); assertThat(FilterParser.parse("q = \"Sonar\"Qube\"")) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("q", EQ, "Sonar\"Qube")); assertThat(FilterParser.parse("q = Sonar\"Qube")) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("q", EQ, "Sonar\"Qube")); assertThat(FilterParser.parse("q=\"Sonar Qube\"")) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("q", EQ, "Sonar Qube")); } @Test public void accept_empty_query() { List<Criterion> criterion = FilterParser.parse(""); assertThat(criterion).isEmpty(); } @Test public void accept_key_ending_by_in() { List<Criterion> criterion = FilterParser.parse("endingbyin > 10"); assertThat(criterion) .extracting(Criterion::getKey, Criterion::getOperator, Criterion::getValue) .containsOnly( tuple("endingbyin", GT, "10")); } @Test public void search_is_case_insensitive() { List<Criterion> criterion = FilterParser.parse("ncloc > 10 AnD coverage <= 80 AND debt = 10 AND issues = 20"); assertThat(criterion).hasSize(4); } @Test public void metric_key_with_and_string() { List<Criterion> criterion = FilterParser.parse("ncloc > 10 and operand = 5"); assertThat(criterion).hasSize(2).extracting(Criterion::getKey, Criterion::getValue).containsExactly(tuple("ncloc", "10"), tuple("operand", "5")); } }
8,619
35.837607
172
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ProjectMeasuresQueryFactoryTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.ws; import java.util.Collections; import java.util.List; import org.junit.Test; import org.sonar.server.component.ws.FilterParser.Criterion; import org.sonar.server.measure.index.ProjectMeasuresQuery; import org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.server.component.ws.ProjectMeasuresQueryFactory.newProjectMeasuresQuery; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.EQ; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.GT; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.IN; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.LT; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.LTE; public class ProjectMeasuresQueryFactoryTest { @Test public void create_query() { List<Criterion> criteria = asList( Criterion.builder().setKey("ncloc").setOperator(GT).setValue("10").build(), Criterion.builder().setKey("coverage").setOperator(LTE).setValue("80").build()); ProjectMeasuresQuery underTest = newProjectMeasuresQuery(criteria, emptySet()); assertThat(underTest.getMetricCriteria()) .extracting(MetricCriterion::getMetricKey, MetricCriterion::getOperator, MetricCriterion::getValue) .containsOnly( tuple("ncloc", GT, 10d), tuple("coverage", Operator.LTE, 80d)); } @Test public void fail_when_no_value() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue(null).build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Value cannot be null for 'ncloc'"); } @Test public void fail_when_not_double() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue("ten").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Value 'ten' is not a number"); } @Test public void fail_when_no_operator() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(null).setValue("ten").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Operator cannot be null for 'ncloc'"); } @Test public void create_query_on_quality_gate() { ProjectMeasuresQuery query = newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("alert_status").setOperator(EQ).setValue("OK").build()), emptySet()); assertThat(query.getQualityGateStatus().get().name()).isEqualTo("OK"); } @Test public void fail_to_create_query_on_quality_gate_when_operator_is_not_equal() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("alert_status").setOperator(GT).setValue("OK").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only equals operator is available for quality gate criteria"); } @Test public void fail_to_create_query_on_quality_gate_when_value_is_incorrect() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("alert_status").setOperator(EQ).setValue("unknown").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unknown quality gate status : 'unknown'"); } @Test public void create_query_on_qualifier() { ProjectMeasuresQuery query = newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("qualifier").setOperator(EQ).setValue("APP").build()), emptySet()); assertThat(query.getQualifiers().get()).containsOnly("APP"); } @Test public void fail_to_create_query_on_qualifier_when_operator_is_not_equal() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("qualifier").setOperator(GT).setValue("APP").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only equals operator is available for qualifier criteria"); } @Test public void fail_to_create_query_on_qualifier_when_value_is_incorrect() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("qualifier").setOperator(EQ).setValue("unknown").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unknown qualifier : 'unknown'"); } @Test public void create_query_on_language_using_in_operator() { ProjectMeasuresQuery query = newProjectMeasuresQuery( singletonList(Criterion.builder().setKey("languages").setOperator(IN).setValues(asList("java", "js")).build()), emptySet()); assertThat(query.getLanguages().get()).containsOnly("java", "js"); } @Test public void create_query_on_language_using_equals_operator() { ProjectMeasuresQuery query = newProjectMeasuresQuery( singletonList(Criterion.builder().setKey("languages").setOperator(EQ).setValue("java").build()), emptySet()); assertThat(query.getLanguages().get()).containsOnly("java"); } @Test public void fail_to_create_query_on_language_using_in_operator_and_value() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("languages").setOperator(IN).setValue("java").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Languages should be set either by using 'languages = java' or 'languages IN (java, js)'"); } @Test public void fail_to_create_query_on_language_using_eq_operator_and_values() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("languages").setOperator(EQ).setValues(asList("java")).build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Languages should be set either by using 'languages = java' or 'languages IN (java, js)'"); } @Test public void create_query_on_tag_using_in_operator() { ProjectMeasuresQuery query = newProjectMeasuresQuery( singletonList(Criterion.builder().setKey("tags").setOperator(IN).setValues(asList("java", "js")).build()), emptySet()); assertThat(query.getTags().get()).containsOnly("java", "js"); } @Test public void create_query_on_tag_using_equals_operator() { ProjectMeasuresQuery query = newProjectMeasuresQuery( singletonList(Criterion.builder().setKey("tags").setOperator(EQ).setValue("java").build()), emptySet()); assertThat(query.getTags().get()).containsOnly("java"); } @Test public void fail_to_create_query_on_tag_using_in_operator_and_value() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("tags").setOperator(IN).setValue("java").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Tags should be set either by using 'tags = java' or 'tags IN (finance, platform)'"); } @Test public void fail_to_create_query_on_tag_using_eq_operator_and_values() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("tags").setOperator(EQ).setValues(asList("java")).build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Tags should be set either by using 'tags = java' or 'tags IN (finance, platform)'"); } @Test public void create_query_having_q() { List<Criterion> criteria = singletonList(Criterion.builder().setKey("query").setOperator(EQ).setValue("Sonar Qube").build()); ProjectMeasuresQuery underTest = newProjectMeasuresQuery(criteria, emptySet()); assertThat(underTest.getQueryText()).contains("Sonar Qube"); } @Test public void create_query_having_q_ignore_case_sensitive() { List<Criterion> criteria = singletonList(Criterion.builder().setKey("query").setOperator(EQ).setValue("Sonar Qube").build()); ProjectMeasuresQuery underTest = newProjectMeasuresQuery(criteria, emptySet()); assertThat(underTest.getQueryText()).contains("Sonar Qube"); } @Test public void fail_to_create_query_having_q_with_no_value() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("query").setOperator(EQ).build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Query is invalid"); } @Test public void fail_to_create_query_having_q_with_other_operator_than_equals() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("query").setOperator(LT).setValue("java").build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Query should only be used with equals operator"); } @Test public void do_not_filter_on_projectUuids_if_criteria_non_empty_and_projectUuid_is_null() { ProjectMeasuresQuery query = newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(EQ).setValue("10").build()), null); assertThat(query.getProjectUuids()).isEmpty(); } @Test public void filter_on_projectUuids_if_projectUuid_is_empty_and_criteria_non_empty() { ProjectMeasuresQuery query = newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue("10").build()), emptySet()); assertThat(query.getProjectUuids()).isPresent(); } @Test public void filter_on_projectUuids_if_projectUuid_is_non_empty_and_criteria_non_empty() { ProjectMeasuresQuery query = newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue("10").build()), Collections.singleton("foo")); assertThat(query.getProjectUuids()).isPresent(); } @Test public void filter_on_projectUuids_if_projectUuid_is_empty_and_criteria_is_empty() { ProjectMeasuresQuery query = newProjectMeasuresQuery(emptyList(), emptySet()); assertThat(query.getProjectUuids()).isPresent(); } @Test public void filter_on_projectUuids_if_projectUuid_is_non_empty_and_criteria_empty() { ProjectMeasuresQuery query = newProjectMeasuresQuery(emptyList(), Collections.singleton("foo")); assertThat(query.getProjectUuids()).isPresent(); } @Test public void convert_metric_to_lower_case() { ProjectMeasuresQuery query = newProjectMeasuresQuery(asList( Criterion.builder().setKey("NCLOC").setOperator(GT).setValue("10").build(), Criterion.builder().setKey("coVERage").setOperator(LTE).setValue("80").build()), emptySet()); assertThat(query.getMetricCriteria()) .extracting(MetricCriterion::getMetricKey, MetricCriterion::getOperator, MetricCriterion::getValue) .containsOnly( tuple("ncloc", GT, 10d), tuple("coverage", Operator.LTE, 80d)); } @Test public void filter_no_data() { List<Criterion> criteria = singletonList(Criterion.builder().setKey("duplicated_lines_density").setOperator(EQ).setValue("NO_DATA").build()); ProjectMeasuresQuery underTest = newProjectMeasuresQuery(criteria, emptySet()); assertThat(underTest.getMetricCriteria()) .extracting(MetricCriterion::getMetricKey, MetricCriterion::isNoData) .containsOnly(tuple("duplicated_lines_density", true)); } @Test public void fail_to_use_no_data_with_operator_lower_than() { List<Criterion> criteria = singletonList(Criterion.builder().setKey("duplicated_lines_density").setOperator(LT).setValue("NO_DATA").build()); assertThatThrownBy(() -> newProjectMeasuresQuery(criteria, emptySet())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("NO_DATA can only be used with equals operator"); } @Test public void filter_no_data_with_other_case() { List<Criterion> criteria = singletonList(Criterion.builder().setKey("duplicated_lines_density").setOperator(EQ).setValue("nO_DaTa").build()); ProjectMeasuresQuery underTest = newProjectMeasuresQuery(criteria, emptySet()); assertThat(underTest.getMetricCriteria()) .extracting(MetricCriterion::getMetricKey, MetricCriterion::isNoData) .containsOnly(tuple("duplicated_lines_density", true)); } @Test public void accept_empty_query() { ProjectMeasuresQuery result = newProjectMeasuresQuery(emptyList(), emptySet()); assertThat(result.getMetricCriteria()).isEmpty(); } }
13,946
39.543605
154
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ProjectMeasuresQueryValidatorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.ws; import java.util.Arrays; import org.junit.Test; import org.sonar.server.measure.index.ProjectMeasuresQuery; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion.create; public class ProjectMeasuresQueryValidatorTest { @Test public void query_with_empty_metrics_is_valid() { ProjectMeasuresQueryValidator.validate(new ProjectMeasuresQuery()); } @Test public void filter_by_ncloc_is_valid() { assertValidFilterKey("ncloc"); } @Test public void filter_by_duplicated_lines_density_is_valid() { assertValidFilterKey("duplicated_lines_density"); } @Test public void filter_by_coverage_is_valid() { assertValidFilterKey("coverage"); } @Test public void filter_by_sqale_rating_is_valid() { assertValidFilterKey("sqale_rating"); } @Test public void filter_by_reliability_rating_is_valid() { assertValidFilterKey("reliability_rating"); } @Test public void filter_by_security_rating_is_valid() { assertValidFilterKey("security_rating"); } @Test public void filter_by_alert_status_is_valid() { assertValidFilterKey("alert_status"); } @Test public void filter_by_ncloc_language_distribution_is_valid() { assertValidFilterKey("ncloc_language_distribution"); } @Test public void filter_by_new_security_rating_is_valid() { assertValidFilterKey("new_security_rating"); } @Test public void filter_by_new_maintainability_rating_is_valid() { assertValidFilterKey("new_maintainability_rating"); } @Test public void filter_by_new_coverage_is_valid() { assertValidFilterKey("new_coverage"); } @Test public void filter_by_new_duplicated_lines_density_is_valid() { assertValidFilterKey("new_duplicated_lines_density"); } @Test public void filter_by_new_lines_is_valid() { assertValidFilterKey("new_lines"); } @Test public void filter_by_new_reliability_rating_is_valid() { assertValidFilterKey("new_reliability_rating"); } @Test public void filter_by_bla_is_invalid() { assertInvalidFilterKey("bla"); } @Test public void filter_by_bla_and_new_lines_is_invalid() { assertInvalidFilterKeys("Following metrics are not supported: 'bla'", "bla", "new_lines"); } @Test public void filter_by_new_lines_and_bla_is_invalid() { assertInvalidFilterKeys("Following metrics are not supported: 'bla'", "new_lines", "bla"); } @Test public void filter_by_NeW_LiNeS_is_invalid() { assertInvalidFilterKey("NeW_LiNeS"); } @Test public void filter_by_empty_string_is_invalid() { assertInvalidFilterKey(""); } @Test public void sort_by_ncloc_is_valid() { assertValidSortKey("ncloc"); } @Test public void sort_by_duplicated_lines_density_is_valid() { assertValidSortKey("duplicated_lines_density"); } @Test public void sort_by_coverage_is_valid() { assertValidSortKey("coverage"); } @Test public void sort_by_sqale_rating_is_valid() { assertValidSortKey("sqale_rating"); } @Test public void sort_by_reliability_rating_is_valid() { assertValidSortKey("reliability_rating"); } @Test public void sort_by_security_rating_is_valid() { assertValidSortKey("security_rating"); } @Test public void sort_by_alert_status_is_valid() { assertValidSortKey("alert_status"); } @Test public void sort_by_ncloc_language_distribution_is_valid() { assertValidSortKey("ncloc_language_distribution"); } @Test public void sort_by_new_security_rating_is_valid() { assertValidSortKey("new_security_rating"); } @Test public void sort_by_new_maintainability_rating_is_valid() { assertValidSortKey("new_maintainability_rating"); } @Test public void sort_by_new_coverage_is_valid() { assertValidSortKey("new_coverage"); } @Test public void sort_by_new_duplicated_lines_density_is_valid() { assertValidSortKey("new_duplicated_lines_density"); } @Test public void sort_by_new_lines_is_valid() { assertValidSortKey("new_lines"); } @Test public void sort_by_new_reliability_rating_is_valid() { assertValidSortKey("new_reliability_rating"); } @Test public void sort_by_bla_is_invalid() { assertInvalidSortKey("bla"); } @Test public void sort_by_NeW_lInEs_is_invalid() { assertInvalidSortKey("NeW_lInEs"); } @Test public void sort_by_empty_string_is_invalid() { assertInvalidSortKey(""); } private void assertValidSortKey(String metricKey) { // do not expect an exception ProjectMeasuresQueryValidator.validate(new ProjectMeasuresQuery().setSort(metricKey)); } private void assertInvalidSortKey(String metricKey) { assertThatThrownBy(() -> ProjectMeasuresQueryValidator.validate(new ProjectMeasuresQuery().setSort(metricKey))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Following metrics are not supported: '" + metricKey + "'"); } private static void assertValidFilterKey(String... metricKeys) { // do not expect an exception validateFilterKeys(metricKeys); } private void assertInvalidFilterKey(String metricKey) { assertInvalidFilterKeys("Following metrics are not supported: '" + metricKey + "'", metricKey); } private void assertInvalidFilterKeys(String message, String... metricKeys) { assertThatThrownBy(() -> validateFilterKeys(metricKeys)) .isInstanceOf(IllegalArgumentException.class) .hasMessage(message); } private static void validateFilterKeys(String... metricKeys) { ProjectMeasuresQuery query = new ProjectMeasuresQuery(); Arrays.stream(metricKeys).forEachOrdered(metricKey -> query.addMetricCriterion(create(metricKey, ProjectMeasuresQuery.Operator.LT, 80d))); ProjectMeasuresQueryValidator.validate(query); } }
6,745
26.092369
142
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/developers/ws/DevelopersWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.developers.ws; import org.junit.Test; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; public class DevelopersWsTest { private DevelopersWs underTest = new DevelopersWs(new SearchEventsAction(null, null, null, null, null)); @Test public void definition() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/developers"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.since()).isEqualTo("1.0"); assertThat(controller.actions()).extracting(WebService.Action::key).isNotEmpty(); } }
1,600
35.386364
98
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/email/ws/EmailsWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.email.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class EmailsWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new EmailsWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(2); } }
1,261
35.057143
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/email/ws/SendActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.email.ws; import javax.annotation.Nullable; import org.apache.commons.mail.EmailException; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class SendActionTest { @Rule public final UserSessionRule userSession = UserSessionRule.standalone(); private final EmailNotificationChannel emailNotificationChannel = mock(EmailNotificationChannel.class); private final WsActionTester ws = new WsActionTester(new SendAction(userSession, emailNotificationChannel)); @Test public void send_test_email() throws Exception { logInAsSystemAdministrator(); executeRequest("john@doo.com", "Test Message from SonarQube", "This is a test message from SonarQube at http://localhost:9000"); verify(emailNotificationChannel).sendTestEmail("john@doo.com", "Test Message from SonarQube", "This is a test message from SonarQube at http://localhost:9000"); } @Test public void does_not_fail_when_subject_param_is_missing() throws Exception { logInAsSystemAdministrator(); executeRequest("john@doo.com", null, "This is a test message from SonarQube at http://localhost:9000"); verify(emailNotificationChannel).sendTestEmail("john@doo.com", null, "This is a test message from SonarQube at http://localhost:9000"); } @Test public void fail_when_to_param_is_missing() { logInAsSystemAdministrator(); assertThatThrownBy(() -> { executeRequest(null, "Test Message from SonarQube", "This is a test message from SonarQube at http://localhost:9000"); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_message_param_is_missing() { logInAsSystemAdministrator(); assertThatThrownBy(() -> { executeRequest("john@doo.com", "Test Message from SonarQube", null); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); var request = ws.newRequest(); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void fail_with_BadRequestException_when_EmailException_is_generated() throws Exception { logInAsSystemAdministrator(); IllegalArgumentException exception1 = new IllegalArgumentException("root cause"); IllegalArgumentException exception2 = new IllegalArgumentException("parent cause", exception1); IllegalArgumentException exception3 = new IllegalArgumentException("child cause", exception2); EmailException emailException = new EmailException("last message", exception3); doThrow(emailException).when(emailNotificationChannel).sendTestEmail(anyString(), anyString(), anyString()); try { executeRequest("john@doo.com", "Test Message from SonarQube", "This is a test message from SonarQube at http://localhost:9000"); fail(); } catch (BadRequestException e) { assertThat(e.errors()).containsExactly("Configuration invalid: please double check SMTP host, port, login and password."); } } @Test public void test_ws_definition() { WebService.Action action = ws.getDef(); assertThat(action).isNotNull(); assertThat(action.isInternal()).isTrue(); assertThat(action.isPost()).isTrue(); assertThat(action.responseExampleAsString()).isNull(); assertThat(action.params()).hasSize(3); } private void executeRequest(@Nullable String to, @Nullable String subject, @Nullable String message) { TestRequest request = ws.newRequest(); if (to != null) { request.setParam("to", to); } if (subject != null) { request.setParam("subject", subject); } if (message != null) { request.setParam("message", message); } request.execute(); } private void logInAsSystemAdministrator() { userSession.logIn().setSystemAdministrator(); } }
5,471
36.737931
164
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/FavoriteModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.favorite; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class FavoriteModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new FavoriteModule().configure(container); assertThat(container.getAddedObjects()).hasSize(2); } }
1,261
35.057143
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/FavoriteWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.favorite.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class FavoriteWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new FavoriteWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(4); } }
1,268
35.257143
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/FavoritesWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.favorite.ws; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; public class FavoritesWsTest { private final FavoritesWsAction[] actions = {new FavoritesWsAction() { @Override public void define(WebService.NewController context) { context.createAction("foo").setHandler(this); } @Override public void handle(Request request, Response response) { } }}; private FavoritesWs underTest = new FavoritesWs(actions); @Test public void definition() { WebService.Context context = new WebService.Context(); underTest.define(context); assertThat(context.controller("api/favorites")).isNotNull(); } }
1,675
30.622642
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/feature/ws/FeatureWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.feature.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class FeatureWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new FeatureWsModule().configure(container); assertThat(container.getAddedObjects()).hasSizeGreaterThanOrEqualTo(2); } }
1,288
32.921053
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/feature/ws/FeatureWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.feature.ws; import java.util.List; import org.junit.Test; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; public class FeatureWsTest { private static final String CONTROLLER_FEATURES = "api/features"; private final FeatureWs underTest = new FeatureWs(new ListAction(List.of())); @Test public void define_shouldHasAtLeastOneAction() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller(CONTROLLER_FEATURES); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.path()).isEqualTo(CONTROLLER_FEATURES); assertThat(controller.since()).isEqualTo("9.6"); assertThat(controller.actions()).hasSizeGreaterThanOrEqualTo(1); } }
1,730
35.0625
79
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/feature/ws/ListActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.feature.ws; import java.util.List; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.server.feature.SonarQubeFeature; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; public class ListActionTest { private static final List<SonarQubeFeature> EXAMPLE_FEATURES = getExampleFeatures(); private final ListAction underTest = new ListAction(EXAMPLE_FEATURES); private final WsActionTester tester = new WsActionTester(underTest); @Test public void define_hasNecessaryInformation() { WebService.Action def = tester.getDef(); assertThat(def.since()).isEqualTo("9.6"); assertTrue(def.isInternal()); assertThat(def.description()).isNotEmpty(); assertThat(def.responseExampleAsString()).isNotEmpty(); } @Test public void handle_returnsValidJsonWithInfoAboutExampleFeatures() { TestResponse execute = tester.newRequest().execute(); execute.assertJson(this.getClass(), "valid-json-with-2-features.json"); } @Test public void handle_returnsEmptyJsonWhenNoFeaturesDefined() { ListAction actionWithNoFeatures = new ListAction(List.of()); WsActionTester tester = new WsActionTester(actionWithNoFeatures); TestResponse execute = tester.newRequest().execute(); execute.assertJson("[]"); } private static List<SonarQubeFeature> getExampleFeatures() { ExampleSonarQubeFeature feature1 = new ExampleSonarQubeFeature("feature1", true); ExampleSonarQubeFeature feature2 = new ExampleSonarQubeFeature("feature2", true); ExampleSonarQubeFeature feature3 = new ExampleSonarQubeFeature("feature3", false); return List.of(feature1, feature2, feature3); } static class ExampleSonarQubeFeature implements SonarQubeFeature { private final String name; private final boolean enabled; public ExampleSonarQubeFeature(String name, boolean enabled) { this.name = name; this.enabled = enabled; } @Override public String getName() { return name; } @Override public boolean isAvailable() { return enabled; } } }
3,082
31.452632
86
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/AppNodeClusterCheckTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import java.util.Arrays; import java.util.Random; import java.util.Set; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Test; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; import static java.util.stream.Collectors.toSet; import static java.util.stream.Stream.of; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.sonar.process.cluster.health.NodeHealth.Status.GREEN; import static org.sonar.process.cluster.health.NodeHealth.Status.RED; import static org.sonar.process.cluster.health.NodeHealth.Status.YELLOW; import static org.sonar.server.health.HealthAssert.assertThat; public class AppNodeClusterCheckTest { private final Random random = new Random(); private AppNodeClusterCheck underTest = new AppNodeClusterCheck(); @Test public void status_RED_when_no_application_node() { Set<NodeHealth> nodeHealths = nodeHealths().collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.RED) .andCauses("No application node"); } @Test public void status_RED_when_single_RED_application_node() { Set<NodeHealth> nodeHealths = nodeHealths(RED).collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.RED) .andCauses("Status of all application nodes is RED", "There should be at least two application nodes"); } @Test public void status_YELLOW_when_single_YELLOW_application_node() { Set<NodeHealth> nodeHealths = nodeHealths(YELLOW).collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.YELLOW) .andCauses( "Status of all application nodes is YELLOW", "There should be at least two application nodes"); } @Test public void status_YELLOW_when_single_GREEN_application_node() { Set<NodeHealth> nodeHealths = nodeHealths(GREEN).collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.YELLOW) .andCauses("There should be at least two application nodes"); } @Test public void status_RED_when_two_RED_application_nodes() { Set<NodeHealth> nodeHealths = nodeHealths(RED, RED).collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.RED) .andCauses("Status of all application nodes is RED"); } @Test public void status_YELLOW_when_two_YELLOW_application_nodes() { Set<NodeHealth> nodeHealths = nodeHealths(YELLOW, YELLOW).collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.YELLOW) .andCauses("Status of all application nodes is YELLOW"); } @Test public void status_YELLOW_when_one_RED_node_and_one_YELLOW_application_node() { Set<NodeHealth> nodeHealths = nodeHealths(RED, YELLOW).collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.YELLOW) .andCauses( "At least one application node is RED", "At least one application node is YELLOW"); } @Test public void status_YELLOW_when_one_RED_node_and_one_GREEN_application_node() { Set<NodeHealth> nodeHealths = nodeHealths(RED, GREEN).collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.YELLOW) .andCauses("At least one application node is RED"); } @Test public void status_YELLOW_when_one_YELLOW_node_and_one_GREEN_application_node() { Set<NodeHealth> nodeHealths = nodeHealths(YELLOW, GREEN).collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.YELLOW) .andCauses("At least one application node is YELLOW"); } @Test public void status_GREEN_when_two_GREEN_application_node() { Set<NodeHealth> nodeHealths = nodeHealths(GREEN, GREEN).collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.GREEN) .andCauses(); } @Test public void status_GREEN_when_two_GREEN_application_node_and_any_number_of_other_is_GREEN() { Set<NodeHealth> nodeHealths = of( // at least 1 extra GREEN of(appNodeHealth(GREEN)), // 0 to 10 GREEN randomNumberOfAppNodeHealthOfAnyStatus(GREEN), // 2 GREEN nodeHealths(GREEN, GREEN)) .flatMap(s -> s) .collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.GREEN) .andCauses(); } @Test public void status_YELLOW_when_two_GREEN_application_node_and_any_number_of_other_is_YELLOW_or_GREEN() { Set<NodeHealth> nodeHealths = of( // at least 1 YELLOW of(appNodeHealth(YELLOW)), // 0 to 10 YELLOW/GREEN randomNumberOfAppNodeHealthOfAnyStatus(GREEN, YELLOW), // 2 GREEN nodeHealths(GREEN, GREEN)) .flatMap(s -> s) .collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.YELLOW) .andCauses("At least one application node is YELLOW"); } @Test public void status_YELLOW_when_two_GREEN_application_node_and_any_number_of_other_is_RED_or_GREEN() { Set<NodeHealth> nodeHealths = of( // at least 1 RED of(appNodeHealth(RED)), // 0 to 10 RED/GREEN randomNumberOfAppNodeHealthOfAnyStatus(GREEN, RED), // 2 GREEN nodeHealths(GREEN, GREEN)) .flatMap(s -> s) .collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.YELLOW) .andCauses("At least one application node is RED"); } @Test public void status_YELLOW_when_two_GREEN_application_node_and_any_number_of_other_is_either_RED_or_YELLOW() { Set<NodeHealth> nodeHealths = of( // at least 1 RED of(appNodeHealth(RED)), // at least 1 YELLOW of(appNodeHealth(YELLOW)), // 0 to 10 RED/YELLOW/GREEN randomNumberOfAppNodeHealthOfAnyStatus(RED, YELLOW, GREEN), // 2 GREEN nodeHealths(GREEN, GREEN)) .flatMap(s -> s) .collect(toSet()); Health check = underTest.check(nodeHealths); assertThat(check) .forInput(nodeHealths) .hasStatus(Health.Status.YELLOW) .andCauses( "At least one application node is YELLOW", "At least one application node is RED"); } /** * Between 0 and 10 NodeHealth of Application node with any of the specified statuses. */ private Stream<NodeHealth> randomNumberOfAppNodeHealthOfAnyStatus(NodeHealth.Status... randomStatuses) { return IntStream.range(0, random.nextInt(10)) .mapToObj(i -> appNodeHealth(randomStatuses[random.nextInt(randomStatuses.length)])); } private Stream<NodeHealth> nodeHealths(NodeHealth.Status... appNodeStatuses) { return of( // random number of Search nodes with random status IntStream.range(0, random.nextInt(3)) .mapToObj(i -> appNodeHealth(NodeDetails.Type.SEARCH, NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)])), Arrays.stream(appNodeStatuses).map(this::appNodeHealth)) .flatMap(s -> s); } private NodeHealth appNodeHealth(NodeHealth.Status status) { return appNodeHealth(NodeDetails.Type.APPLICATION, status); } private NodeHealth appNodeHealth(NodeDetails.Type type, NodeHealth.Status status) { return NodeHealth.newNodeHealthBuilder() .setStatus(status) .setDetails(NodeDetails.newNodeDetailsBuilder() .setType(type) .setHost(randomAlphanumeric(32)) .setName(randomAlphanumeric(32)) .setPort(1 + random.nextInt(88)) .setStartedAt(1 + random.nextInt(54)) .build()) .build(); } }
9,301
31.524476
142
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/CeStatusNodeCheckTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import org.junit.Test; import org.sonar.server.app.ProcessCommandWrapper; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CeStatusNodeCheckTest { private ProcessCommandWrapper processCommandWrapper = mock(ProcessCommandWrapper.class); private CeStatusNodeCheck underTest = new CeStatusNodeCheck(processCommandWrapper); @Test public void check_returns_GREEN_status_without_cause_if_ce_is_operational() { when(processCommandWrapper.isCeOperational()).thenReturn(true); Health health = underTest.check(); assertThat(health).isEqualTo(Health.GREEN); } @Test public void check_returns_RED_status_with_cause_if_ce_is_not_operational() { when(processCommandWrapper.isCeOperational()).thenReturn(false); Health health = underTest.check(); assertThat(health.getStatus()).isEqualTo(Health.Status.RED); assertThat(health.getCauses()).containsOnly("Compute Engine is not operational"); } }
1,910
35.75
90
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/ClusterHealthTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Test; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; import static java.util.stream.Collectors.toSet; import static java.util.stream.Stream.concat; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; public class ClusterHealthTest { private final Random random = new Random(); @Test public void constructor_fails_with_NPE_if_Health_is_null() { assertThatThrownBy(() -> new ClusterHealth(null, Collections.emptySet())) .isInstanceOf(NullPointerException.class) .hasMessageContaining("health can't be null"); } @Test public void constructor_fails_with_NPE_if_NodeHealth_is_null() { assertThatThrownBy(() -> new ClusterHealth(Health.GREEN, null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("nodes can't be null"); } @Test public void verify_getters() { Health health = randomHealth(); Set<NodeHealth> nodeHealths = randomNodeHealths(); ClusterHealth underTest = new ClusterHealth(health, nodeHealths); assertThat(underTest.getHealth()).isSameAs(health); assertThat(underTest.getNodes()).isEqualTo(nodeHealths); } @Test public void equals_is_based_on_content() { Health health = randomHealth(); Set<NodeHealth> nodeHealths = randomNodeHealths(); ClusterHealth underTest = new ClusterHealth(health, nodeHealths); assertThat(underTest) .isEqualTo(underTest) .isEqualTo(new ClusterHealth(health, nodeHealths)) .isNotEqualTo(new Object()) .isNotNull() .isNotEqualTo(new ClusterHealth( Health.builder() .setStatus(health.getStatus()) .addCause("foo_bar") .build(), randomNodeHealths())) .isNotEqualTo(new ClusterHealth( health, concat(nodeHealths.stream(), Stream.of(randomNodeHealth())).collect(toSet()))); } @Test public void hashcode_is_based_on_content() { Health health = randomHealth(); Set<NodeHealth> nodeHealths = randomNodeHealths(); ClusterHealth underTest = new ClusterHealth(health, nodeHealths); assertThat(underTest).hasSameHashCodeAs(underTest); } @Test public void verify_toString() { Health health = randomHealth(); Set<NodeHealth> nodeHealths = randomNodeHealths(); ClusterHealth underTest = new ClusterHealth(health, nodeHealths); assertThat(underTest).hasToString("ClusterHealth{health=" + health + ", nodes=" + nodeHealths + "}"); } @Test public void test_getNodeHealth() { Health health = randomHealth(); Set<NodeHealth> nodeHealths = new HashSet<>(Arrays.asList(newNodeHealth("foo"), newNodeHealth("bar"))); ClusterHealth underTest = new ClusterHealth(health, nodeHealths); assertThat(underTest.getNodeHealth("does_not_exist")).isEmpty(); assertThat(underTest.getNodeHealth("bar")).isPresent(); } private Health randomHealth() { Health.Builder healthBuilder = Health.builder(); healthBuilder.setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]); IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).forEach(healthBuilder::addCause); return healthBuilder.build(); } private Set<NodeHealth> randomNodeHealths() { return IntStream.range(0, random.nextInt(4)).mapToObj(i -> randomNodeHealth()).collect(toSet()); } private NodeHealth randomNodeHealth() { return newNodeHealthBuilder() .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]) .setDetails( NodeDetails.newNodeDetailsBuilder() .setType(random.nextBoolean() ? NodeDetails.Type.SEARCH : NodeDetails.Type.APPLICATION) .setName(randomAlphanumeric(3)) .setHost(randomAlphanumeric(4)) .setPort(1 + random.nextInt(344)) .setStartedAt(1 + random.nextInt(999)) .build()) .build(); } private static NodeHealth newNodeHealth(String nodeName) { return newNodeHealthBuilder() .setStatus(NodeHealth.Status.YELLOW) .setDetails(randomNodeDetails(nodeName)) .build(); } private static NodeDetails randomNodeDetails(String nodeName) { return NodeDetails.newNodeDetailsBuilder() .setType(NodeDetails.Type.APPLICATION) .setName(nodeName) .setHost(randomAlphanumeric(4)) .setPort(3000) .setStartedAt(1_000L) .build(); } }
5,730
34.376543
112
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/DbConnectionNodeCheckTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import org.junit.Before; import org.junit.Test; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.IsAliveMapper; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DbConnectionNodeCheckTest { private DbClient dbClient = mock(DbClient.class); private DbSession dbSession = mock(DbSession.class); private IsAliveMapper isAliveMapper = mock(IsAliveMapper.class); private DbConnectionNodeCheck underTest = new DbConnectionNodeCheck(dbClient); @Before public void wireMocks() { when(dbClient.openSession(anyBoolean())).thenReturn(dbSession); when(dbSession.getMapper(IsAliveMapper.class)).thenReturn(isAliveMapper); } @Test public void status_is_GREEN_without_cause_if_isAlive_returns_1() { when(isAliveMapper.isAlive()).thenReturn(1); Health health = underTest.check(); assertThat(health).isEqualTo(Health.GREEN); } @Test public void status_is_RED_with_single_cause_if_any_error_occurs_when_checking_DB() { when(isAliveMapper.isAlive()).thenThrow(new RuntimeException("simulated runtime exception when querying DB")); Health health = underTest.check(); verifyRedStatus(health); } /** * By contract {@link IsAliveMapper#isAlive()} can not return anything but 1. Still we write this test as a * protection against change in this contract. */ @Test public void status_is_RED_with_single_cause_if_isAlive_does_not_return_1() { when(isAliveMapper.isAlive()).thenReturn(12); Health health = underTest.check(); verifyRedStatus(health); } private void verifyRedStatus(Health health) { assertThat(health.getStatus()).isEqualTo(Health.Status.RED); assertThat(health.getCauses()).containsOnly("Can't connect to DB"); } }
2,782
32.939024
114
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/EsStatusClusterCheckTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import com.google.common.collect.ImmutableSet; import java.util.Random; import java.util.Set; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.junit.Test; import org.mockito.Mockito; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; import org.sonar.server.es.EsClient; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.when; import static org.sonar.process.cluster.health.NodeHealth.Status.GREEN; public class EsStatusClusterCheckTest { private EsClient esClient = Mockito.mock(EsClient.class, RETURNS_DEEP_STUBS); private Random random = new Random(); private EsStatusClusterCheck underTest = new EsStatusClusterCheck(esClient); @Test public void check_ignores_NodeHealth_arg_and_returns_RED_with_cause_if_an_exception_occurs_checking_ES_cluster_status() { Set<NodeHealth> nodeHealths = ImmutableSet.of(newNodeHealth(NodeHealth.Status.GREEN)); when(esClient.clusterHealth(any())).thenThrow(new RuntimeException("Faking an exception occurring while using the EsClient")); Health health = new EsStatusClusterCheck(esClient).check(nodeHealths); assertThat(health.getStatus()).isEqualTo(Health.Status.RED); assertThat(health.getCauses()).containsOnly("Elasticsearch status is RED (unavailable)"); } @Test public void check_ignores_NodeHealth_arg_and_returns_GREEN_without_cause_if_ES_cluster_status_is_GREEN() { Set<NodeHealth> nodeHealths = ImmutableSet.of(newNodeHealth(NodeHealth.Status.YELLOW)); when(esClient.clusterHealth(any()).getStatus()).thenReturn(ClusterHealthStatus.GREEN); when(esClient.clusterHealth(any()).getNumberOfNodes()).thenReturn(3); Health health = underTest.check(nodeHealths); assertThat(health).isEqualTo(Health.GREEN); } @Test public void check_returns_YELLOW_with_cause_if_ES_cluster_has_less_than_three_nodes_but_status_is_green() { Set<NodeHealth> nodeHealths = ImmutableSet.of(newNodeHealth(GREEN)); when(esClient.clusterHealth(any()).getStatus()).thenReturn(ClusterHealthStatus.GREEN); when(esClient.clusterHealth(any()).getNumberOfNodes()).thenReturn(2); Health health = underTest.check(nodeHealths); assertThat(health.getStatus()).isEqualTo(Health.Status.YELLOW); assertThat(health.getCauses()).containsOnly("There should be at least three search nodes"); } @Test public void check_returns_RED_with_cause_if_ES_cluster_has_less_than_three_nodes_and_status_is_RED() { Set<NodeHealth> nodeHealths = ImmutableSet.of(newNodeHealth(GREEN)); when(esClient.clusterHealth(any()).getStatus()).thenReturn(ClusterHealthStatus.RED); when(esClient.clusterHealth(any()).getNumberOfNodes()).thenReturn(2); Health health = underTest.check(nodeHealths); assertThat(health.getStatus()).isEqualTo(Health.Status.RED); assertThat(health.getCauses()).contains("Elasticsearch status is RED", "There should be at least three search nodes"); } private NodeHealth newNodeHealth(NodeHealth.Status status) { return NodeHealth.newNodeHealthBuilder() .setStatus(status) .setDetails(NodeDetails.newNodeDetailsBuilder() .setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH) .setName(randomAlphanumeric(23)) .setHost(randomAlphanumeric(23)) .setPort(1 + random.nextInt(96)) .setStartedAt(1 + random.nextInt(966)) .build()) .build(); } }
4,556
41.990566
130
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/EsStatusNodeCheckTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.junit.Test; import org.mockito.Mockito; import org.sonar.server.es.EsClient; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class EsStatusNodeCheckTest { private EsClient esClient = mock(EsClient.class, Mockito.RETURNS_DEEP_STUBS); private EsStatusNodeCheck underTest = new EsStatusNodeCheck(esClient); @Test public void check_ignores_NodeHealth_arg_and_returns_RED_with_cause_if_an_exception_occurs_checking_ES_cluster_status() { EsClient esClient = mock(EsClient.class); when(esClient.clusterHealth(any())).thenThrow(new RuntimeException("Faking an exception occurring while using the EsClient")); Health health = new EsStatusNodeCheck(esClient).check(); assertThat(health.getStatus()).isEqualTo(Health.Status.RED); assertThat(health.getCauses()).containsOnly("Elasticsearch status is RED (unavailable)"); } @Test public void check_returns_GREEN_without_cause_if_ES_cluster_status_is_GREEN() { when(esClient.clusterHealth(any()).getStatus()).thenReturn(ClusterHealthStatus.GREEN); Health health = underTest.check(); assertThat(health).isEqualTo(Health.GREEN); } }
2,219
37.275862
130
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthAssert.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import com.google.common.collect.ImmutableList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; import org.sonar.process.cluster.health.NodeHealth; final class HealthAssert extends AbstractAssert<HealthAssert, Health> { private Set<NodeHealth> nodeHealths; private HealthAssert(Health actual) { super(actual, HealthAssert.class); } public static HealthAssert assertThat(Health actual) { return new HealthAssert(actual); } public HealthAssert forInput(Set<NodeHealth> nodeHealths) { this.nodeHealths = nodeHealths; return this; } public HealthAssert hasStatus(Health.Status expected) { isNotNull(); if (actual.getStatus() != expected) { failWithMessage( "Expected Status of Health to be <%s> but was <%s> for NodeHealth \n%s", expected, actual.getStatus(), printStatusesAndTypes(this.nodeHealths)); } return this; } public HealthAssert andCauses(String... causes) { isNotNull(); if (!checkCauses(causes)) { failWithMessage( "Expected causes of Health to contain only \n%s\n but was \n%s\n for NodeHealth \n%s", Arrays.asList(causes), actual.getCauses(), printStatusesAndTypes(this.nodeHealths)); } return this; } private String printStatusesAndTypes(@Nullable Set<NodeHealth> nodeHealths) { if (nodeHealths == null) { return "<null>"; } return nodeHealths.stream() // sort by type then status for debugging convenience .sorted(Comparator.<NodeHealth>comparingInt(s1 -> s1.getDetails().getType().ordinal()) .thenComparingInt(s -> s.getStatus().ordinal())) .map(s -> ImmutableList.of(s.getDetails().getType().name(), s.getStatus().name())) .map(String::valueOf) .collect(Collectors.joining(",")); } private boolean checkCauses(String... causes) { if (causes.length != this.actual.getCauses().size()) { return false; } return Objects.equals(new HashSet<>(Arrays.asList(causes)), this.actual.getCauses()); } }
3,117
30.816327
94
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Test; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; import org.sonar.process.cluster.health.SharedHealthState; import org.sonar.server.platform.NodeInformation; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; import static org.sonar.server.health.Health.Status.GREEN; import static org.sonar.server.health.Health.Status.RED; import static org.sonar.server.health.Health.Status.YELLOW; public class HealthCheckerImplTest { private final NodeInformation nodeInformation = mock(NodeInformation.class); private final SharedHealthState sharedHealthState = mock(SharedHealthState.class); private final Random random = new Random(); @Test public void check_returns_green_status_without_any_cause_when_there_is_no_NodeHealthCheck() { HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, new NodeHealthCheck[0]); assertThat(underTest.checkNode()).isEqualTo(Health.GREEN); } @Test public void checkNode_returns_GREEN_status_if_only_GREEN_statuses_returned_by_NodeHealthCheck() { List<Health.Status> statuses = IntStream.range(1, 1 + random.nextInt(20)).mapToObj(i -> GREEN).toList(); HealthCheckerImpl underTest = newNodeHealthCheckerImpl(statuses.stream()); assertThat(underTest.checkNode().getStatus()) .describedAs("%s should have been computed from %s statuses", GREEN, statuses) .isEqualTo(GREEN); } @Test public void checkNode_returns_YELLOW_status_if_only_GREEN_and_at_least_one_YELLOW_statuses_returned_by_NodeHealthCheck() { List<Health.Status> statuses = new ArrayList<>(); Stream.concat( IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> YELLOW), // at least 1 YELLOW IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN)).forEach(statuses::add); // between 0 and 19 GREEN Collections.shuffle(statuses); HealthCheckerImpl underTest = newNodeHealthCheckerImpl(statuses.stream()); assertThat(underTest.checkNode().getStatus()) .describedAs("%s should have been computed from %s statuses", YELLOW, statuses) .isEqualTo(YELLOW); } @Test public void checkNode_returns_RED_status_if_at_least_one_RED_status_returned_by_NodeHealthCheck() { List<Health.Status> statuses = new ArrayList<>(); Stream.of( IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> RED), // at least 1 RED IntStream.range(0, random.nextInt(20)).mapToObj(i -> YELLOW), // between 0 and 19 YELLOW IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN) // between 0 and 19 GREEN ).flatMap(s -> s) .forEach(statuses::add); Collections.shuffle(statuses); HealthCheckerImpl underTest = newNodeHealthCheckerImpl(statuses.stream()); assertThat(underTest.checkNode().getStatus()) .describedAs("%s should have been computed from %s statuses", RED, statuses) .isEqualTo(RED); } @Test public void checkNode_returns_causes_of_all_NodeHealthCheck_whichever_their_status() { NodeHealthCheck[] nodeHealthChecks = IntStream.range(0, 1 + random.nextInt(20)) .mapToObj(s -> new HardcodedHealthNodeCheck(IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).toArray(String[]::new))) .map(NodeHealthCheck.class::cast) .toArray(NodeHealthCheck[]::new); String[] expected = Arrays.stream(nodeHealthChecks).map(NodeHealthCheck::check).flatMap(s -> s.getCauses().stream()).toArray(String[]::new); HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, nodeHealthChecks); assertThat(underTest.checkNode().getCauses()).containsOnly(expected); } @Test public void checkCluster_fails_with_ISE_in_standalone() { when(nodeInformation.isStandalone()).thenReturn(true); HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, new NodeHealthCheck[0], new ClusterHealthCheck[0], sharedHealthState); assertThatThrownBy(() -> underTest.checkCluster()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Clustering is not enabled"); } @Test public void checkCluster_fails_with_ISE_in_clustering_and_HealthState_is_null() { when(nodeInformation.isStandalone()).thenReturn(false); HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, new NodeHealthCheck[0], new ClusterHealthCheck[0], null); assertThatThrownBy(() -> underTest.checkCluster()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("HealthState instance can't be null when clustering is enabled"); } @Test public void checkCluster_returns_GREEN_when_there_is_no_ClusterHealthCheck() { when(nodeInformation.isStandalone()).thenReturn(false); HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, new NodeHealthCheck[0], new ClusterHealthCheck[0], sharedHealthState); assertThat(underTest.checkCluster().getHealth()).isEqualTo(Health.GREEN); } @Test public void checkCluster_returns_GREEN_status_if_only_GREEN_statuses_returned_by_ClusterHealthChecks() { when(nodeInformation.isStandalone()).thenReturn(false); List<Health.Status> statuses = IntStream.range(1, 1 + random.nextInt(20)).mapToObj(i -> GREEN).toList(); HealthCheckerImpl underTest = newClusterHealthCheckerImpl(statuses.stream()); assertThat(underTest.checkCluster().getHealth().getStatus()) .describedAs("%s should have been computed from %s statuses", GREEN, statuses) .isEqualTo(GREEN); } @Test public void checkCluster_returns_YELLOW_status_if_only_GREEN_and_at_least_one_YELLOW_statuses_returned_by_ClusterHealthChecks() { when(nodeInformation.isStandalone()).thenReturn(false); List<Health.Status> statuses = new ArrayList<>(); Stream.concat( IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> YELLOW), // at least 1 YELLOW IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN)).forEach(statuses::add); // between 0 and 19 GREEN Collections.shuffle(statuses); HealthCheckerImpl underTest = newClusterHealthCheckerImpl(statuses.stream()); assertThat(underTest.checkCluster().getHealth().getStatus()) .describedAs("%s should have been computed from %s statuses", YELLOW, statuses) .isEqualTo(YELLOW); } @Test public void checkCluster_returns_RED_status_if_at_least_one_RED_status_returned_by_ClusterHealthChecks() { when(nodeInformation.isStandalone()).thenReturn(false); List<Health.Status> statuses = new ArrayList<>(); Stream.of( IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> RED), // at least 1 RED IntStream.range(0, random.nextInt(20)).mapToObj(i -> YELLOW), // between 0 and 19 YELLOW IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN) // between 0 and 19 GREEN ).flatMap(s -> s) .forEach(statuses::add); Collections.shuffle(statuses); HealthCheckerImpl underTest = newClusterHealthCheckerImpl(statuses.stream()); assertThat(underTest.checkCluster().getHealth().getStatus()) .describedAs("%s should have been computed from %s statuses", RED, statuses) .isEqualTo(RED); } @Test public void checkCluster_returns_causes_of_all_ClusterHealthChecks_whichever_their_status() { when(nodeInformation.isStandalone()).thenReturn(false); List<String[]> causesGroups = IntStream.range(0, 1 + random.nextInt(20)) .mapToObj(s -> IntStream.range(0, random.nextInt(3)).mapToObj(i -> randomAlphanumeric(3)).toArray(String[]::new)) .toList(); ClusterHealthCheck[] clusterHealthChecks = causesGroups.stream() .map(HardcodedHealthClusterCheck::new) .map(ClusterHealthCheck.class::cast) .toArray(ClusterHealthCheck[]::new); String[] expectedCauses = causesGroups.stream().flatMap(Arrays::stream).toArray(String[]::new); HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, new NodeHealthCheck[0], clusterHealthChecks, sharedHealthState); assertThat(underTest.checkCluster().getHealth().getCauses()).containsOnly(expectedCauses); } @Test public void checkCluster_passes_set_of_NodeHealth_returns_by_HealthState_to_all_ClusterHealthChecks() { when(nodeInformation.isStandalone()).thenReturn(false); ClusterHealthCheck[] mockedClusterHealthChecks = IntStream.range(0, 1 + random.nextInt(3)) .mapToObj(i -> mock(ClusterHealthCheck.class)) .toArray(ClusterHealthCheck[]::new); Set<NodeHealth> nodeHealths = IntStream.range(0, 1 + random.nextInt(4)).mapToObj(i -> randomNodeHealth()).collect(Collectors.toSet()); when(sharedHealthState.readAll()).thenReturn(nodeHealths); for (ClusterHealthCheck mockedClusterHealthCheck : mockedClusterHealthChecks) { when(mockedClusterHealthCheck.check(same(nodeHealths))).thenReturn(Health.GREEN); } HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, new NodeHealthCheck[0], mockedClusterHealthChecks, sharedHealthState); underTest.checkCluster(); for (ClusterHealthCheck mockedClusterHealthCheck : mockedClusterHealthChecks) { verify(mockedClusterHealthCheck).check(same(nodeHealths)); } } @Test public void checkCluster_returns_NodeHealths_returned_by_HealthState() { when(nodeInformation.isStandalone()).thenReturn(false); Set<NodeHealth> nodeHealths = IntStream.range(0, 1 + random.nextInt(4)).mapToObj(i -> randomNodeHealth()).collect(Collectors.toSet()); when(sharedHealthState.readAll()).thenReturn(nodeHealths); HealthCheckerImpl underTest = new HealthCheckerImpl(nodeInformation, new NodeHealthCheck[0], new ClusterHealthCheck[0], sharedHealthState); ClusterHealth clusterHealth = underTest.checkCluster(); assertThat(clusterHealth.getNodes()).isEqualTo(nodeHealths); } private NodeHealth randomNodeHealth() { return newNodeHealthBuilder() .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]) .setDetails(newNodeDetailsBuilder() .setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH) .setName(randomAlphanumeric(10)) .setHost(randomAlphanumeric(5)) .setPort(1 + random.nextInt(333)) .setStartedAt(1 + random.nextInt(444)) .build()) .build(); } private HealthCheckerImpl newNodeHealthCheckerImpl(Stream<Health.Status> statuses) { Stream<HardcodedHealthNodeCheck> staticHealthCheckStream = statuses.map(HardcodedHealthNodeCheck::new); return new HealthCheckerImpl( nodeInformation, staticHealthCheckStream.map(NodeHealthCheck.class::cast).toArray(NodeHealthCheck[]::new)); } private HealthCheckerImpl newClusterHealthCheckerImpl(Stream<Health.Status> statuses) { Stream<HardcodedHealthClusterCheck> staticHealthCheckStream = statuses.map(HardcodedHealthClusterCheck::new); return new HealthCheckerImpl( nodeInformation, new NodeHealthCheck[0], staticHealthCheckStream.map(ClusterHealthCheck.class::cast).toArray(ClusterHealthCheck[]::new), sharedHealthState); } private class HardcodedHealthNodeCheck implements NodeHealthCheck { private final Health health; public HardcodedHealthNodeCheck(Health.Status status) { this.health = Health.builder().setStatus(status).build(); } public HardcodedHealthNodeCheck(String... causes) { Health.Builder builder = Health.builder().setStatus(Health.Status.values()[random.nextInt(3)]); Stream.of(causes).forEach(builder::addCause); this.health = builder.build(); } @Override public Health check() { return health; } } private class HardcodedHealthClusterCheck implements ClusterHealthCheck { private final Health health; public HardcodedHealthClusterCheck(Health.Status status) { this.health = Health.builder().setStatus(status).build(); } public HardcodedHealthClusterCheck(String... causes) { Health.Builder builder = Health.builder().setStatus(Health.Status.values()[random.nextInt(3)]); Stream.of(causes).forEach(builder::addCause); this.health = builder.build(); } @Override public Health check(Set<NodeHealth> nodeHealths) { return health; } } }
13,871
44.481967
149
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import com.google.common.base.Strings; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.assertj.core.api.AbstractCharSequenceAssert; import org.junit.Test; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.ThrowableAssert.ThrowingCallable; public class HealthTest { private final Random random = new Random(); private final Health.Status anyStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)]; private final Set<String> randomCauses = IntStream.range(0, random.nextInt(5)).mapToObj(s -> randomAlphanumeric(3)).collect(Collectors.toSet()); @Test public void build_throws_NPE_if_status_is_null() { Health.Builder builder = Health.builder(); expectStatusNotNullNPE(() -> builder.build()); } @Test public void setStatus_throws_NPE_if_status_is_null() { Health.Builder builder = Health.builder(); expectStatusNotNullNPE(() -> builder.setStatus(null)); } @Test public void getStatus_returns_status_from_builder() { Health underTest = Health.builder().setStatus(anyStatus).build(); assertThat(underTest.getStatus()).isEqualTo(anyStatus); } @Test public void addCause_throws_NPE_if_arg_is_null() { Health.Builder builder = Health.builder(); assertThatThrownBy(() -> builder.addCause(null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("cause can't be null"); } @Test public void addCause_throws_IAE_if_arg_is_empty() { Health.Builder builder = Health.builder(); expectCauseCannotBeEmptyIAE(() -> builder.addCause("")); } @Test public void addCause_throws_IAE_if_arg_contains_only_spaces() { Health.Builder builder = Health.builder(); expectCauseCannotBeEmptyIAE(() -> builder.addCause(Strings.repeat(" ", 1 + random.nextInt(5)))); } @Test public void getCause_returns_causes_from_builder() { Health.Builder builder = Health.builder().setStatus(anyStatus); randomCauses.forEach(builder::addCause); Health underTest = builder.build(); assertThat(underTest.getCauses()) .isEqualTo(randomCauses); } @Test public void green_constant() { assertThat(Health.builder().setStatus(Health.Status.GREEN).build()).isEqualTo(Health.GREEN); } @Test public void equals_is_based_on_status_and_causes() { Health.Builder builder1 = Health.builder(); Health.Builder builder2 = Health.builder(); builder1.setStatus(anyStatus); builder2.setStatus(anyStatus); randomCauses.forEach(s -> { builder1.addCause(s); builder2.addCause(s); }); assertThat(builder1.build()) .isEqualTo(builder1.build()) .isEqualTo(builder2.build()) .isEqualTo(builder2.build()); } @Test public void not_equals_to_null_nor_other_type() { assertThat(Health.GREEN) .isNotNull() .isNotEqualTo(new Object()) .isNotEqualTo(Health.Status.GREEN); } @Test public void hashcode_is_based_on_status_and_causes() { Health.Builder builder1 = Health.builder(); Health.Builder builder2 = Health.builder(); builder1.setStatus(anyStatus); builder2.setStatus(anyStatus); randomCauses.forEach(s -> { builder1.addCause(s); builder2.addCause(s); }); assertThat(builder1.build().hashCode()) .isEqualTo(builder1.build().hashCode()) .isEqualTo(builder2.build().hashCode()) .isEqualTo(builder2.build().hashCode()); } @Test public void verify_toString() { assertThat(Health.GREEN).hasToString("Health{GREEN, causes=[]}"); Health.Builder builder = Health.builder().setStatus(anyStatus); randomCauses.forEach(builder::addCause); String underTest = builder.build().toString(); AbstractCharSequenceAssert<?, String> a = assertThat(underTest) .describedAs("toString for status %s and causes %s", anyStatus, randomCauses); if (randomCauses.isEmpty()) { a.isEqualTo("Health{" + anyStatus + ", causes=[]}"); } else if (randomCauses.size() == 1) { a.isEqualTo("Health{" + anyStatus + ", causes=[" + randomCauses.iterator().next() + "]}"); } else { a.startsWith("Health{" + anyStatus + ", causes=[") .endsWith("]}") .contains(randomCauses); } } private void expectStatusNotNullNPE(ThrowingCallable shouldRaiseThrowable) { assertThatThrownBy(shouldRaiseThrowable) .isInstanceOf(NullPointerException.class) .hasMessageContaining("status can't be null"); } private void expectCauseCannotBeEmptyIAE(ThrowingCallable shouldRaiseThrowable) { assertThatThrownBy(shouldRaiseThrowable) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("cause can't be empty"); } }
5,814
32.039773
146
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import java.util.Date; import java.util.Random; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.platform.Server; import org.sonar.api.utils.System2; import org.sonar.core.platform.SpringComponentContainer; import org.sonar.process.NetworkUtils; import org.sonar.process.cluster.health.SharedHealthStateImpl; import org.sonar.process.cluster.hz.HazelcastMember; import org.sonar.core.platform.ListContainer; import static java.lang.String.valueOf; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class NodeHealthModuleTest { private final Random random = new Random(); private final MapSettings mapSettings = new MapSettings(); private final NodeHealthModule underTest = new NodeHealthModule(); @Test public void no_broken_dependencies() { SpringComponentContainer container = new SpringComponentContainer(); Server server = mock(Server.class); NetworkUtils networkUtils = mock(NetworkUtils.class); // settings required by NodeHealthProvider mapSettings.setProperty("sonar.cluster.node.name", randomAlphanumeric(3)); mapSettings.setProperty("sonar.cluster.node.port", valueOf(1 + random.nextInt(10))); when(server.getStartedAt()).thenReturn(new Date()); when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(12)); // upper level dependencies container.add( mock(System2.class), mapSettings.asConfig(), server, networkUtils, mock(HazelcastMember.class)); // HealthAction dependencies container.add(mock(HealthChecker.class)); underTest.configure(container); container.startComponents(); } @Test public void provides_implementation_of_SharedHealthState() { ListContainer container = new ListContainer(); underTest.configure(container); assertThat(container.getAddedObjects()) .contains(SharedHealthStateImpl.class); } }
2,951
36.367089
88
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthProviderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import java.util.Arrays; import java.util.Date; import java.util.Random; import java.util.stream.IntStream; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.platform.Server; import org.sonar.process.NetworkUtils; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; public class NodeHealthProviderImplTest { private final Random random = new Random(); private MapSettings mapSettings = new MapSettings(); private HealthChecker healthChecker = mock(HealthChecker.class); private Server server = mock(Server.class); private NetworkUtils networkUtils = mock(NetworkUtils.class); @Test public void constructor_throws_ISE_if_node_name_property_is_not_set() { assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Property sonar.cluster.node.name is not defined"); } @Test public void constructor_thows_NPE_if_NetworkUtils_getHostname_returns_null() { mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils)) .isInstanceOf(NullPointerException.class); } @Test public void constructor_throws_ISE_if_node_port_property_is_not_set() { mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(23)); assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Property sonar.cluster.node.port is not defined"); } @Test public void constructor_throws_NPE_is_Server_getStartedAt_is_null() { setRequiredPropertiesForConstructor(); assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils)) .isInstanceOf(NullPointerException.class); } @Test public void get_returns_HEALTH_status_and_causes_from_HealthChecker_checkNode() { setRequiredPropertiesForConstructor(); setStartedAt(); when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(4)); Health.Status randomStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)]; String[] expected = IntStream.range(0, random.nextInt(4)).mapToObj(s -> randomAlphabetic(55)).toArray(String[]::new); Health.Builder healthBuilder = Health.builder() .setStatus(randomStatus); Arrays.stream(expected).forEach(healthBuilder::addCause); when(healthChecker.checkNode()).thenReturn(healthBuilder.build()); NodeHealthProviderImpl underTest = new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getStatus().name()).isEqualTo(randomStatus.name()); assertThat(nodeHealth.getCauses()).containsOnly(expected); } @Test public void get_returns_APPLICATION_type() { setRequiredPropertiesForConstructor(); setStartedAt(); when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(23)); when(healthChecker.checkNode()).thenReturn(Health.builder() .setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]) .build()); NodeHealthProviderImpl underTest = new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getDetails().getType()).isEqualTo(NodeDetails.Type.APPLICATION); } @Test public void get_returns_name_and_port_from_properties_at_constructor_time() { String name = randomAlphanumeric(3); int port = 1 + random.nextInt(4); mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), name); mapSettings.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), port); setStartedAt(); when(healthChecker.checkNode()).thenReturn(Health.builder() .setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]) .build()); when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(3)); NodeHealthProviderImpl underTest = new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getDetails().getName()).isEqualTo(name); assertThat(nodeHealth.getDetails().getPort()).isEqualTo(port); // change values in properties setRequiredPropertiesForConstructor(); NodeHealth newNodeHealth = underTest.get(); assertThat(newNodeHealth.getDetails().getName()).isEqualTo(name); assertThat(newNodeHealth.getDetails().getPort()).isEqualTo(port); } @Test public void get_returns_host_from_property_if_set_at_constructor_time() { String host = randomAlphanumeric(4); mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); mapSettings.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), 1 + random.nextInt(4)); mapSettings.setProperty(CLUSTER_NODE_HOST.getKey(), host); setStartedAt(); when(healthChecker.checkNode()).thenReturn(Health.builder() .setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]) .build()); NodeHealthProviderImpl underTest = new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host); // change values in properties mapSettings.setProperty(CLUSTER_NODE_HOST.getKey(), randomAlphanumeric(66)); NodeHealth newNodeHealth = underTest.get(); assertThat(newNodeHealth.getDetails().getHost()).isEqualTo(host); } @Test public void get_returns_hostname_from_NetworkUtils_if_property_is_not_set_at_constructor_time() { getReturnsHostnameFromNetworkUtils(null); } @Test public void get_returns_hostname_from_NetworkUtils_if_property_is_empty_at_constructor_time() { getReturnsHostnameFromNetworkUtils(random.nextBoolean() ? "" : " "); } private void getReturnsHostnameFromNetworkUtils(String hostPropertyValue) { String host = randomAlphanumeric(3); setRequiredPropertiesForConstructor(); if (hostPropertyValue != null) { mapSettings.setProperty(CLUSTER_NODE_HOST.getKey(), hostPropertyValue); } setStartedAt(); when(healthChecker.checkNode()).thenReturn(Health.builder() .setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]) .build()); when(networkUtils.getHostname()).thenReturn(host); NodeHealthProviderImpl underTest = new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getDetails().getHost()).isEqualTo(host); // change hostname when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(4)); NodeHealth newNodeHealth = underTest.get(); assertThat(newNodeHealth.getDetails().getHost()).isEqualTo(host); } @Test public void get_returns_started_from_server_startedAt_at_constructor_time() { setRequiredPropertiesForConstructor(); when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(4)); Date date = new Date(); when(server.getStartedAt()).thenReturn(date); when(healthChecker.checkNode()).thenReturn(Health.builder() .setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]) .build()); NodeHealthProviderImpl underTest = new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils); NodeHealth nodeHealth = underTest.get(); assertThat(nodeHealth.getDetails().getStartedAt()).isEqualTo(date.getTime()); // change startedAt value setStartedAt(); NodeHealth newNodeHealth = underTest.get(); assertThat(newNodeHealth.getDetails().getStartedAt()).isEqualTo(date.getTime()); } private void setStartedAt() { when(server.getStartedAt()).thenReturn(new Date()); } private void setRequiredPropertiesForConstructor() { mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); mapSettings.setProperty(CLUSTER_NODE_HZ_PORT.getKey(), 1 + random.nextInt(4)); } }
9,951
41.169492
127
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/WebServerSafemodeNodeCheckTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class WebServerSafemodeNodeCheckTest { private WebServerSafemodeNodeCheck underTest = new WebServerSafemodeNodeCheck(); @Test public void always_returns_RED_status_with_cause() { Health health = underTest.check(); assertThat(health.getStatus()).isEqualTo(Health.Status.RED); assertThat(health.getCauses()).containsOnly("SonarQube webserver is not up"); } }
1,347
34.473684
82
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/WebServerStatusNodeCheckTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; import java.util.Arrays; import java.util.Random; import org.junit.Test; import org.sonar.server.app.RestartFlagHolder; import org.sonar.server.platform.Platform; import org.sonar.server.platform.db.migration.DatabaseMigrationState; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class WebServerStatusNodeCheckTest { private final DatabaseMigrationState migrationState = mock(DatabaseMigrationState.class); private final Platform platform = mock(Platform.class); private final RestartFlagHolder restartFlagHolder = mock(RestartFlagHolder.class); private final Random random = new Random(); private WebServerStatusNodeCheck underTest = new WebServerStatusNodeCheck(migrationState, platform, restartFlagHolder); @Test public void returns_RED_status_with_cause_if_platform_status_is_not_UP() { Platform.Status[] statusesButUp = Arrays.stream(Platform.Status.values()) .filter(s -> s != Platform.Status.UP) .toArray(Platform.Status[]::new); Platform.Status randomStatusButUp = statusesButUp[random.nextInt(statusesButUp.length)]; when(platform.status()).thenReturn(randomStatusButUp); Health health = underTest.check(); verifyRedHealthWithCause(health); } @Test public void returns_RED_status_with_cause_if_platform_status_is_UP_but_migrationStatus_is_neither_NONE_nor_SUCCEED() { when(platform.status()).thenReturn(Platform.Status.UP); DatabaseMigrationState.Status[] statusesButValidOnes = Arrays.stream(DatabaseMigrationState.Status.values()) .filter(s -> s != DatabaseMigrationState.Status.NONE) .filter(s -> s != DatabaseMigrationState.Status.SUCCEEDED) .toArray(DatabaseMigrationState.Status[]::new); DatabaseMigrationState.Status randomInvalidStatus = statusesButValidOnes[random.nextInt(statusesButValidOnes.length)]; when(migrationState.getStatus()).thenReturn(randomInvalidStatus); Health health = underTest.check(); verifyRedHealthWithCause(health); } @Test public void returns_RED_with_cause_if_platform_status_is_UP_migration_status_is_valid_but_SQ_is_restarting() { when(platform.status()).thenReturn(Platform.Status.UP); when(migrationState.getStatus()).thenReturn(random.nextBoolean() ? DatabaseMigrationState.Status.NONE : DatabaseMigrationState.Status.SUCCEEDED); when(restartFlagHolder.isRestarting()).thenReturn(true); Health health = underTest.check(); verifyRedHealthWithCause(health); } @Test public void returns_GREEN_without_cause_if_platform_status_is_UP_migration_status_is_valid_and_SQ_is_not_restarting() { when(platform.status()).thenReturn(Platform.Status.UP); when(migrationState.getStatus()).thenReturn(random.nextBoolean() ? DatabaseMigrationState.Status.NONE : DatabaseMigrationState.Status.SUCCEEDED); when(restartFlagHolder.isRestarting()).thenReturn(false); Health health = underTest.check(); assertThat(health).isEqualTo(Health.GREEN); } private void verifyRedHealthWithCause(Health health) { assertThat(health.getStatus()).isEqualTo(Health.Status.RED); assertThat(health.getCauses()).containsOnly("SonarQube webserver is not up"); } }
4,123
41.515464
149
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/HotspotsWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.hotspot.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class HotspotsWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new HotspotsWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(12); } }
1,268
35.257143
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/HotspotsWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.hotspot.ws; import java.util.Arrays; import java.util.Random; import java.util.stream.IntStream; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; public class HotspotsWsTest { @Test public void define_controller() { String[] actionKeys = IntStream.range(0, 1 + new Random().nextInt(12)) .mapToObj(i -> i + randomAlphanumeric(10)) .toArray(String[]::new); HotspotsWsAction[] actions = Arrays.stream(actionKeys) .map(actionKey -> new HotspotsWsAction() { @Override public void define(WebService.NewController context) { context.createAction(actionKey).setHandler(this); } @Override public void handle(Request request, Response response) { } }) .toArray(HotspotsWsAction[]::new); WebService.Context context = new WebService.Context(); new HotspotsWs(actions).define(context); WebService.Controller controller = context.controller("api/hotspots"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.since()).isEqualTo("8.1"); assertThat(controller.actions()).extracting(WebService.Action::key).containsOnly(actionKeys); } }
2,316
35.203125
97
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/hotspot/ws/PullHotspotsActionProtobufObjectGeneratorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.hotspot.ws; import java.util.Date; import java.util.Set; import org.junit.Test; import org.sonar.db.issue.IssueDto; import org.sonar.db.protobuf.DbCommons; import org.sonar.db.protobuf.DbIssues; import org.sonar.db.rule.RuleDto; import org.sonarqube.ws.Hotspots.HotspotLite; import org.sonarqube.ws.Hotspots.HotspotPullQueryTimestamp; import static org.assertj.core.api.Assertions.assertThat; public class PullHotspotsActionProtobufObjectGeneratorTest { private final PullHotspotsActionProtobufObjectGenerator underTest = new PullHotspotsActionProtobufObjectGenerator(); @Test public void generateTimestampMessage_shouldMapTimestamp() { long timestamp = System.currentTimeMillis(); HotspotPullQueryTimestamp result = underTest.generateTimestampMessage(timestamp); assertThat(result.getQueryTimestamp()).isEqualTo(timestamp); } @Test public void generateIssueMessage_shouldMapDtoFields() { IssueDto issueDto = new IssueDto() .setKee("key") .setFilePath("/home/src/Class.java") .setProjectKey("my-project-key") .setStatus("REVIEWED") .setResolution("FIXED") .setRuleKey("repo", "rule") .setRuleUuid("rule-uuid-1") .setMessage("Look at me, I'm the issue now!") .setAssigneeLogin("assignee-login") .setIssueCreationDate(new Date()); DbIssues.Locations locations = DbIssues.Locations.newBuilder() .setTextRange(range(2, 3)) .build(); issueDto.setLocations(locations); RuleDto ruleDto = new RuleDto() .setSecurityStandards(Set.of("cwe:489,cwe:570,cwe:571")); HotspotLite result = underTest.generateIssueMessage(issueDto, ruleDto); assertThat(result).extracting( HotspotLite::getKey, HotspotLite::getFilePath, HotspotLite::getVulnerabilityProbability, HotspotLite::getStatus, HotspotLite::getResolution, HotspotLite::getRuleKey, HotspotLite::getAssignee) .containsExactly("key", "/home/src/Class.java", "LOW", "REVIEWED", "FIXED", "repo:rule", "assignee-login"); } @Test public void generateClosedIssueMessage_shouldMapClosedHotspotFields() { HotspotLite result = underTest.generateClosedIssueMessage("uuid"); assertThat(result).extracting(HotspotLite::getKey, HotspotLite::getClosed) .containsExactly("uuid", true); } private static org.sonar.db.protobuf.DbCommons.TextRange range(int startLine, int endLine) { return DbCommons.TextRange.newBuilder().setStartLine(startLine).setEndLine(endLine).build(); } }
3,386
36.21978
118
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import java.util.Collection; import java.util.Map; import org.junit.Test; import org.sonar.core.issue.DefaultIssue; import org.sonar.server.user.UserSession; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ActionTest { @Test public void key_should_not_be_empty() { assertThatThrownBy(() -> new FakeAction("")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Action key must be set"); } @Test public void key_should_not_be_null() { assertThatThrownBy(() -> new FakeAction(null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Action key must be set"); } private static class FakeAction extends Action { FakeAction(String key) { super(key); } @Override public boolean verify(Map<String, Object> properties, Collection<DefaultIssue> issues, UserSession userSession) { return false; } @Override public boolean execute(Map<String, Object> properties, Context context) { return false; } @Override public boolean shouldRefreshMeasures() { return false; } } }
2,008
28.115942
117
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AddTagsActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import com.google.common.collect.ImmutableSet; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.mockito.Mockito; import org.sonar.core.issue.DefaultIssue; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class AddTagsActionTest { private IssueFieldsSetter issueUpdater = new IssueFieldsSetter(); private AddTagsAction underTest = new AddTagsAction(issueUpdater); @Test public void should_execute() { Map<String, Object> properties = new HashMap<>(); properties.put("tags", "tag2,tag3"); DefaultIssue issue = mock(DefaultIssue.class); when(issue.tags()).thenReturn(ImmutableSet.of("tag1", "tag3")); Action.Context context = mock(Action.Context.class, Mockito.RETURNS_DEEP_STUBS); when(context.issue()).thenReturn(issue); underTest.execute(properties, context); verify(issue).setTags(ImmutableSet.of("tag1", "tag2", "tag3")); } @Test public void should_fail_if_tag_is_not_valid() { assertThatThrownBy(() -> { Map<String, Object> properties = new HashMap<>(); properties.put("tags", "th ag"); DefaultIssue issue = mock(DefaultIssue.class); when(issue.tags()).thenReturn(ImmutableSet.of("tag1", "tag3")); Action.Context context = mock(Action.Context.class); when(context.issue()).thenReturn(issue); underTest.execute(properties, context); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Entry 'th ag' is invalid. For Rule tags the entry has to match the regexp ^[a-z0-9\\+#\\-\\.]+$"); } }
2,577
34.315068
117
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AvatarResolverImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.user.UserTesting.newUserDto; public class AvatarResolverImplTest { private AvatarResolverImpl underTest = new AvatarResolverImpl(); @Test public void create() { String avatar = underTest.create(newUserDto("john", "John", "john@doo.com")); assertThat(avatar).isEqualTo("9297bfb538f650da6143b604e82a355d"); } @Test public void create_is_case_insensitive() { assertThat(underTest.create(newUserDto("john", "John", "john@doo.com"))).isEqualTo(underTest.create(newUserDto("john", "John", "John@Doo.com"))); } @Test public void fail_with_NP_when_user_is_null() { assertThatThrownBy(() -> underTest.create(null)) .isInstanceOf(NullPointerException.class) .hasMessage("User cannot be null"); } @Test public void fail_with_NP_when_email_is_null() { assertThatThrownBy(() -> underTest.create(newUserDto("john", "John", null))) .isInstanceOf(NullPointerException.class) .hasMessage("Email cannot be null"); } @Test public void fail_when_email_is_empty() { assertThatThrownBy(() -> underTest.create(newUserDto("john", "John", ""))) .isInstanceOf(NullPointerException.class) .hasMessage("Email cannot be null"); } }
2,255
33.181818
149
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/CommentActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.sonar.api.issue.Issue; import org.sonar.core.issue.DefaultIssue; import org.sonar.server.tester.AnonymousMockUserSession; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class CommentActionTest { private CommentAction action; private IssueFieldsSetter issueUpdater = mock(IssueFieldsSetter.class); @Before public void before() { action = new CommentAction(issueUpdater); } @Test public void should_execute() { String comment = "My bulk change comment"; Map<String, Object> properties = new HashMap<>(); properties.put("comment", comment); DefaultIssue issue = mock(DefaultIssue.class); Action.Context context = mock(Action.Context.class); when(context.issue()).thenReturn(issue); action.execute(properties, context); verify(issueUpdater).addComment(eq(issue), eq(comment), any()); } @Test public void should_verify_fail_if_parameter_not_found() { Map<String, Object> properties = singletonMap("unknwown", "unknown value"); try { action.verify(properties, new ArrayList<>(), new AnonymousMockUserSession()); fail(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("Missing parameter : 'comment'"); } verifyNoInteractions(issueUpdater); } @Test public void should_support_all_issues() { assertThat(action.supports(new DefaultIssue().setResolution(null))).isTrue(); assertThat(action.supports(new DefaultIssue().setResolution(Issue.RESOLUTION_FIXED))).isTrue(); } }
2,918
33.341176
109
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/FakeAvatarResolver.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import org.sonar.db.user.UserDto; public class FakeAvatarResolver implements AvatarResolver { @Override public String create(UserDto user) { return user.getEmail() + "_avatar"; } }
1,070
32.46875
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/IssuesFinderSortTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import java.util.Date; import java.util.List; import org.apache.commons.lang.time.DateUtils; import org.junit.Test; import org.sonar.db.issue.IssueDto; import org.sonar.server.issue.index.IssueQuery; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class IssuesFinderSortTest { @Test public void should_sort_by_status() { IssueDto issue1 = new IssueDto().setKee("A").setStatus("CLOSED"); IssueDto issue2 = new IssueDto().setKee("B").setStatus("REOPENED"); IssueDto issue3 = new IssueDto().setKee("C").setStatus("OPEN"); List<IssueDto> dtoList = newArrayList(issue1, issue2, issue3); IssueQuery query = IssueQuery.builder().sort(IssueQuery.SORT_BY_STATUS).asc(false).build(); IssuesFinderSort issuesFinderSort = new IssuesFinderSort(dtoList, query); List<IssueDto> result = newArrayList(issuesFinderSort.sort()); assertThat(result).hasSize(3); assertThat(result.get(0).getStatus()).isEqualTo("REOPENED"); assertThat(result.get(1).getStatus()).isEqualTo("OPEN"); assertThat(result.get(2).getStatus()).isEqualTo("CLOSED"); } @Test public void should_sort_by_severity() { IssueDto issue1 = new IssueDto().setKee("A").setSeverity("INFO"); IssueDto issue2 = new IssueDto().setKee("B").setSeverity("BLOCKER"); IssueDto issue3 = new IssueDto().setKee("C").setSeverity("MAJOR"); List<IssueDto> dtoList = newArrayList(issue1, issue2, issue3); IssueQuery query = IssueQuery.builder().sort(IssueQuery.SORT_BY_SEVERITY).asc(true).build(); IssuesFinderSort issuesFinderSort = new IssuesFinderSort(dtoList, query); List<IssueDto> result = newArrayList(issuesFinderSort.sort()); assertThat(result).hasSize(3); assertThat(result.get(0).getSeverity()).isEqualTo("INFO"); assertThat(result.get(1).getSeverity()).isEqualTo("MAJOR"); assertThat(result.get(2).getSeverity()).isEqualTo("BLOCKER"); } @Test public void should_sort_by_desc_severity() { IssueDto issue1 = new IssueDto().setKee("A").setSeverity("INFO"); IssueDto issue2 = new IssueDto().setKee("B").setSeverity("BLOCKER"); IssueDto issue3 = new IssueDto().setKee("C").setSeverity("MAJOR"); List<IssueDto> dtoList = newArrayList(issue1, issue2, issue3); IssueQuery query = IssueQuery.builder().sort(IssueQuery.SORT_BY_SEVERITY).asc(false).build(); IssuesFinderSort issuesFinderSort = new IssuesFinderSort(dtoList, query); List<IssueDto> result = newArrayList(issuesFinderSort.sort()); assertThat(result).hasSize(3); assertThat(result.get(0).getSeverity()).isEqualTo("BLOCKER"); assertThat(result.get(1).getSeverity()).isEqualTo("MAJOR"); assertThat(result.get(2).getSeverity()).isEqualTo("INFO"); } @Test public void should_sort_by_creation_date() { Date date = new Date(); Date date1 = DateUtils.addDays(date, -3); Date date2 = DateUtils.addDays(date, -2); Date date3 = DateUtils.addDays(date, -1); IssueDto issue1 = new IssueDto().setKee("A").setIssueCreationDate(date1); IssueDto issue2 = new IssueDto().setKee("B").setIssueCreationDate(date3); IssueDto issue3 = new IssueDto().setKee("C").setIssueCreationDate(date2); List<IssueDto> dtoList = newArrayList(issue1, issue2, issue3); IssueQuery query = IssueQuery.builder().sort(IssueQuery.SORT_BY_CREATION_DATE).asc(false).build(); IssuesFinderSort issuesFinderSort = new IssuesFinderSort(dtoList, query); List<IssueDto> result = newArrayList(issuesFinderSort.sort()); assertThat(result).hasSize(3); assertThat(result.get(0).getIssueCreationDate()).isEqualTo(date3); assertThat(result.get(1).getIssueCreationDate()).isEqualTo(date2); assertThat(result.get(2).getIssueCreationDate()).isEqualTo(date1); } @Test public void should_sort_by_update_date() { Date date = new Date(); Date date1 = DateUtils.addDays(date, -3); Date date2 = DateUtils.addDays(date, -2); Date date3 = DateUtils.addDays(date, -1); IssueDto issue1 = new IssueDto().setKee("A").setIssueUpdateDate(date1); IssueDto issue2 = new IssueDto().setKee("B").setIssueUpdateDate(date3); IssueDto issue3 = new IssueDto().setKee("C").setIssueUpdateDate(date2); List<IssueDto> dtoList = newArrayList(issue1, issue2, issue3); IssueQuery query = IssueQuery.builder().sort(IssueQuery.SORT_BY_UPDATE_DATE).asc(false).build(); IssuesFinderSort issuesFinderSort = new IssuesFinderSort(dtoList, query); List<IssueDto> result = newArrayList(issuesFinderSort.sort()); assertThat(result).hasSize(3); assertThat(result.get(0).getIssueUpdateDate()).isEqualTo(date3); assertThat(result.get(1).getIssueUpdateDate()).isEqualTo(date2); assertThat(result.get(2).getIssueUpdateDate()).isEqualTo(date1); } @Test public void should_sort_by_close_date() { Date date = new Date(); Date date1 = DateUtils.addDays(date, -3); Date date2 = DateUtils.addDays(date, -2); Date date3 = DateUtils.addDays(date, -1); IssueDto issue1 = new IssueDto().setKee("A").setIssueCloseDate(date1); IssueDto issue2 = new IssueDto().setKee("B").setIssueCloseDate(date3); IssueDto issue3 = new IssueDto().setKee("C").setIssueCloseDate(date2); List<IssueDto> dtoList = newArrayList(issue1, issue2, issue3); IssueQuery query = IssueQuery.builder().sort(IssueQuery.SORT_BY_CLOSE_DATE).asc(false).build(); IssuesFinderSort issuesFinderSort = new IssuesFinderSort(dtoList, query); List<IssueDto> result = newArrayList(issuesFinderSort.sort()); assertThat(result).hasSize(3); assertThat(result.get(0).getIssueCloseDate()).isEqualTo(date3); assertThat(result.get(1).getIssueCloseDate()).isEqualTo(date2); assertThat(result.get(2).getIssueCloseDate()).isEqualTo(date1); } @Test public void should_not_sort_with_null_sort() { IssueDto issue1 = new IssueDto().setKee("A").setAssigneeUuid("perceval"); IssueDto issue2 = new IssueDto().setKee("B").setAssigneeUuid("arthur"); IssueDto issue3 = new IssueDto().setKee("C").setAssigneeUuid("vincent"); IssueDto issue4 = new IssueDto().setKee("D").setAssigneeUuid(null); List<IssueDto> dtoList = newArrayList(issue1, issue2, issue3, issue4); IssueQuery query = IssueQuery.builder().sort(null).build(); IssuesFinderSort issuesFinderSort = new IssuesFinderSort(dtoList, query); List<IssueDto> result = newArrayList(issuesFinderSort.sort()); assertThat(result).hasSize(4); assertThat(result.get(0).getAssigneeUuid()).isEqualTo("perceval"); assertThat(result.get(1).getAssigneeUuid()).isEqualTo("arthur"); assertThat(result.get(2).getAssigneeUuid()).isEqualTo("vincent"); assertThat(result.get(3).getAssigneeUuid()).isNull(); } @Test public void should_fail_to_sort_with_unknown_sort() { IssueQuery query = mock(IssueQuery.class); when(query.sort()).thenReturn("unknown"); IssuesFinderSort issuesFinderSort = new IssuesFinderSort(null, query); try { issuesFinderSort.sort(); } catch (Exception e) { assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("Cannot sort on field : unknown"); } } }
8,153
42.142857
110
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/RemoveTagsActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import com.google.common.collect.ImmutableSet; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.mockito.Mockito; import org.sonar.core.issue.DefaultIssue; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class RemoveTagsActionTest { private IssueFieldsSetter issueUpdater = new IssueFieldsSetter(); private RemoveTagsAction action = new RemoveTagsAction(issueUpdater); @Test public void should_execute() { Map<String, Object> properties = new HashMap<>(); properties.put("tags", "tag2,tag3"); DefaultIssue issue = mock(DefaultIssue.class); when(issue.tags()).thenReturn(ImmutableSet.of("tag1", "tag3")); Action.Context context = mock(Action.Context.class, Mockito.RETURNS_DEEP_STUBS); when(context.issue()).thenReturn(issue); action.execute(properties, context); verify(issue).setTags(ImmutableSet.of("tag1")); } @Test public void should_fail_if_tag_is_not_valid() { assertThatThrownBy(() -> { Map<String, Object> properties = new HashMap<>(); properties.put("tags", "th ag"); DefaultIssue issue = mock(DefaultIssue.class); when(issue.tags()).thenReturn(ImmutableSet.of("tag1", "tag3")); Action.Context context = mock(Action.Context.class); when(context.issue()).thenReturn(issue); action.execute(properties, context); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Entry 'th ag' is invalid. For Rule tags the entry has to match the regexp ^[a-z0-9\\+#\\-\\.]+$"); } }
2,561
34.09589
117
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ResultTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ResultTest { @Test public void test_default_result() { Result<Object> result = Result.of(); assertThat(result.ok()).isTrue(); assertThat(result.errors()).isEmpty(); assertThat(result.httpStatus()).isEqualTo(200); assertThat(result.get()).isNull(); Object obj = new Object(); result.set(obj); assertThat(result.get()).isSameAs(obj); } @Test public void test_error() { Result<Object> result = Result.of(); result.addError("Something goes wrong"); assertThat(result.ok()).isFalse(); assertThat(result.errors()).hasSize(1).contains(Result.Message.of("Something goes wrong")); assertThat(result.httpStatus()).isEqualTo(400); assertThat(result.get()).isNull(); } @Test public void test_l10n_errors() { Result<Object> result = Result.of(); Result.Message message = Result.Message.ofL10n("issue.error.123", "10"); result.addError(message); assertThat(result.ok()).isFalse(); assertThat(result.errors()).hasSize(1).containsOnly(message); message = result.errors().get(0); assertThat(message.text()).isNull(); assertThat(message.l10nKey()).isEqualTo("issue.error.123"); assertThat(message.l10nParams()).hasSize(1); assertThat(message.l10nParams()[0]).isEqualTo("10"); } @Test public void test_toString() { String errorMessage = "the error"; Result.Message txtMsg = Result.Message.of(errorMessage); assertThat(txtMsg.toString()).contains(errorMessage); assertThat(txtMsg.toString()).isNotEqualTo(errorMessage); Result.Message msg = Result.Message.ofL10n("issue.error.123", "10"); assertThat(msg.toString()).contains("issue.error.123").contains("10"); assertThat(msg.toString()).isNotEqualTo("issue.error.123"); } @Test public void test_equals_and_hashCode() { String errorMessage = "the error"; Result.Message txtMsg = Result.Message.of(errorMessage); Result.Message sameTxtMsg = Result.Message.of(errorMessage); Result.Message otherTxtMessage = Result.Message.of("other"); assertThat(txtMsg) .isEqualTo(txtMsg) .isEqualTo(sameTxtMsg) .isNotEqualTo(otherTxtMessage); Result.Message msg = Result.Message.ofL10n("issue.error.123", "10"); Result.Message sameMsg = Result.Message.ofL10n("issue.error.123", "10"); Result.Message otherMsg1 = Result.Message.ofL10n("issue.error.123", "200"); Result.Message otherMsg2 = Result.Message.ofL10n("issue.error.50"); assertThat(msg) .isEqualTo(msg) .isEqualTo(sameMsg) .isNotEqualTo(otherMsg1) .isNotEqualTo(otherMsg2) .hasSameHashCodeAs(msg) .hasSameHashCodeAs(sameMsg); assertThat(msg.hashCode()).isNotEqualTo(otherMsg1.hashCode()); } }
3,701
33.598131
95
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/RulesAggregation.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import java.util.Collection; import org.sonar.api.rule.RuleKey; import org.sonar.db.rule.RuleDto; public class RulesAggregation { private Multiset<Rule> rules; public RulesAggregation() { this.rules = HashMultiset.create(); } public RulesAggregation add(RuleDto ruleDto) { rules.add(new Rule(ruleDto.getKey(), ruleDto.getName())); return this; } public Collection<Rule> rules() { return rules.elementSet(); } public int countRule(Rule rule) { return rules.count(rule); } public static class Rule { private RuleKey ruleKey; private String name; public Rule(RuleKey ruleKey, String name) { this.ruleKey = ruleKey; this.name = name; } public RuleKey ruleKey() { return ruleKey; } public String name() { return name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Rule rule = (Rule) o; return ruleKey.equals(rule.ruleKey); } @Override public int hashCode() { return ruleKey.hashCode(); } } }
2,143
23.643678
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/RulesAggregationTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleTesting; import static org.assertj.core.api.Assertions.assertThat; public class RulesAggregationTest { @Test public void empty() { RulesAggregation rulesAggregation = new RulesAggregation(); assertThat(rulesAggregation.rules()).isEmpty(); } @Test public void count_rules() { RulesAggregation rulesAggregation = new RulesAggregation(); RuleKey ruleKey = RuleKey.of("xoo", "S001"); RuleDto ruleDto = RuleTesting.newRule(ruleKey).setName("Rule name"); rulesAggregation.add(ruleDto); rulesAggregation.add(ruleDto); RulesAggregation.Rule rule = new RulesAggregation.Rule(ruleKey, "Rule name"); assertThat(rulesAggregation.rules()).hasSize(1); assertThat(rulesAggregation.rules().iterator().next().name()).isEqualTo("Rule name"); assertThat(rulesAggregation.countRule(rule)).isEqualTo(2); } @Test public void count_rules_with_different_rules() { RulesAggregation rulesAggregation = new RulesAggregation(); RuleDto ruleDto = RuleTesting.newRule(RuleKey.of("xoo", "S001")).setName("Rule name 1"); rulesAggregation.add(ruleDto); rulesAggregation.add(ruleDto); rulesAggregation.add(RuleTesting.newRule(RuleKey.of("xoo", "S002")).setName("Rule name 2")); assertThat(rulesAggregation.rules()).hasSize(2); } @Test public void test_equals_and_hash_code() { RulesAggregation.Rule rule = new RulesAggregation.Rule(RuleKey.of("xoo", "S001"), "S001"); RulesAggregation.Rule ruleSameRuleKey = new RulesAggregation.Rule(RuleKey.of("xoo", "S001"), "S001"); RulesAggregation.Rule ruleWithDifferentRuleKey = new RulesAggregation.Rule(RuleKey.of("xoo", "S002"), "S002"); assertThat(rule) .isEqualTo(rule) .isEqualTo(ruleSameRuleKey) .isNotEqualTo(ruleWithDifferentRuleKey) .hasSameHashCodeAs(rule) .hasSameHashCodeAs(ruleSameRuleKey); assertThat(rule.hashCode()).isNotEqualTo(ruleWithDifferentRuleKey.hashCode()); } }
2,944
36.278481
114
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/TestIssueChangePostProcessor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; public class TestIssueChangePostProcessor implements IssueChangePostProcessor { private boolean called = false; private final List<ComponentDto> calledComponents = new ArrayList<>(); @Override public void process(DbSession dbSession, List<DefaultIssue> changedIssues, Collection<ComponentDto> components, boolean fromAlm) { called = true; calledComponents.addAll(components); } public boolean wasCalled() { return called; } public List<ComponentDto> calledComponents() { return calledComponents; } }
1,612
32.604167
132
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/ComponentTagsActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.ws; import com.google.common.collect.ImmutableMap; import java.util.Arrays; import java.util.Map; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import org.sonar.api.rules.RuleType; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.server.ws.WebService.Param; import org.sonar.db.DbClient; import org.sonar.db.component.ComponentDao; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.server.issue.SearchRequest; import org.sonar.server.issue.index.IssueIndex; import org.sonar.server.issue.index.IssueIndexSyncProgressChecker; import org.sonar.server.issue.index.IssueQuery; import org.sonar.server.issue.index.IssueQueryFactory; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT; import static org.sonar.test.JsonAssert.assertJson; public class ComponentTagsActionTest { private static final String[] ISSUE_RULE_TYPES = Arrays.stream(RuleType.values()) .filter(t -> t != SECURITY_HOTSPOT) .map(Enum::name) .toArray(String[]::new); private final IssueIndex service = mock(IssueIndex.class); private final IssueQueryFactory issueQueryFactory = mock(IssueQueryFactory.class, Mockito.RETURNS_DEEP_STUBS); private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = mock(IssueIndexSyncProgressChecker.class); private final DbClient dbClient = mock(DbClient.class); private final ComponentDao componentDao = mock(ComponentDao.class); private final ComponentTagsAction underTest = new ComponentTagsAction(service, issueIndexSyncProgressChecker, issueQueryFactory, dbClient); private final WsActionTester tester = new WsActionTester(underTest); @Before public void before() { when(dbClient.componentDao()).thenReturn(componentDao); when(componentDao.selectByUuid(any(), any())).thenAnswer((Answer<Optional<ComponentDto>>) invocation -> { Object[] args = invocation.getArguments(); return Optional.of(ComponentTesting.newPrivateProjectDto((String) args[1])); }); when(componentDao.selectByUuid(any(), eq("not-exists"))) .thenAnswer((Answer<Optional<ComponentDto>>) invocation -> Optional.empty()); } @Test public void should_define() { Action action = tester.getDef(); assertThat(action.description()).isNotEmpty(); assertThat(action.responseExampleAsString()).isNotEmpty(); assertThat(action.isPost()).isFalse(); assertThat(action.isInternal()).isTrue(); assertThat(action.handler()).isEqualTo(underTest); assertThat(action.params()).hasSize(3); Param query = action.param("componentUuid"); assertThat(query.isRequired()).isTrue(); assertThat(query.description()).isNotEmpty(); assertThat(query.exampleValue()).isNotEmpty(); Param createdAfter = action.param("createdAfter"); assertThat(createdAfter.isRequired()).isFalse(); assertThat(createdAfter.description()).isNotEmpty(); assertThat(createdAfter.exampleValue()).isNotEmpty(); Param pageSize = action.param("ps"); assertThat(pageSize.isRequired()).isFalse(); assertThat(pageSize.defaultValue()).isEqualTo("10"); assertThat(pageSize.description()).isNotEmpty(); assertThat(pageSize.exampleValue()).isNotEmpty(); } @Test public void should_return_empty_list() { TestResponse response = tester.newRequest() .setParam("componentUuid", "not-exists") .execute(); assertJson(response.getInput()).isSimilarTo("{\"tags\":[]}"); verify(issueIndexSyncProgressChecker).checkIfIssueSyncInProgress(any()); } @Test public void should_return_tag_list() { Map<String, Long> tags = ImmutableMap.<String, Long>builder() .put("convention", 2771L) .put("brain-overload", 998L) .put("cwe", 89L) .put("bug", 32L) .put("cert", 2L) .build(); ArgumentCaptor<SearchRequest> captor = ArgumentCaptor.forClass(SearchRequest.class); when(issueQueryFactory.create(captor.capture())).thenReturn(mock(IssueQuery.class)); when(service.countTags(any(IssueQuery.class), eq(5))).thenReturn(tags); TestResponse response = tester.newRequest() .setParam("componentUuid", "polop") .setParam("ps", "5") .execute(); assertJson(response.getInput()).isSimilarTo(getClass().getResource("ComponentTagsActionTest/component-tags.json")); assertThat(captor.getValue().getTypes()).containsExactlyInAnyOrder(ISSUE_RULE_TYPES); assertThat(captor.getValue().getComponentUuids()).containsOnly("polop"); assertThat(captor.getValue().getResolved()).isFalse(); assertThat(captor.getValue().getCreatedAfter()).isNull(); verify(issueIndexSyncProgressChecker).checkIfComponentNeedIssueSync(any(), eq("KEY_polop")); } @Test public void should_return_tag_list_with_created_after() { Map<String, Long> tags = ImmutableMap.<String, Long>builder() .put("convention", 2771L) .put("brain-overload", 998L) .put("cwe", 89L) .put("bug", 32L) .put("cert", 2L) .build(); ArgumentCaptor<SearchRequest> captor = ArgumentCaptor.forClass(SearchRequest.class); when(issueQueryFactory.create(captor.capture())).thenReturn(mock(IssueQuery.class)); when(service.countTags(any(IssueQuery.class), eq(5))).thenReturn(tags); String componentUuid = "polop"; String createdAfter = "2011-04-25"; TestResponse response = tester.newRequest() .setParam("componentUuid", componentUuid) .setParam("createdAfter", createdAfter) .setParam("ps", "5") .execute(); assertJson(response.getInput()).isSimilarTo(getClass().getResource("ComponentTagsActionTest/component-tags.json")); assertThat(captor.getValue().getTypes()).containsExactlyInAnyOrder(ISSUE_RULE_TYPES); assertThat(captor.getValue().getComponentUuids()).containsOnly(componentUuid); assertThat(captor.getValue().getResolved()).isFalse(); assertThat(captor.getValue().getCreatedAfter()).isEqualTo(createdAfter); verify(issueIndexSyncProgressChecker).checkIfComponentNeedIssueSync(any(), eq("KEY_polop")); } }
7,410
42.594118
120
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/IssueWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class IssueWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new IssueWsModule().configure(container); assertThat(container.getAddedObjects()).isNotEmpty(); } }
1,262
34.083333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchResponseFormatFormatOperationTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.ws; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import org.sonar.api.resources.Languages; import org.sonar.api.utils.Duration; import org.sonar.api.utils.Durations; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.issue.IssueChangeDto; import org.sonar.db.issue.IssueDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.user.UserDto; import org.sonar.server.issue.TextRangeResponseFormatter; import org.sonar.server.issue.workflow.Transition; import org.sonarqube.ws.Common; import org.sonarqube.ws.Issues.Issue; import org.sonarqube.ws.Issues.Operation; import static java.lang.System.currentTimeMillis; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.resources.Qualifiers.UNIT_TEST_FILE; import static org.sonar.api.rule.RuleKey.EXTERNAL_RULE_REPO_PREFIX; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; import static org.sonar.db.issue.IssueTesting.newIssue; import static org.sonar.db.issue.IssueTesting.newIssueChangeDto; import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.db.user.UserTesting.newUserDto; import static org.sonar.server.issue.index.IssueScope.MAIN; import static org.sonar.server.issue.index.IssueScope.TEST; @RunWith(MockitoJUnitRunner.class) public class SearchResponseFormatFormatOperationTest { @Rule public DbTester db = DbTester.create(); private final Durations durations = new Durations(); private final Languages languages = mock(Languages.class); private final TextRangeResponseFormatter textRangeResponseFormatter = mock(TextRangeResponseFormatter.class); private final UserResponseFormatter userResponseFormatter = mock(UserResponseFormatter.class); private final Common.User user = mock(Common.User.class); private final SearchResponseFormat searchResponseFormat = new SearchResponseFormat(durations, languages, textRangeResponseFormatter, userResponseFormatter); private SearchResponseData searchResponseData; private IssueDto issueDto; private ComponentDto componentDto; private UserDto userDto; @Before public void setUp() { searchResponseData = newSearchResponseDataMainBranch(); } @Test public void formatOperation_should_add_components_to_response() { Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getComponentsList()).hasSize(1); assertThat(result.getComponentsList().get(0).getKey()).isEqualTo(issueDto.getComponentKey()); } @Test public void formatOperation_should_add_rules_to_response() { Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getRulesList()).hasSize(1); assertThat(result.getRulesList().get(0).getKey()).isEqualTo(issueDto.getRuleKey().toString()); } @Test public void formatOperation_should_add_users_to_response() { Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getUsersList()).hasSize(1); assertThat(result.getUsers(0)).isSameAs(user); } @Test public void formatOperation_should_add_issue_to_response() { Operation result = searchResponseFormat.formatOperation(searchResponseData); assertIssueEqualsIssueDto(result.getIssue(), issueDto); } private void assertIssueEqualsIssueDto(Issue issue, IssueDto issueDto) { assertThat(issue.getKey()).isEqualTo(issueDto.getKey()); assertThat(issue.getType().getNumber()).isEqualTo(issueDto.getType()); assertThat(issue.getComponent()).isEqualTo(issueDto.getComponentKey()); assertThat(issue.getRule()).isEqualTo(issueDto.getRuleKey().toString()); assertThat(issue.getSeverity()).hasToString(issueDto.getSeverity()); assertThat(issue.getAssignee()).isEqualTo(userDto.getLogin()); assertThat(issue.getResolution()).isEqualTo(issueDto.getResolution()); assertThat(issue.getStatus()).isEqualTo(issueDto.getStatus()); assertThat(issue.getMessage()).isEqualTo(issueDto.getMessage()); assertThat(new ArrayList<>(issue.getTagsList())).containsExactlyInAnyOrderElementsOf(issueDto.getTags()); assertThat(issue.getLine()).isEqualTo(issueDto.getLine()); assertThat(issue.getHash()).isEqualTo(issueDto.getChecksum()); assertThat(issue.getAuthor()).isEqualTo(issueDto.getAuthorLogin()); assertThat(issue.getCreationDate()).isEqualTo(formatDateTime(issueDto.getIssueCreationDate())); assertThat(issue.getUpdateDate()).isEqualTo(formatDateTime(issueDto.getIssueUpdateDate())); assertThat(issue.getCloseDate()).isEqualTo(formatDateTime(issueDto.getIssueCloseDate())); assertThat(issue.getQuickFixAvailable()).isEqualTo(issueDto.isQuickFixAvailable()); assertThat(issue.getRuleDescriptionContextKey()).isEqualTo(issueDto.getOptionalRuleDescriptionContextKey().orElse(null)); assertThat(new ArrayList<>(issue.getCodeVariantsList())).containsExactlyInAnyOrderElementsOf(issueDto.getCodeVariants()); } @Test public void formatOperation_should_not_add_issue_when_several_issue() { searchResponseData = new SearchResponseData(List.of(createIssue(), createIssue())); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue()).isEqualTo(Issue.getDefaultInstance()); } private static IssueDto createIssue() { RuleDto ruleDto = newRule(); String projectUuid = "project_uuid_" + randomAlphanumeric(5); ComponentDto projectDto = newPrivateProjectDto(); projectDto.setBranchUuid(projectUuid); return newIssue(ruleDto, projectUuid, "project_key_" + randomAlphanumeric(5), projectDto); } @Test public void formatOperation_should_add_branch_on_issue() { String branchName = randomAlphanumeric(5); searchResponseData = newSearchResponseDataBranch(branchName); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue().getBranch()).isEqualTo(branchName); } @Test public void formatOperation_should_add_pullrequest_on_issue() { searchResponseData = newSearchResponseDataPr("pr1"); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue().getPullRequest()).isEqualTo("pr1"); } @Test public void formatOperation_should_add_project_on_issue() { issueDto.setProjectUuid(componentDto.uuid()); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue().getProject()).isEqualTo(componentDto.getKey()); } @Test public void formatOperation_should_add_external_rule_engine_on_issue() { issueDto.setExternal(true); String expected = randomAlphanumeric(5); issueDto.setRuleKey(EXTERNAL_RULE_REPO_PREFIX + expected, randomAlphanumeric(5)); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue().getExternalRuleEngine()).isEqualTo(expected); } @Test public void formatOperation_should_add_effort_and_debt_on_issue() { long effort = 60L; issueDto.setEffort(effort); String expected = durations.encode(Duration.create(effort)); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue().getEffort()).isEqualTo(expected); assertThat(result.getIssue().getDebt()).isEqualTo(expected); } @Test public void formatOperation_should_add_scope_test_on_issue_when_unit_test_file() { componentDto.setQualifier(UNIT_TEST_FILE); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue().getScope()).isEqualTo(TEST.name()); } @Test public void formatOperation_should_add_scope_main_on_issue_when_not_unit_test_file() { componentDto.setQualifier(randomAlphanumeric(5)); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue().getScope()).isEqualTo(MAIN.name()); } @Test public void formatOperation_should_add_actions_on_issues() { Set<String> expectedActions = Set.of("actionA", "actionB"); searchResponseData.addActions(issueDto.getKey(), expectedActions); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue().getActions().getActionsList()).containsExactlyInAnyOrderElementsOf(expectedActions); } @Test public void formatOperation_should_add_transitions_on_issues() { Set<String> expectedTransitions = Set.of("transitionone", "transitiontwo"); searchResponseData.addTransitions(issueDto.getKey(), createFakeTransitions(expectedTransitions)); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue().getTransitions().getTransitionsList()).containsExactlyInAnyOrderElementsOf(expectedTransitions); } private static List<Transition> createFakeTransitions(Collection<String> transitions) { return transitions.stream() .map(transition -> Transition.builder(transition).from("OPEN").to("RESOLVED").build()) .collect(toList()); } @Test public void formatOperation_should_add_comments_on_issues() { IssueChangeDto issueChangeDto = newIssueChangeDto(issueDto); searchResponseData.setComments(List.of(issueChangeDto)); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue().getComments().getCommentsList()).hasSize(1).extracting(Common.Comment::getKey).containsExactly(issueChangeDto.getKey()); } @Test public void formatOperation_should_not_set_severity_for_security_hotspot_issue() { issueDto.setType(SECURITY_HOTSPOT); Operation result = searchResponseFormat.formatOperation(searchResponseData); assertThat(result.getIssue().hasSeverity()).isFalse(); } private SearchResponseData newSearchResponseDataMainBranch() { ComponentDto projectDto = db.components().insertPublicProject().getMainBranchComponent(); BranchDto branchDto = db.getDbClient().branchDao().selectByUuid(db.getSession(), projectDto.uuid()).get(); return newSearchResponseData(projectDto, branchDto); } private SearchResponseData newSearchResponseDataBranch(String name) { ProjectDto projectDto = db.components().insertPublicProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(projectDto, b -> b.setKey(name)); ComponentDto branchComponent = db.components().getComponentDto(branch); return newSearchResponseData(branchComponent, branch); } private SearchResponseData newSearchResponseDataPr(String name) { ProjectDto projectDto = db.components().insertPublicProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(projectDto, b -> b.setKey(name).setBranchType(BranchType.PULL_REQUEST)); ComponentDto branchComponent = db.components().getComponentDto(branch); return newSearchResponseData(branchComponent, branch); } private SearchResponseData newSearchResponseData(ComponentDto component, BranchDto branch) { RuleDto ruleDto = newRule(); userDto = newUserDto(); componentDto = component; issueDto = newIssue(ruleDto, component.branchUuid(), component.getKey(), component) .setType(CODE_SMELL) .setRuleDescriptionContextKey("context_key_" + randomAlphanumeric(5)) .setAssigneeUuid(userDto.getUuid()) .setResolution("resolution_" + randomAlphanumeric(5)) .setIssueCreationDate(new Date(currentTimeMillis() - 2_000)) .setIssueUpdateDate(new Date(currentTimeMillis() - 1_000)) .setIssueCloseDate(new Date(currentTimeMillis())); SearchResponseData searchResponseData = new SearchResponseData(issueDto); searchResponseData.addComponents(List.of(component)); searchResponseData.addRules(List.of(ruleDto)); searchResponseData.addUsers(List.of(userDto)); searchResponseData.addBranches(List.of(branch)); when(userResponseFormatter.formatUser(any(Common.User.Builder.class), eq(userDto))).thenReturn(user); return searchResponseData; } }
13,787
42.632911
158
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/pull/PullActionIssuesRetrieverTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.ws.pull; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.db.DbClient; import org.sonar.db.issue.IssueDao; import org.sonar.db.issue.IssueDto; import org.sonar.db.issue.IssueQueryParams; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class PullActionIssuesRetrieverTest { private final DbClient dbClient = mock(DbClient.class); private final String branchUuid = "master-branch-uuid"; private final List<String> languages = List.of("java"); private final List<String> ruleRepositories = List.of("js-security", "java"); private final Long defaultChangedSince = 1_000_000L; private final IssueQueryParams queryParams = new IssueQueryParams(branchUuid, languages, ruleRepositories, null, false, defaultChangedSince); private final IssueDao issueDao = mock(IssueDao.class); @Before public void before() { when(dbClient.issueDao()).thenReturn(issueDao); } @Test public void processIssuesByBatch_givenNoIssuesReturnedByDatabase_noIssuesConsumed() { var pullActionIssuesRetriever = new PullActionIssuesRetriever(dbClient, queryParams); when(issueDao.selectByBranch(any(), any(), any())) .thenReturn(List.of()); List<IssueDto> returnedDtos = new ArrayList<>(); Consumer<List<IssueDto>> listConsumer = returnedDtos::addAll; pullActionIssuesRetriever.processIssuesByBatch(dbClient.openSession(true), Set.of(), listConsumer, issueDto -> true); assertThat(returnedDtos).isEmpty(); } @Test public void processIssuesByBatch_givenThousandOneIssuesReturnedByDatabase_thousandOneIssuesConsumed() { var pullActionIssuesRetriever = new PullActionIssuesRetriever(dbClient, queryParams); List<IssueDto> thousandIssues = IntStream.rangeClosed(1, 1000).mapToObj(i -> new IssueDto().setKee(Integer.toString(i))).toList(); IssueDto singleIssue = new IssueDto().setKee("kee"); when(issueDao.selectByBranch(any(), any(), any())) .thenReturn(thousandIssues) .thenReturn(List.of(singleIssue)); List<IssueDto> returnedDtos = new ArrayList<>(); Consumer<List<IssueDto>> listConsumer = returnedDtos::addAll; Set<String> thousandIssueUuidsSnapshot = thousandIssues.stream().map(IssueDto::getKee).collect(Collectors.toSet()); thousandIssueUuidsSnapshot.add(singleIssue.getKee()); pullActionIssuesRetriever.processIssuesByBatch(dbClient.openSession(true), thousandIssueUuidsSnapshot, listConsumer, issueDto -> true); ArgumentCaptor<Set<String>> uuidsCaptor = ArgumentCaptor.forClass(Set.class); verify(issueDao, times(2)).selectByBranch(any(), uuidsCaptor.capture(), any()); List<Set<String>> capturedSets = uuidsCaptor.getAllValues(); assertThat(capturedSets.get(0)).hasSize(1000); assertThat(capturedSets.get(1)).hasSize(1); assertThat(returnedDtos).hasSize(1001); } @Test public void processIssuesByBatch_correctly_processes_all_issues_regardless_of_creation_timestamp() { var pullActionIssuesRetriever = new PullActionIssuesRetriever(dbClient, queryParams); List<IssueDto> issuesWithSameCreationTimestamp = IntStream.rangeClosed(1, 100).mapToObj(i -> new IssueDto() .setKee(Integer.toString(i)).setCreatedAt(100L)).toList(); when(issueDao.selectByBranch(any(), any(), any())) .thenReturn(issuesWithSameCreationTimestamp); List<IssueDto> returnedDtos = new ArrayList<>(); Consumer<List<IssueDto>> listConsumer = returnedDtos::addAll; Set<String> issueKeysSnapshot = issuesWithSameCreationTimestamp.stream().map(IssueDto::getKee).collect(Collectors.toSet()); pullActionIssuesRetriever.processIssuesByBatch(dbClient.openSession(true), issueKeysSnapshot, listConsumer, issueDto -> true); assertThat(returnedDtos).hasSize(100); } }
5,037
43.584071
139
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/pull/PullActionResponseWriterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.ws.pull; import java.io.IOException; import java.io.OutputStream; import java.util.List; import org.junit.Before; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.issue.IssueDto; import static java.util.Collections.emptyMap; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class PullActionResponseWriterTest { private final System2 system2 = mock(System2.class); private final PullActionProtobufObjectGenerator pullActionProtobufObjectGenerator = new PullActionProtobufObjectGenerator(); private final PullActionResponseWriter underTest = new PullActionResponseWriter(system2, pullActionProtobufObjectGenerator); @Before public void before() { when(system2.now()).thenReturn(1_000_000L); } @Test public void appendIssuesToResponse_outputStreamIsCalledAtLeastOnce() throws IOException { OutputStream outputStream = mock(OutputStream.class); IssueDto issueDto = new IssueDto(); issueDto.setFilePath("filePath"); issueDto.setKee("key"); issueDto.setStatus("OPEN"); issueDto.setRuleKey("repo", "rule"); underTest.appendIssuesToResponse(List.of(issueDto), emptyMap(), outputStream); verify(outputStream, atLeastOnce()).write(any(byte[].class), anyInt(), anyInt()); } @Test public void appendClosedIssuesToResponse_outputStreamIsCalledAtLeastOnce() throws IOException { OutputStream outputStream = mock(OutputStream.class); underTest.appendClosedIssuesUuidsToResponse(List.of("uuid", "uuid2"), outputStream); verify(outputStream, atLeastOnce()).write(any(byte[].class), anyInt(), anyInt()); } @Test public void appendTimestampToResponse_outputStreamIsCalledAtLeastOnce() throws IOException { OutputStream outputStream = mock(OutputStream.class); underTest.appendTimestampToResponse(outputStream); verify(outputStream, atLeastOnce()).write(any(byte[].class), anyInt(), anyInt()); } }
3,013
35.756098
126
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/LanguageParamUtilsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.language; import org.junit.Test; import org.sonar.api.resources.AbstractLanguage; import org.sonar.api.resources.Languages; import static org.assertj.core.api.Assertions.assertThat; public class LanguageParamUtilsTest { @Test public void getOrderedLanguageKeys() { assertThat(LanguageParamUtils.getOrderedLanguageKeys(new Languages())).isEmpty(); Languages languages = new Languages( new TestLanguage("java"), new TestLanguage("abap"), new TestLanguage("js"), new TestLanguage("cobol")); assertThat(LanguageParamUtils.getOrderedLanguageKeys(languages)).containsExactly("abap", "cobol", "java", "js"); } private static class TestLanguage extends AbstractLanguage { TestLanguage(String key) { super(key); } @Override public String[] getFileSuffixes() { return new String[0]; } } }
1,732
31.698113
116
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/LanguageValidationTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.language; import org.junit.Test; import org.sonar.api.resources.Language; import org.sonar.server.plugins.ServerPluginRepository; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LanguageValidationTest { @Test public void fail_if_conflicting_languages() { Language lang1 = mock(Language.class); Language lang2 = mock(Language.class); when(lang1.getKey()).thenReturn("key"); when(lang2.getKey()).thenReturn("key"); ServerPluginRepository repo = mock(ServerPluginRepository.class); when(repo.getPluginKey(lang1)).thenReturn("plugin1"); when(repo.getPluginKey(lang2)).thenReturn("plugin2"); LanguageValidation languageValidation = new LanguageValidation(repo, lang1, lang2); assertThatThrownBy(languageValidation::start) .isInstanceOf(IllegalStateException.class) .hasMessage("There are two languages declared with the same key 'key' declared by the plugins 'plugin1' and 'plugin2'. " + "Please uninstall one of the conflicting plugins."); } @Test public void succeed_if_no_language() { ServerPluginRepository repo = mock(ServerPluginRepository.class); LanguageValidation languageValidation = new LanguageValidation(repo); languageValidation.start(); languageValidation.stop(); } @Test public void succeed_if_no_duplicated_language() { Language lang1 = mock(Language.class); Language lang2 = mock(Language.class); when(lang1.getKey()).thenReturn("key1"); when(lang2.getKey()).thenReturn("key2"); ServerPluginRepository repo = mock(ServerPluginRepository.class); when(repo.getPluginKey(lang1)).thenReturn("plugin1"); when(repo.getPluginKey(lang2)).thenReturn("plugin2"); LanguageValidation languageValidation = new LanguageValidation(repo); languageValidation.start(); languageValidation.stop(); } }
2,816
36.065789
126
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/ws/LanguageWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.language.ws; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.server.ws.WebService.Controller; import static org.assertj.core.api.Assertions.assertThat; public class LanguageWsTest { private static final String CONTROLLER_LANGUAGES = "api/languages"; private static final String ACTION_LIST = "list"; private LanguageWs underTest = new LanguageWs(new ListAction(null)); @Test public void should_be_well_defined() { WebService.Context context = new WebService.Context(); underTest.define(context); Controller controller = context.controller(CONTROLLER_LANGUAGES); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.isInternal()).isFalse(); assertThat(controller.path()).isEqualTo(CONTROLLER_LANGUAGES); assertThat(controller.since()).isEqualTo("5.1"); assertThat(controller.actions()).hasSize(1); Action list = controller.action(ACTION_LIST); assertThat(list).isNotNull(); assertThat(list.description()).isNotEmpty(); assertThat(list.handler()).isInstanceOf(ListAction.class); assertThat(list.isInternal()).isFalse(); assertThat(list.isPost()).isFalse(); assertThat(list.responseExampleAsString()).isNotEmpty(); assertThat(list.params()).hasSize(2); } }
2,256
36.616667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/ws/ListActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.language.ws; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.resources.AbstractLanguage; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.server.ws.WsActionTester; import static org.mockito.Mockito.mock; public class ListActionTest { private static final String EMPTY_JSON_RESPONSE = "{\"languages\": []}"; private Languages languages = mock(Languages.class); private ListAction underTest = new ListAction(languages); private WsActionTester tester = new WsActionTester(underTest); @Before public void setUp() { Mockito.when(languages.all()).thenReturn(new Language[] { new Ook(), new LolCode(), new Whitespace(), new ArnoldC() }); } @Test public void list_all_languages() { tester.newRequest().execute().assertJson(this.getClass(), "list.json"); tester.newRequest() .setParam("ps", "2") .execute().assertJson(this.getClass(), "list_limited.json"); tester.newRequest() .setParam("ps", "4") .execute().assertJson(this.getClass(), "list.json"); tester.newRequest() .setParam("ps", "10") .execute().assertJson(this.getClass(), "list.json"); } @Test public void filter_languages_by_key_or_name() { tester.newRequest() .setParam("q", "ws") .execute().assertJson(this.getClass(), "list_filtered_key.json"); tester.newRequest() .setParam("q", "o") .execute().assertJson(this.getClass(), "list_filtered_name.json"); } /** * Potential vulnerability : the query provided by user must * not be executed as a regexp. */ @Test public void filter_escapes_the_user_query() { // invalid regexp tester.newRequest() .setParam("q", "[") .execute().assertJson(EMPTY_JSON_RESPONSE); // do not consider param as a regexp tester.newRequest() .setParam("q", ".*") .execute().assertJson(EMPTY_JSON_RESPONSE); } static abstract class TestLanguage extends AbstractLanguage { TestLanguage(String key, String language) { super(key, language); } @Override public String[] getFileSuffixes() { return new String[0]; } } static class Ook extends TestLanguage { Ook() { super("ook", "Ook!"); } } static class LolCode extends TestLanguage { LolCode() { super("lol", "LOLCODE"); } } static class Whitespace extends TestLanguage { Whitespace() { super("ws", "Whitespace"); } } static class ArnoldC extends TestLanguage { ArnoldC() { super("ac", "ArnoldC"); } } }
3,516
26.912698
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/management/ManagedInstanceCheckerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.management; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.sonar.server.exceptions.BadRequestException; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ManagedInstanceCheckerTest { @Mock private ManagedInstanceService managedInstanceService; @InjectMocks private ManagedInstanceChecker managedInstanceChecker; @Test public void throwIfInstanceIsManaged_whenInstanceExternallyManaged_throws() { when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(true); assertThatThrownBy(() -> managedInstanceChecker.throwIfInstanceIsManaged()) .isInstanceOf(BadRequestException.class) .hasMessage("Operation not allowed when the instance is externally managed."); } @Test public void throwIfInstanceIsManaged_whenInstanceNotExternallyManaged_doesntThrow() { when(managedInstanceService.isInstanceExternallyManaged()).thenReturn(false); assertThatNoException().isThrownBy(() -> managedInstanceChecker.throwIfInstanceIsManaged()); } }
2,156
37.517857
96
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/HotspotsCounterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.live; import java.util.List; import org.junit.Test; import org.sonar.db.issue.HotspotGroupDto; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; public class HotspotsCounterTest { @Test public void counts_hotspots() { HotspotGroupDto group1 = new HotspotGroupDto().setCount(3).setStatus("TO_REVIEW").setInLeak(false); HotspotGroupDto group2 = new HotspotGroupDto().setCount(2).setStatus("REVIEWED").setInLeak(false); HotspotGroupDto group3 = new HotspotGroupDto().setCount(1).setStatus("TO_REVIEW").setInLeak(true); HotspotGroupDto group4 = new HotspotGroupDto().setCount(1).setStatus("REVIEWED").setInLeak(true); HotspotsCounter counter = new HotspotsCounter(List.of(group1, group2, group3, group4)); assertThat(counter.countHotspotsByStatus("TO_REVIEW", true)).isEqualTo(1); assertThat(counter.countHotspotsByStatus("REVIEWED", true)).isEqualTo(1); assertThat(counter.countHotspotsByStatus("TO_REVIEW", false)).isEqualTo(4); assertThat(counter.countHotspotsByStatus("REVIEWED", false)).isEqualTo(3); } @Test public void count_empty_hotspots() { HotspotsCounter counter = new HotspotsCounter(emptyList()); assertThat(counter.countHotspotsByStatus("TO_REVIEW", true)).isZero(); } }
2,174
42.5
103
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/LiveMeasureModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.live; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class LiveMeasureModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new LiveMeasureModule().configure(container); assertThat(container.getAddedObjects()).isNotEmpty(); } }
1,273
35.4
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/MeasureMatrixTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.live; import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.measure.LiveMeasureDto; import org.sonar.db.metric.MetricDto; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.metric.MetricTesting.newMetricDto; public class MeasureMatrixTest { private static final ComponentDto PROJECT = ComponentTesting.newPublicProjectDto(); private static final ComponentDto FILE = ComponentTesting.newFileDto(PROJECT); private static final MetricDto METRIC_1 = newMetricDto().setUuid("100"); private static final MetricDto METRIC_2 = newMetricDto().setUuid("200"); @Test public void getMetric() { Collection<MetricDto> metrics = asList(METRIC_1, METRIC_2); MeasureMatrix underTest = new MeasureMatrix(asList(PROJECT, FILE), metrics, new ArrayList<>()); assertThat(underTest.getMetricByUuid(METRIC_2.getUuid())).isSameAs(METRIC_2); } @Test public void getMetric_fails_if_metric_is_not_registered() { Collection<MetricDto> metrics = asList(METRIC_1); MeasureMatrix underTest = new MeasureMatrix(asList(PROJECT, FILE), metrics, new ArrayList<>()); assertThatThrownBy(() -> underTest.getMetricByUuid(METRIC_2.getUuid())) .isInstanceOf(NullPointerException.class) .hasMessage("Metric with uuid " + METRIC_2.getUuid() + " not found"); } @Test public void getValue_returns_empty_if_measure_is_absent() { MetricDto metric = newMetricDto(); LiveMeasureDto measure = newMeasure(metric, PROJECT).setValue(null); MeasureMatrix underTest = new MeasureMatrix(asList(PROJECT), asList(metric), asList(measure)); assertThat(underTest.getMeasure(FILE, metric.getKey())).isEmpty(); } @Test public void getMeasure_throws_IAE_if_metric_is_not_registered() { MeasureMatrix underTest = new MeasureMatrix(asList(PROJECT), asList(METRIC_1), emptyList()); assertThatThrownBy(() -> underTest.getMeasure(PROJECT, "_missing_")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Metric with key _missing_ is not registered"); } @Test public void setValue_double_rounds_up_and_updates_value() { MetricDto metric = newMetricDto().setDecimalScale(2); LiveMeasureDto measure = newMeasure(metric, PROJECT).setValue(1.23); MeasureMatrix underTest = new MeasureMatrix(asList(PROJECT), asList(metric), asList(measure)); underTest.setValue(PROJECT, metric.getKey(), 3.14159); assertThat(underTest.getMeasure(PROJECT, metric.getKey()).get().getValue()).isEqualTo(3.14); assertThat(underTest.getChanged()).hasSize(1); underTest.setValue(PROJECT, metric.getKey(), 3.148); verifyValue(underTest, PROJECT, metric, 3.15); } private void verifyValue(MeasureMatrix underTest, ComponentDto component, MetricDto metric, @Nullable Double expectedValue) { Optional<LiveMeasureDto> measure = underTest.getMeasure(component, metric.getKey()); assertThat(measure).isPresent(); assertThat(measure.get().getValue()).isEqualTo(expectedValue); } @Test public void setValue_double_does_nothing_if_value_is_unchanged() { MetricDto metric = newMetricDto().setDecimalScale(2); LiveMeasureDto measure = newMeasure(metric, PROJECT).setValue(3.14); MeasureMatrix underTest = new MeasureMatrix(asList(PROJECT), asList(metric), asList(measure)); underTest.setValue(PROJECT, metric.getKey(), 3.14159); assertThat(underTest.getChanged()).isEmpty(); verifyValue(underTest, PROJECT, metric, 3.14); } @Test public void setValue_String_does_nothing_if_value_is_not_changed() { LiveMeasureDto measure = newMeasure(METRIC_1, PROJECT).setData("foo"); MeasureMatrix underTest = new MeasureMatrix(asList(PROJECT, FILE), asList(METRIC_1), asList(measure)); underTest.setValue(PROJECT, METRIC_1.getKey(), "foo"); assertThat(underTest.getMeasure(PROJECT, METRIC_1.getKey()).get().getDataAsString()).isEqualTo("foo"); assertThat(underTest.getChanged()).isEmpty(); } @Test public void setValue_String_updates_value() { LiveMeasureDto measure = newMeasure(METRIC_1, PROJECT).setData("foo"); MeasureMatrix underTest = new MeasureMatrix(asList(PROJECT, FILE), asList(METRIC_1), asList(measure)); underTest.setValue(PROJECT, METRIC_1.getKey(), "bar"); assertThat(underTest.getMeasure(PROJECT, METRIC_1.getKey()).get().getDataAsString()).isEqualTo("bar"); assertThat(underTest.getChanged()).extracting(LiveMeasureDto::getDataAsString).containsExactly("bar"); } private LiveMeasureDto newMeasure(MetricDto metric, ComponentDto component) { return new LiveMeasureDto().setMetricUuid(metric.getUuid()).setData("foo").setComponentUuid(component.uuid()); } }
5,897
40.829787
127
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/MeasureUpdateFormulaFactoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.live; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.api.issue.Issue; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; import org.sonar.db.component.ComponentDto; import org.sonar.db.issue.IssueGroupDto; import org.sonar.server.measure.DebtRatingGrid; import org.sonar.server.measure.Rating; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_REVIEW_RATING; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_STATUS; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_TO_REVIEW_STATUS; import static org.sonar.api.measures.CoreMetrics.SECURITY_REVIEW_RATING; public class MeasureUpdateFormulaFactoryImplTest { private final MeasureUpdateFormulaFactoryImpl underTest = new MeasureUpdateFormulaFactoryImpl(); @Test public void getFormulaMetrics_include_the_dependent_metrics() { for (MeasureUpdateFormula formula : underTest.getFormulas()) { assertThat(underTest.getFormulaMetrics()).contains(formula.getMetric()); for (Metric<?> dependentMetric : formula.getDependentMetrics()) { assertThat(underTest.getFormulaMetrics()).contains(dependentMetric); } } } @Test public void hierarchy_adding_numbers() { new HierarchyTester(CoreMetrics.VIOLATIONS) .withValue(1d) .withChildrenValues(2d, 3d) .expectedResult(6d); new HierarchyTester(CoreMetrics.BUGS) .withValue(0d) .withChildrenValues(2d, 3d) .expectedResult(5d); new HierarchyTester(CoreMetrics.NEW_BUGS) .withValue(1d) .expectedResult(1d); } @Test public void hierarchy_highest_rating() { new HierarchyTester(CoreMetrics.RELIABILITY_RATING) .withValue(1d) .withChildrenValues(2d, 3d) .expectedRating(Rating.C); // if no children, no need to set a value new HierarchyTester(CoreMetrics.SECURITY_RATING) .withValue(1d) .expectedResult(null); new HierarchyTester(CoreMetrics.NEW_RELIABILITY_RATING) .withValue(5d) .withChildrenValues(2d, 3d) .expectedRating(Rating.E); } @Test public void hierarchy_combining_other_metrics() { new HierarchyTester(SECURITY_HOTSPOTS_TO_REVIEW_STATUS) .withValue(SECURITY_HOTSPOTS_TO_REVIEW_STATUS, 1d) .withChildrenHotspotsCounts(10, 10, 2, 10) .expectedResult(3d); new HierarchyTester(SECURITY_HOTSPOTS_REVIEWED_STATUS) .withValue(SECURITY_HOTSPOTS_REVIEWED_STATUS, 1d) .withChildrenHotspotsCounts(2, 10, 10, 10) .expectedResult(3d); new HierarchyTester(NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS) .withValue(NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS, 1d) .withChildrenHotspotsCounts(10, 10, 10, 2) .expectedResult(3d); new HierarchyTester(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS) .withValue(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS, 1d) .withChildrenHotspotsCounts(10, 2, 10, 10) .expectedResult(3d); new HierarchyTester(CoreMetrics.SECURITY_HOTSPOTS_REVIEWED) .withValue(SECURITY_HOTSPOTS_TO_REVIEW_STATUS, 1d) .withValue(SECURITY_HOTSPOTS_REVIEWED_STATUS, 1d) .expectedResult(50d); new HierarchyTester(CoreMetrics.SECURITY_REVIEW_RATING) .withValue(SECURITY_HOTSPOTS_REVIEWED, 100d) .expectedRating(Rating.A); new HierarchyTester(CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED) .withValue(NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS, 1d) .withValue(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS, 1d) .expectedResult(50d); new HierarchyTester(CoreMetrics.NEW_SECURITY_REVIEW_RATING) .withValue(NEW_SECURITY_HOTSPOTS_REVIEWED, 0d) .expectedRating(Rating.E); } @Test public void test_violations() { withNoIssues().assertThatValueIs(CoreMetrics.VIOLATIONS, 0); with(newGroup(), newGroup().setCount(4)).assertThatValueIs(CoreMetrics.VIOLATIONS, 5); // exclude resolved IssueGroupDto resolved = newResolvedGroup(Issue.RESOLUTION_FIXED, Issue.STATUS_RESOLVED); with(newGroup(), newGroup(), resolved).assertThatValueIs(CoreMetrics.VIOLATIONS, 2); // include issues on leak IssueGroupDto onLeak = newGroup().setCount(11).setInLeak(true); with(newGroup(), newGroup(), onLeak).assertThatValueIs(CoreMetrics.VIOLATIONS, 1 + 1 + 11); } @Test public void test_bugs() { withNoIssues().assertThatValueIs(CoreMetrics.BUGS, 0); with( newGroup(RuleType.BUG).setSeverity(Severity.MAJOR).setCount(3), newGroup(RuleType.BUG).setSeverity(Severity.CRITICAL).setCount(5), // exclude resolved newResolvedGroup(RuleType.BUG).setCount(7), // not bugs newGroup(RuleType.CODE_SMELL).setCount(11)) .assertThatValueIs(CoreMetrics.BUGS, 3 + 5); } @Test public void test_code_smells() { withNoIssues().assertThatValueIs(CoreMetrics.CODE_SMELLS, 0); with( newGroup(RuleType.CODE_SMELL).setSeverity(Severity.MAJOR).setCount(3), newGroup(RuleType.CODE_SMELL).setSeverity(Severity.CRITICAL).setCount(5), // exclude resolved newResolvedGroup(RuleType.CODE_SMELL).setCount(7), // not code smells newGroup(RuleType.BUG).setCount(11)) .assertThatValueIs(CoreMetrics.CODE_SMELLS, 3 + 5); } @Test public void test_vulnerabilities() { withNoIssues().assertThatValueIs(CoreMetrics.VULNERABILITIES, 0); with( newGroup(RuleType.VULNERABILITY).setSeverity(Severity.MAJOR).setCount(3), newGroup(RuleType.VULNERABILITY).setSeverity(Severity.CRITICAL).setCount(5), // exclude resolved newResolvedGroup(RuleType.VULNERABILITY).setCount(7), // not vulnerabilities newGroup(RuleType.BUG).setCount(11)) .assertThatValueIs(CoreMetrics.VULNERABILITIES, 3 + 5); } @Test public void test_security_hotspots() { withNoIssues().assertThatValueIs(CoreMetrics.SECURITY_HOTSPOTS, 0); with( newGroup(RuleType.SECURITY_HOTSPOT).setSeverity(Severity.MAJOR).setCount(3), newGroup(RuleType.SECURITY_HOTSPOT).setSeverity(Severity.CRITICAL).setCount(5), // exclude resolved newResolvedGroup(RuleType.SECURITY_HOTSPOT).setCount(7), // not hotspots newGroup(RuleType.BUG).setCount(11)) .assertThatValueIs(CoreMetrics.SECURITY_HOTSPOTS, 3 + 5); } @Test public void test_security_review_rating() { with( newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED).setCount(3), newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW).setCount(1)) .assertThatValueIs(SECURITY_REVIEW_RATING, Rating.B); withNoIssues() .assertThatValueIs(SECURITY_REVIEW_RATING, Rating.A); } @Test public void test_security_hotspots_reviewed() { with( newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED).setCount(3), newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW).setCount(1)) .assertThatValueIs(SECURITY_HOTSPOTS_REVIEWED, 75.0); withNoIssues() .assertNoValue(SECURITY_HOTSPOTS_REVIEWED); } @Test public void test_security_hotspots_reviewed_status() { with( newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED).setCount(3), newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW).setCount(1)) .assertThatValueIs(CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_STATUS, 3.0); withNoIssues() .assertThatValueIs(CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_STATUS, 0.0); } @Test public void test_security_hotspots_to_review_status() { with( newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED).setCount(3), newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW).setCount(1)) .assertThatValueIs(CoreMetrics.SECURITY_HOTSPOTS_TO_REVIEW_STATUS, 1.0); withNoIssues() .assertThatValueIs(CoreMetrics.SECURITY_HOTSPOTS_TO_REVIEW_STATUS, 0.0); } @Test public void count_unresolved_by_severity() { withNoIssues() .assertThatValueIs(CoreMetrics.BLOCKER_VIOLATIONS, 0) .assertThatValueIs(CoreMetrics.CRITICAL_VIOLATIONS, 0) .assertThatValueIs(CoreMetrics.MAJOR_VIOLATIONS, 0) .assertThatValueIs(CoreMetrics.MINOR_VIOLATIONS, 0) .assertThatValueIs(CoreMetrics.INFO_VIOLATIONS, 0); with( newGroup(RuleType.VULNERABILITY).setSeverity(Severity.MAJOR).setCount(3), newGroup(RuleType.BUG).setSeverity(Severity.MAJOR).setCount(5), newGroup(RuleType.BUG).setSeverity(Severity.CRITICAL).setCount(7), newGroup(RuleType.CODE_SMELL).setSeverity(Severity.BLOCKER).setCount(11), // exclude security hotspot newGroup(RuleType.SECURITY_HOTSPOT).setSeverity(Severity.CRITICAL).setCount(15), // include leak newGroup(RuleType.CODE_SMELL).setSeverity(Severity.BLOCKER).setInLeak(true).setCount(13), // exclude resolved newResolvedGroup(RuleType.VULNERABILITY).setSeverity(Severity.INFO).setCount(17), newResolvedGroup(RuleType.BUG).setSeverity(Severity.MAJOR).setCount(19), newResolvedGroup(RuleType.SECURITY_HOTSPOT).setSeverity(Severity.INFO).setCount(21)) .assertThatValueIs(CoreMetrics.BLOCKER_VIOLATIONS, 11 + 13) .assertThatValueIs(CoreMetrics.CRITICAL_VIOLATIONS, 7) .assertThatValueIs(CoreMetrics.MAJOR_VIOLATIONS, 3 + 5) .assertThatValueIs(CoreMetrics.MINOR_VIOLATIONS, 0) .assertThatValueIs(CoreMetrics.INFO_VIOLATIONS, 0); } @Test public void count_resolved() { withNoIssues() .assertThatValueIs(CoreMetrics.FALSE_POSITIVE_ISSUES, 0) .assertThatValueIs(CoreMetrics.WONT_FIX_ISSUES, 0); with( newResolvedGroup(Issue.RESOLUTION_FIXED, Issue.STATUS_RESOLVED).setCount(3), newResolvedGroup(Issue.RESOLUTION_FALSE_POSITIVE, Issue.STATUS_CLOSED).setCount(5), newResolvedGroup(Issue.RESOLUTION_WONT_FIX, Issue.STATUS_CLOSED).setSeverity(Severity.MAJOR).setCount(7), newResolvedGroup(Issue.RESOLUTION_WONT_FIX, Issue.STATUS_CLOSED).setSeverity(Severity.BLOCKER).setCount(11), newResolvedGroup(Issue.RESOLUTION_REMOVED, Issue.STATUS_CLOSED).setCount(13), // exclude security hotspot newResolvedGroup(Issue.RESOLUTION_WONT_FIX, Issue.STATUS_RESOLVED).setCount(15).setRuleType(RuleType.SECURITY_HOTSPOT.getDbConstant()), // exclude unresolved newGroup(RuleType.VULNERABILITY).setCount(17), newGroup(RuleType.BUG).setCount(19)) .assertThatValueIs(CoreMetrics.FALSE_POSITIVE_ISSUES, 5) .assertThatValueIs(CoreMetrics.WONT_FIX_ISSUES, 7 + 11); } @Test public void count_by_status() { withNoIssues() .assertThatValueIs(CoreMetrics.CONFIRMED_ISSUES, 0) .assertThatValueIs(CoreMetrics.OPEN_ISSUES, 0) .assertThatValueIs(CoreMetrics.REOPENED_ISSUES, 0); with( newGroup().setStatus(Issue.STATUS_CONFIRMED).setSeverity(Severity.BLOCKER).setCount(3), newGroup().setStatus(Issue.STATUS_CONFIRMED).setSeverity(Severity.INFO).setCount(5), newGroup().setStatus(Issue.STATUS_REOPENED).setCount(7), newGroup(RuleType.CODE_SMELL).setStatus(Issue.STATUS_OPEN).setCount(9), newGroup(RuleType.BUG).setStatus(Issue.STATUS_OPEN).setCount(11), // exclude security hotspot newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_OPEN).setCount(12), newResolvedGroup(Issue.RESOLUTION_FALSE_POSITIVE, Issue.STATUS_CLOSED).setCount(13)) .assertThatValueIs(CoreMetrics.CONFIRMED_ISSUES, 3 + 5) .assertThatValueIs(CoreMetrics.OPEN_ISSUES, 9 + 11) .assertThatValueIs(CoreMetrics.REOPENED_ISSUES, 7); } @Test public void test_technical_debt() { withNoIssues().assertThatValueIs(CoreMetrics.TECHNICAL_DEBT, 0); with( newGroup(RuleType.CODE_SMELL).setEffort(3.0).setInLeak(false), newGroup(RuleType.CODE_SMELL).setEffort(5.0).setInLeak(true), // exclude security hotspot newGroup(RuleType.SECURITY_HOTSPOT).setEffort(9).setInLeak(true), newGroup(RuleType.SECURITY_HOTSPOT).setEffort(11).setInLeak(false), // not code smells newGroup(RuleType.BUG).setEffort(7.0), // exclude resolved newResolvedGroup(RuleType.CODE_SMELL).setEffort(17.0)) .assertThatValueIs(CoreMetrics.TECHNICAL_DEBT, 3.0 + 5.0); } @Test public void test_reliability_remediation_effort() { withNoIssues().assertThatValueIs(CoreMetrics.RELIABILITY_REMEDIATION_EFFORT, 0); with( newGroup(RuleType.BUG).setEffort(3.0), newGroup(RuleType.BUG).setEffort(5.0).setSeverity(Severity.BLOCKER), // not bugs newGroup(RuleType.CODE_SMELL).setEffort(7.0), // exclude resolved newResolvedGroup(RuleType.BUG).setEffort(17.0)) .assertThatValueIs(CoreMetrics.RELIABILITY_REMEDIATION_EFFORT, 3.0 + 5.0); } @Test public void test_security_remediation_effort() { withNoIssues().assertThatValueIs(CoreMetrics.SECURITY_REMEDIATION_EFFORT, 0); with( newGroup(RuleType.VULNERABILITY).setEffort(3.0), newGroup(RuleType.VULNERABILITY).setEffort(5.0).setSeverity(Severity.BLOCKER), // not vulnerability newGroup(RuleType.CODE_SMELL).setEffort(7.0), // exclude resolved newResolvedGroup(RuleType.VULNERABILITY).setEffort(17.0)) .assertThatValueIs(CoreMetrics.SECURITY_REMEDIATION_EFFORT, 3.0 + 5.0); } @Test public void test_sqale_debt_ratio_and_sqale_rating() { withNoIssues() .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.A); // technical_debt not computed with(CoreMetrics.DEVELOPMENT_COST, "0") .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.A); with(CoreMetrics.DEVELOPMENT_COST, "20") .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.A); // development_cost not computed with(CoreMetrics.TECHNICAL_DEBT, 0) .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.A); with(CoreMetrics.TECHNICAL_DEBT, 20) .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.A); // input measures are available with(CoreMetrics.TECHNICAL_DEBT, 20.0) .andText(CoreMetrics.DEVELOPMENT_COST, "0") .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 0.0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.A); with(CoreMetrics.TECHNICAL_DEBT, 20.0) .andText(CoreMetrics.DEVELOPMENT_COST, "160") .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 12.5) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.C); with(CoreMetrics.TECHNICAL_DEBT, 20.0) .andText(CoreMetrics.DEVELOPMENT_COST, "10") .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 200.0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.E); // A is 5% --> min debt is exactly 200*0.05=10 with(CoreMetrics.DEVELOPMENT_COST, "200") .and(CoreMetrics.TECHNICAL_DEBT, 10.0) .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 5.0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.A); with(CoreMetrics.TECHNICAL_DEBT, 0.0) .andText(CoreMetrics.DEVELOPMENT_COST, "0") .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 0.0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.A); with(CoreMetrics.TECHNICAL_DEBT, 0.0) .andText(CoreMetrics.DEVELOPMENT_COST, "80") .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 0.0); with(CoreMetrics.TECHNICAL_DEBT, -20.0) .andText(CoreMetrics.DEVELOPMENT_COST, "0") .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 0.0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.A); // bug, debt can't be negative with(CoreMetrics.TECHNICAL_DEBT, -20.0) .andText(CoreMetrics.DEVELOPMENT_COST, "80") .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 0.0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.A); // bug, cost can't be negative with(CoreMetrics.TECHNICAL_DEBT, 20.0) .andText(CoreMetrics.DEVELOPMENT_COST, "-80") .assertThatValueIs(CoreMetrics.SQALE_DEBT_RATIO, 0.0) .assertThatValueIs(CoreMetrics.SQALE_RATING, Rating.A); } @Test public void test_effort_to_reach_maintainability_rating_A() { withNoIssues() .assertThatValueIs(CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A, 0.0); // technical_debt not computed with(CoreMetrics.DEVELOPMENT_COST, 0.0) .assertThatValueIs(CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A, 0.0); with(CoreMetrics.DEVELOPMENT_COST, 20.0) .assertThatValueIs(CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A, 0.0); // development_cost not computed with(CoreMetrics.TECHNICAL_DEBT, 0.0) .assertThatValueIs(CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A, 0.0); with(CoreMetrics.TECHNICAL_DEBT, 20.0) // development cost is considered as zero, so the effort is to reach... zero .assertThatValueIs(CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A, 20.0); // B to A with(CoreMetrics.DEVELOPMENT_COST, "200") .and(CoreMetrics.TECHNICAL_DEBT, 40.0) // B is 5% --> goal is to reach 200*0.05=10 --> effort is 40-10=30 .assertThatValueIs(CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A, 40.0 - (200.0 * 0.05)); // E to A with(CoreMetrics.DEVELOPMENT_COST, "200") .and(CoreMetrics.TECHNICAL_DEBT, 180.0) // B is 5% --> goal is to reach 200*0.05=10 --> effort is 180-10=170 .assertThatValueIs(CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A, 180.0 - (200.0 * 0.05)); // already A with(CoreMetrics.DEVELOPMENT_COST, "200") .and(CoreMetrics.TECHNICAL_DEBT, 8.0) // B is 5% --> goal is to reach 200*0.05=10 --> debt is already at 8 --> effort to reach A is zero .assertThatValueIs(CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A, 0.0); // exactly lower range of B with(CoreMetrics.DEVELOPMENT_COST, "200") .and(CoreMetrics.TECHNICAL_DEBT, 10.0) // B is 5% --> goal is to reach 200*0.05=10 --> debt is 10 --> effort to reach A is zero // FIXME need zero to reach A but effective rating is B ! .assertThatValueIs(CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A, 0.0); } @Test public void test_reliability_rating() { withNoIssues() .assertThatValueIs(CoreMetrics.RELIABILITY_RATING, Rating.A); with( newGroup(RuleType.BUG).setSeverity(Severity.CRITICAL).setCount(1), newGroup(RuleType.BUG).setSeverity(Severity.MINOR).setCount(5), // excluded, not a bug newGroup(RuleType.CODE_SMELL).setSeverity(Severity.BLOCKER).setCount(3)) // highest severity of bugs is CRITICAL --> D .assertThatValueIs(CoreMetrics.RELIABILITY_RATING, Rating.D); with( newGroup(RuleType.CODE_SMELL).setSeverity(Severity.MAJOR).setCount(3), newGroup(RuleType.VULNERABILITY).setSeverity(Severity.CRITICAL).setCount(5)) // no bugs --> A .assertThatValueIs(CoreMetrics.RELIABILITY_RATING, Rating.A); } @Test public void test_security_rating() { withNoIssues() .assertThatValueIs(CoreMetrics.SECURITY_RATING, Rating.A); with( newGroup(RuleType.VULNERABILITY).setSeverity(Severity.CRITICAL).setCount(1), newGroup(RuleType.VULNERABILITY).setSeverity(Severity.MINOR).setCount(5), // excluded, not a vulnerability newGroup(RuleType.CODE_SMELL).setSeverity(Severity.BLOCKER).setCount(3)) // highest severity of vulnerabilities is CRITICAL --> D .assertThatValueIs(CoreMetrics.SECURITY_RATING, Rating.D); with( newGroup(RuleType.CODE_SMELL).setSeverity(Severity.MAJOR).setCount(3), newGroup(RuleType.BUG).setSeverity(Severity.CRITICAL).setCount(5)) // no vulnerabilities --> A .assertThatValueIs(CoreMetrics.SECURITY_RATING, Rating.A); } @Test public void test_new_bugs() { withNoIssues().assertThatLeakValueIs(CoreMetrics.NEW_BUGS, 0.0); with( newGroup(RuleType.BUG).setInLeak(false).setSeverity(Severity.MAJOR).setCount(3), newGroup(RuleType.BUG).setInLeak(true).setSeverity(Severity.CRITICAL).setCount(5), newGroup(RuleType.BUG).setInLeak(true).setSeverity(Severity.MINOR).setCount(7), // not bugs newGroup(RuleType.CODE_SMELL).setInLeak(true).setCount(9), newGroup(RuleType.VULNERABILITY).setInLeak(true).setCount(11)) .assertThatLeakValueIs(CoreMetrics.NEW_BUGS, 5 + 7); } @Test public void test_new_code_smells() { withNoIssues().assertThatLeakValueIs(CoreMetrics.NEW_CODE_SMELLS, 0.0); with( newGroup(RuleType.CODE_SMELL).setInLeak(false).setSeverity(Severity.MAJOR).setCount(3), newGroup(RuleType.CODE_SMELL).setInLeak(true).setSeverity(Severity.CRITICAL).setCount(5), newGroup(RuleType.CODE_SMELL).setInLeak(true).setSeverity(Severity.MINOR).setCount(7), // not code smells newGroup(RuleType.BUG).setInLeak(true).setCount(9), newGroup(RuleType.VULNERABILITY).setInLeak(true).setCount(11)) .assertThatLeakValueIs(CoreMetrics.NEW_CODE_SMELLS, 5 + 7); } @Test public void test_new_vulnerabilities() { withNoIssues().assertThatLeakValueIs(CoreMetrics.NEW_VULNERABILITIES, 0.0); with( newGroup(RuleType.VULNERABILITY).setInLeak(false).setSeverity(Severity.MAJOR).setCount(3), newGroup(RuleType.VULNERABILITY).setInLeak(true).setSeverity(Severity.CRITICAL).setCount(5), newGroup(RuleType.VULNERABILITY).setInLeak(true).setSeverity(Severity.MINOR).setCount(7), // not vulnerabilities newGroup(RuleType.BUG).setInLeak(true).setCount(9), newGroup(RuleType.CODE_SMELL).setInLeak(true).setCount(11)) .assertThatLeakValueIs(CoreMetrics.NEW_VULNERABILITIES, 5 + 7); } @Test public void test_new_security_hotspots() { withNoIssues().assertThatLeakValueIs(CoreMetrics.NEW_SECURITY_HOTSPOTS, 0); with( newGroup(RuleType.SECURITY_HOTSPOT).setInLeak(false).setSeverity(Severity.MAJOR).setCount(3), newGroup(RuleType.SECURITY_HOTSPOT).setInLeak(true).setSeverity(Severity.CRITICAL).setCount(5), newGroup(RuleType.SECURITY_HOTSPOT).setInLeak(true).setSeverity(Severity.MINOR).setCount(7), // not hotspots newGroup(RuleType.BUG).setInLeak(true).setCount(9), newGroup(RuleType.CODE_SMELL).setInLeak(true).setCount(11)) .assertThatLeakValueIs(CoreMetrics.NEW_SECURITY_HOTSPOTS, 5 + 7); } @Test public void test_new_violations() { withNoIssues().assertThatLeakValueIs(CoreMetrics.NEW_VIOLATIONS, 0.0); with( newGroup(RuleType.BUG).setInLeak(true).setCount(5), newGroup(RuleType.CODE_SMELL).setInLeak(true).setCount(7), newGroup(RuleType.VULNERABILITY).setInLeak(true).setCount(9), // not in leak newGroup(RuleType.BUG).setInLeak(false).setCount(11), newGroup(RuleType.CODE_SMELL).setInLeak(false).setCount(13), newGroup(RuleType.VULNERABILITY).setInLeak(false).setCount(17)) .assertThatLeakValueIs(CoreMetrics.NEW_VIOLATIONS, 5 + 7 + 9); } @Test public void test_new_blocker_violations() { withNoIssues() .assertThatLeakValueIs(CoreMetrics.NEW_BLOCKER_VIOLATIONS, 0.0); with( newGroup(RuleType.CODE_SMELL).setSeverity(Severity.BLOCKER).setInLeak(true).setCount(3), newGroup(RuleType.BUG).setSeverity(Severity.BLOCKER).setInLeak(true).setCount(5), newGroup(RuleType.VULNERABILITY).setSeverity(Severity.BLOCKER).setInLeak(true).setCount(7), // not blocker newGroup(RuleType.CODE_SMELL).setSeverity(Severity.CRITICAL).setInLeak(true).setCount(9), // not in leak newGroup(RuleType.CODE_SMELL).setSeverity(Severity.BLOCKER).setInLeak(false).setCount(11), newGroup(RuleType.BUG).setSeverity(Severity.BLOCKER).setInLeak(false).setCount(13)) .assertThatLeakValueIs(CoreMetrics.NEW_BLOCKER_VIOLATIONS, 3 + 5 + 7); } @Test public void test_new_critical_violations() { withNoIssues() .assertThatLeakValueIs(CoreMetrics.NEW_CRITICAL_VIOLATIONS, 0.0); with( newGroup(RuleType.CODE_SMELL).setSeverity(Severity.CRITICAL).setInLeak(true).setCount(3), newGroup(RuleType.BUG).setSeverity(Severity.CRITICAL).setInLeak(true).setCount(5), newGroup(RuleType.VULNERABILITY).setSeverity(Severity.CRITICAL).setInLeak(true).setCount(7), // not CRITICAL newGroup(RuleType.CODE_SMELL).setSeverity(Severity.MAJOR).setInLeak(true).setCount(9), // not in leak newGroup(RuleType.CODE_SMELL).setSeverity(Severity.CRITICAL).setInLeak(false).setCount(11), newGroup(RuleType.BUG).setSeverity(Severity.CRITICAL).setInLeak(false).setCount(13)) .assertThatLeakValueIs(CoreMetrics.NEW_CRITICAL_VIOLATIONS, 3 + 5 + 7); } @Test public void test_new_major_violations() { withNoIssues() .assertThatLeakValueIs(CoreMetrics.NEW_MAJOR_VIOLATIONS, 0.0); with( newGroup(RuleType.CODE_SMELL).setSeverity(Severity.MAJOR).setInLeak(true).setCount(3), newGroup(RuleType.BUG).setSeverity(Severity.MAJOR).setInLeak(true).setCount(5), newGroup(RuleType.VULNERABILITY).setSeverity(Severity.MAJOR).setInLeak(true).setCount(7), // not MAJOR newGroup(RuleType.CODE_SMELL).setSeverity(Severity.CRITICAL).setInLeak(true).setCount(9), // not in leak newGroup(RuleType.CODE_SMELL).setSeverity(Severity.MAJOR).setInLeak(false).setCount(11), newGroup(RuleType.BUG).setSeverity(Severity.MAJOR).setInLeak(false).setCount(13)) .assertThatLeakValueIs(CoreMetrics.NEW_MAJOR_VIOLATIONS, 3 + 5 + 7); } @Test public void test_new_minor_violations() { withNoIssues() .assertThatLeakValueIs(CoreMetrics.NEW_MINOR_VIOLATIONS, 0.0); with( newGroup(RuleType.CODE_SMELL).setSeverity(Severity.MINOR).setInLeak(true).setCount(3), newGroup(RuleType.BUG).setSeverity(Severity.MINOR).setInLeak(true).setCount(5), newGroup(RuleType.VULNERABILITY).setSeverity(Severity.MINOR).setInLeak(true).setCount(7), // not MINOR newGroup(RuleType.CODE_SMELL).setSeverity(Severity.CRITICAL).setInLeak(true).setCount(9), // not in leak newGroup(RuleType.CODE_SMELL).setSeverity(Severity.MINOR).setInLeak(false).setCount(11), newGroup(RuleType.BUG).setSeverity(Severity.MINOR).setInLeak(false).setCount(13)) .assertThatLeakValueIs(CoreMetrics.NEW_MINOR_VIOLATIONS, 3 + 5 + 7); } @Test public void test_new_info_violations() { withNoIssues() .assertThatLeakValueIs(CoreMetrics.NEW_INFO_VIOLATIONS, 0.0); with( newGroup(RuleType.CODE_SMELL).setSeverity(Severity.INFO).setInLeak(true).setCount(3), newGroup(RuleType.BUG).setSeverity(Severity.INFO).setInLeak(true).setCount(5), newGroup(RuleType.VULNERABILITY).setSeverity(Severity.INFO).setInLeak(true).setCount(7), // not INFO newGroup(RuleType.CODE_SMELL).setSeverity(Severity.CRITICAL).setInLeak(true).setCount(9), // not in leak newGroup(RuleType.CODE_SMELL).setSeverity(Severity.INFO).setInLeak(false).setCount(11), newGroup(RuleType.BUG).setSeverity(Severity.INFO).setInLeak(false).setCount(13)) .assertThatLeakValueIs(CoreMetrics.NEW_INFO_VIOLATIONS, 3 + 5 + 7); } @Test public void test_new_technical_debt() { withNoIssues().assertThatLeakValueIs(CoreMetrics.NEW_TECHNICAL_DEBT, 0.0); with( newGroup(RuleType.CODE_SMELL).setEffort(3.0).setInLeak(true), // not in leak newGroup(RuleType.CODE_SMELL).setEffort(5.0).setInLeak(false), // not code smells newGroup(RuleType.SECURITY_HOTSPOT).setEffort(9.0).setInLeak(true), newGroup(RuleType.BUG).setEffort(7.0).setInLeak(true), // exclude resolved newResolvedGroup(RuleType.CODE_SMELL).setEffort(17.0).setInLeak(true)) .assertThatLeakValueIs(CoreMetrics.NEW_TECHNICAL_DEBT, 3.0); } @Test public void test_new_reliability_remediation_effort() { withNoIssues().assertThatLeakValueIs(CoreMetrics.NEW_RELIABILITY_REMEDIATION_EFFORT, 0.0); with( newGroup(RuleType.BUG).setEffort(3.0).setInLeak(true), // not in leak newGroup(RuleType.BUG).setEffort(5.0).setInLeak(false), // not bugs newGroup(RuleType.CODE_SMELL).setEffort(7.0).setInLeak(true), // exclude resolved newResolvedGroup(RuleType.BUG).setEffort(17.0).setInLeak(true)) .assertThatLeakValueIs(CoreMetrics.NEW_RELIABILITY_REMEDIATION_EFFORT, 3.0); } @Test public void test_new_security_remediation_effort() { withNoIssues().assertThatLeakValueIs(CoreMetrics.NEW_SECURITY_REMEDIATION_EFFORT, 0.0); with( newGroup(RuleType.VULNERABILITY).setEffort(3.0).setInLeak(true), // not in leak newGroup(RuleType.VULNERABILITY).setEffort(5.0).setInLeak(false), // not vulnerability newGroup(RuleType.CODE_SMELL).setEffort(7.0).setInLeak(true), // exclude resolved newResolvedGroup(RuleType.VULNERABILITY).setEffort(17.0).setInLeak(true)) .assertThatLeakValueIs(CoreMetrics.NEW_SECURITY_REMEDIATION_EFFORT, 3.0); } @Test public void test_new_reliability_rating() { withNoIssues().assertThatLeakValueIs(CoreMetrics.NEW_RELIABILITY_RATING, Rating.A); with( newGroup(RuleType.BUG).setSeverity(Severity.INFO).setCount(3).setInLeak(true), newGroup(RuleType.BUG).setSeverity(Severity.MINOR).setCount(1).setInLeak(true), // not in leak newGroup(RuleType.BUG).setSeverity(Severity.BLOCKER).setInLeak(false), // not bug newGroup(RuleType.CODE_SMELL).setSeverity(Severity.BLOCKER).setInLeak(true), // exclude resolved newResolvedGroup(RuleType.BUG).setSeverity(Severity.BLOCKER).setInLeak(true)) // highest severity of bugs on leak period is minor -> B .assertThatLeakValueIs(CoreMetrics.NEW_RELIABILITY_RATING, Rating.B); } @Test public void test_new_security_rating() { withNoIssues().assertThatLeakValueIs(CoreMetrics.NEW_SECURITY_RATING, Rating.A); with( newGroup(RuleType.VULNERABILITY).setSeverity(Severity.INFO).setCount(3).setInLeak(true), newGroup(RuleType.VULNERABILITY).setSeverity(Severity.MINOR).setCount(1).setInLeak(true), // not in leak newGroup(RuleType.VULNERABILITY).setSeverity(Severity.BLOCKER).setInLeak(false), // not vulnerability newGroup(RuleType.CODE_SMELL).setSeverity(Severity.BLOCKER).setInLeak(true), // exclude resolved newResolvedGroup(RuleType.VULNERABILITY).setSeverity(Severity.BLOCKER).setInLeak(true)) // highest severity of bugs on leak period is minor -> B .assertThatLeakValueIs(CoreMetrics.NEW_SECURITY_RATING, Rating.B); } @Test public void test_new_security_review_rating() { with( newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED).setCount(3).setInLeak(true), newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW).setCount(1).setInLeak(true), // not in leak newGroup(RuleType.SECURITY_HOTSPOT).setSeverity(Issue.STATUS_TO_REVIEW).setInLeak(false)) .assertThatLeakValueIs(NEW_SECURITY_REVIEW_RATING, Rating.B); withNoIssues() .assertThatLeakValueIs(NEW_SECURITY_REVIEW_RATING, Rating.A); } @Test public void test_new_security_hotspots_reviewed() { with( newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED).setCount(3).setInLeak(true), newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW).setCount(1).setInLeak(true), // not in leak newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW).setCount(5).setInLeak(false)) .assertThatLeakValueIs(CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED, 75.0); withNoIssues() .assertNoLeakValue(CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED); } @Test public void test_new_security_hotspots_reviewed_status() { with( newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED).setCount(3).setInLeak(true), newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW).setCount(1).setInLeak(true), // not in leak newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW).setCount(5).setInLeak(false)) .assertThatLeakValueIs(CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS, 3.0); withNoIssues() .assertThatLeakValueIs(CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS, 0.0); } @Test public void test_new_security_hotspots_to_review_status() { with( newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED).setCount(3).setInLeak(true), newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW).setCount(1).setInLeak(true), // not in leak newGroup(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW).setCount(5).setInLeak(false)) .assertThatLeakValueIs(CoreMetrics.NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS, 1.0); withNoIssues() .assertThatLeakValueIs(CoreMetrics.NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS, 0.0); } @Test public void test_new_sqale_debt_ratio_and_new_maintainability_rating() { withNoIssues() .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.A); // technical_debt not computed with(CoreMetrics.NEW_DEVELOPMENT_COST, 0) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.A); with(CoreMetrics.NEW_DEVELOPMENT_COST, 20) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.A); // development_cost not computed with(CoreMetrics.NEW_TECHNICAL_DEBT, 0) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.A); with(CoreMetrics.NEW_TECHNICAL_DEBT, 20) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.A); // input measures are available with(CoreMetrics.NEW_TECHNICAL_DEBT, 20.0) .and(CoreMetrics.NEW_DEVELOPMENT_COST, 0.0) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 0.0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.A); with(CoreMetrics.NEW_TECHNICAL_DEBT, 20.0) .and(CoreMetrics.NEW_DEVELOPMENT_COST, 160.0) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 12.5) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.C); with(CoreMetrics.NEW_TECHNICAL_DEBT, 20.0) .and(CoreMetrics.NEW_DEVELOPMENT_COST, 10.0D) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 200.0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.E); // A is 5% --> min debt is exactly 200*0.05=10 with(CoreMetrics.NEW_DEVELOPMENT_COST, 200.0) .and(CoreMetrics.NEW_TECHNICAL_DEBT, 10.0) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 5.0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.A); with(CoreMetrics.NEW_TECHNICAL_DEBT, 0.0) .and(CoreMetrics.NEW_DEVELOPMENT_COST, 0.0) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 0.0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.A); with(CoreMetrics.NEW_TECHNICAL_DEBT, 0.0) .and(CoreMetrics.NEW_DEVELOPMENT_COST, 80.0) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 0.0); with(CoreMetrics.NEW_TECHNICAL_DEBT, -20.0) .and(CoreMetrics.NEW_DEVELOPMENT_COST, 0.0) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 0.0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.A); // bug, debt can't be negative with(CoreMetrics.NEW_TECHNICAL_DEBT, -20.0) .and(CoreMetrics.NEW_DEVELOPMENT_COST, 80.0) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 0.0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.A); // bug, cost can't be negative with(CoreMetrics.NEW_TECHNICAL_DEBT, 20.0) .and(CoreMetrics.NEW_DEVELOPMENT_COST, -80.0) .assertThatLeakValueIs(CoreMetrics.NEW_SQALE_DEBT_RATIO, 0.0) .assertThatLeakValueIs(CoreMetrics.NEW_MAINTAINABILITY_RATING, Rating.A); } private Verifier with(IssueGroupDto... groups) { return new Verifier(groups); } private Verifier withNoIssues() { return new Verifier(new IssueGroupDto[0]); } private Verifier with(Metric metric, double value) { return new Verifier(new IssueGroupDto[0]).and(metric, value); } private Verifier with(Metric metric, String value) { return new Verifier(new IssueGroupDto[0]).andText(metric, value); } private class Verifier { private final IssueGroupDto[] groups; private final InitialValues initialValues = new InitialValues(); private Verifier(IssueGroupDto[] groups) { this.groups = groups; } Verifier and(Metric metric, double value) { this.initialValues.values.put(metric, value); return this; } Verifier andText(Metric metric, String value) { this.initialValues.text.put(metric, value); return this; } Verifier assertThatValueIs(Metric metric, double expectedValue) { TestContext context = run(metric, false); assertThat(context.doubleValue).isNotNull().isEqualTo(expectedValue); return this; } Verifier assertThatLeakValueIs(Metric metric, double expectedValue) { TestContext context = run(metric, true); assertThat(context.doubleValue).isNotNull().isEqualTo(expectedValue); return this; } Verifier assertThatLeakValueIs(Metric metric, Rating expectedRating) { TestContext context = run(metric, true); assertThat(context.ratingValue).isNotNull().isEqualTo(expectedRating); return this; } Verifier assertNoLeakValue(Metric metric) { TestContext context = run(metric, true); assertThat(context.ratingValue).isNull(); return this; } Verifier assertThatValueIs(Metric metric, Rating expectedValue) { TestContext context = run(metric, false); assertThat(context.ratingValue).isNotNull().isEqualTo(expectedValue); return this; } Verifier assertNoValue(Metric metric) { TestContext context = run(metric, false); assertThat(context.ratingValue).isNull(); return this; } private TestContext run(Metric metric, boolean expectLeakFormula) { MeasureUpdateFormula formula = underTest.getFormulas().stream() .filter(f -> f.getMetric().getKey().equals(metric.getKey())) .findFirst() .get(); assertThat(formula.isOnLeak()).isEqualTo(expectLeakFormula); TestContext context = new TestContext(formula.getDependentMetrics(), initialValues); formula.compute(context, newIssueCounter(groups)); return context; } } private static IssueCounter newIssueCounter(IssueGroupDto... issues) { return new IssueCounter(asList(issues)); } private static IssueGroupDto newGroup() { return newGroup(RuleType.CODE_SMELL); } private static IssueGroupDto newGroup(RuleType ruleType) { IssueGroupDto dto = new IssueGroupDto(); // set non-null fields dto.setRuleType(ruleType.getDbConstant()); dto.setCount(1); dto.setEffort(0.0); dto.setSeverity(Severity.INFO); dto.setStatus(Issue.STATUS_OPEN); dto.setInLeak(false); return dto; } private static IssueGroupDto newResolvedGroup(RuleType ruleType) { return newGroup(ruleType).setResolution(Issue.RESOLUTION_FALSE_POSITIVE).setStatus(Issue.STATUS_CLOSED); } private static IssueGroupDto newResolvedGroup(String resolution, String status) { return newGroup().setResolution(resolution).setStatus(status); } private static class TestContext implements MeasureUpdateFormula.Context { private final Set<Metric> dependentMetrics; private final InitialValues initialValues; private Double doubleValue; private Rating ratingValue; private TestContext(Collection<Metric> dependentMetrics, InitialValues initialValues) { this.dependentMetrics = new HashSet<>(dependentMetrics); this.initialValues = initialValues; } @Override public List<Double> getChildrenValues() { return initialValues.childrenValues; } @Override public long getChildrenHotspotsReviewed() { return initialValues.childrenHotspotsReviewed; } @Override public long getChildrenHotspotsToReview() { return initialValues.childrenHotspotsToReview; } @Override public long getChildrenNewHotspotsReviewed() { return initialValues.childrenNewHotspotsReviewed; } @Override public long getChildrenNewHotspotsToReview() { return initialValues.childrenNewHotspotsToReview; } @Override public ComponentDto getComponent() { throw new UnsupportedOperationException(); } @Override public DebtRatingGrid getDebtRatingGrid() { return new DebtRatingGrid(new double[] {0.05, 0.1, 0.2, 0.5}); } @Override public Optional<Double> getValue(Metric metric) { if (!dependentMetrics.contains(metric)) { throw new IllegalStateException("Metric " + metric.getKey() + " is not declared as a dependency"); } if (initialValues.values.containsKey(metric)) { return Optional.of(initialValues.values.get(metric)); } return Optional.empty(); } @Override public Optional<String> getText(Metric metric) { if (initialValues.text.containsKey(metric)) { return Optional.of(initialValues.text.get(metric)); } return Optional.empty(); } @Override public void setValue(double value) { this.doubleValue = value; } @Override public void setValue(Rating value) { this.ratingValue = value; } } private class InitialValues { private final Map<Metric, Double> values = new HashMap<>(); private final List<Double> childrenValues = new ArrayList<>(); private final Map<Metric, String> text = new HashMap<>(); private long childrenHotspotsReviewed = 0; private long childrenNewHotspotsReviewed = 0; private long childrenHotspotsToReview = 0; private long childrenNewHotspotsToReview = 0; } private class HierarchyTester { private final Metric metric; private final InitialValues initialValues; private final MeasureUpdateFormula formula; public HierarchyTester(Metric metric) { this.metric = metric; this.initialValues = new InitialValues(); this.formula = underTest.getFormulas().stream().filter(f -> f.getMetric().equals(metric)).findAny().get(); } public HierarchyTester withValue(Metric metric, Double value) { this.initialValues.values.put(metric, value); return this; } public HierarchyTester withChildrenHotspotsCounts(long childrenHotspotsReviewed, long childrenNewHotspotsReviewed, long childrenHotspotsToReview, long childrenNewHotspotsToReview) { this.initialValues.childrenHotspotsReviewed = childrenHotspotsReviewed; this.initialValues.childrenNewHotspotsReviewed = childrenNewHotspotsReviewed; this.initialValues.childrenHotspotsToReview = childrenHotspotsToReview; this.initialValues.childrenNewHotspotsToReview = childrenNewHotspotsToReview; return this; } public HierarchyTester withValue(Double value) { return withValue(metric, value); } public HierarchyTester withChildrenValues(Double... values) { this.initialValues.childrenValues.addAll(asList(values)); return this; } public HierarchyTester expectedResult(@Nullable Double expected) { TestContext ctx = run(); assertThat(ctx.doubleValue).isEqualTo(expected); return this; } public HierarchyTester expectedRating(@Nullable Rating rating) { TestContext ctx = run(); assertThat(ctx.ratingValue).isEqualTo(rating); return this; } private TestContext run() { List<Metric> deps = new LinkedList<>(formula.getDependentMetrics()); deps.add(formula.getMetric()); deps.addAll(initialValues.values.keySet()); deps.addAll(initialValues.text.keySet()); TestContext context = new TestContext(deps, initialValues); formula.computeHierarchy(context); return context; } } }
46,256
39.683377
149
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentTreeSortTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.ws; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import java.util.List; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric.ValueType; import org.sonar.api.resources.Qualifiers; import org.sonar.core.util.Uuids; import org.sonar.db.component.ComponentDto; import org.sonar.db.measure.LiveMeasureDto; import org.sonar.db.metric.MetricDto; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.metric.MetricTesting.newMetricDto; import static org.sonar.server.measure.ws.ComponentTreeAction.METRIC_PERIOD_SORT; import static org.sonar.server.measure.ws.ComponentTreeAction.METRIC_SORT; import static org.sonar.server.measure.ws.ComponentTreeAction.NAME_SORT; import static org.sonar.server.measure.ws.ComponentTreeAction.PATH_SORT; import static org.sonar.server.measure.ws.ComponentTreeAction.QUALIFIER_SORT; import static org.sonar.server.measure.ws.ComponentTreeData.Measure.createFromMeasureDto; public class ComponentTreeSortTest { private static final String NUM_METRIC_KEY = "violations"; private static final String NEW_METRIC_KEY = "new_violations"; private static final String TEXT_METRIC_KEY = "sqale_index"; private List<MetricDto> metrics; private Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric; private List<ComponentDto> components; @Before public void setUp() { components = newArrayList( newComponentWithoutSnapshotId("name-1", "qualifier-2", "path-9"), newComponentWithoutSnapshotId("name-3", "qualifier-3", "path-8"), newComponentWithoutSnapshotId("name-2", "qualifier-4", "path-7"), newComponentWithoutSnapshotId("name-4", "qualifier-5", "path-6"), newComponentWithoutSnapshotId("name-7", "qualifier-6", "path-5"), newComponentWithoutSnapshotId("name-6", "qualifier-7", "path-4"), newComponentWithoutSnapshotId("name-5", "qualifier-8", "path-3"), newComponentWithoutSnapshotId("name-9", "qualifier-9", "path-2"), newComponentWithoutSnapshotId("name-8", "qualifier-1", "path-1")); MetricDto violationsMetric = newMetricDto() .setKey(NUM_METRIC_KEY) .setValueType(ValueType.INT.name()); MetricDto newViolationsMetric = newMetricDto() .setKey(NEW_METRIC_KEY) .setValueType(ValueType.INT.name()); MetricDto sqaleIndexMetric = newMetricDto() .setKey(TEXT_METRIC_KEY) .setValueType(ValueType.STRING.name()); metrics = newArrayList(violationsMetric, sqaleIndexMetric, newViolationsMetric); measuresByComponentUuidAndMetric = HashBasedTable.create(components.size(), 2); // same number than path field double currentValue = 9; for (ComponentDto component : components) { measuresByComponentUuidAndMetric.put(component.uuid(), violationsMetric, createFromMeasureDto(new LiveMeasureDto().setValue(currentValue))); measuresByComponentUuidAndMetric.put(component.uuid(), newViolationsMetric, createFromMeasureDto(new LiveMeasureDto().setValue(currentValue))); measuresByComponentUuidAndMetric.put(component.uuid(), sqaleIndexMetric, createFromMeasureDto(new LiveMeasureDto().setData(String.valueOf(currentValue)))); currentValue--; } } @Test public void sort_by_names() { ComponentTreeRequest wsRequest = newRequest(singletonList(NAME_SORT), true, null); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("name") .containsExactly("name-1", "name-2", "name-3", "name-4", "name-5", "name-6", "name-7", "name-8", "name-9"); } @Test public void sort_by_qualifier() { ComponentTreeRequest wsRequest = newRequest(singletonList(QUALIFIER_SORT), false, null); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("qualifier") .containsExactly("qualifier-9", "qualifier-8", "qualifier-7", "qualifier-6", "qualifier-5", "qualifier-4", "qualifier-3", "qualifier-2", "qualifier-1"); } @Test public void sort_by_path() { ComponentTreeRequest wsRequest = newRequest(singletonList(PATH_SORT), true, null); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("path") .containsExactly("path-1", "path-2", "path-3", "path-4", "path-5", "path-6", "path-7", "path-8", "path-9"); } @Test public void sort_by_numerical_metric_key_ascending() { components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure")); ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_SORT), true, NUM_METRIC_KEY); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("path") .containsExactly("path-1", "path-2", "path-3", "path-4", "path-5", "path-6", "path-7", "path-8", "path-9", "path-without-measure"); } @Test public void sort_by_numerical_metric_key_descending() { components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure")); ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_SORT), false, NUM_METRIC_KEY); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("path") .containsExactly("path-9", "path-8", "path-7", "path-6", "path-5", "path-4", "path-3", "path-2", "path-1", "path-without-measure"); } @Test public void sort_by_name_ascending_in_case_of_equality() { components = newArrayList( newComponentWithoutSnapshotId("PROJECT 12", Qualifiers.PROJECT, "PROJECT_PATH_1"), newComponentWithoutSnapshotId("PROJECT 11", Qualifiers.PROJECT, "PROJECT_PATH_1"), newComponentWithoutSnapshotId("PROJECT 0", Qualifiers.PROJECT, "PROJECT_PATH_2")); ComponentTreeRequest wsRequest = newRequest(newArrayList(PATH_SORT), false, null); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("name").containsExactly("PROJECT 0", "PROJECT 11", "PROJECT 12"); } @Test public void sort_by_alert_status_ascending() { components = newArrayList( newComponentWithoutSnapshotId("PROJECT OK 1", Qualifiers.PROJECT, "PROJECT_OK_PATH_1"), newComponentWithoutSnapshotId("PROJECT ERROR 1", Qualifiers.PROJECT, "PROJECT_ERROR_PATH_1"), newComponentWithoutSnapshotId("PROJECT OK 2", Qualifiers.PROJECT, "PROJECT_OK_PATH_2"), newComponentWithoutSnapshotId("PROJECT ERROR 2", Qualifiers.PROJECT, "PROJECT_ERROR_PATH_2")); metrics = singletonList(newMetricDto() .setKey(CoreMetrics.ALERT_STATUS_KEY) .setValueType(ValueType.LEVEL.name())); measuresByComponentUuidAndMetric = HashBasedTable.create(); List<String> statuses = newArrayList("OK", "ERROR"); for (int i = 0; i < components.size(); i++) { ComponentDto component = components.get(i); String alertStatus = statuses.get(i % 2); measuresByComponentUuidAndMetric.put(component.uuid(), metrics.get(0), createFromMeasureDto(new LiveMeasureDto().setData(alertStatus))); } ComponentTreeRequest wsRequest = newRequest(newArrayList(METRIC_SORT, NAME_SORT), true, CoreMetrics.ALERT_STATUS_KEY); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("name").containsExactly( "PROJECT ERROR 1", "PROJECT ERROR 2", "PROJECT OK 1", "PROJECT OK 2"); } @Test public void sort_by_numerical_metric_period_1_key_descending() { components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure")); ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_PERIOD_SORT), false, NEW_METRIC_KEY).setMetricPeriodSort(1); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("path") .containsExactly("path-9", "path-8", "path-7", "path-6", "path-5", "path-4", "path-3", "path-2", "path-1", "path-without-measure"); } @Test public void sort_by_numerical_metric_period_1_key_ascending() { components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure")); ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_PERIOD_SORT), true, NEW_METRIC_KEY).setMetricPeriodSort(1); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("path") .containsExactly("path-1", "path-2", "path-3", "path-4", "path-5", "path-6", "path-7", "path-8", "path-9", "path-without-measure"); } @Test public void sort_by_numerical_metric_period_5_key() { components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure")); ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_SORT), false, NUM_METRIC_KEY).setMetricPeriodSort(5); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("path") .containsExactly("path-9", "path-8", "path-7", "path-6", "path-5", "path-4", "path-3", "path-2", "path-1", "path-without-measure"); } @Test public void sort_by_textual_metric_key_ascending() { components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure")); ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_SORT), true, TEXT_METRIC_KEY); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("path") .containsExactly("path-1", "path-2", "path-3", "path-4", "path-5", "path-6", "path-7", "path-8", "path-9", "path-without-measure"); } @Test public void sort_by_textual_metric_key_descending() { components.add(newComponentWithoutSnapshotId("name-without-measure", "qualifier-without-measure", "path-without-measure")); ComponentTreeRequest wsRequest = newRequest(singletonList(METRIC_SORT), false, TEXT_METRIC_KEY); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("path") .containsExactly("path-9", "path-8", "path-7", "path-6", "path-5", "path-4", "path-3", "path-2", "path-1", "path-without-measure"); } @Test public void sort_on_multiple_fields() { components = newArrayList( newComponentWithoutSnapshotId("name-1", "qualifier-1", "path-2"), newComponentWithoutSnapshotId("name-1", "qualifier-1", "path-3"), newComponentWithoutSnapshotId("name-1", "qualifier-1", "path-1")); ComponentTreeRequest wsRequest = newRequest(newArrayList(NAME_SORT, QUALIFIER_SORT, PATH_SORT), true, null); List<ComponentDto> result = sortComponents(wsRequest); assertThat(result).extracting("path") .containsExactly("path-1", "path-2", "path-3"); } private List<ComponentDto> sortComponents(ComponentTreeRequest wsRequest) { return ComponentTreeSort.sortComponents(components, wsRequest, metrics, measuresByComponentUuidAndMetric); } private static ComponentDto newComponentWithoutSnapshotId(String name, String qualifier, String path) { return new ComponentDto() .setUuid(Uuids.createFast()) .setName(name) .setQualifier(qualifier) .setPath(path); } private static ComponentTreeRequest newRequest(List<String> sortFields, boolean isAscending, @Nullable String metricKey) { return new ComponentTreeRequest() .setAsc(isAscending) .setSort(sortFields) .setMetricSort(metricKey); } }
12,562
45.357934
161
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/MeasureValueFormatterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.ws; import org.junit.Test; import org.sonar.api.measures.Metric; import org.sonar.db.measure.MeasureDto; import org.sonar.db.metric.MetricDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.measures.Metric.ValueType.BOOL; import static org.sonar.api.measures.Metric.ValueType.DATA; import static org.sonar.api.measures.Metric.ValueType.FLOAT; import static org.sonar.api.measures.Metric.ValueType.INT; import static org.sonar.api.measures.Metric.ValueType.MILLISEC; import static org.sonar.api.measures.Metric.ValueType.PERCENT; import static org.sonar.api.measures.Metric.ValueType.WORK_DUR; import static org.sonar.db.metric.MetricTesting.newMetricDto; import static org.sonar.server.measure.ws.MeasureValueFormatter.formatMeasureValue; import static org.sonar.server.measure.ws.MeasureValueFormatter.formatNumericalValue; public class MeasureValueFormatterTest { @Test public void test_formatNumericalValue() { assertThat(formatNumericalValue(-1.0d, newMetric(BOOL))).isEqualTo("false"); assertThat(formatNumericalValue(1.0d, newMetric(BOOL))).isEqualTo("true"); assertThat(formatNumericalValue(1_000.123d, newMetric(FLOAT))).isEqualTo("1000.123"); assertThat(formatNumericalValue(1_000.0d, newMetric(INT))).isEqualTo("1000"); assertThat(formatNumericalValue(1_000.0d, newMetric(WORK_DUR))).isEqualTo("1000"); assertThat(formatNumericalValue(6_000_000_000_000.0d, newMetric(MILLISEC))).isEqualTo("6000000000000"); } @Test public void test_formatMeasureValue() { assertThat(formatMeasureValue(newNumericMeasure(-1.0d), newMetric(BOOL))).isEqualTo("false"); assertThat(formatMeasureValue(newNumericMeasure(1.0d), newMetric(BOOL))).isEqualTo("true"); assertThat(formatMeasureValue(newNumericMeasure(1000.123d), newMetric(PERCENT))).isEqualTo("1000.123"); assertThat(formatMeasureValue(newNumericMeasure(1000.0d), newMetric(WORK_DUR))).isEqualTo("1000"); assertThat(formatMeasureValue(newNumericMeasure(6_000_000_000_000.0d), newMetric(MILLISEC))).isEqualTo("6000000000000"); assertThat(formatMeasureValue(newTextMeasure("text-value"), newMetric(DATA))).isEqualTo("text-value"); } @Test public void fail_if_text_value_type_for_numeric_formatter() { assertThatThrownBy(() -> formatNumericalValue(42.0d, newMetric(DATA))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unsupported metric type 'DATA' for numerical value"); } private static MetricDto newMetric(Metric.ValueType valueType) { return newMetricDto().setValueType(valueType.name()); } private static MeasureDto newNumericMeasure(Double value) { return new MeasureDto().setValue(value); } private static MeasureDto newTextMeasure(String data) { return new MeasureDto().setData(data); } }
3,754
44.792683
124
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/MeasuresWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class MeasuresWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new MeasuresWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(5); } }
1,267
35.228571
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/MeasuresWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.ws; import org.junit.Test; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; public class MeasuresWsTest { private MeasuresWs underTest = new MeasuresWs(new ComponentAction(null, null, null)); @Test public void define_ws() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/measures"); assertThat(controller).isNotNull(); assertThat(controller.since()).isEqualTo("5.4"); } }
1,428
33.853659
87
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/prMeasureFixTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.ws; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.db.measure.LiveMeasureDto; import org.sonar.db.metric.MetricDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.measures.CoreMetrics.BUGS_KEY; import static org.sonar.api.measures.CoreMetrics.MINOR_VIOLATIONS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_BUGS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_MINOR_VIOLATIONS_KEY; public class prMeasureFixTest { @Test public void should_add_replacement_metrics() { List<String> metricList = new ArrayList<>(Arrays.asList(NEW_BUGS_KEY, NEW_MINOR_VIOLATIONS_KEY)); PrMeasureFix.addReplacementMetricKeys(metricList); assertThat(metricList).contains(BUGS_KEY, NEW_BUGS_KEY, MINOR_VIOLATIONS_KEY, NEW_MINOR_VIOLATIONS_KEY); } @Test public void should_remove_metrics_not_initially_requested() { Set<String> originalMetricList = new HashSet<>(Arrays.asList(NEW_BUGS_KEY, MINOR_VIOLATIONS_KEY, NEW_MINOR_VIOLATIONS_KEY)); MetricDto dto1 = new MetricDto().setKey(BUGS_KEY).setUuid("1"); MetricDto dto2 = new MetricDto().setKey(NEW_BUGS_KEY).setUuid("2"); MetricDto dto3 = new MetricDto().setKey(MINOR_VIOLATIONS_KEY).setUuid("3"); MetricDto dto4 = new MetricDto().setKey(NEW_MINOR_VIOLATIONS_KEY).setUuid("4"); List<MetricDto> metricList = new ArrayList<>(Arrays.asList(dto1, dto2, dto3, dto4)); PrMeasureFix.removeMetricsNotRequested(metricList, originalMetricList); assertThat(metricList).containsOnly(dto2, dto3, dto4); } @Test public void should_transform_measures() { Set<String> requestedKeys = new HashSet<>(Arrays.asList(NEW_BUGS_KEY, MINOR_VIOLATIONS_KEY, NEW_MINOR_VIOLATIONS_KEY)); MetricDto bugsMetric = new MetricDto().setKey(BUGS_KEY).setUuid("1"); MetricDto newBugsMetric = new MetricDto().setKey(NEW_BUGS_KEY).setUuid("2"); MetricDto violationsMetric = new MetricDto().setKey(MINOR_VIOLATIONS_KEY).setUuid("3"); MetricDto newViolationsMetric = new MetricDto().setKey(NEW_MINOR_VIOLATIONS_KEY).setUuid("4"); List<MetricDto> metricList = Arrays.asList(bugsMetric, newBugsMetric, violationsMetric, newViolationsMetric); LiveMeasureDto bugs = createLiveMeasure(bugsMetric.getUuid(), 10.0); LiveMeasureDto newBugs = createLiveMeasure(newBugsMetric.getUuid(), 5.0); LiveMeasureDto violations = createLiveMeasure(violationsMetric.getUuid(), 20.0); LiveMeasureDto newViolations = createLiveMeasure(newViolationsMetric.getUuid(), 3.0); Map<MetricDto, LiveMeasureDto> measureByMetric = new HashMap<>(); measureByMetric.put(bugsMetric, bugs); measureByMetric.put(newBugsMetric, newBugs); measureByMetric.put(violationsMetric, violations); measureByMetric.put(newViolationsMetric, newViolations); PrMeasureFix.createReplacementMeasures(metricList, measureByMetric, requestedKeys); assertThat(measureByMetric.entrySet()).extracting(e -> e.getKey().getKey(), e -> e.getValue().getValue()) .containsOnly(tuple(NEW_BUGS_KEY, 10.0), tuple(MINOR_VIOLATIONS_KEY, 20.0), tuple(NEW_MINOR_VIOLATIONS_KEY, 20.0)); } private static LiveMeasureDto createLiveMeasure(String metricUuid, @Nullable Double value) { return new LiveMeasureDto().setMetricUuid(metricUuid).setValue(value); } }
4,432
44.701031
128
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/MetricsWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.metric.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class MetricsWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new MetricsWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(3); } }
1,264
35.142857
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/MetricsWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.metric.ws; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class MetricsWsTest { private final DbClient dbClient = mock(DbClient.class); private final MetricsWs underTest = new MetricsWs( new SearchAction(dbClient), new TypesAction()); @Test public void define_ws() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/metrics"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.actions()).hasSize(2); } }
1,627
32.22449
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/TypesActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.metric.ws; import org.junit.Test; import org.sonar.api.measures.Metric; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; public class TypesActionTest { private TypesAction underTest = new TypesAction(); private WsActionTester tester = new WsActionTester(underTest); @Test public void validate_content() { TestResponse response = tester.newRequest().execute(); assertThat(response.getInput()).contains(Metric.ValueType.names()); } }
1,417
33.585366
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/monitoring/MonitoringWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.monitoring; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class MonitoringWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new MonitoringWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(3); } }
1,271
35.342857
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/monitoring/MonitoringWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.monitoring; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; public class MonitoringWsTest { private final MonitoringWs underTest = new MonitoringWs(new MonitoringWsAction() { @Override public void handle(Request request, Response response) { // nothing to do } @Override public void define(WebService.NewController context) { context.createAction("foo").setHandler(this); } }); @Test public void define_controller() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/monitoring"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.since()).isEqualTo("9.3"); assertThat(controller.actions()).hasSize(1); } }
1,866
31.754386
84
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/NewCodePeriodsWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.newcodeperiod.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class NewCodePeriodsWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new NewCodePeriodsWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(5); } }
1,285
35.742857
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/NewCodePeriodsWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.newcodeperiod.ws; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.core.documentation.DocumentationLinkGenerator; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class NewCodePeriodsWsTest { private String actionKey = randomAlphanumeric(10); private DocumentationLinkGenerator documentationLinkGenerator = mock(DocumentationLinkGenerator.class); private NewCodePeriodsWs underTest = new NewCodePeriodsWs( documentationLinkGenerator, new NewCodePeriodsWsAction() { @Override public void define(WebService.NewController context) { context.createAction(actionKey).setHandler(this); } @Override public void handle(Request request, Response response) { } } ); @Test public void define_ws() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/new_code_periods"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.actions()).hasSize(1); } }
2,201
33.40625
105
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/DispatchersImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification.ws; import org.junit.Test; import org.sonar.api.notifications.NotificationChannel; import org.sonar.server.issue.notification.FPOrWontFixNotificationHandler; import org.sonar.server.issue.notification.MyNewIssuesNotificationHandler; import org.sonar.server.issue.notification.NewIssuesNotificationHandler; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.qualitygate.notification.QGChangeNotificationHandler; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION; import static org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION; public class DispatchersImplTest { private NotificationCenter notificationCenter = new NotificationCenter( new NotificationDispatcherMetadata[] { NotificationDispatcherMetadata.create(MyNewIssuesNotificationHandler.KEY) .setProperty(GLOBAL_NOTIFICATION, "true") .setProperty(PER_PROJECT_NOTIFICATION, "true"), NotificationDispatcherMetadata.create(NewIssuesNotificationHandler.KEY) .setProperty(GLOBAL_NOTIFICATION, "false"), NotificationDispatcherMetadata.create(QGChangeNotificationHandler.KEY) .setProperty(GLOBAL_NOTIFICATION, "true") .setProperty(PER_PROJECT_NOTIFICATION, "true"), NotificationDispatcherMetadata.create(FPOrWontFixNotificationHandler.KEY) .setProperty(GLOBAL_NOTIFICATION, "false") .setProperty(PER_PROJECT_NOTIFICATION, "true") }, new NotificationChannel[] {}); private DispatchersImpl underTest = new DispatchersImpl(notificationCenter); @Test public void get_sorted_global_dispatchers() { underTest.start(); assertThat(underTest.getGlobalDispatchers()).containsExactly( QGChangeNotificationHandler.KEY, MyNewIssuesNotificationHandler.KEY); } @Test public void get_sorted_project_dispatchers() { underTest.start(); assertThat(underTest.getProjectDispatchers()).containsExactly( QGChangeNotificationHandler.KEY, FPOrWontFixNotificationHandler.KEY, MyNewIssuesNotificationHandler.KEY); } }
3,052
42
111
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/NotificationCenterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification.ws; import org.junit.Before; import org.junit.Test; import org.sonar.api.notifications.NotificationChannel; import org.sonar.server.notification.NotificationDispatcherMetadata; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class NotificationCenterTest { private NotificationChannel emailChannel = mock(NotificationChannel.class); private NotificationChannel gtalkChannel = mock(NotificationChannel.class); private NotificationCenter underTest; @Before public void init() { NotificationDispatcherMetadata metadata1 = NotificationDispatcherMetadata.create("Dispatcher1").setProperty("global", "true").setProperty("on-project", "true"); NotificationDispatcherMetadata metadata2 = NotificationDispatcherMetadata.create("Dispatcher2").setProperty("global", "true"); NotificationDispatcherMetadata metadata3 = NotificationDispatcherMetadata.create("Dispatcher3").setProperty("global", "FOO").setProperty("on-project", "BAR"); underTest = new NotificationCenter( new NotificationDispatcherMetadata[] {metadata1, metadata2, metadata3}, new NotificationChannel[] {emailChannel, gtalkChannel} ); } @Test public void shouldReturnChannels() { assertThat(underTest.getChannels()).containsOnly(emailChannel, gtalkChannel); } @Test public void shouldReturnDispatcherKeysForSpecificPropertyValue() { assertThat(underTest.getDispatcherKeysForProperty("global", "true")).containsOnly("Dispatcher1", "Dispatcher2"); } @Test public void shouldReturnDispatcherKeysForExistenceOfProperty() { assertThat(underTest.getDispatcherKeysForProperty("on-project", null)).containsOnly("Dispatcher1", "Dispatcher3"); } @Test public void testDefaultConstructors() { underTest = new NotificationCenter(new NotificationChannel[] {emailChannel}); assertThat(underTest.getChannels()).hasSize(1); underTest = new NotificationCenter(); assertThat(underTest.getChannels()).isEmpty(); underTest = new NotificationCenter(new NotificationDispatcherMetadata[] {NotificationDispatcherMetadata.create("Dispatcher1").setProperty("global", "true")}); assertThat(underTest.getChannels()).isEmpty(); assertThat(underTest.getDispatcherKeysForProperty("global", null)).hasSize(1); } }
3,203
40.076923
164
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/NotificationWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class NotificationWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new NotificationWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(7); } }
1,280
35.6
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/NotificationsWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification.ws; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Controller; import static org.assertj.core.api.Assertions.assertThat; public class NotificationsWsTest { private NotificationsWsAction action = new FakeNotificationAction(); private NotificationsWsAction[] actions = {action}; private NotificationsWs underTest = new NotificationsWs(actions); @Test public void definition() { WebService.Context context = new WebService.Context(); underTest.define(context); Controller controller = context.controller("api/notifications"); assertThat(controller.path()).isEqualTo("api/notifications"); } private static class FakeNotificationAction implements NotificationsWsAction { @Override public void define(WebService.NewController context) { context.createAction("fake") .setHandler(this); } @Override public void handle(Request request, Response response) { // do nothing } } }
1,975
33.068966
80
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ApplyPermissionTemplateQueryTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission; import java.util.Collections; import org.junit.Test; import org.sonar.server.exceptions.BadRequestException; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.permission.ApplyPermissionTemplateQuery.create; public class ApplyPermissionTemplateQueryTest { @Test public void should_populate_with_params() { ApplyPermissionTemplateQuery query = create("my_template_key", newArrayList("1", "2", "3")); assertThat(query.getTemplateUuid()).isEqualTo("my_template_key"); assertThat(query.getComponentKeys()).containsOnly("1", "2", "3"); } @Test public void should_invalidate_query_with_empty_name() { assertThatThrownBy(() -> create("", newArrayList("1", "2", "3"))) .isInstanceOf(BadRequestException.class) .hasMessage("Permission template is mandatory"); } @Test public void should_invalidate_query_with_no_components() { assertThatThrownBy(() -> create("my_template_key", Collections.emptyList())) .isInstanceOf(BadRequestException.class) .hasMessage("No project provided. Please provide at least one project."); } }
2,128
37.017857
96
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/PermissionsWsModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class PermissionsWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new PermissionsWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(26); } }
1,277
35.514286
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/PermissionsWsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; public class PermissionsWsTest { private PermissionsWs underTest = new PermissionsWs(new PermissionsWsAction() { @Override public void define(WebService.NewController context) { context.createAction("foo").setHandler(this); } @Override public void handle(Request request, Response response) { } }); @Test public void define_controller() { WebService.Context context = new WebService.Context(); underTest.define(context); WebService.Controller controller = context.controller("api/permissions"); assertThat(controller).isNotNull(); assertThat(controller.description()).isNotEmpty(); assertThat(controller.since()).isEqualTo("3.7"); assertThat(controller.actions()).hasSize(1); } }
1,846
31.403509
81
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/PermissionTemplateDtoToPermissionTemplateResponseTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.test.TestUtils.hasOnlyPrivateConstructors; public class PermissionTemplateDtoToPermissionTemplateResponseTest { @Test public void only_private_constructors() { assertThat(hasOnlyPrivateConstructors(PermissionTemplateDtoToPermissionTemplateResponse.class)).isTrue(); } }
1,281
36.705882
109
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesDataTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import com.google.common.collect.HashBasedTable; import org.junit.Test; import org.sonar.server.permission.DefaultTemplatesResolverImpl; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto; public class SearchTemplatesDataTest { SearchTemplatesData.Builder underTest = SearchTemplatesData.builder() .defaultTemplates(new DefaultTemplatesResolverImpl.ResolvedDefaultTemplates("template_uuid", null, null)) .templates(singletonList(newPermissionTemplateDto())) .userCountByTemplateUuidAndPermission(HashBasedTable.create()) .groupCountByTemplateUuidAndPermission(HashBasedTable.create()) .withProjectCreatorByTemplateUuidAndPermission(HashBasedTable.create()); @Test public void fail_if_templates_is_null() { assertThatThrownBy(() -> { underTest.templates(null); underTest.build(); }) .isInstanceOf(IllegalStateException.class); } @Test public void fail_if_default_templates_are_null() { assertThatThrownBy(() -> { underTest.defaultTemplates(null); underTest.build(); }) .isInstanceOf(IllegalStateException.class); } @Test public void fail_if_user_count_is_null() { assertThatThrownBy(() -> { underTest.userCountByTemplateUuidAndPermission(null); underTest.build(); }) .isInstanceOf(IllegalStateException.class); } @Test public void fail_if_group_count_is_null() { assertThatThrownBy(() -> { underTest.groupCountByTemplateUuidAndPermission(null); underTest.build(); }) .isInstanceOf(IllegalStateException.class); } @Test public void fail_if_with_project_creators_is_null() { assertThatThrownBy(() -> { underTest.withProjectCreatorByTemplateUuidAndPermission(null); underTest.build(); }) .isInstanceOf(IllegalStateException.class); } }
2,889
31.47191
109
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/ChangeLogLevelActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.ce.http.CeHttpClient; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.log.ServerLogging; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class ChangeLogLevelActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private ServerLogging serverLogging = mock(ServerLogging.class); private CeHttpClient ceHttpClient = mock(CeHttpClient.class); private ChangeLogLevelAction underTest = new ChangeLogLevelAction(userSession, new ChangeLogLevelStandaloneService(serverLogging, ceHttpClient)); private WsActionTester actionTester = new WsActionTester(underTest); @Test public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { assertThatThrownBy(() -> actionTester.newRequest().setMethod("POST").execute()) .isInstanceOf(ForbiddenException.class); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); assertThatThrownBy(() -> actionTester.newRequest().setMethod("POST").execute()) .isInstanceOf(ForbiddenException.class); } @Test public void enable_debug_logs() { logInAsSystemAdministrator(); actionTester.newRequest() .setParam("level", "DEBUG") .setMethod("POST") .execute(); verify(serverLogging).changeLevel(LoggerLevel.DEBUG); verify(ceHttpClient).changeLogLevel(LoggerLevel.DEBUG); } @Test public void enable_trace_logs() { logInAsSystemAdministrator(); actionTester.newRequest() .setParam("level", "TRACE") .setMethod("POST") .execute(); verify(serverLogging).changeLevel(LoggerLevel.TRACE); verify(ceHttpClient).changeLogLevel(LoggerLevel.TRACE); } @Test public void fail_if_unsupported_level() { logInAsSystemAdministrator(); assertThatThrownBy(() -> actionTester.newRequest() .setParam("level", "ERROR") .setMethod("POST") .execute()) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_missing_level() { logInAsSystemAdministrator(); assertThatThrownBy(() -> actionTester.newRequest() .setMethod("POST") .execute()) .isInstanceOf(IllegalArgumentException.class); } private void logInAsSystemAdministrator() { userSession.logIn().setSystemAdministrator(); } }
3,584
31.590909
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/ChangeLogLevelServiceModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import org.sonar.server.platform.NodeInformation; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ChangeLogLevelServiceModuleTest { private final NodeInformation nodeInformation = mock(NodeInformation.class); private final ChangeLogLevelServiceModule underTest = new ChangeLogLevelServiceModule(nodeInformation); @Test public void provide_returns_ChangeLogLevelClusterService() { when(nodeInformation.isStandalone()).thenReturn(false); ListContainer container = new ListContainer(); underTest.configure(container); assertThat(container.getAddedObjects()).containsOnly(ChangeLogLevelClusterService.class); } @Test public void provide_returns_ChangeLogLevelStandaloneService_if_SQ_standalone() { when(nodeInformation.isStandalone()).thenReturn(true); ListContainer container = new ListContainer(); underTest.configure(container); verifyInStandaloneSQ(container); } private void verifyInStandaloneSQ(ListContainer container) { assertThat(container.getAddedObjects()).containsOnly(ChangeLogLevelStandaloneService.class); } }
2,140
35.913793
105
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/DbMigrationStatusActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import com.google.common.collect.ImmutableList; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import java.util.Date; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.utils.DateUtils; import org.sonar.db.Database; import org.sonar.db.dialect.Dialect; import org.sonar.server.platform.db.migration.DatabaseMigrationState; import org.sonar.server.platform.db.migration.DatabaseMigrationState.Status; import org.sonar.server.platform.db.migration.version.DatabaseVersion; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.Iterables.filter; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import static org.sonar.server.platform.db.migration.DatabaseMigrationState.Status.FAILED; import static org.sonar.server.platform.db.migration.DatabaseMigrationState.Status.NONE; import static org.sonar.server.platform.db.migration.DatabaseMigrationState.Status.RUNNING; import static org.sonar.server.platform.db.migration.DatabaseMigrationState.Status.SUCCEEDED; import static org.sonar.server.platform.ws.DbMigrationJsonWriter.MESSAGE_MIGRATION_REQUIRED; import static org.sonar.server.platform.ws.DbMigrationJsonWriter.MESSAGE_NO_MIGRATION_ON_EMBEDDED_DATABASE; import static org.sonar.server.platform.ws.DbMigrationJsonWriter.MESSAGE_STATUS_NONE; import static org.sonar.server.platform.ws.DbMigrationJsonWriter.MESSAGE_STATUS_RUNNING; import static org.sonar.server.platform.ws.DbMigrationJsonWriter.MESSAGE_STATUS_SUCCEEDED; import static org.sonar.server.platform.ws.DbMigrationJsonWriter.STATUS_MIGRATION_FAILED; import static org.sonar.server.platform.ws.DbMigrationJsonWriter.STATUS_MIGRATION_REQUIRED; import static org.sonar.server.platform.ws.DbMigrationJsonWriter.STATUS_MIGRATION_RUNNING; import static org.sonar.server.platform.ws.DbMigrationJsonWriter.STATUS_MIGRATION_SUCCEEDED; import static org.sonar.server.platform.ws.DbMigrationJsonWriter.STATUS_NOT_SUPPORTED; import static org.sonar.server.platform.ws.DbMigrationJsonWriter.STATUS_NO_MIGRATION; import static org.sonar.test.JsonAssert.assertJson; @RunWith(DataProviderRunner.class) public class DbMigrationStatusActionTest { private static final Date SOME_DATE = new Date(); private static final String SOME_THROWABLE_MSG = "blablabla pop !"; private static final String DEFAULT_ERROR_MSG = "No failure error"; private DatabaseVersion databaseVersion = mock(DatabaseVersion.class); private Database database = mock(Database.class); private Dialect dialect = mock(Dialect.class); private DatabaseMigrationState migrationState = mock(DatabaseMigrationState.class); private DbMigrationStatusAction underTest = new DbMigrationStatusAction(databaseVersion, database, migrationState); private WsActionTester tester = new WsActionTester(underTest); @Before public void wireMocksTogether() { when(database.getDialect()).thenReturn(dialect); when(databaseVersion.getVersion()).thenReturn(Optional.of(150L)); } @Test public void verify_example() { when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(RUNNING); when(migrationState.getStartedAt()).thenReturn(DateUtils.parseDateTime("2015-02-23T18:54:23+0100")); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(getClass().getResource("example-migrate_db.json")); } @Test public void throws_ISE_when_database_has_no_version() { reset(database); when(databaseVersion.getVersion()).thenReturn(Optional.empty()); assertThatThrownBy(() -> tester.newRequest().execute()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Cannot connect to Database."); } @Test public void msg_is_operational_and_state_from_databasemigration_when_databaseversion_status_is_UP_TO_DATE() { when(databaseVersion.getStatus()).thenReturn(DatabaseVersion.Status.UP_TO_DATE); when(migrationState.getStatus()).thenReturn(NONE); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_NO_MIGRATION, MESSAGE_STATUS_NONE)); } // this test will raise a IllegalArgumentException when an unsupported value is added to the Status enum @Test @UseDataProvider("statusRequiringDbMigration") public void defensive_test_all_values_of_Status_must_be_supported(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); for (Status migrationStatus : filter(Arrays.asList(DatabaseMigrationState.Status.values()), not(in(ImmutableList.of(NONE, RUNNING, FAILED, SUCCEEDED))))) { when(migrationState.getStatus()).thenReturn(migrationStatus); tester.newRequest().execute(); } } @Test public void state_from_databasemigration_when_databaseversion_status_is_REQUIRES_DOWNGRADE() { when(databaseVersion.getStatus()).thenReturn(DatabaseVersion.Status.REQUIRES_DOWNGRADE); when(migrationState.getStatus()).thenReturn(NONE); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_NO_MIGRATION, MESSAGE_STATUS_NONE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void state_is_NONE_with_specific_msg_when_db_requires_upgrade_but_dialect_does_not_support_migration(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(false); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_NOT_SUPPORTED, MESSAGE_NO_MIGRATION_ON_EMBEDDED_DATABASE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void state_from_database_migration_when_dbmigration_status_is_RUNNING(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(RUNNING); when(migrationState.getStartedAt()).thenReturn(SOME_DATE); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_MIGRATION_RUNNING, MESSAGE_STATUS_RUNNING, SOME_DATE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void state_from_database_migration_and_msg_includes_error_when_dbmigration_status_is_FAILED(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(FAILED); when(migrationState.getStartedAt()).thenReturn(SOME_DATE); when(migrationState.getError()).thenReturn(new UnsupportedOperationException(SOME_THROWABLE_MSG)); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_MIGRATION_FAILED, failedMsg(SOME_THROWABLE_MSG), SOME_DATE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void state_from_database_migration_and_msg_has_default_msg_when_dbmigration_status_is_FAILED(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(FAILED); when(migrationState.getStartedAt()).thenReturn(SOME_DATE); when(migrationState.getError()).thenReturn(null); // no failure throwable caught TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_MIGRATION_FAILED, failedMsg(DEFAULT_ERROR_MSG), SOME_DATE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void state_from_database_migration_and_msg_has_default_msg_when_dbmigration_status_is_SUCCEEDED(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(SUCCEEDED); when(migrationState.getStartedAt()).thenReturn(SOME_DATE); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_MIGRATION_SUCCEEDED, MESSAGE_STATUS_SUCCEEDED, SOME_DATE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void start_migration_and_return_state_from_databasemigration_when_dbmigration_status_is_NONE(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(NONE); when(migrationState.getStartedAt()).thenReturn(SOME_DATE); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_MIGRATION_REQUIRED, MESSAGE_MIGRATION_REQUIRED)); } @DataProvider public static Object[][] statusRequiringDbMigration() { return new Object[][] { {DatabaseVersion.Status.FRESH_INSTALL}, {DatabaseVersion.Status.REQUIRES_UPGRADE}, }; } private static String failedMsg(@Nullable String t) { return "Migration failed: " + t + ".<br/> Please check logs."; } private static String expectedResponse(String status, String msg) { return "{" + "\"state\":\"" + status + "\"," + "\"message\":\"" + msg + "\"" + "}"; } private static String expectedResponse(String status, String msg, Date date) { return "{" + "\"state\":\"" + status + "\"," + "\"message\":\"" + msg + "\"," + "\"startedAt\":\"" + DateUtils.formatDateTime(date) + "\"" + "}"; } }
11,163
44.754098
159
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import com.google.common.collect.ImmutableSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.stream.IntStream; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.health.ClusterHealth; import org.sonar.server.health.Health; import org.sonar.server.health.HealthChecker; import org.sonar.server.platform.NodeInformation; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.SystemPasscode; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.System; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.ThrowableAssert.ThrowingCallable; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.api.utils.DateUtils.parseDateTime; import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; import static org.sonar.server.health.Health.GREEN; import static org.sonar.test.JsonAssert.assertJson; public class HealthActionTest { @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); private final Random random = new Random(); private HealthChecker healthChecker = mock(HealthChecker.class); private NodeInformation nodeInformation = mock(NodeInformation.class); private SystemPasscode systemPasscode = mock(SystemPasscode.class); private WsActionTester underTest = new WsActionTester(new HealthAction(nodeInformation, new HealthActionSupport(healthChecker), systemPasscode, userSessionRule)); @Test public void verify_definition() { WebService.Action definition = underTest.getDef(); assertThat(definition.key()).isEqualTo("health"); assertThat(definition.isPost()).isFalse(); assertThat(definition.description()).isNotEmpty(); assertThat(definition.since()).isEqualTo("6.6"); assertThat(definition.isInternal()).isFalse(); assertThat(definition.responseExample()).isNotNull(); assertThat(definition.params()).isEmpty(); } @Test public void request_fails_with_ForbiddenException_when_anonymous() { TestRequest request = underTest.newRequest(); expectForbiddenException(() -> request.execute()); } @Test public void request_fails_with_SystemPasscode_enabled_and_anonymous() { when(systemPasscode.isValid(any())).thenReturn(false); TestRequest request = underTest.newRequest(); expectForbiddenException(() -> request.execute()); } @Test public void request_fails_with_SystemPasscode_enabled_but_no_passcode_and_user_is_not_system_administrator() { when(systemPasscode.isValid(any())).thenReturn(false); userSessionRule.logIn(); when(healthChecker.checkCluster()).thenReturn(randomStatusMinimalClusterHealth()); TestRequest request = underTest.newRequest(); expectForbiddenException(() -> request.execute()); } @Test public void request_succeeds_with_SystemPasscode_enabled_and_passcode() { when(systemPasscode.isValid(any())).thenReturn(true); when(healthChecker.checkCluster()).thenReturn(randomStatusMinimalClusterHealth()); TestRequest request = underTest.newRequest(); request.execute(); } @Test public void request_succeeds_with_SystemPasscode_incorrect_and_user_is_system_administrator() { when(systemPasscode.isValid(any())).thenReturn(false); userSessionRule.logIn().setSystemAdministrator(); when(healthChecker.checkCluster()).thenReturn(randomStatusMinimalClusterHealth()); TestRequest request = underTest.newRequest(); request.execute(); } @Test public void verify_response_example() { authenticateWithRandomMethod(); when(nodeInformation.isStandalone()).thenReturn(false); long time = parseDateTime("2015-08-13T23:34:59+0200").getTime(); when(healthChecker.checkCluster()) .thenReturn( new ClusterHealth(Health.builder() .setStatus(Health.Status.RED) .addCause("Application node app-1 is RED") .build(), ImmutableSet.of( newNodeHealthBuilder() .setStatus(NodeHealth.Status.RED) .addCause("foo") .setDetails( newNodeDetailsBuilder() .setName("app-1") .setType(NodeDetails.Type.APPLICATION) .setHost("192.168.1.1") .setPort(999) .setStartedAt(time) .build()) .build(), newNodeHealthBuilder() .setStatus(NodeHealth.Status.YELLOW) .addCause("bar") .setDetails( newNodeDetailsBuilder() .setName("app-2") .setType(NodeDetails.Type.APPLICATION) .setHost("192.168.1.2") .setPort(999) .setStartedAt(time) .build()) .build()))); TestResponse response = underTest.newRequest().execute(); assertJson(response.getInput()) .isSimilarTo(underTest.getDef().responseExampleAsString()); } @Test public void request_returns_status_and_causes_from_HealthChecker_checkNode_method_when_standalone() { authenticateWithRandomMethod(); Health.Status randomStatus = Health.Status.values()[new Random().nextInt(Health.Status.values().length)]; Health.Builder builder = Health.builder() .setStatus(randomStatus); IntStream.range(0, new Random().nextInt(5)).mapToObj(i -> RandomStringUtils.randomAlphanumeric(3)).forEach(builder::addCause); Health health = builder.build(); when(healthChecker.checkNode()).thenReturn(health); when(nodeInformation.isStandalone()).thenReturn(true); TestRequest request = underTest.newRequest(); System.HealthResponse healthResponse = request.executeProtobuf(System.HealthResponse.class); assertThat(healthResponse.getHealth().name()).isEqualTo(randomStatus.name()); assertThat(health.getCauses()).isEqualTo(health.getCauses()); } @Test public void response_contains_status_and_causes_from_HealthChecker_checkCluster_when_standalone() { authenticateWithRandomMethod(); Health.Status randomStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)]; String[] causes = IntStream.range(0, random.nextInt(33)).mapToObj(i -> randomAlphanumeric(4)).toArray(String[]::new); Health.Builder healthBuilder = Health.builder() .setStatus(randomStatus); Arrays.stream(causes).forEach(healthBuilder::addCause); when(nodeInformation.isStandalone()).thenReturn(false); when(healthChecker.checkCluster()).thenReturn(new ClusterHealth(healthBuilder.build(), emptySet())); System.HealthResponse clusterHealthResponse = underTest.newRequest().executeProtobuf(System.HealthResponse.class); assertThat(clusterHealthResponse.getHealth().name()).isEqualTo(randomStatus.name()); assertThat(clusterHealthResponse.getCausesList()) .extracting(System.Cause::getMessage) .containsOnly(causes); } @Test public void response_contains_information_of_nodes_when_clustered() { authenticateWithRandomMethod(); NodeHealth nodeHealth = randomNodeHealth(); when(nodeInformation.isStandalone()).thenReturn(false); when(healthChecker.checkCluster()).thenReturn(new ClusterHealth(GREEN, singleton(nodeHealth))); System.HealthResponse response = underTest.newRequest().executeProtobuf(System.HealthResponse.class); assertThat(response.getNodes().getNodesList()) .hasSize(1); System.Node node = response.getNodes().getNodesList().iterator().next(); assertThat(node.getHealth().name()).isEqualTo(nodeHealth.getStatus().name()); assertThat(node.getCausesList()) .extracting(System.Cause::getMessage) .containsOnly(nodeHealth.getCauses().toArray(new String[0])); assertThat(node.getName()).isEqualTo(nodeHealth.getDetails().getName()); assertThat(node.getHost()).isEqualTo(nodeHealth.getDetails().getHost()); assertThat(node.getPort()).isEqualTo(nodeHealth.getDetails().getPort()); assertThat(node.getStartedAt()).isEqualTo(formatDateTime(nodeHealth.getDetails().getStartedAt())); assertThat(node.getType().name()).isEqualTo(nodeHealth.getDetails().getType().name()); } @Test public void response_sort_nodes_by_type_name_host_then_port_when_clustered() { authenticateWithRandomMethod(); // using created field as a unique identifier. pseudo random value to ensure sorting is not based on created field List<NodeHealth> nodeHealths = new ArrayList<>(Arrays.asList( randomNodeHealth(NodeDetails.Type.APPLICATION, "1_name", "1_host", 1, 99), randomNodeHealth(NodeDetails.Type.APPLICATION, "1_name", "2_host", 1, 85), randomNodeHealth(NodeDetails.Type.APPLICATION, "1_name", "2_host", 2, 12), randomNodeHealth(NodeDetails.Type.APPLICATION, "2_name", "1_host", 1, 6), randomNodeHealth(NodeDetails.Type.APPLICATION, "2_name", "1_host", 2, 30), randomNodeHealth(NodeDetails.Type.APPLICATION, "2_name", "2_host", 1, 75), randomNodeHealth(NodeDetails.Type.APPLICATION, "2_name", "2_host", 2, 258), randomNodeHealth(NodeDetails.Type.SEARCH, "1_name", "1_host", 1, 963), randomNodeHealth(NodeDetails.Type.SEARCH, "1_name", "1_host", 2, 1), randomNodeHealth(NodeDetails.Type.SEARCH, "1_name", "2_host", 1, 35), randomNodeHealth(NodeDetails.Type.SEARCH, "1_name", "2_host", 2, 45), randomNodeHealth(NodeDetails.Type.SEARCH, "2_name", "1_host", 1, 39), randomNodeHealth(NodeDetails.Type.SEARCH, "2_name", "1_host", 2, 28), randomNodeHealth(NodeDetails.Type.SEARCH, "2_name", "2_host", 1, 66), randomNodeHealth(NodeDetails.Type.SEARCH, "2_name", "2_host", 2, 77))); String[] expected = nodeHealths.stream().map(s -> formatDateTime(new Date(s.getDetails().getStartedAt()))).toArray(String[]::new); Collections.shuffle(nodeHealths); when(nodeInformation.isStandalone()).thenReturn(false); when(healthChecker.checkCluster()).thenReturn(new ClusterHealth(GREEN, new HashSet<>(nodeHealths))); System.HealthResponse response = underTest.newRequest().executeProtobuf(System.HealthResponse.class); assertThat(response.getNodes().getNodesList()) .extracting(System.Node::getStartedAt) .containsExactly(expected); } private NodeHealth randomNodeHealth() { NodeHealth.Builder builder = newNodeHealthBuilder() .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]); IntStream.range(0, random.nextInt(4)).mapToObj(i -> randomAlphabetic(5)).forEach(builder::addCause); return builder.setDetails( newNodeDetailsBuilder() .setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH) .setName(randomAlphanumeric(3)) .setHost(randomAlphanumeric(4)) .setPort(1 + random.nextInt(3)) .setStartedAt(1 + random.nextInt(23)) .build()) .build(); } private NodeHealth randomNodeHealth(NodeDetails.Type type, String name, String host, int port, long started) { NodeHealth.Builder builder = newNodeHealthBuilder() .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]); IntStream.range(0, random.nextInt(4)).mapToObj(i -> randomAlphabetic(5)).forEach(builder::addCause); return builder.setDetails( newNodeDetailsBuilder() .setType(type) .setName(name) .setHost(host) .setPort(port) .setStartedAt(started) .build()) .build(); } private ClusterHealth randomStatusMinimalClusterHealth() { return new ClusterHealth(Health.builder() .setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)]) .build(), emptySet()); } private void expectForbiddenException(ThrowingCallable shouldRaiseThrowable) { assertThatThrownBy(shouldRaiseThrowable) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } /** * Randomly choose of one the valid authentication method: * <ul> * <li>system administrator and passcode disabled</li> * <li>system administrator and passcode enabled</li> * <li>passcode</li> * </ul> */ private void authenticateWithRandomMethod() { if (random.nextBoolean()) { if (random.nextBoolean()) { when(systemPasscode.isValid(any())).thenReturn(true); } else { when(systemPasscode.isValid(any())).thenReturn(false); userSessionRule.logIn().setSystemAdministrator(); } } else { userSessionRule.logIn().setSystemAdministrator(); } } }
14,517
42.728916
164
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthCheckerModuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import org.junit.Test; import org.sonar.core.platform.ListContainer; import org.sonar.server.health.AppNodeClusterCheck; import org.sonar.server.health.CeStatusNodeCheck; import org.sonar.server.health.ClusterHealthCheck; import org.sonar.server.health.DbConnectionNodeCheck; import org.sonar.server.health.EsStatusClusterCheck; import org.sonar.server.health.EsStatusNodeCheck; import org.sonar.server.health.HealthCheckerImpl; import org.sonar.server.health.NodeHealthCheck; import org.sonar.server.health.WebServerStatusNodeCheck; import org.sonar.server.platform.NodeInformation; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class HealthCheckerModuleTest { private final NodeInformation nodeInformation = mock(NodeInformation.class); private final HealthCheckerModule underTest = new HealthCheckerModule(nodeInformation); @Test public void verify_HealthChecker() { boolean standalone = new Random().nextBoolean(); when(nodeInformation.isStandalone()).thenReturn(standalone); ListContainer container = new ListContainer(); underTest.configure(container); assertThat(container.getAddedObjects()) .describedAs("Verifying action and HealthChecker with standalone=%s", standalone) .contains(HealthCheckerImpl.class) .doesNotContain(HealthActionSupport.class) .doesNotContain(HealthAction.class) .doesNotContain(SafeModeHealthAction.class); } @Test public void verify_installed_NodeHealthChecks_implementations_when_standalone() { when(nodeInformation.isStandalone()).thenReturn(true); ListContainer container = new ListContainer(); underTest.configure(container); List<Class<?>> checks = container.getAddedObjects().stream() .filter(o -> o instanceof Class) .map(o -> (Class<?>) o) .filter(NodeHealthCheck.class::isAssignableFrom).collect(Collectors.toList()); assertThat(checks).containsOnly(WebServerStatusNodeCheck.class, DbConnectionNodeCheck.class, EsStatusNodeCheck.class, CeStatusNodeCheck.class); } @Test public void verify_installed_NodeHealthChecks_implementations_when_clustered() { when(nodeInformation.isStandalone()).thenReturn(false); ListContainer container = new ListContainer(); underTest.configure(container); List<Class<?>> checks = container.getAddedObjects().stream() .filter(o -> o instanceof Class) .map(o -> (Class<?>) o) .filter(NodeHealthCheck.class::isAssignableFrom).collect(Collectors.toList()); assertThat(checks).containsOnly(WebServerStatusNodeCheck.class, DbConnectionNodeCheck.class, CeStatusNodeCheck.class); } @Test public void verify_installed_ClusterHealthChecks_implementations_in_standalone() { when(nodeInformation.isStandalone()).thenReturn(true); ListContainer container = new ListContainer(); underTest.configure(container); List<Class<?>> checks = container.getAddedObjects().stream() .filter(o -> o instanceof Class<?>) .map(o -> (Class<?>) o) .filter(ClusterHealthCheck.class::isAssignableFrom).collect(Collectors.toList()); assertThat(checks).isEmpty(); } @Test public void verify_installed_ClusterHealthChecks_implementations_in_clustering() { when(nodeInformation.isStandalone()).thenReturn(false); ListContainer container = new ListContainer(); underTest.configure(container); List<Class<?>> checks = container.getAddedObjects().stream() .filter(o -> o instanceof Class<?>) .map(o -> (Class<?>) o) .filter(ClusterHealthCheck.class::isAssignableFrom).collect(Collectors.toList()); assertThat(checks).containsOnly(EsStatusClusterCheck.class, AppNodeClusterCheck.class); } }
4,742
39.194915
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/IndexActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import com.google.common.collect.ImmutableSet; import java.net.HttpURLConnection; import java.util.Date; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.api.platform.Server; import org.sonar.api.utils.DateUtils; import org.sonar.core.i18n.DefaultI18n; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static java.util.Locale.ENGLISH; import static java.util.Locale.PRC; import static java.util.Locale.UK; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.test.JsonAssert.assertJson; public class IndexActionTest { private static final String KEY_1 = "key1"; private static final String KEY_2 = "key2"; private static final String KEY_3 = "key3"; private DefaultI18n i18n = mock(DefaultI18n.class); private Server server = mock(Server.class); private IndexAction underTest = new IndexAction(i18n, server); private WsActionTester ws = new WsActionTester(underTest); @Test public void allow_client_to_cache_messages() { Date now = new Date(); Date aBitLater = new Date(now.getTime() + 1000); when(server.getStartedAt()).thenReturn(now); TestResponse result = call(null, DateUtils.formatDateTime(aBitLater)); verifyNoInteractions(i18n); verify(server).getStartedAt(); assertThat(result.getStatus()).isEqualTo(HttpURLConnection.HTTP_NOT_MODIFIED); } @Test public void return_all_l10n_messages_using_accept_header_with_cache_expired() { Date now = new Date(); Date aBitEarlier = new Date(now.getTime() - 1000); when(server.getStartedAt()).thenReturn(now); when(i18n.getPropertyKeys()).thenReturn(ImmutableSet.of(KEY_1, KEY_2, KEY_3)); when(i18n.message(PRC, KEY_1, KEY_1)).thenReturn(KEY_1); when(i18n.message(PRC, KEY_2, KEY_2)).thenReturn(KEY_2); when(i18n.message(PRC, KEY_3, KEY_3)).thenReturn(KEY_3); when(i18n.getEffectiveLocale(PRC)).thenReturn(PRC); TestResponse result = call(PRC.toLanguageTag(), DateUtils.formatDateTime(aBitEarlier)); verify(i18n).getPropertyKeys(); verify(i18n).message(PRC, KEY_1, KEY_1); verify(i18n).message(PRC, KEY_2, KEY_2); verify(i18n).message(PRC, KEY_3, KEY_3); assertJson(result.getInput()).isSimilarTo("{\"effectiveLocale\":\"zh-CN\", \"messages\": {\"key1\":\"key1\",\"key2\":\"key2\",\"key3\":\"key3\"}}"); } @Test public void default_locale_is_english() { String key1 = "key1"; String key2 = "key2"; String key3 = "key3"; when(i18n.getPropertyKeys()).thenReturn(ImmutableSet.of(key1, key2, key3)); when(i18n.message(ENGLISH, key1, key1)).thenReturn(key1); when(i18n.message(ENGLISH, key2, key2)).thenReturn(key2); when(i18n.message(ENGLISH, key3, key3)).thenReturn(key3); when(i18n.getEffectiveLocale(ENGLISH)).thenReturn(ENGLISH); TestResponse result = call(null, null); verify(i18n).getPropertyKeys(); verify(i18n).message(ENGLISH, key1, key1); verify(i18n).message(ENGLISH, key2, key2); verify(i18n).message(ENGLISH, key3, key3); assertJson(result.getInput()).isSimilarTo("{\"messages\": {\"key1\":\"key1\",\"key2\":\"key2\",\"key3\":\"key3\"}}"); } @Test public void support_BCP47_formatted_language_tags() { String key1 = "key1"; when(i18n.getPropertyKeys()).thenReturn(ImmutableSet.of(key1)); when(i18n.message(UK, key1, key1)).thenReturn(key1); when(i18n.getEffectiveLocale(UK)).thenReturn(UK); TestResponse result = call("en-GB", null); verify(i18n).getPropertyKeys(); verify(i18n).message(UK, key1, key1); assertJson(result.getInput()).isSimilarTo("{\"messages\": {\"key1\":\"key1\"}}"); } @Test public void fail_when_java_formatted_language_tags() { String key1 = "key1"; when(i18n.getPropertyKeys()).thenReturn(ImmutableSet.of(key1)); when(i18n.message(UK, key1, key1)).thenReturn(key1); when(i18n.getEffectiveLocale(UK)).thenReturn(UK); assertThatThrownBy(() -> call("en_GB", null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Locale cannot be parsed as a BCP47 language tag"); } private TestResponse call(@Nullable String locale, @Nullable String timestamp) { TestRequest request = ws.newRequest(); if (locale != null) { request.setParam("locale", locale); } if (timestamp != null) { request.setParam("ts", timestamp); } return request.execute(); } }
5,604
36.366667
152
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/InfoActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.platform.SystemInfoWriter; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class InfoActionTest { @Rule public final UserSessionRule userSessionRule = UserSessionRule.standalone() .logIn("login") .setName("name"); private final SystemInfoWriter jsonWriter = json -> json.prop("key", "value"); private final InfoAction underTest = new InfoAction(userSessionRule, jsonWriter); private final WsActionTester ws = new WsActionTester(underTest); @Test public void test_definition() { assertThat(ws.getDef().key()).isEqualTo("info"); assertThat(ws.getDef().isInternal()).isFalse(); assertThat(ws.getDef().responseExampleAsString()).isNotEmpty(); assertThat(ws.getDef().params()).isEmpty(); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(ForbiddenException.class); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSessionRule.logIn().setNonSystemAdministrator(); assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(ForbiddenException.class); } @Test public void write_json() { logInAsSystemAdministrator(); TestResponse response = ws.newRequest().execute(); assertThat(response.getInput()).isEqualTo("{\"key\":\"value\"}"); } private void logInAsSystemAdministrator() { userSessionRule.logIn().setSystemAdministrator(); } }
2,727
34.428571
93
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/LivenessActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.SystemPasscode; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LivenessActionTest { @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); private final SystemPasscode systemPasscode = mock(SystemPasscode.class); private final LivenessChecker livenessChecker = mock(LivenessChecker.class); private final LivenessActionSupport livenessActionSupport = new LivenessActionSupport(livenessChecker); private final WsActionTester underTest = new WsActionTester(new LivenessAction(livenessActionSupport, systemPasscode, userSessionRule)); @Test public void verify_definition() { WebService.Action definition = underTest.getDef(); assertThat(definition.key()).isEqualTo("liveness"); assertThat(definition.isPost()).isFalse(); assertThat(definition.description()).isNotEmpty(); assertThat(definition.since()).isEqualTo("9.1"); assertThat(definition.isInternal()).isTrue(); assertThat(definition.responseExample()).isNull(); assertThat(definition.params()).isEmpty(); } @Test public void fail_when_system_passcode_is_invalid() { when(systemPasscode.isValid(any())).thenReturn(false); TestRequest request = underTest.newRequest(); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void fail_when_user_is_not_system_admin() { when(systemPasscode.isValid(any())).thenReturn(false); userSessionRule.logIn(); TestRequest request = underTest.newRequest(); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void liveness_check_failed_expect_500() { when(systemPasscode.isValid(any())).thenReturn(true); when(livenessChecker.liveness()).thenReturn(false); TestRequest request = underTest.newRequest(); assertThatThrownBy(request::execute) .isInstanceOf(IllegalStateException.class) .hasMessage("Liveness check failed"); } @Test public void liveness_check_success_expect_204() { when(systemPasscode.isValid(any())).thenReturn(true); when(livenessChecker.liveness()).thenReturn(true); assertThat(underTest.newRequest().execute().getStatus()).isEqualTo(204); } }
3,712
35.762376
138
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/LivenessCheckerImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import org.assertj.core.api.Assertions; import org.junit.Test; import org.sonar.server.health.CeStatusNodeCheck; import org.sonar.server.health.DbConnectionNodeCheck; import org.sonar.server.health.EsStatusNodeCheck; import org.sonar.server.health.Health; import org.sonar.server.health.WebServerStatusNodeCheck; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LivenessCheckerImplTest { public static final Health RED = Health.builder().setStatus(Health.Status.RED).build(); private final DbConnectionNodeCheck dbConnectionNodeCheck = mock(DbConnectionNodeCheck.class); private final WebServerStatusNodeCheck webServerStatusNodeCheck = mock(WebServerStatusNodeCheck.class); private final CeStatusNodeCheck ceStatusNodeCheck = mock(CeStatusNodeCheck.class); private final EsStatusNodeCheck esStatusNodeCheck = mock(EsStatusNodeCheck.class); LivenessCheckerImpl underTest = new LivenessCheckerImpl(dbConnectionNodeCheck, webServerStatusNodeCheck, ceStatusNodeCheck, esStatusNodeCheck); LivenessCheckerImpl underTestDCE = new LivenessCheckerImpl(dbConnectionNodeCheck, webServerStatusNodeCheck, ceStatusNodeCheck, null); @Test public void fail_when_db_connection_check_fail() { when(dbConnectionNodeCheck.check()).thenReturn(RED); Assertions.assertThat(underTest.liveness()).isFalse(); } @Test public void fail_when_web_check_fail() { when(dbConnectionNodeCheck.check()).thenReturn(Health.GREEN); when(webServerStatusNodeCheck.check()).thenReturn(RED); Assertions.assertThat(underTest.liveness()).isFalse(); } @Test public void fail_when_ce_check_fail() { when(dbConnectionNodeCheck.check()).thenReturn(Health.GREEN); when(webServerStatusNodeCheck.check()).thenReturn(Health.GREEN); when(ceStatusNodeCheck.check()).thenReturn(RED); Assertions.assertThat(underTest.liveness()).isFalse(); } @Test public void fail_when_es_check_fail() { when(dbConnectionNodeCheck.check()).thenReturn(Health.GREEN); when(webServerStatusNodeCheck.check()).thenReturn(Health.GREEN); when(ceStatusNodeCheck.check()).thenReturn(Health.GREEN); when(esStatusNodeCheck.check()).thenReturn(RED); Assertions.assertThat(underTest.liveness()).isFalse(); } @Test public void success_when_db_web_ce_es_succeed() { when(dbConnectionNodeCheck.check()).thenReturn(Health.GREEN); when(webServerStatusNodeCheck.check()).thenReturn(Health.GREEN); when(ceStatusNodeCheck.check()).thenReturn(Health.GREEN); when(esStatusNodeCheck.check()).thenReturn(Health.GREEN); Assertions.assertThat(underTest.liveness()).isTrue(); } @Test public void success_when_db_web_ce_succeed() { when(dbConnectionNodeCheck.check()).thenReturn(Health.GREEN); when(webServerStatusNodeCheck.check()).thenReturn(Health.GREEN); when(ceStatusNodeCheck.check()).thenReturn(Health.GREEN); Assertions.assertThat(underTestDCE.liveness()).isTrue(); } }
3,863
38.428571
145
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/MigrateDbActionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import com.google.common.collect.ImmutableList; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import java.util.Date; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.utils.DateUtils; import org.sonar.db.Database; import org.sonar.db.dialect.Dialect; import org.sonar.server.platform.db.migration.DatabaseMigration; import org.sonar.server.platform.db.migration.DatabaseMigrationState; import org.sonar.server.platform.db.migration.DatabaseMigrationState.Status; import org.sonar.server.platform.db.migration.version.DatabaseVersion; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.Iterables.filter; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.server.platform.db.migration.DatabaseMigrationState.Status.FAILED; import static org.sonar.server.platform.db.migration.DatabaseMigrationState.Status.NONE; import static org.sonar.server.platform.db.migration.DatabaseMigrationState.Status.RUNNING; import static org.sonar.server.platform.db.migration.DatabaseMigrationState.Status.SUCCEEDED; import static org.sonar.test.JsonAssert.assertJson; @RunWith(DataProviderRunner.class) public class MigrateDbActionTest { private static final Date SOME_DATE = new Date(); private static final String SOME_THROWABLE_MSG = "blablabla pop !"; private static final String DEFAULT_ERROR_MSG = "No failure error"; private static final String STATUS_NO_MIGRATION = "NO_MIGRATION"; private static final String STATUS_NOT_SUPPORTED = "NOT_SUPPORTED"; private static final String STATUS_MIGRATION_RUNNING = "MIGRATION_RUNNING"; private static final String STATUS_MIGRATION_FAILED = "MIGRATION_FAILED"; private static final String STATUS_MIGRATION_SUCCEEDED = "MIGRATION_SUCCEEDED"; private static final String MESSAGE_NO_MIGRATION_ON_EMBEDDED_DATABASE = "Upgrade is not supported on embedded database."; private static final String MESSAGE_STATUS_NONE = "Database is up-to-date, no migration needed."; private static final String MESSAGE_STATUS_RUNNING = "Database migration is running."; private static final String MESSAGE_STATUS_SUCCEEDED = "Migration succeeded."; private DatabaseVersion databaseVersion = mock(DatabaseVersion.class); private Database database = mock(Database.class); private Dialect dialect = mock(Dialect.class); private DatabaseMigration databaseMigration = mock(DatabaseMigration.class); private DatabaseMigrationState migrationState = mock(DatabaseMigrationState.class); private MigrateDbAction underTest = new MigrateDbAction(databaseVersion, database, migrationState, databaseMigration); private WsActionTester tester = new WsActionTester(underTest); @Before public void wireMocksTogether() { when(database.getDialect()).thenReturn(dialect); when(databaseVersion.getVersion()).thenReturn(Optional.of(150L)); } @Test public void ISE_is_thrown_when_version_can_not_be_retrieved_from_database() { reset(databaseVersion); when(databaseVersion.getVersion()).thenReturn(Optional.empty()); assertThatThrownBy(() -> tester.newRequest().execute()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Cannot connect to Database."); } @Test public void verify_example() { when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(RUNNING); when(migrationState.getStartedAt()).thenReturn(DateUtils.parseDateTime("2015-02-23T18:54:23+0100")); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(getClass().getResource("example-migrate_db.json")); } @Test public void msg_is_operational_and_state_from_database_migration_when_databaseversion_status_is_UP_TO_DATE() { when(databaseVersion.getStatus()).thenReturn(DatabaseVersion.Status.UP_TO_DATE); when(migrationState.getStatus()).thenReturn(NONE); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_NO_MIGRATION, MESSAGE_STATUS_NONE)); } // this test will raise a IllegalArgumentException when an unsupported value is added to the Status enum @Test public void defensive_test_all_values_of_migration_Status_must_be_supported() { for (Status status : filter(Arrays.asList(DatabaseMigrationState.Status.values()), not(in(ImmutableList.of(NONE, RUNNING, FAILED, SUCCEEDED))))) { when(migrationState.getStatus()).thenReturn(status); tester.newRequest().execute(); } } @Test public void state_from_database_migration_when_databaseversion_status_is_REQUIRES_DOWNGRADE() { when(databaseVersion.getStatus()).thenReturn(DatabaseVersion.Status.REQUIRES_DOWNGRADE); when(migrationState.getStatus()).thenReturn(NONE); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_NO_MIGRATION, MESSAGE_STATUS_NONE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void state_is_NONE_with_specific_msg_when_db_requires_upgrade_but_dialect_does_not_support_migration(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(false); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_NOT_SUPPORTED, MESSAGE_NO_MIGRATION_ON_EMBEDDED_DATABASE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void state_from_database_migration_when_dbmigration_status_is_RUNNING(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(RUNNING); when(migrationState.getStartedAt()).thenReturn(SOME_DATE); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_MIGRATION_RUNNING, MESSAGE_STATUS_RUNNING, SOME_DATE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void state_from_database_migration_and_msg_includes_error_when_dbmigration_status_is_FAILED(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(FAILED); when(migrationState.getStartedAt()).thenReturn(SOME_DATE); when(migrationState.getError()).thenReturn(new UnsupportedOperationException(SOME_THROWABLE_MSG)); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_MIGRATION_FAILED, failedMsg(SOME_THROWABLE_MSG), SOME_DATE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void state_from_database_migration_and_msg_has_default_msg_when_dbmigration_status_is_FAILED(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(FAILED); when(migrationState.getStartedAt()).thenReturn(SOME_DATE); when(migrationState.getError()).thenReturn(null); // no failure throwable caught TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_MIGRATION_FAILED, failedMsg(DEFAULT_ERROR_MSG), SOME_DATE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void state_from_database_migration_and_msg_has_default_msg_when_dbmigration_status_is_SUCCEEDED(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(SUCCEEDED); when(migrationState.getStartedAt()).thenReturn(SOME_DATE); TestResponse response = tester.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_MIGRATION_SUCCEEDED, MESSAGE_STATUS_SUCCEEDED, SOME_DATE)); } @Test @UseDataProvider("statusRequiringDbMigration") public void start_migration_and_return_state_from_databasemigration_when_dbmigration_status_is_NONE(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); when(dialect.supportsMigration()).thenReturn(true); when(migrationState.getStatus()).thenReturn(NONE); when(migrationState.getStartedAt()).thenReturn(SOME_DATE); TestResponse response = tester.newRequest().execute(); verify(databaseMigration).startIt(); assertJson(response.getInput()).isSimilarTo(expectedResponse(STATUS_MIGRATION_RUNNING, MESSAGE_STATUS_RUNNING, SOME_DATE)); } @DataProvider public static Object[][] statusRequiringDbMigration() { return new Object[][]{ {DatabaseVersion.Status.FRESH_INSTALL}, {DatabaseVersion.Status.REQUIRES_UPGRADE}, }; } private static String failedMsg(@Nullable String t) { return "Migration failed: " + t + ".<br/> Please check logs."; } private static String expectedResponse(String status, String msg) { return "{" + "\"state\":\"" + status + "\"," + "\"message\":\"" + msg + "\"" + "}"; } private static String expectedResponse(String status, String msg, Date date) { return "{" + "\"state\":\"" + status + "\"," + "\"message\":\"" + msg + "\"," + "\"startedAt\":\"" + DateUtils.formatDateTime(date) + "\"" + "}"; } }
11,041
43.886179
150
java