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/platform/ws/PingActionTest.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.api.server.ws.WebService;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
public class PingActionTest {
private PingAction underTest = new PingAction();
private WsActionTester tester = new WsActionTester(underTest);
@Test
public void test_definition() {
WebService.Action action = tester.getDef();
assertThat(action.key()).isEqualTo("ping");
assertThat(action.isPost()).isFalse();
assertThat(action.isInternal()).isFalse();
assertThat(action.params()).isEmpty();
}
@Test
public void returns_pong_as_plain_text() {
TestResponse response = tester.newRequest().execute();
assertThat(response.getMediaType()).isEqualTo("text/plain");
assertThat(response.getInput()).isEqualTo("pong");
assertThat(response.getInput()).isEqualTo(tester.getDef().responseExampleAsString());
}
}
| 1,846 | 33.849057 | 89 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/RestartActionTest.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.mockito.InOrder;
import org.mockito.Mockito;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.server.app.ProcessCommandWrapper;
import org.sonar.server.app.RestartFlagHolder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.platform.NodeInformation;
import org.sonar.server.tester.UserSessionRule;
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.Mockito.mock;
import static org.mockito.Mockito.when;
public class RestartActionTest {
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Rule
public LogTester logTester = new LogTester();
private ProcessCommandWrapper processCommandWrapper = mock(ProcessCommandWrapper.class);
private RestartFlagHolder restartFlagHolder = mock(RestartFlagHolder.class);
private NodeInformation nodeInformation = mock(NodeInformation.class);
private RestartAction sut = new RestartAction(userSessionRule, processCommandWrapper, restartFlagHolder, nodeInformation);
private InOrder inOrder = Mockito.inOrder(restartFlagHolder, processCommandWrapper);
private WsActionTester actionTester = new WsActionTester(sut);
@Test
public void request_fails_in_production_mode_with_ForbiddenException_when_user_is_not_logged_in() {
when(nodeInformation.isStandalone()).thenReturn(true);
assertThatThrownBy(() -> actionTester.newRequest().execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void request_fails_in_production_mode_with_ForbiddenException_when_user_is_not_system_administrator() {
when(nodeInformation.isStandalone()).thenReturn(true);
userSessionRule.logIn().setNonSystemAdministrator();
assertThatThrownBy(() -> actionTester.newRequest().execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void request_fails_in_cluster_mode_with_IllegalArgumentException() {
when(nodeInformation.isStandalone()).thenReturn(false);
assertThatThrownBy(() -> actionTester.newRequest().execute())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Restart not allowed for cluster nodes");
}
@Test
public void calls_ProcessCommandWrapper_requestForSQRestart_in_production_mode() {
when(nodeInformation.isStandalone()).thenReturn(true);
userSessionRule.logIn().setSystemAdministrator();
actionTester.newRequest().execute();
inOrder.verify(restartFlagHolder).set();
inOrder.verify(processCommandWrapper).requestSQRestart();
}
@Test
public void logs_login_of_authenticated_user_requesting_the_restart_in_production_mode() {
when(nodeInformation.isStandalone()).thenReturn(true);
String login = "BigBother";
userSessionRule.logIn(login).setSystemAdministrator();
actionTester.newRequest().execute();
assertThat(logTester.logs(Level.INFO))
.contains("SonarQube restart requested by " + login);
}
}
| 4,005 | 37.519231 | 124 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.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.Arrays;
import java.util.Random;
import java.util.stream.IntStream;
import org.apache.commons.lang.RandomStringUtils;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.health.Health;
import org.sonar.server.health.HealthChecker;
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 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.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.test.JsonAssert.assertJson;
public class SafeModeHealthActionTest {
private final Random random = new Random();
private HealthChecker healthChecker = mock(HealthChecker.class);
private SystemPasscode systemPasscode = mock(SystemPasscode.class);
private WsActionTester underTest = new WsActionTester(new SafeModeHealthAction(new HealthActionSupport(healthChecker), systemPasscode));
@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_PassCode_disabled_or_incorrect() {
when(systemPasscode.isValid(any())).thenReturn(false);
TestRequest request = underTest.newRequest();
expectForbiddenException(() -> request.execute());
}
@Test
public void request_succeeds_when_valid_passcode() {
authenticateWithPasscode();
when(healthChecker.checkNode())
.thenReturn(Health.builder()
.setStatus(Health.Status.values()[random.nextInt(Health.Status.values().length)])
.build());
TestRequest request = underTest.newRequest();
request.execute();
}
@Test
public void verify_response_example() {
authenticateWithPasscode();
when(healthChecker.checkNode())
.thenReturn(Health.builder()
.setStatus(Health.Status.RED)
.addCause("Application node app-1 is RED")
.build());
TestResponse response = underTest.newRequest().execute();
assertJson(response.getInput())
.ignoreFields("nodes")
.isSimilarTo(underTest.getDef().responseExampleAsString());
}
@Test
public void request_returns_status_and_causes_from_HealthChecker_checkNode_method() {
authenticateWithPasscode();
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);
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() {
authenticateWithPasscode();
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(healthChecker.checkNode()).thenReturn(healthBuilder.build());
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);
}
private void expectForbiddenException(ThrowingCallable shouldRaiseThrowable) {
assertThatThrownBy(shouldRaiseThrowable)
.isInstanceOf(ForbiddenException.class)
.hasMessageContaining("Insufficient privileges");
}
private void authenticateWithPasscode() {
when(systemPasscode.isValid(any())).thenReturn(true);
}
}
| 5,878 | 39.267123 | 138 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthCheckerModuleTest.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.stream.Collectors;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import org.sonar.server.health.DbConnectionNodeCheck;
import org.sonar.server.health.EsStatusNodeCheck;
import org.sonar.server.health.HealthCheckerImpl;
import org.sonar.server.health.NodeHealthCheck;
import org.sonar.server.health.WebServerSafemodeNodeCheck;
import static org.assertj.core.api.Assertions.assertThat;
public class SafeModeHealthCheckerModuleTest {
private final SafeModeHealthCheckerModule underTest = new SafeModeHealthCheckerModule();
@Test
public void verify_HealthChecker() {
ListContainer container = new ListContainer();
underTest.configure(container);
assertThat(container.getAddedObjects())
.contains(HealthCheckerImpl.class)
.doesNotContain(HealthActionSupport.class)
.doesNotContain(SafeModeHealthAction.class)
.doesNotContain(HealthAction.class);
}
@Test
public void verify_installed_HealthChecks_implementations() {
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(WebServerSafemodeNodeCheck.class, DbConnectionNodeCheck.class, EsStatusNodeCheck.class);
}
}
| 2,356 | 35.828125 | 124 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeLivenessActionTest.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.api.server.ws.WebService;
import org.sonar.server.exceptions.ForbiddenException;
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 SafeModeLivenessActionTest {
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 SafeModeLivenessAction(livenessActionSupport, systemPasscode));
@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 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,220 | 36.894118 | 129 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeLivenessCheckerImplTest.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.DbConnectionNodeCheck;
import org.sonar.server.health.Health;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class SafeModeLivenessCheckerImplTest {
public static final Health RED = Health.builder().setStatus(Health.Status.RED).build();
private final DbConnectionNodeCheck dbConnectionNodeCheck = mock(DbConnectionNodeCheck.class);
private final SafeModeLivenessCheckerImpl underTest = new SafeModeLivenessCheckerImpl(dbConnectionNodeCheck);
@Test
public void fail_when_db_connection_check_fail() {
when(dbConnectionNodeCheck.check()).thenReturn(RED);
Assertions.assertThat(underTest.liveness()).isFalse();
}
@Test
public void succeed_when_db_connection_check_success() {
when(dbConnectionNodeCheck.check()).thenReturn(Health.GREEN);
Assertions.assertThat(underTest.liveness()).isTrue();
}
}
| 1,850 | 35.294118 | 111 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafemodeSystemWsModuleTest.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 static org.assertj.core.api.Assertions.assertThat;
public class SafemodeSystemWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new SafemodeSystemWsModule().configure(container);
assertThat(container.getAddedObjects()).isNotEmpty();
}
}
| 1,282 | 35.657143 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/ServerWsTest.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.api.platform.Server;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.ws.DumbResponse;
import org.sonar.server.ws.TestResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ServerWsTest {
private Server server = mock(Server.class);
private ServerWs underTest = new ServerWs(server);
@Test
public void define_version_action() {
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/server");
assertThat(controller.actions()).hasSize(1);
WebService.Action versionAction = controller.action("version");
assertThat(versionAction.since()).isEqualTo("2.10");
assertThat(versionAction.description()).isNotEmpty();
assertThat(versionAction.isPost()).isFalse();
}
@Test
public void returns_version_as_plain_text() throws Exception {
when(server.getVersion()).thenReturn("6.4-SNAPSHOT");
DumbResponse response = new DumbResponse();
underTest.handle(mock(Request.class), response);
assertThat(new TestResponse(response).getInput()).isEqualTo("6.4-SNAPSHOT");
}
@Test
public void test_example_of_version() {
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Action action = context.controller("api/server").action("version");
assertThat(action).isNotNull();
assertThat(action.responseExampleAsString()).isEqualTo("6.3.0.1234");
}
}
| 2,538 | 33.780822 | 82 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/StatusActionTest.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.Date;
import java.util.Set;
import org.junit.Test;
import org.sonar.api.platform.Server;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.app.RestartFlagHolder;
import org.sonar.server.app.RestartFlagHolderImpl;
import org.sonar.server.platform.Platform;
import org.sonar.server.platform.db.migration.DatabaseMigrationState;
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.ImmutableSet.of;
import static com.google.common.collect.Iterables.filter;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.test.JsonAssert.assertJson;
public class StatusActionTest {
private static final String SERVER_ID = "20150504120436";
private static final String SERVER_VERSION = "5.1";
private static final String STATUS_UP = "UP";
private static final String STATUS_STARTING = "STARTING";
private static final String STATUS_DOWN = "DOWN";
private static final String STATUS_MIGRATION_NEEDED = "DB_MIGRATION_NEEDED";
private static final String STATUS_MIGRATION_RUNNING = "DB_MIGRATION_RUNNING";
private static final String STATUS_RESTARTING = "RESTARTING";
private static final Set<DatabaseMigrationState.Status> SUPPORTED_DATABASE_MIGRATION_STATUSES = of(DatabaseMigrationState.Status.FAILED, DatabaseMigrationState.Status.NONE,
DatabaseMigrationState.Status.SUCCEEDED, DatabaseMigrationState.Status.RUNNING);
private static final Set<Platform.Status> SUPPORTED_PLATFORM_STATUSES = of(Platform.Status.BOOTING, Platform.Status.SAFEMODE, Platform.Status.STARTING, Platform.Status.UP);
private static Server server = new Dummy51Server();
private DatabaseMigrationState migrationState = mock(DatabaseMigrationState.class);
private Platform platform = mock(Platform.class);
private RestartFlagHolder restartFlagHolder = new RestartFlagHolderImpl();
private WsActionTester underTest = new WsActionTester(new StatusAction(server, migrationState, platform, restartFlagHolder));
@Test
public void action_status_is_defined() {
WebService.Action action = underTest.getDef();
assertThat(action.isPost()).isFalse();
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExample()).isNotNull();
assertThat(action.params()).isEmpty();
}
@Test
public void verify_example() {
when(platform.status()).thenReturn(Platform.Status.UP);
restartFlagHolder.unset();
assertJson(underTest.newRequest().execute().getInput()).isSimilarTo(getClass().getResource("example-status.json"));
}
@Test
public void status_is_UP_if_platform_is_UP_and_restartFlag_is_false_whatever_databaseMigration_status_is() {
for (DatabaseMigrationState.Status databaseMigrationStatus : DatabaseMigrationState.Status.values()) {
verifyStatus(Platform.Status.UP, databaseMigrationStatus, STATUS_UP);
}
}
@Test
public void status_is_RESTARTING_if_platform_is_UP_and_restartFlag_is_true_whatever_databaseMigration_status_is() {
restartFlagHolder.set();
for (DatabaseMigrationState.Status databaseMigrationStatus : DatabaseMigrationState.Status.values()) {
verifyStatus(Platform.Status.UP, databaseMigrationStatus, STATUS_RESTARTING);
}
}
@Test
public void status_is_DOWN_if_platform_is_BOOTING_whatever_databaseMigration_status_is() {
for (DatabaseMigrationState.Status databaseMigrationStatus : DatabaseMigrationState.Status.values()) {
verifyStatus(Platform.Status.BOOTING, databaseMigrationStatus, STATUS_DOWN);
}
}
@Test
public void status_is_DB_MIGRATION_NEEDED_if_platform_is_SAFEMODE_and_databaseMigration_is_NONE() {
verifyStatus(Platform.Status.SAFEMODE, DatabaseMigrationState.Status.NONE, STATUS_MIGRATION_NEEDED);
}
@Test
public void status_is_DB_MIGRATION_RUNNING_if_platform_is_SAFEMODE_and_databaseMigration_is_RUNNING() {
verifyStatus(Platform.Status.SAFEMODE, DatabaseMigrationState.Status.RUNNING, STATUS_MIGRATION_RUNNING);
}
@Test
public void status_is_STATUS_STARTING_if_platform_is_SAFEMODE_and_databaseMigration_is_SUCCEEDED() {
verifyStatus(Platform.Status.SAFEMODE, DatabaseMigrationState.Status.SUCCEEDED, STATUS_STARTING);
}
@Test
public void status_is_DOWN_if_platform_is_SAFEMODE_and_databaseMigration_is_FAILED() {
verifyStatus(Platform.Status.SAFEMODE, DatabaseMigrationState.Status.FAILED, STATUS_DOWN);
}
@Test
public void status_is_STARTING_if_platform_is_STARTING_and_databaseMigration_is_NONE() {
verifyStatus(Platform.Status.STARTING, DatabaseMigrationState.Status.NONE, STATUS_STARTING);
}
@Test
public void status_is_DB_MIGRATION_RUNNING_if_platform_is_STARTING_and_databaseMigration_is_RUNNING() {
verifyStatus(Platform.Status.STARTING, DatabaseMigrationState.Status.RUNNING, STATUS_MIGRATION_RUNNING);
}
@Test
public void status_is_STARTING_if_platform_is_STARTING_and_databaseMigration_is_SUCCEEDED() {
verifyStatus(Platform.Status.STARTING, DatabaseMigrationState.Status.SUCCEEDED, STATUS_STARTING);
}
@Test
public void status_is_DOWN_if_platform_is_STARTING_and_databaseMigration_is_FAILED() {
verifyStatus(Platform.Status.STARTING, DatabaseMigrationState.Status.FAILED, STATUS_DOWN);
}
@Test
public void safety_test_for_new_platform_status() {
for (Platform.Status platformStatus : filter(asList(Platform.Status.values()), not(in(SUPPORTED_PLATFORM_STATUSES)))) {
for (DatabaseMigrationState.Status databaseMigrationStatus : DatabaseMigrationState.Status.values()) {
verifyStatus(platformStatus, databaseMigrationStatus, STATUS_DOWN);
}
}
}
@Test
public void safety_test_for_new_databaseMigration_status_when_platform_is_SAFEMODE() {
for (DatabaseMigrationState.Status databaseMigrationStatus : filter(asList(DatabaseMigrationState.Status.values()), not(in(SUPPORTED_DATABASE_MIGRATION_STATUSES)))) {
when(platform.status()).thenReturn(Platform.Status.SAFEMODE);
when(migrationState.getStatus()).thenReturn(databaseMigrationStatus);
underTest.newRequest().execute();
}
}
private void verifyStatus(Platform.Status platformStatus, DatabaseMigrationState.Status databaseMigrationStatus, String expectedStatus) {
when(platform.status()).thenReturn(platformStatus);
when(migrationState.getStatus()).thenReturn(databaseMigrationStatus);
assertJson(underTest.newRequest().execute().getInput()).isSimilarTo("{" +
" \"status\": \"" + expectedStatus + "\"\n" +
"}");
}
private static class Dummy51Server extends Server {
@Override
public String getId() {
return SERVER_ID;
}
@Override
public String getVersion() {
return SERVER_VERSION;
}
@Override
public Date getStartedAt() {
throw new UnsupportedOperationException();
}
@Override
public String getContextPath() {
throw new UnsupportedOperationException();
}
@Override
public String getPublicRootUrl() {
throw new UnsupportedOperationException();
}
@Override
public boolean isSecured() {
throw new UnsupportedOperationException();
}
@Override
public String getPermanentServerId() {
throw new UnsupportedOperationException();
}
}
}
| 8,354 | 38.976077 | 174 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SystemWsModuleTest.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 static org.assertj.core.api.Assertions.assertThat;
public class SystemWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new SystemWsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(15);
}
}
| 1,265 | 35.171429 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SystemWsTest.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.api.server.ws.WebService;
import org.sonar.server.app.ProcessCommandWrapper;
import org.sonar.server.app.RestartFlagHolder;
import org.sonar.server.platform.NodeInformation;
import org.sonar.server.platform.SystemInfoWriter;
import org.sonar.server.tester.AnonymousMockUserSession;
import org.sonar.server.user.UserSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class SystemWsTest {
@Test
public void define() {
RestartAction action1 = new RestartAction(mock(UserSession.class), mock(ProcessCommandWrapper.class),
mock(RestartFlagHolder.class), mock(NodeInformation.class));
InfoAction action2 = new InfoAction(new AnonymousMockUserSession(), mock(SystemInfoWriter.class));
SystemWs ws = new SystemWs(action1, action2);
WebService.Context context = new WebService.Context();
ws.define(context);
assertThat(context.controllers()).hasSize(1);
assertThat(context.controller("api/system").actions()).hasSize(2);
assertThat(context.controller("api/system").action("info")).isNotNull();
}
}
| 2,023 | 38.686275 | 105 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/UpgradesActionTest.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.Optional;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.DateUtils;
import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.Release;
import org.sonar.updatecenter.common.Sonar;
import org.sonar.updatecenter.common.SonarUpdate;
import org.sonar.updatecenter.common.UpdateCenter;
import org.sonar.updatecenter.common.Version;
import static com.google.common.collect.ImmutableList.of;
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;
import static org.sonar.test.JsonAssert.assertJson;
public class UpgradesActionTest {
private static final String JSON_EMPTY_UPGRADE_LIST = "{" +
" \"upgrades\":" + "[]" +
"}";
private UpdateCenterMatrixFactory updateCenterFactory = mock(UpdateCenterMatrixFactory.class);
private UpdateCenter updateCenter = mock(UpdateCenter.class);
private Sonar sonar = mock(Sonar.class);
private UpgradesAction underTest = new UpgradesAction(updateCenterFactory);
private WsActionTester tester = new WsActionTester(underTest);
private static SonarUpdate createSonar_51_update() {
Plugin brandingPlugin = Plugin.factory("branding")
.setCategory("Integration")
.setName("Branding")
.setDescription("Allows to add your own logo to the SonarQube UI.")
.setHomepageUrl("http://docs.codehaus.org/display/SONAR/Branding+Plugin")
.setLicense("GNU LGPL 3")
.setOrganization("SonarSource")
.setOrganizationUrl("http://www.sonarsource.com")
.setIssueTrackerUrl("http://jira.sonarsource.com/browse/SONARPLUGINS/component/14663")
.setSourcesUrl("https://github.com/SonarCommunity/sonar-branding");
Plugin viewsPlugin = Plugin.factory("views")
.setName("Views")
.setCategory("Governance")
.setDescription("Create aggregation trees to group projects. Projects can for instance be grouped by applications, applications by team, teams by department.")
.setHomepageUrl("https://redirect.sonarsource.com/plugins/views.html")
.setLicense("Commercial")
.setOrganization("SonarSource")
.setOrganizationUrl("http://www.sonarsource.com")
.setTermsConditionsUrl("http://dist.sonarsource.com/SonarSource_Terms_And_Conditions.pdf")
.setIssueTrackerUrl("http://jira.sonarsource.com/browse/VIEWS");
Release release = new Release(new Sonar(), Version.create("5.1.0.5498"))
.setDate(DateUtils.parseDate("2015-04-02"))
.setDescription("New overall layout, merge Issues Drilldown [...]")
.setDownloadUrl("http://dist.sonar.codehaus.org/sonarqube-5.1.zip")
.setChangelogUrl("http://jira.sonarsource.com/secure/ReleaseNote.jspa?projectId=11694&version=20666");
SonarUpdate sonarUpdate = new SonarUpdate(release);
sonarUpdate.addIncompatiblePlugin(brandingPlugin);
sonarUpdate.addPluginToUpgrade(new Release(viewsPlugin, Version.create("2.8.0.5498")).setDisplayVersion("2.8 (build 5498)"));
return sonarUpdate;
}
@Before
public void wireMocks() {
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.of(updateCenter));
when(updateCenter.getSonar()).thenReturn(sonar);
when(updateCenter.getDate()).thenReturn(DateUtils.parseDateTime("2015-04-24T16:08:36+0200"));
}
@Test
public void action_updates_is_defined() {
WebService.Action def = tester.getDef();
assertThat(def.key()).isEqualTo("upgrades");
assertThat(def.isPost()).isFalse();
assertThat(def.description()).isNotEmpty();
assertThat(def.responseExample()).isNotNull();
assertThat(def.params()).isEmpty();
}
@Test
public void empty_array_is_returned_when_there_is_no_upgrade_available() {
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_UPGRADE_LIST);
}
@Test
public void empty_array_is_returned_when_update_center_is_unavailable() {
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.empty());
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_UPGRADE_LIST);
}
@Test
public void verify_JSON_response_against_example() {
SonarUpdate sonarUpdate = createSonar_51_update();
when(sonar.getLtsRelease()).thenReturn(new Release(sonar, Version.create("8.9.2")));
when(updateCenter.findSonarUpdates()).thenReturn(of(sonarUpdate));
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).withStrictArrayOrder()
.isSimilarTo(tester.getDef().responseExampleAsString());
}
}
| 5,850 | 41.398551 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/AbstractUpdateCenterBasedPluginsWsActionTest.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.plugins.ws;
import java.util.Optional;
import org.junit.Before;
import org.sonar.api.utils.DateUtils;
import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.Release;
import org.sonar.updatecenter.common.UpdateCenter;
import org.sonar.updatecenter.common.Version;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.updatecenter.common.PluginUpdate.Status.COMPATIBLE;
import static org.sonar.updatecenter.common.Version.create;
public abstract class AbstractUpdateCenterBasedPluginsWsActionTest {
protected static final String DUMMY_CONTROLLER_KEY = "dummy";
protected static final String JSON_EMPTY_PLUGIN_LIST = "{" +
" \"plugins\":" + "[]" +
"}";
protected static final Plugin PLUGIN_1 = Plugin.factory("pkey1").setName("p_name_1");
protected static final Plugin PLUGIN_2 = Plugin.factory("pkey2").setName("p_name_2").setDescription("p_desc_2");
protected UpdateCenterMatrixFactory updateCenterFactory = mock(UpdateCenterMatrixFactory.class);
protected UpdateCenter updateCenter = mock(UpdateCenter.class);
protected static Release release(Plugin plugin1, String version) {
return new Release(plugin1, create(version));
}
protected static PluginUpdate pluginUpdate(Release pluginRelease, PluginUpdate.Status compatible) {
return PluginUpdate.createWithStatus(pluginRelease, compatible);
}
protected static PluginUpdate pluginUpdate(String key, String name) {
return PluginUpdate.createWithStatus(
new Release(Plugin.factory(key).setName(name), Version.create("1.0")),
COMPATIBLE);
}
@Before
public void wireMocksTogether() {
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.of(updateCenter));
when(updateCenter.getDate()).thenReturn(DateUtils.parseDateTime("2015-04-24T16:08:36+0200"));
}
}
| 2,911 | 41.202899 | 114 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/AvailableActionTest.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.plugins.ws;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.DateUtils;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.Release;
import static com.google.common.collect.ImmutableList.of;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.when;
import static org.sonar.test.JsonAssert.assertJson;
import static org.sonar.updatecenter.common.PluginUpdate.Status.COMPATIBLE;
import static org.sonar.updatecenter.common.PluginUpdate.Status.DEPENDENCIES_REQUIRE_SONAR_UPGRADE;
import static org.sonar.updatecenter.common.PluginUpdate.Status.INCOMPATIBLE;
import static org.sonar.updatecenter.common.PluginUpdate.Status.REQUIRE_SONAR_UPGRADE;
public class AvailableActionTest extends AbstractUpdateCenterBasedPluginsWsActionTest {
private static final Plugin FULL_PROPERTIES_PLUGIN = Plugin.factory("pkey")
.setName("p_name")
.setCategory("p_category")
.setDescription("p_description")
.setLicense("p_license")
.setOrganization("p_orga_name")
.setOrganizationUrl("p_orga_url")
.setHomepageUrl("p_homepage_url")
.setIssueTrackerUrl("p_issue_url")
.setTermsConditionsUrl("p_t_and_c_url");
private static final Release FULL_PROPERTIES_PLUGIN_RELEASE = release(FULL_PROPERTIES_PLUGIN, "1.12.1")
.setDate(DateUtils.parseDate("2015-04-16"))
.setDownloadUrl("http://p_file.jar")
.addOutgoingDependency(release(PLUGIN_1, "0.3.6"))
.addOutgoingDependency(release(PLUGIN_2, "1.0.0"));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private AvailableAction underTest = new AvailableAction(userSession, updateCenterFactory);
private WsActionTester tester = new WsActionTester(underTest);
@Test
public void action_available_is_defined() {
WebService.Action action = tester.getDef();
assertThat(action.key()).isEqualTo("available");
assertThat(action.isPost()).isFalse();
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExample()).isNotNull();
}
@Test
public void verify_example() {
logInAsSystemAdministrator();
when(updateCenter.findAvailablePlugins()).thenReturn(of(
pluginUpdate(release(Plugin.factory("abap")
.setName("ABAP")
.setCategory("Languages")
.setDescription("Enable analysis and reporting on ABAP projects")
.setLicense("Commercial")
.setOrganization("SonarSource")
.setOrganizationUrl("http://www.sonarsource.com")
.setTermsConditionsUrl("http://dist.sonarsource.com/SonarSource_Terms_And_Conditions.pdf"),
"3.2")
.setDate(DateUtils.parseDate("2015-03-10")),
COMPATIBLE),
pluginUpdate(release(Plugin.factory("android")
.setName("Android")
.setCategory("Languages")
.setDescription("Import Android Lint reports.")
.setLicense("GNU LGPL 3")
.setOrganization("SonarSource and Jerome Van Der Linden, Stephane Nicolas, Florian Roncari, Thomas Bores")
.setOrganizationUrl("http://www.sonarsource.com"),
"1.0")
.setDate(DateUtils.parseDate("2014-03-31"))
.addOutgoingDependency(release(Plugin.factory("java").setName("Java").setDescription("SonarQube rule engine."), "0.3.6")),
COMPATIBLE)));
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).isSimilarTo(tester.getDef().responseExampleAsString());
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() {
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() {
userSession.logIn().setNonSystemAdministrator();
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void empty_array_is_returned_when_there_is_no_plugin_available() {
logInAsSystemAdministrator();
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST);
}
@Test
public void empty_array_is_returned_when_update_center_is_not_accessible() {
logInAsSystemAdministrator();
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.empty());
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST);
}
@Test
public void verify_properties_displayed_in_json_per_plugin() {
logInAsSystemAdministrator();
when(updateCenter.findAvailablePlugins()).thenReturn(of(
pluginUpdate(FULL_PROPERTIES_PLUGIN_RELEASE, COMPATIBLE)));
TestResponse response = tester.newRequest().execute();
response.assertJson(
"{" +
" \"plugins\": [" +
" {" +
" \"key\": \"pkey\"," +
" \"name\": \"p_name\"," +
" \"category\": \"p_category\"," +
" \"description\": \"p_description\"," +
" \"license\": \"p_license\"," +
" \"termsAndConditionsUrl\": \"p_t_and_c_url\"," +
" \"organizationName\": \"p_orga_name\"," +
" \"organizationUrl\": \"p_orga_url\"," +
" \"homepageUrl\": \"p_homepage_url\"," +
" \"issueTrackerUrl\": \"p_issue_url\"," +
" \"release\": {" +
" \"version\": \"1.12.1\"," +
" \"date\": \"2015-04-16\"" +
" }," +
" \"update\": {" +
" \"status\": \"COMPATIBLE\"," +
" \"requires\": [" +
" {" +
" \"key\": \"pkey1\"," +
" \"name\": \"p_name_1\"" +
" }," +
" {" +
" \"key\": \"pkey2\"," +
" \"name\": \"p_name_2\"," +
" \"description\": \"p_desc_2\"" +
" }" +
" ]" +
" }" +
" }" +
" ]," +
" \"updateCenterRefresh\": \"2015-04-24T16:08:36+0200\"" +
"}");
}
@Test
public void status_COMPATIBLE_is_displayed_COMPATIBLE_in_JSON() {
logInAsSystemAdministrator();
checkStatusDisplayedInJson(COMPATIBLE, "COMPATIBLE");
}
@Test
public void status_INCOMPATIBLE_is_displayed_INCOMPATIBLE_in_JSON() {
logInAsSystemAdministrator();
checkStatusDisplayedInJson(INCOMPATIBLE, "INCOMPATIBLE");
}
@Test
public void status_REQUIRE_SONAR_UPGRADE_is_displayed_REQUIRES_SYSTEM_UPGRADE_in_JSON() {
logInAsSystemAdministrator();
checkStatusDisplayedInJson(REQUIRE_SONAR_UPGRADE, "REQUIRES_SYSTEM_UPGRADE");
}
@Test
public void status_DEPENDENCIES_REQUIRE_SONAR_UPGRADE_is_displayed_DEPS_REQUIRE_SYSTEM_UPGRADE_in_JSON() {
logInAsSystemAdministrator();
checkStatusDisplayedInJson(DEPENDENCIES_REQUIRE_SONAR_UPGRADE, "DEPS_REQUIRE_SYSTEM_UPGRADE");
}
private void checkStatusDisplayedInJson(PluginUpdate.Status status, String expectedValue) {
when(updateCenter.findAvailablePlugins()).thenReturn(of(
pluginUpdate(release(PLUGIN_1, "1.0.0"), status)));
TestResponse response = tester.newRequest().execute();
response.assertJson(
"{" +
" \"plugins\": [" +
" {" +
" \"update\": {" +
" \"status\": \"" + expectedValue + "\"" +
" }" +
" }" +
" ]" +
"}");
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
}
| 9,058 | 37.223629 | 132 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/CancelAllActionTest.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.plugins.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.plugins.PluginDownloader;
import org.sonar.server.plugins.PluginUninstaller;
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;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class CancelAllActionTest {
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
private PluginDownloader pluginDownloader = mock(PluginDownloader.class);
private PluginUninstaller pluginUninstaller = mock(PluginUninstaller.class);
private CancelAllAction underTest = new CancelAllAction(pluginDownloader, pluginUninstaller, userSessionRule);
private WsActionTester tester = new WsActionTester(underTest);
@Test
public void action_cancel_all_is_defined() {
WebService.Action action = tester.getDef();
assertThat(action.key()).isEqualTo("cancel_all");
assertThat(action.isPost()).isTrue();
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExample()).isNull();
assertThat(action.params()).isEmpty();
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() {
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(ForbiddenException.class)
.hasMessageContaining("Insufficient privileges");
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() {
userSessionRule.logIn().setNonSystemAdministrator();
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(ForbiddenException.class)
.hasMessageContaining("Insufficient privileges");
}
@Test
public void triggers_cancel_for_downloads_and_uninstalls() {
userSessionRule.logIn().setSystemAdministrator();
TestResponse response = tester.newRequest().execute();
verify(pluginDownloader, times(1)).cancelDownloads();
verify(pluginUninstaller, times(1)).cancelUninstalls();
assertThat(response.getInput()).isEmpty();
}
}
| 3,251 | 36.813953 | 112 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/DownloadActionTest.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.plugins.ws;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.assertj.core.groups.Tuple;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.platform.PluginInfo;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.plugins.PluginFilesAndMd5.FileAndMd5;
import org.sonar.core.plugin.PluginType;
import org.sonar.server.plugins.ServerPlugin;
import org.sonar.server.plugins.ServerPluginRepository;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsAction;
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.Mockito.mock;
import static org.mockito.Mockito.when;
public class DownloadActionTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private final ServerPluginRepository serverPluginRepository = mock(ServerPluginRepository.class);
private final WsAction underTest = new DownloadAction(serverPluginRepository);
private final WsActionTester tester = new WsActionTester(underTest);
@Test
public void test_definition() {
WebService.Action def = tester.getDef();
assertThat(def.isInternal()).isTrue();
assertThat(def.since()).isEqualTo("7.2");
assertThat(def.params())
.extracting(WebService.Param::key)
.containsExactlyInAnyOrder("plugin");
assertThat(def.changelog())
.extracting(Change::getVersion, Change::getDescription)
.containsExactlyInAnyOrder(new Tuple("9.8", "Parameter 'acceptCompressions' removed"));
}
@Test
public void return_404_if_plugin_not_found() {
when(serverPluginRepository.findPlugin("foo")).thenReturn(Optional.empty());
TestRequest request = tester.newRequest().setParam("plugin", "foo");
assertThatThrownBy(request::execute)
.isInstanceOf(NotFoundException.class)
.hasMessage("Plugin foo not found");
}
@Test
public void return_jar_if_plugin_exists() throws Exception {
ServerPlugin plugin = newPlugin();
when(serverPluginRepository.findPlugin(plugin.getPluginInfo().getKey())).thenReturn(Optional.of(plugin));
TestResponse response = tester.newRequest()
.setParam("plugin", plugin.getPluginInfo().getKey())
.execute();
assertThat(response.getHeader("Sonar-MD5")).isEqualTo(plugin.getJar().getMd5());
assertThat(response.getHeader("Sonar-Compression")).isNull();
assertThat(response.getMediaType()).isEqualTo("application/java-archive");
verifySameContent(response, plugin.getJar().getFile());
}
private ServerPlugin newPlugin() throws IOException {
FileAndMd5 jar = new FileAndMd5(temp.newFile());
return new ServerPlugin(new PluginInfo("foo"), PluginType.BUNDLED, null, jar, null);
}
private static void verifySameContent(TestResponse response, File file) throws IOException {
assertThat(IOUtils.toByteArray(response.getInputStream())).isEqualTo(FileUtils.readFileToByteArray(file));
}
}
| 4,148 | 38.514286 | 110 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/InstallActionTest.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.plugins.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.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.extension.PluginRiskConsent;
import org.sonar.core.platform.EditionProvider.Edition;
import org.sonar.core.platform.PlatformEditionProvider;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.plugins.PluginDownloader;
import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.Release;
import org.sonar.updatecenter.common.UpdateCenter;
import org.sonar.updatecenter.common.Version;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.core.config.CorePropertyDefinitions.PLUGINS_RISK_CONSENT;
@RunWith(DataProviderRunner.class)
public class InstallActionTest {
private static final String ACTION_KEY = "install";
private static final String KEY_PARAM = "key";
private static final String PLUGIN_KEY = "pluginKey";
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
private UpdateCenterMatrixFactory updateCenterFactory = mock(UpdateCenterMatrixFactory.class);
private UpdateCenter updateCenter = mock(UpdateCenter.class);
private PluginDownloader pluginDownloader = mock(PluginDownloader.class);
private Configuration configuration = mock(Configuration.class);
private PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class);
private InstallAction underTest = new InstallAction(updateCenterFactory, pluginDownloader, userSessionRule, configuration,
editionProvider);
private WsActionTester tester = new WsActionTester(underTest);
@Before
public void wireMocks() {
when(editionProvider.get()).thenReturn(Optional.of(Edition.COMMUNITY));
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.of(updateCenter));
when(configuration.get(PLUGINS_RISK_CONSENT)).thenReturn(Optional.of(PluginRiskConsent.ACCEPTED.name()));
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() {
TestRequest wsRequest = tester.newRequest();
assertThatThrownBy(wsRequest::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() {
userSessionRule.logIn().setNonSystemAdministrator();
TestRequest request = tester.newRequest();
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void action_install_is_defined() {
WebService.Action action = tester.getDef();
assertThat(action.isPost()).isTrue();
assertThat(action.key()).isEqualTo(ACTION_KEY);
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExample()).isNull();
assertThat(action.params()).hasSize(1);
WebService.Param keyParam = action.param(KEY_PARAM);
assertThat(keyParam).isNotNull();
assertThat(keyParam.isRequired()).isTrue();
assertThat(keyParam.description()).isNotNull();
}
@Test
public void IAE_is_raised_when_key_param_is_not_provided() {
logInAsSystemAdministrator();
TestRequest request = tester.newRequest();
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void IAE_is_raised_when_there_is_no_available_plugin_for_the_key() {
logInAsSystemAdministrator();
TestRequest request = tester.newRequest()
.setParam(KEY_PARAM, PLUGIN_KEY);
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("No plugin with key 'pluginKey'");
}
@Test
@UseDataProvider("editionBundledOrganizationAndLicense")
public void IAE_is_raised_when_plugin_is_edition_bundled(String organization, String license) {
logInAsSystemAdministrator();
Version version = Version.create("1.0");
when(updateCenter.findAvailablePlugins()).thenReturn(ImmutableList.of(
PluginUpdate.createWithStatus(new Release(Plugin.factory(PLUGIN_KEY)
.setLicense(license)
.setOrganization(organization), version), PluginUpdate.Status.COMPATIBLE)));
TestRequest request = tester.newRequest()
.setParam(KEY_PARAM, PLUGIN_KEY);
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("SonarSource commercial plugin with key '" + PLUGIN_KEY + "' can only be installed as part of a SonarSource edition");
}
@DataProvider
public static Object[][] editionBundledOrganizationAndLicense() {
return new Object[][] {
{"SonarSource", "SonarSource"},
{"SonarSource", "Commercial"},
{"sonarsource", "SOnArSOURCE"}
};
}
@Test
public void IAE_is_raised_when_WS_used_on_commercial_edition() {
logInAsSystemAdministrator();
Version version = Version.create("1.0");
when(updateCenter.findAvailablePlugins()).thenReturn(ImmutableList.of(
PluginUpdate.createWithStatus(new Release(Plugin.factory(PLUGIN_KEY), version), PluginUpdate.Status.COMPATIBLE)));
when(editionProvider.get()).thenReturn(Optional.of(Edition.DEVELOPER));
TestRequest request = tester.newRequest()
.setParam(KEY_PARAM, PLUGIN_KEY);
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("This WS is unsupported in commercial edition. Please install plugin manually.");
}
@Test
public void IAE_is_raised_when_update_center_is_unavailable() {
logInAsSystemAdministrator();
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.empty());
TestRequest request = tester.newRequest()
.setParam(KEY_PARAM, PLUGIN_KEY);
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("No plugin with key 'pluginKey'");
}
@Test
public void if_plugin_is_found_available_download_is_triggered_with_latest_version_from_updatecenter() {
logInAsSystemAdministrator();
Version version = Version.create("1.0");
when(updateCenter.findAvailablePlugins()).thenReturn(ImmutableList.of(
PluginUpdate.createWithStatus(new Release(Plugin.factory(PLUGIN_KEY), version), PluginUpdate.Status.COMPATIBLE)));
TestResponse response = tester.newRequest()
.setParam(KEY_PARAM, PLUGIN_KEY)
.execute();
verify(pluginDownloader).download(PLUGIN_KEY, version);
response.assertNoContent();
}
@Test
public void handle_givenRiskConsentNotAccepted_expectServerError() {
logInAsSystemAdministrator();
when(configuration.get(PLUGINS_RISK_CONSENT)).thenReturn(Optional.of(PluginRiskConsent.NOT_ACCEPTED.name()));
TestRequest request = tester.newRequest()
.setParam(KEY_PARAM, PLUGIN_KEY);
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Can't install plugin without accepting firstly plugins risk consent");
}
private void logInAsSystemAdministrator() {
userSessionRule.logIn().setSystemAdministrator();
}
}
| 8,908 | 38.950673 | 136 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PendingActionTest.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.plugins.ws;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.platform.PluginInfo;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.plugins.PluginDownloader;
import org.sonar.server.plugins.PluginUninstaller;
import org.sonar.server.plugins.ServerPluginRepository;
import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.UpdateCenter;
import org.sonar.updatecenter.common.Version;
import static com.google.common.collect.ImmutableList.of;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.test.JsonAssert.assertJson;
public class PendingActionTest {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private PluginDownloader pluginDownloader = mock(PluginDownloader.class);
private PluginUninstaller pluginUninstaller = mock(PluginUninstaller.class);
private ServerPluginRepository serverPluginRepository = mock(ServerPluginRepository.class);
private UpdateCenterMatrixFactory updateCenterMatrixFactory = mock(UpdateCenterMatrixFactory.class, RETURNS_DEEP_STUBS);
private PendingAction underTest = new PendingAction(userSession, pluginDownloader, serverPluginRepository,
pluginUninstaller, updateCenterMatrixFactory);
private WsActionTester tester = new WsActionTester(underTest);
@Test
public void action_pending_is_defined() {
WebService.Action action = tester.getDef();
assertThat(action.isPost()).isFalse();
assertThat(action.key()).isEqualTo("pending");
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExample()).isNotNull();
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() {
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() {
userSession.logIn().setNonSystemAdministrator();
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void empty_arrays_are_returned_when_there_nothing_pending() {
logInAsSystemAdministrator();
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(
"{" +
" \"installing\": []," +
" \"removing\": []," +
" \"updating\": []" +
"}");
}
@Test
public void empty_arrays_are_returned_when_update_center_is_unavailable() {
logInAsSystemAdministrator();
when(updateCenterMatrixFactory.getUpdateCenter(false)).thenReturn(Optional.empty());
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(
"{" +
" \"installing\": []," +
" \"removing\": []," +
" \"updating\": []" +
"}");
}
@Test
public void verify_properties_displayed_in_json_per_installing_plugin() {
logInAsSystemAdministrator();
newUpdateCenter("scmgit");
when(pluginDownloader.getDownloadedPlugins()).thenReturn(of(newScmGitPluginInfo()));
TestResponse response = tester.newRequest().execute();
response.assertJson(
"{" +
" \"installing\": " +
" [" +
" {" +
" \"key\": \"scmgit\"," +
" \"name\": \"Git\"," +
" \"description\": \"Git SCM Provider.\"," +
" \"version\": \"1.0\"," +
" \"license\": \"GNU LGPL 3\"," +
" \"category\":\"cat_1\"," +
" \"organizationName\": \"SonarSource\"," +
" \"organizationUrl\": \"http://www.sonarsource.com\"," +
" \"homepageUrl\": \"https://redirect.sonarsource.com/plugins/scmgit.html\"," +
" \"issueTrackerUrl\": \"http://jira.sonarsource.com/browse/SONARSCGIT\"," +
" \"implementationBuild\": \"9ce9d330c313c296fab051317cc5ad4b26319e07\"" +
" }" +
" ]," +
" \"removing\": []," +
" \"updating\": []" +
"}");
}
@Test
public void verify_properties_displayed_in_json_per_removing_plugin() {
logInAsSystemAdministrator();
when(pluginUninstaller.getUninstalledPlugins()).thenReturn(of(newScmGitPluginInfo()));
TestResponse response = tester.newRequest().execute();
response.assertJson(
"{" +
" \"installing\": []," +
" \"updating\": []," +
" \"removing\": " +
" [" +
" {" +
" \"key\": \"scmgit\"," +
" \"name\": \"Git\"," +
" \"description\": \"Git SCM Provider.\"," +
" \"version\": \"1.0\"," +
" \"license\": \"GNU LGPL 3\"," +
" \"organizationName\": \"SonarSource\"," +
" \"organizationUrl\": \"http://www.sonarsource.com\"," +
" \"homepageUrl\": \"https://redirect.sonarsource.com/plugins/scmgit.html\"," +
" \"issueTrackerUrl\": \"http://jira.sonarsource.com/browse/SONARSCGIT\"," +
" \"implementationBuild\": \"9ce9d330c313c296fab051317cc5ad4b26319e07\"" +
" }" +
" ]" +
"}");
}
@Test
public void verify_properties_displayed_in_json_per_updating_plugin() {
logInAsSystemAdministrator();
newUpdateCenter("scmgit");
when(serverPluginRepository.getPluginInfos()).thenReturn(of(newScmGitPluginInfo()));
when(pluginDownloader.getDownloadedPlugins()).thenReturn(of(newScmGitPluginInfo()));
TestResponse response = tester.newRequest().execute();
response.assertJson(
"{" +
" \"installing\": []," +
" \"removing\": []," +
" \"updating\": " +
" [" +
" {" +
" \"key\": \"scmgit\"" +
" }" +
" ]" +
"}");
}
@Test
public void verify_properties_displayed_in_json_per_installing_removing_and_updating_plugins() {
logInAsSystemAdministrator();
PluginInfo installed = newPluginInfo("java");
PluginInfo removedPlugin = newPluginInfo("js");
PluginInfo newPlugin = newPluginInfo("php");
newUpdateCenter("scmgit");
when(serverPluginRepository.getPluginInfos()).thenReturn(of(installed));
when(pluginUninstaller.getUninstalledPlugins()).thenReturn(of(removedPlugin));
when(pluginDownloader.getDownloadedPlugins()).thenReturn(of(newPlugin, installed));
TestResponse response = tester.newRequest().execute();
response.assertJson(
"{" +
" \"installing\":" +
" [" +
" {" +
" \"key\": \"php\"" +
" }" +
" ]," +
" \"removing\":" +
" [" +
" {" +
" \"key\": \"js\"" +
" }" +
" ]," +
" \"updating\": " +
" [" +
" {" +
" \"key\": \"java\"" +
" }" +
" ]" +
"}");
}
@Test
public void installing_plugins_are_sorted_by_name_then_key_and_are_unique() {
logInAsSystemAdministrator();
when(pluginDownloader.getDownloadedPlugins()).thenReturn(of(
newPluginInfo(0).setName("Foo"),
newPluginInfo(3).setName("Bar"),
newPluginInfo(2).setName("Bar")));
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(
"{" +
" \"installing\": " +
" [" +
" {" +
" \"key\": \"key2\"," +
" \"name\": \"Bar\"," +
" }," +
" {" +
" \"key\": \"key3\"," +
" \"name\": \"Bar\"," +
" }," +
" {" +
" \"key\": \"key0\"," +
" \"name\": \"Foo\"," +
" }" +
" ]," +
" \"removing\": []," +
" \"updating\": []" +
"}");
}
@Test
public void removing_plugins_are_sorted_and_unique() {
logInAsSystemAdministrator();
when(pluginUninstaller.getUninstalledPlugins()).thenReturn(of(
newPluginInfo(0).setName("Foo"),
newPluginInfo(3).setName("Bar"),
newPluginInfo(2).setName("Bar")));
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(
"{" +
" \"installing\": []," +
" \"updating\": []," +
" \"removing\": " +
" [" +
" {" +
" \"key\": \"key2\"," +
" \"name\": \"Bar\"," +
" }," +
" {" +
" \"key\": \"key3\"," +
" \"name\": \"Bar\"," +
" }," +
" {" +
" \"key\": \"key0\"," +
" \"name\": \"Foo\"," +
" }" +
" ]" +
"}");
}
private PluginInfo newScmGitPluginInfo() {
return new PluginInfo("scmgit")
.setName("Git")
.setDescription("Git SCM Provider.")
.setVersion(Version.create("1.0"))
.setLicense("GNU LGPL 3")
.setOrganizationName("SonarSource")
.setOrganizationUrl("http://www.sonarsource.com")
.setHomepageUrl("https://redirect.sonarsource.com/plugins/scmgit.html")
.setIssueTrackerUrl("http://jira.sonarsource.com/browse/SONARSCGIT")
.setImplementationBuild("9ce9d330c313c296fab051317cc5ad4b26319e07");
}
private PluginInfo newPluginInfo(String key) {
return new PluginInfo(key);
}
private UpdateCenter newUpdateCenter(String... pluginKeys) {
UpdateCenter updateCenter = mock(UpdateCenter.class);
when(updateCenterMatrixFactory.getUpdateCenter(false)).thenReturn(Optional.of(updateCenter));
List<Plugin> plugins = new ArrayList<>();
for (String pluginKey : pluginKeys) {
plugins.add(Plugin.factory(pluginKey).setCategory("cat_1"));
}
when(updateCenter.findAllCompatiblePlugins()).thenReturn(plugins);
return updateCenter;
}
private PluginInfo newPluginInfo(int id) {
return new PluginInfo("key" + id).setName("name" + id);
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
}
| 11,517 | 33.692771 | 122 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginUpdateAggregateBuilderTest.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.plugins.ws;
import org.junit.Test;
import org.sonar.server.plugins.ws.PluginUpdateAggregator.PluginUpdateAggregateBuilder;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.Release;
import org.sonar.updatecenter.common.Version;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class PluginUpdateAggregateBuilderTest {
private static final Plugin PLUGIN_1 = Plugin.factory("key1");
private static final Plugin PLUGIN_2 = Plugin.factory("key2");
private static final Version SOME_VERSION = Version.create("1.0");
private static final PluginUpdate.Status SOME_STATUS = PluginUpdate.Status.COMPATIBLE;
@Test
public void plugin_can_not_be_null_and_builderFor_enforces_it_with_NPE() {
assertThatThrownBy(() -> PluginUpdateAggregateBuilder.builderFor(null))
.isInstanceOf(NullPointerException.class);
}
@Test
public void add_throws_IAE_when_plugin_is_not_equal_to_the_one_of_the_builder() {
PluginUpdateAggregateBuilder builder = PluginUpdateAggregateBuilder.builderFor(PLUGIN_1);
assertThatThrownBy(() -> builder.add(createPluginUpdate(PLUGIN_2)))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void add_uses_equals_which_takes_only_key_into_account() {
PluginUpdateAggregateBuilder builder = PluginUpdateAggregateBuilder.builderFor(PLUGIN_1);
builder.add(createPluginUpdate(Plugin.factory(PLUGIN_1.getKey())));
}
private static PluginUpdate createPluginUpdate(Plugin plugin) {
return PluginUpdate.createWithStatus(new Release(plugin, SOME_VERSION), SOME_STATUS);
}
}
| 2,528 | 39.142857 | 93 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginUpdateAggregatorTest.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.plugins.ws;
import com.google.common.collect.ImmutableList;
import java.util.Collection;
import java.util.Collections;
import org.junit.Test;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.Release;
import org.sonar.updatecenter.common.Version;
import static org.assertj.core.api.Assertions.assertThat;
public class PluginUpdateAggregatorTest {
public static final Version SOME_VERSION = Version.create("1.0");
public static final PluginUpdate.Status SOME_STATUS = PluginUpdate.Status.COMPATIBLE;
private PluginUpdateAggregator underTest = new PluginUpdateAggregator();
@Test
public void aggregates_returns_an_empty_collection_when_plugin_collection_is_null() {
assertThat(underTest.aggregate(null)).isEmpty();
}
@Test
public void aggregates_returns_an_empty_collection_when_plugin_collection_is_empty() {
assertThat(underTest.aggregate(Collections.emptyList())).isEmpty();
}
@Test
public void aggregates_groups_pluginUpdate_per_plugin_key() {
Collection<PluginUpdateAggregator.PluginUpdateAggregate> aggregates = underTest.aggregate(ImmutableList.of(
createPluginUpdate("key1"),
createPluginUpdate("key1"),
createPluginUpdate("key0"),
createPluginUpdate("key2"),
createPluginUpdate("key0")));
assertThat(aggregates).hasSize(3);
assertThat(aggregates).extracting("plugin.key").containsOnlyOnce("key1", "key0", "key2");
}
@Test
public void aggregate_put_pluginUpdates_with_same_plugin_in_the_same_PluginUpdateAggregate() {
PluginUpdate pluginUpdate1 = createPluginUpdate("key1");
PluginUpdate pluginUpdate2 = createPluginUpdate("key1");
PluginUpdate pluginUpdate3 = createPluginUpdate("key1");
Collection<PluginUpdateAggregator.PluginUpdateAggregate> aggregates = underTest.aggregate(ImmutableList.of(
pluginUpdate1,
pluginUpdate2,
pluginUpdate3));
assertThat(aggregates).hasSize(1);
Collection<PluginUpdate> releases = aggregates.iterator().next().getUpdates();
assertThat(releases)
.hasSize(3)
.contains(pluginUpdate1)
.contains(pluginUpdate2)
.contains(pluginUpdate3);
}
private PluginUpdate createPluginUpdate(String pluginKey) {
return PluginUpdate.createWithStatus(new Release(Plugin.factory(pluginKey), SOME_VERSION), SOME_STATUS);
}
}
| 3,264 | 37.411765 | 111 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginsWsTest.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.plugins.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 PluginsWsTest {
private PluginsWs underTest = new PluginsWs(new DummyPluginsWsAction());
@Test
public void defines_controller_and_binds_PluginsWsActions() {
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/plugins");
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo("5.2");
assertThat(controller.description()).isNotEmpty();
assertThat(controller.actions()).extracting("key").containsOnly("dummy");
}
private static class DummyPluginsWsAction implements PluginsWsAction {
@Override
public void define(WebService.NewController context) {
context
.createAction("dummy")
.setDescription("Dummy Description")
.setPost(true)
.setSince("5.3")
.setHandler(this);
}
@Override
public void handle(Request request, Response response) {
// not relevant to test
}
}
}
| 2,097 | 32.83871 | 77 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UninstallActionTest.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.plugins.ws;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.plugins.PluginUninstaller;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
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;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@RunWith(DataProviderRunner.class)
public class UninstallActionTest {
private static final String ACTION_KEY = "uninstall";
private static final String KEY_PARAM = "key";
private static final String PLUGIN_KEY = "findbugs";
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
private PluginUninstaller pluginUninstaller = mock(PluginUninstaller.class);
private UninstallAction underTest = new UninstallAction(pluginUninstaller, userSessionRule);
private WsActionTester tester = new WsActionTester(underTest);
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() {
TestRequest request = tester.newRequest();
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() {
userSessionRule.logIn().setNonSystemAdministrator();
TestRequest request = tester.newRequest();
assertThatThrownBy(request::execute)
.isInstanceOf(ForbiddenException.class)
.hasMessage("Insufficient privileges");
}
@Test
public void action_uninstall_is_defined() {
WebService.Action action = tester.getDef();
assertThat(action.key()).isEqualTo(ACTION_KEY);
assertThat(action.isPost()).isTrue();
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExample()).isNull();
assertThat(action.params()).hasSize(1);
WebService.Param keyParam = action.param(KEY_PARAM);
assertThat(keyParam).isNotNull();
assertThat(keyParam.isRequired()).isTrue();
assertThat(keyParam.description()).isNotNull();
}
@Test
public void IAE_is_raised_when_key_param_is_not_provided() {
logInAsSystemAdministrator();
TestRequest request = tester.newRequest();
assertThatThrownBy(request::execute)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void uninstaller_is_called() {
logInAsSystemAdministrator();
TestResponse response = tester.newRequest()
.setParam(KEY_PARAM, PLUGIN_KEY)
.execute();
verify(pluginUninstaller).uninstall(PLUGIN_KEY);
assertThat(response.getInput()).isEmpty();
}
private void logInAsSystemAdministrator() {
userSessionRule.logIn().setSystemAdministrator();
}
}
| 3,924 | 33.734513 | 94 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdateActionTest.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.plugins.ws;
import com.google.common.collect.ImmutableList;
import java.util.Optional;
import org.junit.Before;
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.plugins.PluginDownloader;
import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.PluginUpdate.Status;
import org.sonar.updatecenter.common.Release;
import org.sonar.updatecenter.common.UpdateCenter;
import org.sonar.updatecenter.common.Version;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class UpdateActionTest {
private static final String ACTION_KEY = "update";
private static final String KEY_PARAM = "key";
private static final String PLUGIN_KEY = "pluginKey";
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
private UpdateCenterMatrixFactory updateCenterFactory = mock(UpdateCenterMatrixFactory.class);
private UpdateCenter updateCenter = mock(UpdateCenter.class);
private PluginDownloader pluginDownloader = mock(PluginDownloader.class);
private UpdateAction underTest = new UpdateAction(updateCenterFactory, pluginDownloader, userSessionRule);
private WsActionTester tester = new WsActionTester(underTest);
@Before
public void setUp() {
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.of(updateCenter));
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() {
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(ForbiddenException.class)
.hasMessageContaining("Insufficient privileges");
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() {
userSessionRule.logIn().setNonSystemAdministrator();
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(ForbiddenException.class)
.hasMessageContaining("Insufficient privileges");
}
@Test
public void action_update_is_defined() {
WebService.Action action = tester.getDef();
assertThat(action.key()).isEqualTo(ACTION_KEY);
assertThat(action.isPost()).isTrue();
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExample()).isNull();
assertThat(action.params()).hasSize(1);
WebService.Param key = action.param(KEY_PARAM);
assertThat(key).isNotNull();
assertThat(key.isRequired()).isTrue();
assertThat(key.description()).isNotNull();
}
@Test
public void IAE_is_raised_when_key_param_is_not_provided() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void IAE_is_raised_when_there_is_no_plugin_update_for_the_key() {
logInAsSystemAdministrator();
assertThatThrownBy(() -> tester.newRequest().setParam(KEY_PARAM, PLUGIN_KEY).execute())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("No plugin with key 'pluginKey'");
}
@Test
public void IAE_is_raised_when_update_center_is_unavailable() {
logInAsSystemAdministrator();
when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.empty());
assertThatThrownBy(() -> tester.newRequest().setParam(KEY_PARAM, PLUGIN_KEY).execute())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("No plugin with key 'pluginKey'");
}
@Test
public void if_plugin_has_an_update_download_is_triggered_with_latest_version_from_updatecenter() {
logInAsSystemAdministrator();
Version version = Version.create("1.0");
when(updateCenter.findPluginUpdates()).thenReturn(ImmutableList.of(
PluginUpdate.createWithStatus(new Release(Plugin.factory(PLUGIN_KEY), version), Status.COMPATIBLE)));
TestResponse response = tester.newRequest()
.setParam(KEY_PARAM, PLUGIN_KEY)
.execute();
verify(pluginDownloader).download(PLUGIN_KEY, version);
assertThat(response.getInput()).isEmpty();
}
private void logInAsSystemAdministrator() {
userSessionRule.logIn().setSystemAdministrator();
}
}
| 5,555 | 37.054795 | 108 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdatesActionTest.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.plugins.ws;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.DateUtils;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.Release;
import static com.google.common.collect.ImmutableList.of;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.when;
import static org.sonar.test.JsonAssert.assertJson;
import static org.sonar.updatecenter.common.PluginUpdate.Status.COMPATIBLE;
import static org.sonar.updatecenter.common.PluginUpdate.Status.INCOMPATIBLE;
public class UpdatesActionTest extends AbstractUpdateCenterBasedPluginsWsActionTest {
private static final Plugin JAVA_PLUGIN = Plugin.factory("java")
.setName("Java")
.setDescription("SonarQube rule engine.");
private static final Plugin ABAP_PLUGIN = Plugin.factory("abap")
.setName("ABAP")
.setCategory("Languages")
.setDescription("Enable analysis and reporting on ABAP projects")
.setLicense("Commercial")
.setOrganization("SonarSource")
.setOrganizationUrl("http://www.sonarsource.com")
.setTermsConditionsUrl("http://dist.sonarsource.com/SonarSource_Terms_And_Conditions.pdf");
private static final Release ABAP_31 = release(ABAP_PLUGIN, "3.1")
.setDate(DateUtils.parseDate("2014-12-21"))
.setDescription("New rules, several improvements")
.setDownloadUrl("http://dist.sonarsource.com/abap/download/sonar-abap-plugin-3.1.jar")
.setChangelogUrl("http://jira.sonarsource.com/secure/ReleaseNote.jspa?projectId=10054&version=10552");
private static final Release ABAP_32 = release(ABAP_PLUGIN, "3.2")
.setDate(DateUtils.parseDate("2015-03-10"))
.setDescription("14 new rules, most of them designed to detect potential performance hotspots.")
.setDownloadUrl("http://dist.sonarsource.com/abap/download/sonar-abap-plugin-3.2.jar")
.setChangelogUrl("http://jira.sonarsource.com/secure/ReleaseNote.jspa?projectId=10054&version=10575");
private static final Plugin ANDROID_PLUGIN = Plugin.factory("android")
.setName("Android")
.setCategory("Languages")
.setDescription("Import Android Lint reports.")
.setLicense("GNU LGPL 3")
.setOrganization("SonarSource and Jerome Van Der Linden, Stephane Nicolas, Florian Roncari, Thomas Bores")
.setOrganizationUrl("http://www.sonarsource.com");
private static final Release ANDROID_10 = release(ANDROID_PLUGIN, "1.0")
.setDate(DateUtils.parseDate("2014-03-31"))
.setDescription("Makes the plugin compatible with multi-language analysis introduced in SonarQube 4.2 and adds support of Emma 2.0 reports")
.setDownloadUrl("http://repository.codehaus.org/org/codehaus/sonar-plugins/android/sonar-android-plugin/1.0/sonar-android-plugin-1.0.jar")
.setChangelogUrl("http://jira.sonarsource.com/secure/ReleaseNote.jspa?projectId=13235&version=20187")
.addOutgoingDependency(release(JAVA_PLUGIN, "1.0"));
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private UpdatesAction underTest = new UpdatesAction(userSession, updateCenterFactory, new PluginUpdateAggregator());
private WsActionTester tester = new WsActionTester(underTest);
@Test
public void action_updatable_is_defined() {
WebService.Action action = tester.getDef();
assertThat(action.isPost()).isFalse();
assertThat(action.key()).isEqualTo("updates");
assertThat(action.description()).isNotEmpty();
assertThat(action.responseExample()).isNotNull();
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() {
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() {
userSession.logIn();
assertThatThrownBy(() -> tester.newRequest().execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void empty_array_is_returned_when_there_is_no_plugin_available() {
logInAsSystemAdministrator();
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST);
}
@Test
public void verify_response_against_example() {
logInAsSystemAdministrator();
when(updateCenter.findPluginUpdates()).thenReturn(of(
pluginUpdate(ABAP_32, COMPATIBLE),
pluginUpdate(ABAP_31, INCOMPATIBLE),
pluginUpdate(ANDROID_10, COMPATIBLE)));
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput())
.isSimilarTo(new WsActionTester(underTest).getDef().responseExampleAsString());
}
@Test
public void status_COMPATIBLE_is_displayed_COMPATIBLE_in_JSON() {
logInAsSystemAdministrator();
when(updateCenter.findPluginUpdates()).thenReturn(of(
pluginUpdate(release(PLUGIN_1, "1.0.0"), COMPATIBLE)));
TestResponse response = tester.newRequest().execute();
response.assertJson(
"{" +
" \"plugins\": [" +
" {" +
" \"updates\": [" +
" {" +
" \"status\": \"COMPATIBLE\"" +
" }" +
" ]" +
" }" +
" ]" +
"}");
}
@Test
public void plugins_are_sorted_by_name_and_made_unique() {
logInAsSystemAdministrator();
when(updateCenter.findPluginUpdates()).thenReturn(of(
pluginUpdate("key2", "name2"),
pluginUpdate("key2", "name2"),
pluginUpdate("key0", "name0"),
pluginUpdate("key1", "name1")));
TestResponse response = tester.newRequest().execute();
assertJson(response.getInput()).withStrictArrayOrder().isSimilarTo(
"{" +
" \"plugins\": [" +
" {" +
" \"key\": \"key0\"," +
" \"name\": \"name0\"" +
" }," +
" {" +
" \"key\": \"key1\"," +
" \"name\": \"name1\"" +
" }," +
" {" +
" \"key\": \"key2\"," +
" \"name\": \"name2\"" +
" }," +
" ]" +
"}");
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
}
| 7,369 | 38.623656 | 144 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/project/ws/ProjectsWsModuleTest.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.project.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class ProjectsWsModuleTest {
@Test
public void verify_count_of_added_components_on_SonarQube() {
ListContainer container = new ListContainer();
new ProjectsWsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(13);
}
}
| 1,281 | 35.628571 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/project/ws/SearchMyProjectsDataTest.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.project.ws;
import org.junit.Test;
import org.sonar.server.project.ws.SearchMyProjectsData.Builder;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class SearchMyProjectsDataTest {
private final SearchMyProjectsData.Builder underTest = SearchMyProjectsData.builder();
@Test
public void fail_if_projects_are_not_provided() {
Builder builder = underTest
.setProjects(null)
.setProjectLinks(emptyList())
.setSnapshots(emptyList())
.setQualityGates(emptyList())
.setTotalNbOfProjects(0);
assertThatThrownBy(builder::build)
.isInstanceOf(NullPointerException.class);
}
@Test
public void fail_if_projects_links_are_not_provided() {
Builder builder = underTest
.setProjects(emptyList())
.setBranches(emptyList())
.setProjectLinks(null)
.setSnapshots(emptyList())
.setQualityGates(emptyList())
.setTotalNbOfProjects(0);
assertThatThrownBy(builder::build)
.isInstanceOf(NullPointerException.class);
}
@Test
public void fail_if_snapshots_are_not_provided() {
Builder builder = underTest
.setProjects(emptyList())
.setBranches(emptyList())
.setProjectLinks(emptyList())
.setSnapshots(null)
.setQualityGates(emptyList())
.setTotalNbOfProjects(0);
assertThatThrownBy(builder::build)
.isInstanceOf(NullPointerException.class);
}
@Test
public void fail_if_quality_gates_are_not_provided() {
Builder builder = underTest
.setBranches(emptyList())
.setProjectLinks(emptyList())
.setSnapshots(emptyList())
.setQualityGates(null);
assertThatThrownBy(builder::build)
.isInstanceOf(NullPointerException.class);
}
@Test
public void fail_if_total_number_of_projects_is_not_provided() {
Builder builder = underTest
.setBranches(emptyList())
.setProjectLinks(emptyList())
.setSnapshots(emptyList())
.setQualityGates(emptyList())
.setTotalNbOfProjects(null);
assertThatThrownBy(builder::build)
.isInstanceOf(NullPointerException.class);
}
}
| 3,021 | 31.494624 | 88 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/EventValidatorTest.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.projectanalysis.ws;
import org.junit.Test;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.event.EventDto;
import org.sonar.db.event.EventTesting;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.component.SnapshotTesting.newAnalysis;
import static org.sonar.server.projectanalysis.ws.EventCategory.QUALITY_GATE;
public class EventValidatorTest {
@Test
public void fail_with_WS_categories() {
assertThatThrownBy(() -> EventValidator.checkModifiable().accept(newEvent().setCategory(QUALITY_GATE.getLabel())))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Event of category 'QUALITY_GATE' cannot be modified.");
}
private EventDto newEvent() {
return EventTesting.newEvent(newAnalysis(ComponentTesting.newPrivateProjectDto()));
}
}
| 1,720 | 38.113636 | 118 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/ProjectAnalysisWsModuleTest.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.projectanalysis.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class ProjectAnalysisWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new ProjectAnalysisWsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(6);
}
}
| 1,289 | 35.857143 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectdump/ws/ProjectDumpWsTest.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.projectdump.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 ProjectDumpWsTest {
@Test
public void testDefine() {
ProjectDumpWs underTest = new ProjectDumpWs(new DumbAction());
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/project_dump");
assertThat(controller.since()).isNotEmpty();
assertThat(controller.description()).isNotEmpty();
assertThat(controller.isInternal()).isFalse();
assertThat(controller.action("dumb")).isNotNull();
}
private static class DumbAction implements ProjectDumpAction {
@Override
public void define(WebService.NewController newController) {
newController.createAction("dumb").setHandler(this);
}
@Override
public void handle(Request request, Response response) {
}
}
}
| 1,913 | 33.178571 | 78 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/ProjectLinksWsModuleTest.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.projectlink.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class ProjectLinksWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new ProjectLinksModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(4);
}
}
| 1,277 | 35.514286 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projecttag/ws/ProjectTagsWsModuleTest.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.projecttag.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class ProjectTagsWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new ProjectTagsWsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(4);
}
}
| 1,276 | 35.485714 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projecttag/ws/ProjectTagsWsTest.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.projecttag.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 java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
public class ProjectTagsWsTest {
private ProjectTagsWs underTest = new ProjectTagsWs(singletonList(new FakeAction()));
@Test
public void definition() {
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/project_tags");
assertThat(controller.path()).isEqualTo("api/project_tags");
assertThat(controller.since()).isEqualTo("6.4");
assertThat(controller.description()).isNotEmpty();
}
private static class FakeAction implements ProjectTagsWsAction {
@Override
public void define(WebService.NewController context) {
context.createAction("blaba").setHandler(this);
}
@Override
public void handle(Request request, Response response) {
// do nothing
}
}
}
| 1,959 | 32.793103 | 87 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/QualityGateModuleTest.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.qualitygate;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class QualityGateModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new QualityGateModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(5);
}
}
| 1,270 | 35.314286 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/QualityGateDetailsFormatterTest.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.qualitygate.ws;
import java.io.IOException;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.sonar.db.component.SnapshotDto;
import org.sonarqube.ws.Qualitygates.ProjectStatusResponse;
import org.sonarqube.ws.Qualitygates.ProjectStatusResponse.ProjectStatus;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.server.qualitygate.QualityGateCaycStatus.NON_COMPLIANT;
public class QualityGateDetailsFormatterTest {
private QualityGateDetailsFormatter underTest;
@Test
public void map_level_conditions_and_period() throws IOException {
String measureData = IOUtils.toString(getClass().getResource("QualityGateDetailsFormatterTest/quality_gate_details.json"));
SnapshotDto snapshot = new SnapshotDto()
.setPeriodMode("last_version")
.setPeriodParam("2015-12-07")
.setPeriodDate(1449404331764L);
underTest = newQualityGateDetailsFormatter(measureData, snapshot);
ProjectStatus result = underTest.format();
assertThat(result.getStatus()).isEqualTo(ProjectStatusResponse.Status.ERROR);
assertEquals(NON_COMPLIANT.toString(), result.getCaycStatus());
// check conditions
assertThat(result.getConditionsCount()).isEqualTo(3);
List<ProjectStatusResponse.Condition> conditions = result.getConditionsList();
assertThat(conditions).extracting("status").containsExactly(
ProjectStatusResponse.Status.ERROR,
ProjectStatusResponse.Status.WARN,
ProjectStatusResponse.Status.OK);
assertThat(conditions).extracting("metricKey").containsExactly("new_coverage", "new_blocker_violations", "new_critical_violations");
assertThat(conditions).extracting("comparator").containsExactly(
ProjectStatusResponse.Comparator.LT,
ProjectStatusResponse.Comparator.GT,
ProjectStatusResponse.Comparator.GT);
assertThat(conditions).extracting("warningThreshold").containsOnly("80", "");
assertThat(conditions).extracting("errorThreshold").containsOnly("85", "0", "0");
assertThat(conditions).extracting("actualValue").containsExactly("82.2985024398452", "1", "0");
// check period
ProjectStatusResponse.NewCodePeriod period = result.getPeriod();
assertThat(period).extracting("mode").isEqualTo("last_version");
assertThat(period).extracting("parameter").isEqualTo("2015-12-07");
assertThat(period.getDate()).isEqualTo(formatDateTime(snapshot.getPeriodDate()));
}
@Test
public void ignore_period_not_set_on_leak_period() throws IOException {
String measureData = IOUtils.toString(getClass().getResource("QualityGateDetailsFormatterTest/non_leak_period.json"));
SnapshotDto snapshot = new SnapshotDto()
.setPeriodMode("last_version")
.setPeriodParam("2015-12-07")
.setPeriodDate(1449404331764L);
underTest = newQualityGateDetailsFormatter(measureData, snapshot);
ProjectStatus result = underTest.format();
// check conditions
assertThat(result.getConditionsCount()).isOne();
List<ProjectStatusResponse.Condition> conditions = result.getConditionsList();
assertThat(conditions).extracting("status").containsExactly(ProjectStatusResponse.Status.ERROR);
assertThat(conditions).extracting("metricKey").containsExactly("new_coverage");
assertThat(conditions).extracting("comparator").containsExactly(ProjectStatusResponse.Comparator.LT);
assertThat(conditions).extracting("errorThreshold").containsOnly("85");
assertThat(conditions).extracting("actualValue").containsExactly("82.2985024398452");
}
@Test
public void fail_when_measure_level_is_unknown() {
String measureData = "{\n" +
" \"level\": \"UNKNOWN\",\n" +
" \"conditions\": [\n" +
" {\n" +
" \"metric\": \"new_coverage\",\n" +
" \"op\": \"LT\",\n" +
" \"period\": 1,\n" +
" \"warning\": \"80\",\n" +
" \"error\": \"85\",\n" +
" \"actual\": \"82.2985024398452\",\n" +
" \"level\": \"ERROR\"\n" +
" }\n" +
" ]\n" +
"}";
underTest = newQualityGateDetailsFormatter(measureData, new SnapshotDto());
assertThatThrownBy(() -> underTest.format())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Unknown quality gate status 'UNKNOWN'");
}
@Test
public void fail_when_measure_op_is_unknown() {
String measureData = "{\n" +
" \"level\": \"ERROR\",\n" +
" \"conditions\": [\n" +
" {\n" +
" \"metric\": \"new_coverage\",\n" +
" \"op\": \"UNKNOWN\",\n" +
" \"period\": 1,\n" +
" \"warning\": \"80\",\n" +
" \"error\": \"85\",\n" +
" \"actual\": \"82.2985024398452\",\n" +
" \"level\": \"ERROR\"\n" +
" }\n" +
" ]\n" +
"}";
underTest = newQualityGateDetailsFormatter(measureData, new SnapshotDto());
assertThatThrownBy(() -> underTest.format())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Unknown quality gate comparator 'UNKNOWN'");
}
private static QualityGateDetailsFormatter newQualityGateDetailsFormatter(@Nullable String measureData, @Nullable SnapshotDto snapshotDto) {
return new QualityGateDetailsFormatter(measureData, snapshotDto, NON_COMPLIANT);
}
}
| 6,394 | 42.209459 | 142 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/QualityGateWsModuleTest.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.qualitygate.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class QualityGateWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new QualityGateWsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(23);
}
}
| 1,278 | 35.542857 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileParserTest.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.qualityprofile;
import java.io.Reader;
import java.io.StringReader;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class QProfileParserTest {
@Test
public void readXml() {
Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" +
"<profile>" +
"<name>custom rule</name>" +
"<language>js</language>" +
"<rules><rule>" +
"<repositoryKey>sonarjs</repositoryKey>" +
"<key>s001</key>" +
"<type>CODE_SMELL</type>" +
"<priority>CRITICAL</priority>" +
"<name>custom rule name</name>" +
"<templateKey>rule_mc8</templateKey>" +
"<description>custom rule description</description>" +
"<parameters><parameter>" +
"<key>bar</key>" +
"<value>baz</value>" +
"</parameter>" +
"</parameters>" +
"</rule></rules></profile>");
var parser = new QProfileParser();
var importedQProfile = parser.readXml(backup);
assertThat(importedQProfile.getRules()).hasSize(1);
var importedRule = importedQProfile.getRules().get(0);
assertThat(importedRule.getDescription()).isEqualTo("custom rule description");
}
}
| 2,044 | 34.877193 | 83 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationHandlerTest.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.qualityprofile.builtin;
import java.util.Random;
import java.util.Set;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.EmailSubscriberDto;
import org.sonar.db.permission.AuthorizationDao;
import org.sonar.server.notification.email.EmailNotificationChannel;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class BuiltInQPChangeNotificationHandlerTest {
private DbClient dbClient = mock(DbClient.class);
private DbSession dbSession = mock(DbSession.class);
private AuthorizationDao authorizationDao = mock(AuthorizationDao.class);
private EmailNotificationChannel emailNotificationChannel = mock(EmailNotificationChannel.class);
private BuiltInQPChangeNotificationHandler underTest = new BuiltInQPChangeNotificationHandler(dbClient, emailNotificationChannel);
@Before
public void wire_mocks() {
when(dbClient.openSession(false)).thenReturn(dbSession);
when(dbClient.authorizationDao()).thenReturn(authorizationDao);
}
@Test
public void getMetadata_returns_empty() {
assertThat(underTest.getMetadata()).isEmpty();
}
@Test
public void getNotificationClass_is_BuiltInQPChangeNotification() {
assertThat(underTest.getNotificationClass()).isEqualTo(BuiltInQPChangeNotification.class);
}
@Test
public void deliver_has_no_effect_if_emailNotificationChannel_is_disabled() {
when(emailNotificationChannel.isActivated()).thenReturn(false);
Set<BuiltInQPChangeNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> mock(BuiltInQPChangeNotification.class))
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
verifyNoInteractions(dbClient);
notifications.forEach(Mockito::verifyNoInteractions);
}
@Test
public void deliver_has_no_effect_if_there_is_no_global_administer_email_subscriber() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<BuiltInQPChangeNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> mock(BuiltInQPChangeNotification.class))
.collect(toSet());
when(authorizationDao.selectQualityProfileAdministratorLogins(dbSession))
.thenReturn(emptySet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
verify(dbClient).openSession(false);
verify(dbClient).authorizationDao();
verifyNoMoreInteractions(dbClient);
verify(authorizationDao).selectQualityProfileAdministratorLogins(dbSession);
verifyNoMoreInteractions(authorizationDao);
notifications.forEach(Mockito::verifyNoInteractions);
}
@Test
public void deliver_create_emailRequest_for_each_notification_and_for_each_global_administer_email_subscriber() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<BuiltInQPChangeNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> mock(BuiltInQPChangeNotification.class))
.collect(toSet());
Set<EmailSubscriberDto> emailSubscribers = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> EmailSubscriberDto.create("login_" + i, true, "login_" + i + "@foo"))
.collect(toSet());
when(authorizationDao.selectQualityProfileAdministratorLogins(dbSession))
.thenReturn(emailSubscribers);
Set<EmailNotificationChannel.EmailDeliveryRequest> expectedRequests = notifications.stream()
.flatMap(notification -> emailSubscribers.stream().map(subscriber -> new EmailNotificationChannel.EmailDeliveryRequest(subscriber.getEmail(), notification)))
.collect(toSet());
int deliveries = new Random().nextInt(expectedRequests.size());
when(emailNotificationChannel.deliverAll(expectedRequests)).thenReturn(deliveries);
int deliver = underTest.deliver(notifications);
assertThat(deliver).isEqualTo(deliveries);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(expectedRequests);
verifyNoMoreInteractions(emailNotificationChannel);
verify(dbClient).openSession(false);
verify(dbClient).authorizationDao();
verifyNoMoreInteractions(dbClient);
verify(authorizationDao).selectQualityProfileAdministratorLogins(dbSession);
verifyNoMoreInteractions(authorizationDao);
notifications.forEach(Mockito::verifyNoInteractions);
}
}
| 5,948 | 42.423358 | 163 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationTemplateTest.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.qualityprofile.builtin;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.platform.Server;
import org.sonar.server.issue.notification.EmailMessage;
import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile;
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;
import static org.sonar.api.utils.DateUtils.formatDate;
public class BuiltInQPChangeNotificationTemplateTest {
private Server server = mock(Server.class);
private BuiltInQPChangeNotificationTemplate underTest = new BuiltInQPChangeNotificationTemplate(server);
@Before
public void setUp() {
when(server.getPublicRootUrl()).thenReturn("http://" + randomAlphanumeric(10));
}
@Test
public void notification_contains_a_subject() {
String profileName = newProfileName();
String languageKey = newLanguageKey();
String languageName = newLanguageName();
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName)
.setLanguageKey(languageKey)
.setLanguageName(languageName)
.setNewRules(2)
.build());
EmailMessage emailMessage = underTest.format(notification.build());
assertThat(emailMessage.getSubject()).isEqualTo("Built-in quality profiles have been updated");
}
@Test
public void notification_contains_count_of_new_rules() {
String profileName = newProfileName();
String languageKey = newLanguageKey();
String languageName = newLanguageName();
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName)
.setLanguageKey(languageKey)
.setLanguageName(languageName)
.setNewRules(2)
.build());
EmailMessage emailMessage = underTest.format(notification.build());
assertMessage(emailMessage, "\n 2 new rules\n");
}
@Test
public void notification_contains_count_of_updated_rules() {
String profileName = newProfileName();
String languageKey = newLanguageKey();
String languageName = newLanguageName();
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName)
.setLanguageKey(languageKey)
.setLanguageName(languageName)
.setUpdatedRules(2)
.build());
EmailMessage emailMessage = underTest.format(notification.build());
assertMessage(emailMessage, "\n 2 rules have been updated\n");
}
@Test
public void notification_contains_count_of_removed_rules() {
String profileName = newProfileName();
String languageKey = newLanguageKey();
String languageName = newLanguageName();
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName)
.setLanguageKey(languageKey)
.setLanguageName(languageName)
.setRemovedRules(2)
.build());
EmailMessage emailMessage = underTest.format(notification.build());
assertMessage(emailMessage, "\n 2 rules removed\n");
}
@Test
public void notification_supports_grammar_for_single_rule_added_removed_or_updated() {
String profileName = newProfileName();
String languageKey = newLanguageKey();
String languageName = newLanguageName();
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName)
.setLanguageKey(languageKey)
.setLanguageName(languageName)
.setNewRules(1)
.setUpdatedRules(1)
.setRemovedRules(1)
.build());
EmailMessage emailMessage = underTest.format(notification.build());
assertThat(emailMessage.getMessage())
.contains("\n 1 new rule\n")
.contains("\n 1 rule has been updated\n")
.contains("\n 1 rule removed\n");
}
@Test
public void notification_contains_list_of_new_updated_and_removed_rules() {
String profileName = newProfileName();
String languageKey = newLanguageKey();
String languageName = newLanguageName();
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName)
.setLanguageKey(languageKey)
.setLanguageName(languageName)
.setNewRules(2)
.setUpdatedRules(3)
.setRemovedRules(4)
.build());
EmailMessage emailMessage = underTest.format(notification.build());
assertMessage(emailMessage,
"\n" +
" 2 new rules\n" +
" 3 rules have been updated\n" +
" 4 rules removed\n");
}
@Test
public void notification_contains_many_profiles() {
String profileName1 = "profile1_" + randomAlphanumeric(20);
String languageKey1 = "langkey1_" + randomAlphanumeric(20);
String languageName1 = "langName1_" + randomAlphanumeric(20);
String profileName2 = "profile2_" + randomAlphanumeric(20);
String languageKey2 = "langkey2_" + randomAlphanumeric(20);
String languageName2 = "langName2_" + randomAlphanumeric(20);
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName1)
.setLanguageKey(languageKey1)
.setLanguageName(languageName1)
.setNewRules(2)
.build())
.addProfile(Profile.newBuilder()
.setProfileName(profileName2)
.setLanguageKey(languageKey2)
.setLanguageName(languageName2)
.setNewRules(13)
.build());
EmailMessage emailMessage = underTest.format(notification.build());
assertThat(emailMessage.getMessage()).containsSubsequence("The following built-in profiles have been updated:\n",
profileTitleText(profileName1, languageKey1, languageName1),
" 2 new rules\n",
profileTitleText(profileName2, languageKey2, languageName2),
" 13 new rules\n",
"This is a good time to review your quality profiles and update them to benefit from the latest evolutions: " + server.getPublicRootUrl() + "/profiles");
}
@Test
public void notification_contains_profiles_sorted_by_language_then_by_profile_name() {
String languageKey1 = "langkey1_" + randomAlphanumeric(20);
String languageName1 = "langName1_" + randomAlphanumeric(20);
String languageKey2 = "langKey2_" + randomAlphanumeric(20);
String languageName2 = "langName2_" + randomAlphanumeric(20);
String profileName1 = "profile1_" + randomAlphanumeric(20);
String profileName2 = "profile2_" + randomAlphanumeric(20);
String profileName3 = "profile3_" + randomAlphanumeric(20);
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder().setProfileName(profileName3).setLanguageKey(languageKey2).setLanguageName(languageName2).build())
.addProfile(Profile.newBuilder().setProfileName(profileName2).setLanguageKey(languageKey1).setLanguageName(languageName1).build())
.addProfile(Profile.newBuilder().setProfileName(profileName1).setLanguageKey(languageKey2).setLanguageName(languageName2).build());
EmailMessage emailMessage = underTest.format(notification.build());
assertThat(emailMessage.getMessage()).containsSubsequence(
"\"" + profileName2 + "\" - " + languageName1,
"\"" + profileName1 + "\" - " + languageName2,
"\"" + profileName3 + "\" - " + languageName2);
}
@Test
public void notification_contains_encoded_profile_name() {
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName("Sonar Way")
.setLanguageKey("java")
.setLanguageName(newLanguageName())
.build());
EmailMessage emailMessage = underTest.format(notification.build());
assertThat(emailMessage.getMessage()).contains(server.getPublicRootUrl() + "/profiles/changelog?language=java&name=Sonar+Way");
}
@Test
public void notification_contains_from_and_to_date() {
String profileName = newProfileName();
String languageKey = newLanguageKey();
String languageName = newLanguageName();
long startDate = 1_000_000_000_000L;
long endDate = startDate + 1_100_000_000_000L;
BuiltInQPChangeNotificationBuilder notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName)
.setLanguageKey(languageKey)
.setLanguageName(languageName)
.setStartDate(startDate)
.setEndDate(endDate)
.build());
EmailMessage emailMessage = underTest.format(notification.build());
assertMessage(emailMessage,
profileTitleText(profileName, languageKey, languageName, formatDate(new Date(startDate)), formatDate(new Date(endDate))));
}
private void assertMessage(EmailMessage emailMessage, String expectedProfileDetails) {
assertThat(emailMessage.getMessage())
.containsSubsequence(
"The following built-in profiles have been updated:\n\n",
expectedProfileDetails,
"\nThis is a good time to review your quality profiles and update them to benefit from the latest evolutions: " + server.getPublicRootUrl() + "/profiles");
}
private String profileTitleText(String profileName, String languageKey, String languageName) {
return "\"" + profileName + "\" - " + languageName + ": " + server.getPublicRootUrl() + "/profiles/changelog?language=" + languageKey + "&name=" + profileName;
}
private String profileTitleText(String profileName, String languageKey, String languageName, String startDate, String endDate) {
return "\"" + profileName + "\" - " + languageName + ": " + server.getPublicRootUrl() + "/profiles/changelog?language=" + languageKey + "&name=" + profileName +
"&since=" + startDate + "&to=" + endDate + "\n";
}
private static String newProfileName() {
return "profileName_" + randomAlphanumeric(20);
}
private static String newLanguageName() {
return "languageName_" + randomAlphanumeric(20);
}
private static String newLanguageKey() {
return "languageKey_" + randomAlphanumeric(20);
}
}
| 11,540 | 39.637324 | 164 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQPChangeNotificationTest.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.qualityprofile.builtin;
import java.util.Random;
import org.junit.Test;
import org.sonar.api.notifications.Notification;
import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile;
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.Assertions.tuple;
public class BuiltInQPChangeNotificationTest {
private static final Random RANDOM = new Random();
@Test
public void serialize_and_parse_no_profile() {
Notification notification = new BuiltInQPChangeNotificationBuilder().build();
BuiltInQPChangeNotificationBuilder result = BuiltInQPChangeNotificationBuilder.parse(notification);
assertThat(result.getProfiles()).isEmpty();
}
@Test
public void serialize_and_parse_single_profile() {
String profileName = randomAlphanumeric(20);
String languageKey = randomAlphanumeric(20);
String languageName = randomAlphanumeric(20);
int newRules = RANDOM.nextInt(5000);
int updatedRules = RANDOM.nextInt(5000);
int removedRules = RANDOM.nextInt(5000);
long startDate = RANDOM.nextInt(5000);
long endDate = startDate + RANDOM.nextInt(5000);
BuiltInQPChangeNotification notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName)
.setLanguageKey(languageKey)
.setLanguageName(languageName)
.setNewRules(newRules)
.setUpdatedRules(updatedRules)
.setRemovedRules(removedRules)
.setStartDate(startDate)
.setEndDate(endDate)
.build())
.build();
BuiltInQPChangeNotificationBuilder result = BuiltInQPChangeNotificationBuilder.parse(notification);
assertThat(result.getProfiles())
.extracting(Profile::getProfileName, Profile::getLanguageKey, Profile::getLanguageName, Profile::getNewRules, Profile::getUpdatedRules, Profile::getRemovedRules,
Profile::getStartDate, Profile::getEndDate)
.containsExactlyInAnyOrder(tuple(profileName, languageKey, languageName, newRules, updatedRules, removedRules, startDate, endDate));
}
@Test
public void serialize_and_parse_multiple_profiles() {
String profileName1 = randomAlphanumeric(20);
String languageKey1 = randomAlphanumeric(20);
String languageName1 = randomAlphanumeric(20);
String profileName2 = randomAlphanumeric(20);
String languageKey2 = randomAlphanumeric(20);
String languageName2 = randomAlphanumeric(20);
BuiltInQPChangeNotification notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName1)
.setLanguageKey(languageKey1)
.setLanguageName(languageName1)
.build())
.addProfile(Profile.newBuilder()
.setProfileName(profileName2)
.setLanguageKey(languageKey2)
.setLanguageName(languageName2)
.build())
.build();
BuiltInQPChangeNotificationBuilder result = BuiltInQPChangeNotificationBuilder.parse(notification);
assertThat(result.getProfiles()).extracting(Profile::getProfileName, Profile::getLanguageKey, Profile::getLanguageName)
.containsExactlyInAnyOrder(tuple(profileName1, languageKey1, languageName1), tuple(profileName2, languageKey2, languageName2));
}
@Test
public void serialize_and_parse_max_values() {
String profileName = randomAlphanumeric(20);
String languageKey = randomAlphanumeric(20);
String languageName = randomAlphanumeric(20);
int newRules = Integer.MAX_VALUE;
int updatedRules = Integer.MAX_VALUE;
int removedRules = Integer.MAX_VALUE;
long startDate = Long.MAX_VALUE;
long endDate = Long.MAX_VALUE;
BuiltInQPChangeNotification notification = new BuiltInQPChangeNotificationBuilder()
.addProfile(Profile.newBuilder()
.setProfileName(profileName)
.setLanguageKey(languageKey)
.setLanguageName(languageName)
.setNewRules(newRules)
.setUpdatedRules(updatedRules)
.setRemovedRules(removedRules)
.setStartDate(startDate)
.setEndDate(endDate)
.build())
.build();
BuiltInQPChangeNotificationBuilder result = BuiltInQPChangeNotificationBuilder.parse(notification);
assertThat(result.getProfiles())
.extracting(Profile::getProfileName, Profile::getLanguageKey, Profile::getLanguageName, Profile::getNewRules, Profile::getUpdatedRules, Profile::getRemovedRules,
Profile::getStartDate, Profile::getEndDate)
.containsExactlyInAnyOrder(tuple(profileName, languageKey, languageName, newRules, updatedRules, removedRules, startDate, endDate));
}
@Test
public void fail_with_ISE_when_parsing_empty_notification() {
assertThatThrownBy(() -> BuiltInQPChangeNotificationBuilder.parse(new Notification(BuiltInQPChangeNotification.TYPE)))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Could not read the built-in quality profile notification");
}
}
| 5,990 | 41.190141 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQProfileLoaderTest.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.qualityprofile.builtin;
import org.junit.Rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class BuiltInQProfileLoaderTest {
@Rule
public BuiltInQProfileRepositoryRule builtInQProfileRepositoryRule = new BuiltInQProfileRepositoryRule();
private BuiltInQProfileLoader underTest = new BuiltInQProfileLoader(builtInQProfileRepositoryRule);
@Test
public void start_initializes_DefinedQProfileRepository() {
underTest.start();
assertThat(builtInQProfileRepositoryRule.isInitialized()).isTrue();
}
}
| 1,432 | 34.825 | 107 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/builtin/BuiltInQualityProfilesUpdateListenerTest.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.qualityprofile.builtin;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.assertj.core.groups.Tuple;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.core.util.Uuids;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.notification.NotificationManager;
import org.sonar.server.qualityprofile.ActiveRuleChange;
import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationBuilder.Profile;
import static java.util.Arrays.asList;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
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.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.sonar.core.config.CorePropertyDefinitions.DISABLE_NOTIFICATION_ON_BUILT_IN_QPROFILES;
import static org.sonar.server.language.LanguageTesting.newLanguage;
import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.ACTIVATED;
import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.DEACTIVATED;
import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.UPDATED;
public class BuiltInQualityProfilesUpdateListenerTest {
private NotificationManager notificationManager = mock(NotificationManager.class);
private MapSettings settings = new MapSettings();
@Test
public void add_profile_to_notification_for_added_rules() {
enableNotificationInGlobalSettings();
Multimap<QProfileName, ActiveRuleChange> profiles = ArrayListMultimap.create();
Languages languages = new Languages();
Tuple expectedTuple = addProfile(profiles, languages, ACTIVATED);
BuiltInQualityProfilesUpdateListener underTest = new BuiltInQualityProfilesUpdateListener(notificationManager, languages, settings.asConfig());
underTest.onChange(profiles, 0, 1);
ArgumentCaptor<Notification> notificationArgumentCaptor = ArgumentCaptor.forClass(Notification.class);
verify(notificationManager).scheduleForSending(notificationArgumentCaptor.capture());
verifyNoMoreInteractions(notificationManager);
assertThat(BuiltInQPChangeNotificationBuilder.parse(notificationArgumentCaptor.getValue()).getProfiles())
.extracting(Profile::getProfileName, Profile::getLanguageKey, Profile::getLanguageName, Profile::getNewRules)
.containsExactlyInAnyOrder(expectedTuple);
}
@Test
public void add_profile_to_notification_for_updated_rules() {
enableNotificationInGlobalSettings();
Multimap<QProfileName, ActiveRuleChange> profiles = ArrayListMultimap.create();
Languages languages = new Languages();
Tuple expectedTuple = addProfile(profiles, languages, UPDATED);
BuiltInQualityProfilesUpdateListener underTest = new BuiltInQualityProfilesUpdateListener(notificationManager, languages, settings.asConfig());
underTest.onChange(profiles, 0, 1);
ArgumentCaptor<Notification> notificationArgumentCaptor = ArgumentCaptor.forClass(Notification.class);
verify(notificationManager).scheduleForSending(notificationArgumentCaptor.capture());
verifyNoMoreInteractions(notificationManager);
assertThat(BuiltInQPChangeNotificationBuilder.parse(notificationArgumentCaptor.getValue()).getProfiles())
.extracting(Profile::getProfileName, Profile::getLanguageKey, Profile::getLanguageName, Profile::getUpdatedRules)
.containsExactlyInAnyOrder(expectedTuple);
}
@Test
public void add_profile_to_notification_for_removed_rules() {
enableNotificationInGlobalSettings();
Multimap<QProfileName, ActiveRuleChange> profiles = ArrayListMultimap.create();
Languages languages = new Languages();
Tuple expectedTuple = addProfile(profiles, languages, DEACTIVATED);
BuiltInQualityProfilesUpdateListener underTest = new BuiltInQualityProfilesUpdateListener(notificationManager, languages, settings.asConfig());
underTest.onChange(profiles, 0, 1);
ArgumentCaptor<Notification> notificationArgumentCaptor = ArgumentCaptor.forClass(Notification.class);
verify(notificationManager).scheduleForSending(notificationArgumentCaptor.capture());
verifyNoMoreInteractions(notificationManager);
assertThat(BuiltInQPChangeNotificationBuilder.parse(notificationArgumentCaptor.getValue()).getProfiles())
.extracting(Profile::getProfileName, Profile::getLanguageKey, Profile::getLanguageName, Profile::getRemovedRules)
.containsExactlyInAnyOrder(expectedTuple);
}
@Test
public void add_multiple_profiles_to_notification() {
enableNotificationInGlobalSettings();
Multimap<QProfileName, ActiveRuleChange> profiles = ArrayListMultimap.create();
Languages languages = new Languages();
Tuple expectedTuple1 = addProfile(profiles, languages, ACTIVATED);
Tuple expectedTuple2 = addProfile(profiles, languages, ACTIVATED);
BuiltInQualityProfilesUpdateListener underTest = new BuiltInQualityProfilesUpdateListener(notificationManager, languages, settings.asConfig());
underTest.onChange(profiles, 0, 1);
ArgumentCaptor<Notification> notificationArgumentCaptor = ArgumentCaptor.forClass(Notification.class);
verify(notificationManager).scheduleForSending(notificationArgumentCaptor.capture());
verifyNoMoreInteractions(notificationManager);
assertThat(BuiltInQPChangeNotificationBuilder.parse(notificationArgumentCaptor.getValue()).getProfiles())
.extracting(Profile::getProfileName, Profile::getLanguageKey, Profile::getLanguageName, Profile::getNewRules)
.containsExactlyInAnyOrder(expectedTuple1, expectedTuple2);
}
@Test
public void add_start_and_end_dates_to_notification() {
enableNotificationInGlobalSettings();
Multimap<QProfileName, ActiveRuleChange> profiles = ArrayListMultimap.create();
Languages languages = new Languages();
addProfile(profiles, languages, ACTIVATED);
long startDate = 10_000_000_000L;
long endDate = 15_000_000_000L;
BuiltInQualityProfilesUpdateListener underTest = new BuiltInQualityProfilesUpdateListener(notificationManager, languages, settings.asConfig());
underTest.onChange(profiles, startDate, endDate);
ArgumentCaptor<Notification> notificationArgumentCaptor = ArgumentCaptor.forClass(Notification.class);
verify(notificationManager).scheduleForSending(notificationArgumentCaptor.capture());
verifyNoMoreInteractions(notificationManager);
assertThat(BuiltInQPChangeNotificationBuilder.parse(notificationArgumentCaptor.getValue()).getProfiles())
.extracting(Profile::getStartDate, Profile::getEndDate)
.containsExactlyInAnyOrder(tuple(startDate, endDate));
}
@Test
public void avoid_notification_if_configured_in_settings() {
settings.setProperty(DISABLE_NOTIFICATION_ON_BUILT_IN_QPROFILES, true);
Multimap<QProfileName, ActiveRuleChange> profiles = ArrayListMultimap.create();
Languages languages = new Languages();
addProfile(profiles, languages, ACTIVATED);
BuiltInQualityProfilesUpdateListener underTest = new BuiltInQualityProfilesUpdateListener(notificationManager, languages, settings.asConfig());
underTest.onChange(profiles, 0, 1);
verifyNoInteractions(notificationManager);
}
private Tuple addProfile(Multimap<QProfileName, ActiveRuleChange> profiles, Languages languages, ActiveRuleChange.Type type) {
String profileName = randomLowerCaseText();
String ruleUuid1 = Uuids.createFast();
String ruleUuid2 = Uuids.createFast();
Language language = newLanguage(randomLowerCaseText(), randomLowerCaseText());
languages.add(language);
profiles.putAll(new QProfileName(language.getKey(), profileName),
asList(new ActiveRuleChange(
type,
ActiveRuleKey.parse("qp:repo:rule1"), new RuleDto().setUuid(ruleUuid1)),
new ActiveRuleChange(type, ActiveRuleKey.parse("qp:repo:rule2"), new RuleDto().setUuid(ruleUuid2))));
return tuple(profileName, language.getKey(), language.getName(), 2);
}
private static String randomLowerCaseText() {
return randomAlphanumeric(20).toLowerCase();
}
private void enableNotificationInGlobalSettings() {
settings.setProperty(DISABLE_NOTIFICATION_ON_BUILT_IN_QPROFILES, false);
}
}
| 9,437 | 50.016216 | 147 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ExportersActionTest.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.qualityprofile.ws;
import java.io.Writer;
import org.junit.Test;
import org.sonar.api.profiles.ProfileExporter;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.test.JsonAssert.assertJson;
public class ExportersActionTest {
private WsActionTester ws = new WsActionTester(new ExportersAction(createExporters()));
@Test
public void importers_nominal() {
String result = ws.newRequest().execute().getInput();
assertJson(result).isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void define_exporters_action() {
WebService.Action exporters = ws.getDef();
assertThat(exporters).isNotNull();
assertThat(exporters.isPost()).isFalse();
assertThat(exporters.params()).isEmpty();
assertThat(exporters.responseExampleAsString()).isNotEmpty();
}
private ProfileExporter[] createExporters() {
class NoopImporter extends ProfileExporter {
private NoopImporter(String key, String name, String... languages) {
super(key, name);
setSupportedLanguages(languages);
}
@Override
public void exportProfile(RulesProfile profile, Writer writer) {
// Nothing
}
}
return new ProfileExporter[] {
new NoopImporter("pmd", "PMD", "java"),
new NoopImporter("checkstyle", "Checkstyle", "java"),
new NoopImporter("js-lint", "JS Lint", "js"),
new NoopImporter("android-lint", "Android Lint", "xml", "java")
};
}
}
| 2,477 | 33.416667 | 89 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ImportersActionTest.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.qualityprofile.ws;
import java.io.Reader;
import org.junit.Test;
import org.sonar.api.profiles.ProfileImporter;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.test.JsonAssert.assertJson;
public class ImportersActionTest {
private WsActionTester ws = new WsActionTester(new ImportersAction(createImporters()));
@Test
public void empty_importers() {
ws = new WsActionTester(new ImportersAction());
String result = ws.newRequest().execute().getInput();
assertJson(result).isSimilarTo("{ \"importers\": [] }");
}
@Test
public void json_example() {
String result = ws.newRequest().execute().getInput();
assertJson(result).isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void define_importers_action() {
WebService.Action importers = ws.getDef();
assertThat(importers).isNotNull();
assertThat(importers.isPost()).isFalse();
assertThat(importers.params()).isEmpty();
assertThat(importers.responseExampleAsString()).isNotEmpty();
}
private ProfileImporter[] createImporters() {
class NoopImporter extends ProfileImporter {
private NoopImporter(String key, String name, String... languages) {
super(key, name);
setSupportedLanguages(languages);
}
@Override
public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
return RulesProfile.create();
}
}
return new ProfileImporter[] {
new NoopImporter("pmd", "PMD", "java"),
new NoopImporter("checkstyle", "Checkstyle", "java"),
new NoopImporter("js-lint", "JS Lint", "js"),
new NoopImporter("android-lint", "Android Lint", "xml", "java")
};
}
}
| 2,775 | 32.047619 | 89 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.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.qualityprofile.ws;
import org.junit.Test;
import org.sonar.api.impl.ws.SimpleGetRequest;
import org.sonar.api.resources.Languages;
import org.sonar.api.server.ws.WebService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.language.LanguageTesting.newLanguage;
public class QProfileReferenceTest {
@Test
public void fromKey_creates_reference_by_key() {
QProfileReference ref = QProfileReference.fromKey("foo");
assertThat(ref.hasKey()).isTrue();
assertThat(ref.getKey()).isEqualTo("foo");
}
@Test
public void getLanguage_throws_ISE_on_reference_by_key() {
QProfileReference ref = QProfileReference.fromKey("foo");
assertThatThrownBy(() -> ref.getLanguage())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Language is not defined. Please call hasKey().");
}
@Test
public void getName_throws_ISE_on_reference_by_key() {
QProfileReference ref = QProfileReference.fromKey("foo");
assertThatThrownBy(() -> ref.getName())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Name is not defined. Please call hasKey().");
}
@Test
public void fromName_creates_reference_by_name() {
QProfileReference ref = QProfileReference.fromName("js", "Sonar way");
assertThat(ref.hasKey()).isFalse();
assertThat(ref.getLanguage()).isEqualTo("js");
assertThat(ref.getName()).isEqualTo("Sonar way");
}
@Test
public void getKey_throws_ISE_on_reference_by_name() {
QProfileReference ref = QProfileReference.fromName("js", "Sonar way");
assertThatThrownBy(() -> ref.getKey())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Key is not defined. Please call hasKey().");
}
@Test
public void fromName_reads_request_parameters_and_creates_reference_by_name() {
SimpleGetRequest req = new SimpleGetRequest();
req.setParam("language", "js");
req.setParam("qualityProfile", "Sonar way");
QProfileReference ref = QProfileReference.fromName(req);
assertThat(ref.getLanguage()).isEqualTo("js");
assertThat(ref.getName()).isEqualTo("Sonar way");
}
@Test
public void throw_IAE_if_request_does_not_define_ref() {
SimpleGetRequest req = new SimpleGetRequest();
assertThatThrownBy(() -> QProfileReference.fromName(req))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void define_ws_parameters() {
WebService.Context context = new WebService.Context();
WebService.NewController controller = context.createController("api/qualityprofiles");
WebService.NewAction newAction = controller.createAction("do").setHandler((request, response) -> {
});
Languages languages = new Languages(newLanguage("java"), newLanguage("js"));
QProfileReference.defineParams(newAction, languages);
controller.done();
WebService.Action action = context.controller("api/qualityprofiles").action("do");
assertThat(action.param("language")).isNotNull();
assertThat(action.param("language").possibleValues()).containsOnly("java", "js");
assertThat(action.param("qualityProfile")).isNotNull();
}
@Test
public void test_equals_and_hashCode_of_key_ref() {
QProfileReference key1 = QProfileReference.fromKey("one");
QProfileReference key1bis = QProfileReference.fromKey("one");
QProfileReference key2 = QProfileReference.fromKey("two");
QProfileReference name = QProfileReference.fromName("js", "one");
assertThat(key1.equals(key1)).isTrue();
assertThat(key1.equals(key1bis)).isTrue();
assertThat(key1.equals(key2)).isFalse();
assertThat(key1.equals(name)).isFalse();
assertThat(key1)
.hasSameHashCodeAs(key1)
.hasSameHashCodeAs(key1bis);
}
@Test
public void test_equals_and_hashCode_of_name_ref() {
QProfileReference name1 = QProfileReference.fromName("js", "one");
QProfileReference name1bis = QProfileReference.fromName("js", "one");
QProfileReference name2 = QProfileReference.fromName("js", "two");
QProfileReference name1OtherLang = QProfileReference.fromName("java", "one");
QProfileReference key = QProfileReference.fromKey("one");
assertThat(name1.equals(name1)).isTrue();
assertThat(name1.equals(name1bis)).isTrue();
assertThat(name1.equals(name2)).isFalse();
assertThat(name1.equals(name1OtherLang)).isFalse();
assertThat(name1.equals(key)).isFalse();
assertThat(name1)
.hasSameHashCodeAs(name1)
.hasSameHashCodeAs(name1bis);
}
}
| 5,436 | 35.489933 | 102 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfilesWsModuleTest.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.qualityprofile.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class QProfilesWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new QProfilesWsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(31);
}
}
| 1,277 | 35.514286 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleTagHelperTest.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.rule;
import com.google.common.collect.Sets;
import org.junit.Test;
import org.sonar.db.rule.RuleDto;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public class RuleTagHelperTest {
@Test
public void applyTags() {
RuleDto rule = new RuleDto().setTags(Sets.newHashSet("performance"));
boolean changed = RuleTagHelper.applyTags(rule, Sets.newHashSet("java8", "security"));
assertThat(rule.getTags()).containsOnly("java8", "security");
assertThat(changed).isTrue();
}
@Test
public void applyTags_remove_all_existing_tags() {
RuleDto rule = new RuleDto().setTags(Sets.newHashSet("performance"));
boolean changed = RuleTagHelper.applyTags(rule, Collections.emptySet());
assertThat(rule.getTags()).isEmpty();
assertThat(changed).isTrue();
}
@Test
public void applyTags_no_changes() {
RuleDto rule = new RuleDto().setTags(Sets.newHashSet("performance"));
boolean changed = RuleTagHelper.applyTags(rule, Sets.newHashSet("performance"));
assertThat(rule.getTags()).containsOnly("performance");
assertThat(changed).isFalse();
}
@Test
public void applyTags_validate_format() {
RuleDto rule = new RuleDto();
boolean changed = RuleTagHelper.applyTags(rule, Sets.newHashSet("java8", "security"));
assertThat(rule.getTags()).containsOnly("java8", "security");
assertThat(changed).isTrue();
try {
RuleTagHelper.applyTags(rule, Sets.newHashSet("Java Eight"));
fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage()).startsWith("Entry 'Java Eight' is invalid");
}
}
@Test
public void applyTags_do_not_duplicate_system_tags() {
RuleDto rule = new RuleDto()
.setTags(Sets.newHashSet("performance"))
.setSystemTags(Sets.newHashSet("security"));
boolean changed = RuleTagHelper.applyTags(rule, Sets.newHashSet("java8", "security"));
assertThat(changed).isTrue();
assertThat(rule.getTags()).containsOnly("java8");
assertThat(rule.getSystemTags()).containsOnly("security");
}
}
| 2,986 | 34.141176 | 90 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/saml/ws/SamlValidationModuleTest.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.saml.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class SamlValidationModuleTest {
@Test
public void load_configure_module() {
ListContainer container = new ListContainer();
new SamlValidationModule().configure(container);
assertThat(container.getAddedObjects()).isNotEmpty();
}
}
| 1,264 | 34.138889 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/saml/ws/SamlValidationWsTest.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.saml.ws;
import java.util.Collections;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class SamlValidationWsTest {
private final SamlValidationWs underTest = new SamlValidationWs(Collections.emptyList());
@Test
public void define() {
WebService.Context context = mock(WebService.Context.class);
WebService.NewController newController = mock(WebService.NewController.class);
when(context.createController(anyString())).thenReturn(newController);
underTest.define(context);
verify(newController).setDescription(anyString());
verify(newController).done();
}
}
| 1,666 | 34.468085 | 91 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/saml/ws/ValidationActionTest.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.saml.ws;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.FilterChain;
import org.sonar.auth.saml.SamlAuthenticator;
import org.sonar.auth.saml.SamlIdentityProvider;
import org.sonar.server.authentication.OAuth2ContextFactory;
import org.sonar.server.authentication.OAuthCsrfVerifier;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
import org.sonar.server.http.JavaxHttpRequest;
import org.sonar.server.http.JavaxHttpResponse;
import org.sonar.server.user.ThreadLocalUserSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
public class ValidationActionTest {
private ValidationAction underTest;
private SamlAuthenticator samlAuthenticator;
private ThreadLocalUserSession userSession;
private OAuthCsrfVerifier oAuthCsrfVerifier;
private SamlIdentityProvider samlIdentityProvider;
public static final List<String> CSP_HEADERS = List.of("Content-Security-Policy", "X-Content-Security-Policy", "X-WebKit-CSP");
@Before
public void setup() {
samlAuthenticator = mock(SamlAuthenticator.class);
userSession = mock(ThreadLocalUserSession.class);
oAuthCsrfVerifier = mock(OAuthCsrfVerifier.class);
samlIdentityProvider = mock(SamlIdentityProvider.class);
var oAuth2ContextFactory = mock(OAuth2ContextFactory.class);
underTest = new ValidationAction(userSession, samlAuthenticator, oAuth2ContextFactory, samlIdentityProvider, oAuthCsrfVerifier);
}
@Test
public void do_get_pattern() {
assertThat(underTest.doGetPattern().matches("/saml/validation")).isTrue();
assertThat(underTest.doGetPattern().matches("/saml/validation2")).isFalse();
assertThat(underTest.doGetPattern().matches("/api/saml/validation")).isFalse();
assertThat(underTest.doGetPattern().matches("/saml/validation_callback2")).isFalse();
assertThat(underTest.doGetPattern().matches("/saml/")).isFalse();
}
@Test
public void do_filter_admin() throws IOException {
HttpServletRequest servletRequest = spy(HttpServletRequest.class);
HttpServletResponse servletResponse = mock(HttpServletResponse.class);
StringWriter stringWriter = new StringWriter();
doReturn(new PrintWriter(stringWriter)).when(servletResponse).getWriter();
FilterChain filterChain = mock(FilterChain.class);
doReturn(true).when(userSession).hasSession();
doReturn(true).when(userSession).isSystemAdministrator();
final String mockedHtmlContent = "mocked html content";
doReturn(mockedHtmlContent).when(samlAuthenticator).getAuthenticationStatusPage(any(), any());
underTest.doFilter(new JavaxHttpRequest(servletRequest), new JavaxHttpResponse(servletResponse), filterChain);
verify(samlAuthenticator).getAuthenticationStatusPage(any(), any());
verify(servletResponse).getWriter();
CSP_HEADERS.forEach(h -> verify(servletResponse).setHeader(eq(h), anyString()));
assertEquals(mockedHtmlContent, stringWriter.toString());
}
@Test
public void do_filter_not_authorized() throws IOException {
HttpRequest servletRequest = spy(HttpRequest.class);
HttpResponse servletResponse = mock(HttpResponse.class);
StringWriter stringWriter = new StringWriter();
doReturn(new PrintWriter(stringWriter)).when(servletResponse).getWriter();
FilterChain filterChain = mock(FilterChain.class);
doReturn(true).when(userSession).hasSession();
doReturn(false).when(userSession).isSystemAdministrator();
underTest.doFilter(servletRequest, servletResponse, filterChain);
verifyNoInteractions(samlAuthenticator);
}
@Test
public void do_filter_failed_csrf_verification() throws IOException {
HttpRequest servletRequest = spy(HttpRequest.class);
HttpResponse servletResponse = mock(HttpResponse.class);
StringWriter stringWriter = new StringWriter();
doReturn(new PrintWriter(stringWriter)).when(servletResponse).getWriter();
FilterChain filterChain = mock(FilterChain.class);
doReturn("IdentityProviderName").when(samlIdentityProvider).getName();
doThrow(AuthenticationException.newBuilder()
.setSource(AuthenticationEvent.Source.oauth2(samlIdentityProvider))
.setMessage("Cookie is missing").build()).when(oAuthCsrfVerifier).verifyState(any(), any(), any(), any());
doReturn(true).when(userSession).hasSession();
doReturn(true).when(userSession).isSystemAdministrator();
underTest.doFilter(servletRequest, servletResponse, filterChain);
verifyNoInteractions(samlAuthenticator);
}
@Test
public void verify_definition() {
String controllerKey = "foo";
WebService.Context context = new WebService.Context();
WebService.NewController newController = context.createController(controllerKey);
underTest.define(newController);
newController.done();
WebService.Action validationInitAction = context.controller(controllerKey)
.action(ValidationAction.VALIDATION_CALLBACK_KEY);
assertThat(validationInitAction).isNotNull();
assertThat(validationInitAction.description()).isNotEmpty();
assertThat(validationInitAction.handler()).isNotNull();
}
}
| 6,824 | 42.471338 | 132 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/saml/ws/ValidationInitActionTest.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.saml.ws;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.http.HttpRequest;
import org.sonar.api.server.http.HttpResponse;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.FilterChain;
import org.sonar.auth.saml.SamlAuthenticator;
import org.sonar.server.authentication.OAuth2ContextFactory;
import org.sonar.server.authentication.OAuthCsrfVerifier;
import org.sonar.server.tester.UserSessionRule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.matches;
import static org.mockito.Mockito.doThrow;
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 ValidationInitActionTest {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private ValidationInitAction underTest;
private SamlAuthenticator samlAuthenticator;
private OAuth2ContextFactory oAuth2ContextFactory;
private OAuthCsrfVerifier oAuthCsrfVerifier;
@Before
public void setUp() throws Exception {
samlAuthenticator = mock(SamlAuthenticator.class);
oAuth2ContextFactory = mock(OAuth2ContextFactory.class);
oAuthCsrfVerifier = mock(OAuthCsrfVerifier.class);
underTest = new ValidationInitAction(samlAuthenticator, oAuthCsrfVerifier, oAuth2ContextFactory, userSession);
}
@Test
public void do_get_pattern() {
assertThat(underTest.doGetPattern().matches("/saml/validation_init")).isTrue();
assertThat(underTest.doGetPattern().matches("/api/saml")).isFalse();
assertThat(underTest.doGetPattern().matches("/api/saml/validation_init")).isFalse();
assertThat(underTest.doGetPattern().matches("/saml/validation_init2")).isFalse();
}
@Test
public void do_filter_as_admin() throws IOException {
userSession.logIn().setSystemAdministrator();
HttpRequest servletRequest = mock(HttpRequest.class);
HttpResponse servletResponse = mock(HttpResponse.class);
FilterChain filterChain = mock(FilterChain.class);
String callbackUrl = "http://localhost:9000/api/validation_test";
mockCsrfTokenGeneration(servletRequest, servletResponse);
when(oAuth2ContextFactory.generateCallbackUrl(anyString())).thenReturn(callbackUrl);
underTest.doFilter(servletRequest, servletResponse, filterChain);
verify(samlAuthenticator).initLogin(matches(callbackUrl),
matches(ValidationInitAction.VALIDATION_RELAY_STATE),
any(), any());
}
@Test
public void do_filter_as_admin_with_init_issues() throws IOException {
userSession.logIn().setSystemAdministrator();
HttpRequest servletRequest = mock(HttpRequest.class);
HttpResponse servletResponse = mock(HttpResponse.class);
FilterChain filterChain = mock(FilterChain.class);
String callbackUrl = "http://localhost:9000/api/validation_test";
when(oAuth2ContextFactory.generateCallbackUrl(anyString()))
.thenReturn(callbackUrl);
mockCsrfTokenGeneration(servletRequest, servletResponse);
doThrow(new IllegalStateException()).when(samlAuthenticator).initLogin(any(), any(), any(), any());
underTest.doFilter(servletRequest, servletResponse, filterChain);
verify(servletResponse).sendRedirect("/saml/validation");
}
@Test
public void do_filter_as_not_admin() throws IOException {
userSession.logIn();
HttpRequest servletRequest = mock(HttpRequest.class);
HttpResponse servletResponse = mock(HttpResponse.class);
FilterChain filterChain = mock(FilterChain.class);
String callbackUrl = "http://localhost:9000/api/validation_test";
when(oAuth2ContextFactory.generateCallbackUrl(anyString()))
.thenReturn(callbackUrl);
underTest.doFilter(servletRequest, servletResponse, filterChain);
verifyNoInteractions(samlAuthenticator);
verify(servletResponse).sendRedirect(anyString());
}
@Test
public void do_filter_as_anonymous() throws IOException {
userSession.anonymous();
HttpRequest servletRequest = mock(HttpRequest.class);
HttpResponse servletResponse = mock(HttpResponse.class);
FilterChain filterChain = mock(FilterChain.class);
String callbackUrl = "http://localhost:9000/api/validation_test";
when(oAuth2ContextFactory.generateCallbackUrl(anyString()))
.thenReturn(callbackUrl);
underTest.doFilter(servletRequest, servletResponse, filterChain);
verifyNoInteractions(samlAuthenticator);
verify(servletResponse).sendRedirect(anyString());
}
@Test
public void verify_definition() {
String controllerKey = "foo";
WebService.Context context = new WebService.Context();
WebService.NewController newController = context.createController(controllerKey);
underTest.define(newController);
newController.done();
WebService.Action validationInitAction = context.controller(controllerKey).action("validation_init");
assertThat(validationInitAction).isNotNull();
assertThat(validationInitAction.description()).isNotEmpty();
assertThat(validationInitAction.handler()).isNotNull();
}
private void mockCsrfTokenGeneration(HttpRequest servletRequest, HttpResponse servletResponse) {
when(oAuthCsrfVerifier.generateState(servletRequest, servletResponse)).thenReturn("CSRF_TOKEN");
}
}
| 6,336 | 39.883871 | 114 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/scannercache/ws/AnalysisCacheWsModuleTest.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.scannercache.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class AnalysisCacheWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new AnalysisCacheWsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(3);
}
}
| 1,283 | 34.666667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/scannercache/ws/AnalysisCacheWsTest.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.scannercache.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 AnalysisCacheWsTest {
@Test
public void define_ws() {
AnalysisCacheWsAction action = new FakeAction();
AnalysisCacheWs underTest = new AnalysisCacheWs(action);
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/analysis_cache");
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo("9.4");
assertThat(controller.description()).isNotEmpty();
assertThat(controller.actions()).hasSize(1);
}
private static class FakeAction implements AnalysisCacheWsAction {
@Override
public void define(WebService.NewController newController) {
newController.createAction("fake").setHandler(this);
}
@Override
public void handle(Request request, Response response) throws Exception {
}
}
}
| 1,972 | 33.614035 | 80 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/TestProjectConfigurationLoader.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.setting;
import org.sonar.api.config.Configuration;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
public class TestProjectConfigurationLoader implements ProjectConfigurationLoader {
private final Configuration config;
public TestProjectConfigurationLoader(Configuration config) {
this.config = config;
}
@Override
public Configuration loadBranchConfiguration(DbSession dbSession, BranchDto branch) {
return config;
}
@Override
public Configuration loadProjectConfiguration(DbSession dbSession, String projectUuid) {
return config;
}
}
| 1,465 | 32.318182 | 90 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/LoginMessageActionTest.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.setting.ws;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.property.PropertiesDao;
import org.sonar.db.property.PropertyDto;
import org.sonar.server.loginmessage.LoginMessageFeature;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.core.config.WebConstants.SONAR_LOGIN_DISPLAY_MESSAGE;
import static org.sonar.core.config.WebConstants.SONAR_LOGIN_MESSAGE;
public class LoginMessageActionTest {
private final DbClient dbClient = mock(DbClient.class);
private final LoginMessageFeature loginMessageFeature = mock(LoginMessageFeature.class);
private final LoginMessageAction underTest = new LoginMessageAction(dbClient, loginMessageFeature);
private final WsActionTester ws = new WsActionTester(underTest);
private static final String LOGIN_MESSAGE_TEXT = "test link [SonarQube™ Home Page](https://www.sonarqube.org)\n* list 1\n* list 2";
private static final String FORMATTED_LOGIN_MESSAGE_TEXT = "test link \\u003ca href\\u003d\\\"https://www.sonarqube.org\\\" target\\u003d\\\"_blank\\\" rel\\u003d\\\"noopener noreferrer\\\"\\u003eSonarQube\\u0026trade; Home Page\\u003c/a\\u003e\\u003cbr/\\u003e\\u003cul\\u003e\\u003cli\\u003elist 1\\u003c/li\\u003e\\n\\u003cli\\u003elist 2\\u003c/li\\u003e\\u003c/ul\\u003e";
private static final String JSON_RESPONSE = "{\"message\":\"" + FORMATTED_LOGIN_MESSAGE_TEXT + "\"}";
private static final String EMPTY_JSON_RESPONSE = "{\"message\":\"\"}";
private PropertiesDao propertiesDao;
@Before
public void setup() {
propertiesDao = mock(PropertiesDao.class);
doReturn(true).when(loginMessageFeature).isAvailable();
doReturn(propertiesDao).when(dbClient).propertiesDao();
}
@Test
public void test_definition() {
WebService.Action action = ws.getDef();
assertThat(action.key()).isEqualTo("login_message");
assertThat(action.isPost()).isFalse();
assertThat(action.isInternal()).isTrue();
assertThat(action.params()).isEmpty();
}
@Test
public void returns_login_formatted_message_json() {
mockProperty(SONAR_LOGIN_DISPLAY_MESSAGE, "true");
mockProperty(SONAR_LOGIN_MESSAGE, LOGIN_MESSAGE_TEXT);
TestResponse response = ws.newRequest().execute();
assertThat(response.getInput()).isEqualTo(JSON_RESPONSE);
}
@Test
public void return_empty_message_when_no_message_saved() {
mockProperty(SONAR_LOGIN_DISPLAY_MESSAGE, "true");
TestResponse response = ws.newRequest().execute();
assertThat(response.getInput()).isEqualTo(EMPTY_JSON_RESPONSE);
}
@Test
public void return_empty_message_when_feature_not_enabled() {
mockProperty(SONAR_LOGIN_DISPLAY_MESSAGE, "true");
mockProperty(SONAR_LOGIN_MESSAGE, LOGIN_MESSAGE_TEXT);
when(loginMessageFeature.isAvailable()).thenReturn(false);
TestResponse response = ws.newRequest().execute();
assertThat(response.getInput()).isEqualTo(EMPTY_JSON_RESPONSE);
}
@Test
public void return_empty_message_when_login_message_flag_is_disabled() {
mockProperty(SONAR_LOGIN_DISPLAY_MESSAGE, "false");
mockProperty(SONAR_LOGIN_MESSAGE, LOGIN_MESSAGE_TEXT);
TestResponse response = ws.newRequest().execute();
assertThat(response.getInput()).isEqualTo(EMPTY_JSON_RESPONSE);
}
private void mockProperty(String key, String value) {
var propertyDto = mock(PropertyDto.class);
doReturn(value).when(propertyDto).getValue();
doReturn(key).when(propertyDto).getKey();
doReturn(propertyDto).when(propertiesDao).selectGlobalProperty(key);
}
}
| 4,675 | 40.75 | 379 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SettingsWsModuleTest.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.setting.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class SettingsWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new SettingsWsModule().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/setting/ws/SettingsWsSupportTest.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.setting.ws;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.StringJoiner;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.InjectMocks;
import org.sonar.api.web.UserRole;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.user.UserSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.openMocks;
@RunWith(value = Parameterized.class)
public class SettingsWsSupportTest {
private static final String KEY_REQUIRING_ADMIN_PERMISSION = "sonar.auth.bitbucket.workspaces";
private static final String STANDARD_KEY = "sonar.auth.bitbucket.enabled";
private static final String SECURED_KEY = "sonar.auth.bitbucket" + SettingsWsSupport.DOT_SECURED;
@Parameterized.Parameters(name = "{index}: {0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
// admin cases
{testCaseBuilderForAdminOnlyKey().isAdmin(true).expectedIsVisible(true).build()},
{testCaseBuilderForStandardKey().isAdmin(true).expectedIsVisible(true).build()},
{testCaseBuilderForSecuredKey().isAdmin(true).expectedIsVisible(true).build()},
// non-admin cases
{testCaseBuilderForAdminOnlyKey().isAdmin(false).hasGlobalPermission(true).hasComponentPermission(true).expectedIsVisible(true).build()},
{testCaseBuilderForAdminOnlyKey().isAdmin(false).hasGlobalPermission(true).hasComponentPermission(false).expectedIsVisible(true).build()},
{testCaseBuilderForAdminOnlyKey().isAdmin(false).hasGlobalPermission(false).hasComponentPermission(true).expectedIsVisible(true).build()},
{testCaseBuilderForAdminOnlyKey().isAdmin(false).hasGlobalPermission(false).hasComponentPermission(false).expectedIsVisible(false).build()},
{testCaseBuilderForSecuredKey().isAdmin(false).hasGlobalPermission(true).hasComponentPermission(true).expectedIsVisible(true).build()},
{testCaseBuilderForSecuredKey().isAdmin(false).hasGlobalPermission(true).hasComponentPermission(false).expectedIsVisible(true).build()},
{testCaseBuilderForSecuredKey().isAdmin(false).hasGlobalPermission(false).hasComponentPermission(true).expectedIsVisible(true).build()},
{testCaseBuilderForSecuredKey().isAdmin(false).hasGlobalPermission(false).hasComponentPermission(false).expectedIsVisible(false).build()},
{testCaseBuilderForStandardKey().isAdmin(false).hasGlobalPermission(false).hasComponentPermission(false).expectedIsVisible(true).build()},
{testCaseBuilderForStandardKey().isAdmin(false).hasGlobalPermission(false).hasComponentPermission(true).expectedIsVisible(true).build()},
{testCaseBuilderForStandardKey().isAdmin(false).hasGlobalPermission(true).hasComponentPermission(true).expectedIsVisible(true).build()},
{testCaseBuilderForStandardKey().isAdmin(false).hasGlobalPermission(true).hasComponentPermission(false).expectedIsVisible(true).build()},
});
}
private final boolean isAdmin;
private final String property;
private final boolean hasGlobalPermission;
private final boolean hasComponentPermission;
private final boolean expectedIsVisible;
private final ProjectDto componentDto = mock(ProjectDto.class);
private final UserSession userSession = mock(UserSession.class);
@InjectMocks
private SettingsWsSupport settingsWsSupport;
public SettingsWsSupportTest(TestCase testCase) {
this.isAdmin = testCase.isAdmin;
this.property = testCase.property;
this.hasGlobalPermission = testCase.hasGlobalPermission;
this.hasComponentPermission = testCase.hasComponentPermission;
this.expectedIsVisible = testCase.expectedIsVisible;
}
@Test
public void isVisible() {
openMocks(this);
when(userSession.isSystemAdministrator()).thenReturn(isAdmin);
when(userSession.hasPermission(GlobalPermission.SCAN)).thenReturn(hasGlobalPermission);
when(userSession.hasEntityPermission(UserRole.SCAN, componentDto)).thenReturn(hasComponentPermission);
boolean isVisible = settingsWsSupport.isVisible(property, Optional.of(componentDto));
assertThat(isVisible).isEqualTo(expectedIsVisible);
}
private static TestCase.TestCaseBuilder testCaseBuilderForAdminOnlyKey() {
return testCaseBuilder().property(KEY_REQUIRING_ADMIN_PERMISSION);
}
private static TestCase.TestCaseBuilder testCaseBuilderForSecuredKey() {
return testCaseBuilder().property(SECURED_KEY);
}
private static TestCase.TestCaseBuilder testCaseBuilderForStandardKey() {
return testCaseBuilder().property(STANDARD_KEY);
}
private static TestCase.TestCaseBuilder testCaseBuilder() {
return new TestCase.TestCaseBuilder();
}
static final class TestCase {
private final boolean isAdmin;
private final String property;
private final boolean hasGlobalPermission;
private final boolean hasComponentPermission;
private final boolean expectedIsVisible;
TestCase(boolean isAdmin, String property, boolean hasGlobalPermission, boolean hasComponentPermission, boolean expectedIsVisible) {
this.isAdmin = isAdmin;
this.property = property;
this.hasGlobalPermission = hasGlobalPermission;
this.hasComponentPermission = hasComponentPermission;
this.expectedIsVisible = expectedIsVisible;
}
@Override public String toString() {
return new StringJoiner(", ", TestCase.class.getSimpleName() + "[", "]")
.add("isAdmin=" + isAdmin)
.add("property='" + property + "'")
.add("hasComponentPermission=" + hasComponentPermission)
.add("hasGlobalPermission=" + hasGlobalPermission)
.add("expectedIsVisible=" + expectedIsVisible)
.toString();
}
static final class TestCaseBuilder {
private boolean isAdmin = false;
private String property;
private boolean hasGlobalPermission = false;
private boolean hasComponentPermission = false;
private boolean expectedIsVisible;
TestCaseBuilder isAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
return this;
}
TestCaseBuilder property(String property) {
this.property = property;
return this;
}
TestCaseBuilder hasGlobalPermission(boolean hasGlobalPermission) {
this.hasGlobalPermission = hasGlobalPermission;
return this;
}
TestCaseBuilder hasComponentPermission(boolean hasComponentPermission) {
this.hasComponentPermission = hasComponentPermission;
return this;
}
TestCaseBuilder expectedIsVisible(boolean expectedIsVisible) {
this.expectedIsVisible = expectedIsVisible;
return this;
}
TestCase build() {
return new TestCase(isAdmin, property, hasGlobalPermission, hasComponentPermission, expectedIsVisible);
}
}
}
}
| 7,893 | 42.61326 | 146 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/DecorationDataHolderTest.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.source;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class DecorationDataHolderTest {
private static final String SAMPLE_SYNTAX_HIGHLIGHTING_RULES = "0,8,k;0,52,cppd;54,67,a;69,75,k;106,130,cppd;114,130,k;";
private static final String SAMPLE_SYMBOLS_REFERENCES = "80,85,80,90,140;";
private DecorationDataHolder decorationDataHolder;
@Before
public void setUpHighlightingContext() {
decorationDataHolder = new DecorationDataHolder();
decorationDataHolder.loadSyntaxHighlightingData(SAMPLE_SYNTAX_HIGHLIGHTING_RULES);
decorationDataHolder.loadSymbolReferences(SAMPLE_SYMBOLS_REFERENCES);
}
@Test
public void should_extract_lower_bounds_from_serialized_rules() {
List<OpeningHtmlTag> openingTagsEntries = decorationDataHolder.getOpeningTagsEntries();
assertThat(openingTagsEntries.get(0)).isEqualTo(new OpeningHtmlTag(0, "k"));
assertThat(openingTagsEntries.get(1)).isEqualTo(new OpeningHtmlTag(0, "cppd"));
assertThat(openingTagsEntries.get(2)).isEqualTo(new OpeningHtmlTag(54, "a"));
assertThat(openingTagsEntries.get(3)).isEqualTo(new OpeningHtmlTag(69, "k"));
assertThat(openingTagsEntries.get(4)).isEqualTo(new OpeningHtmlTag(80, "sym-80 sym"));
assertThat(openingTagsEntries.get(5)).isEqualTo(new OpeningHtmlTag(90, "sym-80 sym"));
assertThat(openingTagsEntries.get(6)).isEqualTo(new OpeningHtmlTag(106, "cppd"));
assertThat(openingTagsEntries.get(7)).isEqualTo(new OpeningHtmlTag(114, "k"));
assertThat(openingTagsEntries.get(8)).isEqualTo(new OpeningHtmlTag(140, "sym-80 sym"));
}
@Test
public void should_extract_upper_bounds_from_serialized_rules() {
List<Integer> offsets = decorationDataHolder.getClosingTagsOffsets();
assertThat(offsets.get(0)).isEqualTo(8);
assertThat(offsets.get(1)).isEqualTo(52);
assertThat(offsets.get(2)).isEqualTo(67);
assertThat(offsets.get(3)).isEqualTo(75);
assertThat(offsets.get(4)).isEqualTo(85);
assertThat(offsets.get(5)).isEqualTo(95);
assertThat(offsets.get(6)).isEqualTo(130);
assertThat(offsets.get(7)).isEqualTo(130);
assertThat(offsets.get(8)).isEqualTo(145);
}
}
| 3,102 | 40.373333 | 123 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/HtmlSourceDecoratorTest.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.source;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class HtmlSourceDecoratorTest {
HtmlSourceDecorator sourceDecorator;
@Before
public void setUpDatasets() {
sourceDecorator = new HtmlSourceDecorator();
}
@Test
public void should_decorate_single_line() {
String sourceLine = "package org.polop;";
String highlighting = "0,7,k";
String symbols = "8,17,42";
assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, highlighting, symbols)).isEqualTo(
"<span class=\"k\">package</span> <span class=\"sym-42 sym\">org.polop</span>;");
}
@Test
public void should_handle_highlighting_too_long() {
String sourceLine = "abc";
String highlighting = "0,5,c";
String symbols = "";
assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, highlighting, symbols)).isEqualTo("<span class=\"c\">abc</span>");
}
@Test
public void should_ignore_missing_highlighting() {
String sourceLine = " if (toto < 42) {";
assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, null, null)).isEqualTo(" if (toto < 42) {");
assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, "", null)).isEqualTo(" if (toto < 42) {");
}
@Test
public void should_ignore_null_source() {
assertThat(sourceDecorator.getDecoratedSourceAsHtml(null, null, null)).isNull();
}
@Test
public void should_ignore_empty_source() {
assertThat(sourceDecorator.getDecoratedSourceAsHtml("", "0,1,cppd", "")).isEmpty();
}
@Test
public void should_ignore_empty_rule() {
String sourceLine = "@Deprecated";
String highlighting = "0,0,a;0,11,a";
String symbols = "1,11,1";
assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, highlighting, symbols)).isEqualTo("<span class=\"a\">@<span class=\"sym-1 sym\">Deprecated</span></span>");
}
}
| 2,801 | 34.468354 | 175 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/HtmlTextDecoratorTest.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.source;
import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.source.HtmlTextDecorator.CR_END_OF_LINE;
import static org.sonar.server.source.HtmlTextDecorator.LF_END_OF_LINE;
public class HtmlTextDecoratorTest {
@Test
public void should_decorate_simple_character_range() {
String packageDeclaration = "package org.sonar.core.source;";
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,7,k;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(packageDeclaration, decorationData);
assertThat(htmlOutput).containsOnly("<span class=\"k\">package</span> org.sonar.core.source;");
}
@Test
public void should_decorate_multiple_lines_characters_range() {
String firstCommentLine = "/*";
String secondCommentLine = " * Test";
String thirdCommentLine = " */";
String blockComment = firstCommentLine + LF_END_OF_LINE
+ secondCommentLine + LF_END_OF_LINE
+ thirdCommentLine + LF_END_OF_LINE;
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,14,cppd;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(blockComment, decorationData);
assertThat(htmlOutput).containsExactly(
"<span class=\"cppd\">" + firstCommentLine + "</span>",
"<span class=\"cppd\">" + secondCommentLine + "</span>",
"<span class=\"cppd\">" + thirdCommentLine + "</span>",
""
);
}
@Test
public void should_highlight_multiple_words_in_one_line() {
String classDeclaration = "public class MyClass implements MyInterface {";
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,6,k;7,12,k;21,31,k;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(classDeclaration, decorationData);
assertThat(htmlOutput).containsOnly(
"<span class=\"k\">public</span> " +
"<span class=\"k\">class</span> MyClass " +
"<span class=\"k\">implements</span> MyInterface {");
}
@Test
public void should_allow_multiple_levels_highlighting() {
String javaDocSample =
"/**" + LF_END_OF_LINE +
" * Creates a FormulaDecorator" + LF_END_OF_LINE +
" *" + LF_END_OF_LINE +
" * @param metric the metric should have an associated formula" + LF_END_OF_LINE +
" * " + LF_END_OF_LINE +
" * @throws IllegalArgumentException if no formula is associated to the metric" + LF_END_OF_LINE +
" */" + LF_END_OF_LINE;
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,184,cppd;47,53,k;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(javaDocSample, decorationData);
assertThat(htmlOutput).containsExactly(
"<span class=\"cppd\">/**</span>",
"<span class=\"cppd\"> * Creates a FormulaDecorator</span>",
"<span class=\"cppd\"> *</span>",
"<span class=\"cppd\"> * @param <span class=\"k\">metric</span> the metric should have an associated formula</span>",
"<span class=\"cppd\"> * </span>",
"<span class=\"cppd\"> * @throws IllegalArgumentException if no formula is associated to the metric</span>",
"<span class=\"cppd\"> */</span>",
""
);
}
@Test
public void should_support_crlf_line_breaks() {
String crlfCodeSample =
"/**" + CR_END_OF_LINE + LF_END_OF_LINE +
"* @return metric generated by the decorator" + CR_END_OF_LINE + LF_END_OF_LINE +
"*/" + CR_END_OF_LINE + LF_END_OF_LINE +
"@DependedUpon" + CR_END_OF_LINE + LF_END_OF_LINE +
"public Metric generatesMetric() {" + CR_END_OF_LINE + LF_END_OF_LINE +
" return metric;" + CR_END_OF_LINE + LF_END_OF_LINE +
"}" + CR_END_OF_LINE + LF_END_OF_LINE;
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,52,cppd;54,67,a;69,75,k;106,112,k;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(crlfCodeSample, decorationData);
assertThat(htmlOutput).containsExactly(
"<span class=\"cppd\">/**</span>",
"<span class=\"cppd\">* @return metric generated by the decorator</span>",
"<span class=\"cppd\">*/</span>",
"<span class=\"a\">@DependedUpon</span>",
"<span class=\"k\">public</span> Metric generatesMetric() {",
" <span class=\"k\">return</span> metric;",
"}",
""
);
}
@Test
public void should_close_tags_at_end_of_file() {
String classDeclarationSample =
"/*" + LF_END_OF_LINE +
" * Header" + LF_END_OF_LINE +
" */" + LF_END_OF_LINE +
LF_END_OF_LINE +
"public class HelloWorld {" + LF_END_OF_LINE +
"}";
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,16,cppd;18,25,k;25,31,k;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(classDeclarationSample, decorationData);
assertThat(htmlOutput).containsExactly(
"<span class=\"cppd\">/*</span>",
"<span class=\"cppd\"> * Header</span>",
"<span class=\"cppd\"> */</span>",
"",
"<span class=\"k\">public </span><span class=\"k\">class </span>HelloWorld {",
"}"
);
}
@Test
public void should_escape_markup_chars() {
String javadocWithHtml =
"/**\n" +
" * Provides a basic framework to sequentially read any kind of character stream in order to feed a generic OUTPUT.\n" +
" * \n" +
" * This framework can used for instance in order to :\n" +
" * <ul>\n" +
" * <li>Create a lexer in charge to generate a list of tokens from a character stream</li>\n" +
" * <li>Create a source code syntax highligther in charge to decorate a source code with HTML tags</li>\n" +
" * <li>Create a javadoc generator</li>\n" +
" * <li>...</li>\n" +
" * </ul>\n" +
" */\n";
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,453,cppd;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(javadocWithHtml, decorationData);
assertThat(htmlOutput).containsExactly(
"<span class=\"cppd\">/**</span>",
"<span class=\"cppd\"> * Provides a basic framework to sequentially read any kind of character stream in order to feed a generic OUTPUT.</span>",
"<span class=\"cppd\"> * </span>",
"<span class=\"cppd\"> * This framework can used for instance in order to :</span>",
"<span class=\"cppd\"> * <ul></span>",
"<span class=\"cppd\"> * <li>Create a lexer in charge to generate a list of tokens from a character stream</li></span>",
"<span class=\"cppd\"> * <li>Create a source code syntax highligther in charge to decorate a source code with HTML tags</li></span>",
"<span class=\"cppd\"> * <li>Create a javadoc generator</li></span>",
"<span class=\"cppd\"> * <li>...</li></span>",
"<span class=\"cppd\"> * </ul></span>",
"<span class=\"cppd\"> */</span>",
"");
}
@Test
public void should_escape_ampersand_char() {
String javadocWithAmpersandChar =
"/**\n" +
" * Definition of a dashboard.\n" +
" * <p/>\n" +
" * Its name and description can be retrieved using the i18n mechanism, using the keys \"dashboard.<id>.name\" and\n" +
" * \"dashboard.<id>.description\".\n" +
" *\n" +
" * @since 2.13\n" +
" */\n";
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,220,cppd;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(javadocWithAmpersandChar, decorationData);
assertThat(htmlOutput).containsExactly(
"<span class=\"cppd\">/**</span>",
"<span class=\"cppd\"> * Definition of a dashboard.</span>",
"<span class=\"cppd\"> * <p/></span>",
"<span class=\"cppd\"> * Its name and description can be retrieved using the i18n mechanism, using the keys \"dashboard.&lt;id&gt;.name\" and</span>",
"<span class=\"cppd\"> * \"dashboard.&lt;id&gt;.description\".</span>",
"<span class=\"cppd\"> *</span>",
"<span class=\"cppd\"> * @since 2.13</span>",
"<span class=\"cppd\"> */</span>",
"");
}
@Test
public void should_support_cr_line_breaks() {
String crCodeSample =
"/**" + CR_END_OF_LINE +
"* @return metric generated by the decorator" + CR_END_OF_LINE +
"*/" + CR_END_OF_LINE +
"@DependedUpon" + CR_END_OF_LINE +
"public Metric generatesMetric() {" + CR_END_OF_LINE +
" return metric;" + CR_END_OF_LINE +
"}" + CR_END_OF_LINE;
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,50,cppd;51,64,a;65,71,k;101,107,k;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(crCodeSample, decorationData);
assertThat(htmlOutput).containsExactly(
"<span class=\"cppd\">/**</span>",
"<span class=\"cppd\">* @return metric generated by the decorator</span>",
"<span class=\"cppd\">*/</span>",
"<span class=\"a\">@DependedUpon</span>",
"<span class=\"k\">public</span> Metric generatesMetric() {",
" <span class=\"k\">return</span> metric;",
"}",
""
);
}
@Test
public void should_support_multiple_empty_lines_at_end_of_file() {
String classDeclarationSample =
"/*" + LF_END_OF_LINE +
" * Header" + LF_END_OF_LINE +
" */" + LF_END_OF_LINE +
LF_END_OF_LINE +
"public class HelloWorld {" + LF_END_OF_LINE +
"}" + LF_END_OF_LINE + LF_END_OF_LINE + LF_END_OF_LINE;
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,16,cppd;18,25,k;25,31,k;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(classDeclarationSample, decorationData);
assertThat(htmlOutput).containsExactly(
"<span class=\"cppd\">/*</span>",
"<span class=\"cppd\"> * Header</span>",
"<span class=\"cppd\"> */</span>",
"",
"<span class=\"k\">public </span><span class=\"k\">class </span>HelloWorld {",
"}",
"",
"",
""
);
}
@Test
public void returned_code_begin_from_given_param() {
String javadocWithHtml =
"/**\n" +
" * Provides a basic framework to sequentially read any kind of character stream in order to feed a generic OUTPUT.\n" +
" * \n" +
" * This framework can used for instance in order to :\n" +
" * <ul>\n" +
" * <li>Create a lexer in charge to generate a list of tokens from a character stream</li>\n" +
" * <li>Create a source code syntax highligther in charge to decorate a source code with HTML tags</li>\n" +
" * <li>Create a javadoc generator</li>\n" +
" * <li>...</li>\n" +
" * </ul>\n" +
" */\n";
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,453,cppd;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(javadocWithHtml, decorationData, 4, null);
assertThat(htmlOutput)
.hasSize(9)
// Begin from line 4
.containsExactly(
"<span class=\"cppd\"> * This framework can used for instance in order to :</span>",
"<span class=\"cppd\"> * <ul></span>",
"<span class=\"cppd\"> * <li>Create a lexer in charge to generate a list of tokens from a character stream</li></span>",
"<span class=\"cppd\"> * <li>Create a source code syntax highligther in charge to decorate a source code with HTML tags</li></span>",
"<span class=\"cppd\"> * <li>Create a javadoc generator</li></span>",
"<span class=\"cppd\"> * <li>...</li></span>",
"<span class=\"cppd\"> * </ul></span>",
"<span class=\"cppd\"> */</span>",
"");
}
@Test
public void returned_code_end_to_given_param() {
String javadocWithHtml =
"/**\n" +
" * Provides a basic framework to sequentially read any kind of character stream in order to feed a generic OUTPUT.\n" +
" * \n" +
" * This framework can used for instance in order to :\n" +
" * <ul>\n" +
" * <li>Create a lexer in charge to generate a list of tokens from a character stream</li>\n" +
" * <li>Create a source code syntax highligther in charge to decorate a source code with HTML tags</li>\n" +
" * <li>Create a javadoc generator</li>\n" +
" * <li>...</li>\n" +
" * </ul>\n" +
" */\n";
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,453,cppd;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(javadocWithHtml, decorationData, null, 4);
assertThat(htmlOutput)
.hasSize(4)
// End at line 4
.containsExactly(
"<span class=\"cppd\">/**</span>",
"<span class=\"cppd\"> * Provides a basic framework to sequentially read any kind of character stream in order to feed a generic OUTPUT.</span>",
"<span class=\"cppd\"> * </span>",
"<span class=\"cppd\"> * This framework can used for instance in order to :</span>");
}
@Test
public void returned_code_is_between_from_and_to_params() {
String javadocWithHtml =
"/**\n" +
" * Provides a basic framework to sequentially read any kind of character stream in order to feed a generic OUTPUT.\n" +
" * \n" +
" * This framework can used for instance in order to :\n" +
" * <ul>\n" +
" * <li>Create a lexer in charge to generate a list of tokens from a character stream</li>\n" +
" * <li>Create a source code syntax highligther in charge to decorate a source code with HTML tags</li>\n" +
" * <li>Create a javadoc generator</li>\n" +
" * <li>...</li>\n" +
" * </ul>\n" +
" */\n";
DecorationDataHolder decorationData = new DecorationDataHolder();
decorationData.loadSyntaxHighlightingData("0,453,cppd;");
HtmlTextDecorator htmlTextDecorator = new HtmlTextDecorator();
List<String> htmlOutput = htmlTextDecorator.decorateTextWithHtml(javadocWithHtml, decorationData, 4, 8);
assertThat(htmlOutput)
.hasSize(5)
// Begin from line 4 and finish at line 8
.containsExactly(
"<span class=\"cppd\"> * This framework can used for instance in order to :</span>",
"<span class=\"cppd\"> * <ul></span>",
"<span class=\"cppd\"> * <li>Create a lexer in charge to generate a list of tokens from a character stream</li></span>",
"<span class=\"cppd\"> * <li>Create a source code syntax highligther in charge to decorate a source code with HTML tags</li></span>",
"<span class=\"cppd\"> * <li>Create a javadoc generator</li></span>"
);
}
}
| 17,163 | 41.590571 | 164 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/OpeningHtmlTagTest.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.source;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class OpeningHtmlTagTest {
@Test
public void test_getters() {
OpeningHtmlTag openingHtmlTag = new OpeningHtmlTag(3, "tag");
assertThat(openingHtmlTag.getStartOffset()).isEqualTo(3);
assertThat(openingHtmlTag.getCssClass()).isEqualTo("tag");
}
@Test
public void test_equals() {
OpeningHtmlTag openingHtmlTag = new OpeningHtmlTag(3, "tag");
OpeningHtmlTag openingHtmlTagWithSameValues = new OpeningHtmlTag(3, "tag");
OpeningHtmlTag openingHtmlTagWithDifferentValues = new OpeningHtmlTag(5, "tag2");
OpeningHtmlTag openingHtmlTagWithNoCssClass = new OpeningHtmlTag(3, null);
assertThat(openingHtmlTag)
.isEqualTo(openingHtmlTagWithSameValues)
.isEqualTo(openingHtmlTag)
.isNotEqualTo(openingHtmlTagWithDifferentValues)
.isNotEqualTo(openingHtmlTagWithNoCssClass)
.isNotEqualTo(new OpeningHtmlTag(3, "tag") {
});
}
@Test
public void test_hashcode() {
OpeningHtmlTag openingHtmlTag = new OpeningHtmlTag(3, "tag");
OpeningHtmlTag openingHtmlTagWithSameValues = new OpeningHtmlTag(3, "tag");
OpeningHtmlTag openingHtmlTagWithDifferentValue = new OpeningHtmlTag(5, "tag2");
assertThat(openingHtmlTag)
.hasSameHashCodeAs(openingHtmlTagWithSameValues)
.hasSameHashCodeAs(openingHtmlTag);
assertThat(openingHtmlTag.hashCode()).isNotEqualTo(openingHtmlTagWithDifferentValue.hashCode());
}
}
| 2,369 | 36.619048 | 100 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/SourceWsModuleTest.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.source.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import org.sonar.server.ws.WsAction;
import static org.assertj.core.api.Assertions.assertThat;
public class SourceWsModuleTest {
private final SourceWsModule underTest = new SourceWsModule();
@Test
public void verify_count_of_actions() {
ListContainer container = new ListContainer();
underTest.configure(container);
assertThat(container.getAddedObjects().stream().filter(o -> o instanceof Class && WsAction.class.isAssignableFrom((Class<?>) o)))
.hasSize(6);
}
}
| 1,442 | 36 | 133 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/SourcesWsTest.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.source.ws;
import java.util.Random;
import java.util.stream.IntStream;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.tester.UserSessionRule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
public class SourcesWsTest {
@Rule
public UserSessionRule userSessionRule = UserSessionRule.standalone();
@Test
public void define_ws() {
SourcesWsAction[] actions = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> {
SourcesWsAction wsAction = mock(SourcesWsAction.class);
doAnswer(invocation -> {
WebService.NewController controller = invocation.getArgument(0);
controller.createAction("action_" + i)
.setHandler(wsAction);
return null;
}).when(wsAction).define(any(WebService.NewController.class));
return wsAction;
})
.toArray(SourcesWsAction[]::new);
SourcesWs underTest = new SourcesWs(actions);
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/sources");
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo("4.2");
assertThat(controller.description()).isNotEmpty();
assertThat(controller.actions()).hasSize(actions.length);
}
}
| 2,377 | 35.584615 | 80 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/text/MacroInterpreterTest.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.text;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.platform.Server;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MacroInterpreterTest {
String path = "http://sonar";
MacroInterpreter interpreter;
@Before
public void setUp() {
Server server = mock(Server.class);
when(server.getContextPath()).thenReturn(path);
interpreter = new MacroInterpreter(server);
}
@Test
public void should_do_nothing_if_no_macro_detected() {
String origin = "nothing to do";
String result = interpreter.interpret(origin);
assertThat(result).isEqualTo(origin);
}
@Test
public void should_replace_rule_macro() {
// key of repository and rule can contain alphanumeric latin characters, dashes, underscores and dots
String ruleKey = "Some_Repo-Key.1:Some_Rule-Key.1";
String origin = "See {rule:" + ruleKey + "} for detail.";
String result = interpreter.interpret(origin);
// colon should be escaped
assertThat(result).isEqualTo("See <a href='" + path + "/coding_rules#rule_key=Some_Repo-Key.1%3ASome_Rule-Key.1'>Some_Rule-Key.1</a> for detail.");
}
}
| 2,099 | 34 | 151 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/PageRepositoryTest.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.ui;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.web.page.Page;
import org.sonar.api.web.page.Page.Qualifier;
import org.sonar.api.web.page.PageDefinition;
import org.sonar.core.extension.CoreExtensionRepository;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.web.page.Page.Scope.COMPONENT;
import static org.sonar.api.web.page.Page.Scope.GLOBAL;
public class PageRepositoryTest {
@Rule
public LogTester logTester = new LogTester();
private PluginRepository pluginRepository = mock(PluginRepository.class);
private final CoreExtensionRepository coreExtensionRepository = mock(CoreExtensionRepository.class);
private PageRepository underTest = new PageRepository(pluginRepository, coreExtensionRepository);
@Before
public void setUp() {
when(pluginRepository.hasPlugin(any())).thenReturn(true);
when(pluginRepository.getPluginInfo(any())).thenReturn(new PluginInfo("unused"));
}
@Test
public void pages_from_different_page_definitions_ordered_by_key() {
PageDefinition firstPlugin = context -> context
.addPage(Page.builder("my_plugin/K1").setName("N1").build())
.addPage(Page.builder("my_plugin/K3").setName("N3").build());
PageDefinition secondPlugin = context -> context.addPage(Page.builder("my_plugin/K2").setName("N2").build());
underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[]{firstPlugin, secondPlugin});
underTest.start();
List<Page> result = underTest.getAllPages();
assertThat(result)
.extracting(Page::getKey, Page::getName)
.containsExactly(
tuple("my_plugin/K1", "N1"),
tuple("my_plugin/K2", "N2"),
tuple("my_plugin/K3", "N3"));
}
@Test
public void filter_by_navigation_and_qualifier() {
PageDefinition plugin = context -> context
// Default with GLOBAL navigation and no qualifiers
.addPage(Page.builder("my_plugin/K1").setName("K1").build())
.addPage(Page.builder("my_plugin/K2").setName("K2").setScope(COMPONENT).setComponentQualifiers(Qualifier.PROJECT).build())
.addPage(Page.builder("my_plugin/K3").setName("K3").setScope(COMPONENT).setComponentQualifiers(Qualifier.MODULE).build())
.addPage(Page.builder("my_plugin/K4").setName("K4").setScope(GLOBAL).build())
.addPage(Page.builder("my_plugin/K5").setName("K5").setScope(COMPONENT).setComponentQualifiers(Qualifier.VIEW).build())
.addPage(Page.builder("my_plugin/K6").setName("K6").setScope(COMPONENT).setComponentQualifiers(Qualifier.APP).build());
underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[]{plugin});
underTest.start();
List<Page> result = underTest.getComponentPages(false, Qualifiers.PROJECT);
assertThat(result)
.extracting(Page::getKey)
.containsExactly("my_plugin/K2");
}
@Test
public void empty_pages_if_no_page_definition() {
underTest.start();
List<Page> result = underTest.getAllPages();
assertThat(result).isEmpty();
}
@Test
public void filter_pages_without_qualifier() {
PageDefinition plugin = context -> context
.addPage(Page.builder("my_plugin/K1").setName("N1").build())
.addPage(Page.builder("my_plugin/K2").setName("N2").build())
.addPage(Page.builder("my_plugin/K3").setName("N3").build());
underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[]{plugin});
underTest.start();
List<Page> result = underTest.getGlobalPages(false);
assertThat(result)
.extracting(Page::getKey)
.containsExactly("my_plugin/K1", "my_plugin/K2", "my_plugin/K3");
}
@Test
public void fail_if_pages_called_before_server_startup() {
assertThatThrownBy(() -> underTest.getAllPages())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("Pages haven't been initialized yet");
}
@Test
public void fail_if_page_with_unknown_plugin() {
PageDefinition governance = context -> context.addPage(Page.builder("governance/my_key").setName("N1").build());
PageDefinition plugin42 = context -> context.addPage(Page.builder("plugin_42/my_key").setName("N2").build());
pluginRepository = mock(PluginRepository.class);
when(pluginRepository.hasPlugin("governance")).thenReturn(true);
underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[]{governance, plugin42});
assertThatThrownBy(() -> underTest.start())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Page 'N2' references plugin 'plugin_42' that does not exist");
}
}
| 6,027 | 40.861111 | 128 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/VersionFormatterTest.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.ui;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class VersionFormatterTest {
@Test
public void format_technical_version() {
assertThat(format("6.3")).isEqualTo("6.3");
assertThat(format("6.3.2")).isEqualTo("6.3.2");
assertThat(format("6.3.2.5498")).isEqualTo("6.3.2 (build 5498)");
assertThat(format("6.3.0.5499")).isEqualTo("6.3 (build 5499)");
}
private static String format(String technicalVersion) {
return VersionFormatter.format(technicalVersion);
}
}
| 1,404 | 35.025641 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/WebAnalyticsLoaderImplTest.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.ui;
import org.junit.Test;
import org.sonar.api.utils.MessageException;
import org.sonar.api.web.WebAnalytics;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class WebAnalyticsLoaderImplTest {
@Test
public void return_empty_if_no_analytics_plugin() {
assertThat(new WebAnalyticsLoaderImpl(null).getUrlPathToJs()).isEmpty();
assertThat(new WebAnalyticsLoaderImpl(new WebAnalytics[0]).getUrlPathToJs()).isEmpty();
}
@Test
public void return_js_path_if_analytics_plugin_is_installed() {
WebAnalytics analytics = newWebAnalytics("api/google/analytics");
WebAnalyticsLoaderImpl underTest = new WebAnalyticsLoaderImpl(new WebAnalytics[] {analytics});
assertThat(underTest.getUrlPathToJs()).hasValue("/api/google/analytics");
}
@Test
public void return_empty_if_path_starts_with_slash() {
WebAnalytics analytics = newWebAnalytics("/api/google/analytics");
WebAnalyticsLoaderImpl underTest = new WebAnalyticsLoaderImpl(new WebAnalytics[] {analytics});
assertThat(underTest.getUrlPathToJs()).isEmpty();
}
@Test
public void return_empty_if_path_is_an_url() {
WebAnalytics analytics = newWebAnalytics("http://foo");
WebAnalyticsLoaderImpl underTest = new WebAnalyticsLoaderImpl(new WebAnalytics[] {analytics});
assertThat(underTest.getUrlPathToJs()).isEmpty();
}
@Test
public void return_empty_if_path_has_up_operation() {
WebAnalytics analytics = newWebAnalytics("foo/../bar");
WebAnalyticsLoaderImpl underTest = new WebAnalyticsLoaderImpl(new WebAnalytics[] {analytics});
assertThat(underTest.getUrlPathToJs()).isEmpty();
}
@Test
public void fail_if_multiple_analytics_plugins_are_installed() {
WebAnalytics analytics1 = newWebAnalytics("foo");
WebAnalytics analytics2 = newWebAnalytics("bar");
Throwable thrown = catchThrowable(() -> new WebAnalyticsLoaderImpl(new WebAnalytics[] {analytics1, analytics2}));
assertThat(thrown)
.isInstanceOf(MessageException.class)
.hasMessage("Limited to only one web analytics plugin. Found multiple implementations: [" +
analytics1.getClass().getName() + ", " + analytics2.getClass().getName() + "]");
}
private static WebAnalytics newWebAnalytics(String path) {
WebAnalytics analytics = mock(WebAnalytics.class);
when(analytics.getUrlPathToJs()).thenReturn(path);
return analytics;
}
}
| 3,403 | 36.822222 | 117 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/ws/BranchFeatureRule.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.ui.ws;
import org.junit.rules.ExternalResource;
import org.sonar.server.branch.BranchFeatureProxy;
public class BranchFeatureRule extends ExternalResource implements BranchFeatureProxy {
private boolean enabled;
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
protected void after() {
reset();
}
public void reset() {
this.enabled = false;
}
@Override
public boolean isEnabled() {
return enabled;
}
}
| 1,345 | 27.041667 | 87 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/ws/GlobalActionTest.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.ui.ws;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.platform.Server;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypeTree;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.web.page.Page;
import org.sonar.api.web.page.PageDefinition;
import org.sonar.core.documentation.DocumentationLinkGenerator;
import org.sonar.core.extension.CoreExtensionRepository;
import org.sonar.core.platform.EditionProvider;
import org.sonar.core.platform.PlatformEditionProvider;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
import org.sonar.db.DbClient;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.server.authentication.DefaultAdminCredentialsVerifier;
import org.sonar.server.issue.index.IssueIndexSyncProgressChecker;
import org.sonar.server.platform.NodeInformation;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ui.PageRepository;
import org.sonar.server.ui.WebAnalyticsLoader;
import org.sonar.server.ws.WsActionTester;
import org.sonar.updatecenter.common.Version;
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.mock;
import static org.mockito.Mockito.when;
import static org.sonar.test.JsonAssert.assertJson;
public class GlobalActionTest {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
private final MapSettings settings = new MapSettings();
private final Server server = mock(Server.class);
private final NodeInformation nodeInformation = mock(NodeInformation.class);
private final DbClient dbClient = mock(DbClient.class, RETURNS_DEEP_STUBS);
private final IssueIndexSyncProgressChecker indexSyncProgressChecker = mock(IssueIndexSyncProgressChecker.class);
private final BranchFeatureRule branchFeature = new BranchFeatureRule();
private final PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class);
private final WebAnalyticsLoader webAnalyticsLoader = mock(WebAnalyticsLoader.class);
private final DefaultAdminCredentialsVerifier defaultAdminCredentialsVerifier = mock(DefaultAdminCredentialsVerifier.class);
private final DocumentationLinkGenerator documentationLinkGenerator = mock(DocumentationLinkGenerator.class);
private WsActionTester ws;
@Test
public void empty_call() {
init();
assertJson(call()).isSimilarTo("{" +
" \"globalPages\": []," +
" \"settings\": {}," +
" \"qualifiers\": []" +
"}");
}
@Test
public void return_qualifiers() {
init(new Page[] {}, new ResourceTypeTree[] {
ResourceTypeTree.builder()
.addType(ResourceType.builder("POL").build())
.addType(ResourceType.builder("LOP").build())
.addRelations("POL", "LOP")
.build(),
ResourceTypeTree.builder()
.addType(ResourceType.builder("PAL").build())
.addType(ResourceType.builder("LAP").build())
.addRelations("PAL", "LAP")
.build()
});
assertJson(call()).isSimilarTo("{" +
" \"qualifiers\": [\"POL\", \"PAL\"]" +
"}");
}
@Test
public void return_settings() {
settings.setProperty("sonar.lf.logoUrl", "http://example.com/my-custom-logo.png");
settings.setProperty("sonar.lf.logoWidthPx", 135);
settings.setProperty("sonar.lf.gravatarServerUrl", "https://secure.gravatar.com/avatar/{EMAIL_MD5}.jpg?s={SIZE}&d=identicon");
settings.setProperty("sonar.lf.enableGravatar", true);
settings.setProperty("sonar.updatecenter.activate", false);
settings.setProperty("sonar.technicalDebt.ratingGrid", "0.05,0.1,0.2,0.5");
settings.setProperty("sonar.developerAggregatedInfo.disabled", false);
// This setting should be ignored as it's not needed
settings.setProperty("sonar.defaultGroup", "sonar-users");
init();
assertJson(call()).isSimilarTo("{" +
" \"settings\": {" +
" \"sonar.lf.logoUrl\": \"http://example.com/my-custom-logo.png\"," +
" \"sonar.lf.logoWidthPx\": \"135\"," +
" \"sonar.lf.gravatarServerUrl\": \"https://secure.gravatar.com/avatar/{EMAIL_MD5}.jpg?s={SIZE}&d=identicon\"," +
" \"sonar.lf.enableGravatar\": \"true\"," +
" \"sonar.updatecenter.activate\": \"false\"," +
" \"sonar.technicalDebt.ratingGrid\": \"0.05,0.1,0.2,0.5\"" +
" \"sonar.developerAggregatedInfo.disabled\": \"false\"" +
" }" +
"}");
}
@Test
public void return_developer_info_disabled_setting() {
init();
settings.setProperty("sonar.developerAggregatedInfo.disabled", true);
assertJson(call()).isSimilarTo("{" +
" \"settings\": {" +
" \"sonar.developerAggregatedInfo.disabled\": \"true\"" +
" }" +
"}");
}
@Test
public void return_deprecated_logo_settings() {
init();
settings.setProperty("sonar.lf.logoUrl", "http://example.com/my-custom-logo.png");
settings.setProperty("sonar.lf.logoWidthPx", 135);
assertJson(call()).isSimilarTo("{" +
" \"settings\": {" +
" \"sonar.lf.logoUrl\": \"http://example.com/my-custom-logo.png\"," +
" \"sonar.lf.logoWidthPx\": \"135\"" +
" }," +
" \"logoUrl\": \"http://example.com/my-custom-logo.png\"," +
" \"logoWidth\": \"135\"" +
"}");
}
@Test
public void the_returned_global_pages_do_not_include_administration_pages() {
init(createPages(), new ResourceTypeTree[] {});
assertJson(call()).isSimilarTo("{" +
" \"globalPages\": [" +
" {" +
" \"key\": \"another_plugin/page\"," +
" \"name\": \"My Another Page\"" +
" }," +
" {" +
" \"key\": \"my_plugin/page\"," +
" \"name\": \"My Plugin Page\"" +
" }" +
" ]" +
"}");
}
@Test
public void return_sonarqube_version() {
init();
when(server.getVersion()).thenReturn("6.2");
assertJson(call()).isSimilarTo("{" +
" \"version\": \"6.2\"" +
"}");
}
@Test
public void functional_version_when_4_digits() {
init();
when(server.getVersion()).thenReturn("6.3.1.1234");
String result = call();
assertThat(result).contains("6.3.1 (build 1234)");
}
@Test
public void functional_version_when_third_digit_is_0() {
init();
when(server.getVersion()).thenReturn("6.3.0.1234");
String result = call();
assertThat(result).contains("6.3 (build 1234)");
}
@Test
public void return_if_production_database_or_not() {
init();
when(dbClient.getDatabase().getDialect()).thenReturn(new PostgreSql());
assertJson(call()).isSimilarTo("{" +
" \"productionDatabase\": true" +
"}");
}
@Test
public void return_need_issue_sync() {
init();
when(indexSyncProgressChecker.isIssueSyncInProgress(any())).thenReturn(true);
assertJson(call()).isSimilarTo("{\"needIssueSync\": true}");
when(indexSyncProgressChecker.isIssueSyncInProgress(any())).thenReturn(false);
assertJson(call()).isSimilarTo("{\"needIssueSync\": false}");
}
@Test
public void instance_uses_default_admin_credentials() {
init();
when(defaultAdminCredentialsVerifier.hasDefaultCredentialUser()).thenReturn(true);
// Even if the default credentials are used, if the current user it not a system admin, the flag is not returned.
assertJson(call()).isNotSimilarTo("{\"instanceUsesDefaultAdminCredentials\":true}");
userSession.logIn().setSystemAdministrator();
assertJson(call()).isSimilarTo("{\"instanceUsesDefaultAdminCredentials\":true}");
when(defaultAdminCredentialsVerifier.hasDefaultCredentialUser()).thenReturn(false);
assertJson(call()).isSimilarTo("{\"instanceUsesDefaultAdminCredentials\":false}");
}
@Test
public void standalone_flag() {
init();
userSession.logIn().setSystemAdministrator();
when(nodeInformation.isStandalone()).thenReturn(true);
assertJson(call()).isSimilarTo("{\"standalone\":true}");
}
@Test
public void not_standalone_flag() {
init();
userSession.logIn().setSystemAdministrator();
when(nodeInformation.isStandalone()).thenReturn(false);
assertJson(call()).isSimilarTo("{\"standalone\":false}");
}
@Test
public void test_example_response() {
settings.setProperty("sonar.lf.logoUrl", "http://example.com/my-custom-logo.png");
settings.setProperty("sonar.lf.logoWidthPx", 135);
settings.setProperty("sonar.lf.gravatarServerUrl", "http://some-server.tld/logo.png");
settings.setProperty("sonar.lf.enableGravatar", true);
settings.setProperty("sonar.updatecenter.activate", false);
settings.setProperty("sonar.technicalDebt.ratingGrid", "0.05,0.1,0.2,0.5");
init(createPages(), new ResourceTypeTree[] {
ResourceTypeTree.builder()
.addType(ResourceType.builder("POL").build())
.addType(ResourceType.builder("LOP").build())
.addRelations("POL", "LOP")
.build(),
ResourceTypeTree.builder()
.addType(ResourceType.builder("PAL").build())
.addType(ResourceType.builder("LAP").build())
.addRelations("PAL", "LAP")
.build()
});
when(server.getVersion()).thenReturn("6.2");
when(dbClient.getDatabase().getDialect()).thenReturn(new PostgreSql());
when(nodeInformation.isStandalone()).thenReturn(true);
when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY));
when(documentationLinkGenerator.getDocumentationLink(null)).thenReturn("http://docs.example.com/10.0");
String result = call();
assertJson(result).isSimilarTo(ws.getDef().responseExampleAsString());
}
@Test
public void edition_is_not_returned_if_not_defined() {
init();
when(editionProvider.get()).thenReturn(Optional.empty());
String json = call();
assertThat(json).doesNotContain("edition");
}
@Test
public void edition_is_returned_if_defined() {
init();
when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER));
String json = call();
assertJson(json).isSimilarTo("{\"edition\":\"developer\"}");
}
@Test
public void web_analytics_js_path_is_not_returned_if_not_defined() {
init();
when(webAnalyticsLoader.getUrlPathToJs()).thenReturn(Optional.empty());
String json = call();
assertThat(json).doesNotContain("webAnalyticsJsPath");
}
@Test
public void web_analytics_js_path_is_returned_if_defined() {
init();
String path = "static/googleanalytics/analytics.js";
when(webAnalyticsLoader.getUrlPathToJs()).thenReturn(Optional.of(path));
String json = call();
assertJson(json).isSimilarTo("{\"webAnalyticsJsPath\":\"" + path + "\"}");
}
@Test
public void call_shouldReturnDocumentationUrl() {
init();
String url = "https://docs.sonarqube.org/10.0";
when(documentationLinkGenerator.getDocumentationLink(null)).thenReturn(url);
String json = call();
assertJson(json).isSimilarTo("{\"documentationUrl\":\"" + url + "\"}");
}
private void init() {
init(new org.sonar.api.web.page.Page[] {}, new ResourceTypeTree[] {});
}
private void init(org.sonar.api.web.page.Page[] pages, ResourceTypeTree[] resourceTypeTrees) {
when(dbClient.getDatabase().getDialect()).thenReturn(new H2());
when(server.getVersion()).thenReturn("6.42");
PluginRepository pluginRepository = mock(PluginRepository.class);
when(pluginRepository.hasPlugin(any())).thenReturn(true);
when(pluginRepository.getPluginInfo(any())).thenReturn(new PluginInfo("unused").setVersion(Version.create("1.0")));
CoreExtensionRepository coreExtensionRepository = mock(CoreExtensionRepository.class);
when(coreExtensionRepository.isInstalled(any())).thenReturn(false);
PageRepository pageRepository = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[] {context -> {
for (Page page : pages) {
context.addPage(page);
}
}});
pageRepository.start();
GlobalAction wsAction = new GlobalAction(pageRepository, settings.asConfig(), new ResourceTypes(resourceTypeTrees), server,
nodeInformation, dbClient, userSession, editionProvider, webAnalyticsLoader,
indexSyncProgressChecker, defaultAdminCredentialsVerifier, documentationLinkGenerator);
ws = new WsActionTester(wsAction);
wsAction.start();
}
private String call() {
return ws.newRequest().execute().getInput();
}
private Page[] createPages() {
Page page = Page.builder("my_plugin/page").setName("My Plugin Page").build();
Page anotherPage = Page.builder("another_plugin/page").setName("My Another Page").build();
Page adminPage = Page.builder("my_plugin/admin_page").setName("Admin Page").setAdmin(true).build();
return new Page[] {page, anotherPage, adminPage};
}
}
| 13,910 | 35.899204 | 132 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/ws/NavigationWsModuleTest.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.ui.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class NavigationWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new NavigationWsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(5);
}
}
| 1,266 | 35.2 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/EmailValidatorTest.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.user.ws;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.user.ws.EmailValidator.isValidIfPresent;
public class EmailValidatorTest {
@Test
public void valid_if_absent_or_empty() {
assertThat(isValidIfPresent(null)).isTrue();
assertThat(isValidIfPresent("")).isTrue();
}
@Test
public void various_examples_of_unusual_but_valid_emails() {
assertThat(isValidIfPresent("info@sonarsource.com")).isTrue();
assertThat(isValidIfPresent("guillaume.jambet+sonarsource-emailvalidatortest@gmail.com")).isTrue();
assertThat(isValidIfPresent("webmaster@kiné-beauté.fr")).isTrue();
assertThat(isValidIfPresent("Chuck Norris <coup-de-pied-retourné@chucknorris.com>")).isTrue();
assertThat(isValidIfPresent("\"Fred Bloggs\"@example.com")).isTrue();
assertThat(isValidIfPresent("pipo@127.0.0.1")).isTrue();
assertThat(isValidIfPresent("admin@admin")).isTrue();
}
@Test
public void various_examples_of_invalid_emails() {
assertThat(isValidIfPresent("infosonarsource.com")).isFalse();
assertThat(isValidIfPresent("info@.sonarsource.com")).isFalse();
assertThat(isValidIfPresent("info\"@.sonarsource.com")).isFalse();
}
}
| 2,105 | 38 | 103 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/HomepageTypesImplTest.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.user.ws;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.user.ws.HomepageTypes.Type.APPLICATION;
import static org.sonar.server.user.ws.HomepageTypes.Type.ISSUES;
import static org.sonar.server.user.ws.HomepageTypes.Type.PORTFOLIO;
import static org.sonar.server.user.ws.HomepageTypes.Type.PORTFOLIOS;
import static org.sonar.server.user.ws.HomepageTypes.Type.PROJECT;
import static org.sonar.server.user.ws.HomepageTypes.Type.PROJECTS;
public class HomepageTypesImplTest {
private HomepageTypesImpl underTest = new HomepageTypesImpl();
@Test
public void types() {
assertThat(underTest.getTypes()).containsExactlyInAnyOrder(PROJECT, PROJECTS, ISSUES, PORTFOLIOS, PORTFOLIO, APPLICATION);
}
@Test
public void default_type() {
assertThat(underTest.getDefaultType()).isEqualTo(PROJECTS);
}
}
| 1,750 | 36.255319 | 126 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UsersWsModuleTest.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.user.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class UsersWsModuleTest {
@Test
public void verify_container_is_not_empty() {
ListContainer container = new ListContainer();
new UsersWsModule().configure(container);
assertThat(container.getAddedObjects()).isNotEmpty();
}
}
| 1,258 | 33.972222 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UsersWsTest.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.user.ws;
import java.util.List;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.ws.ServletFilterHandler;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
public class UsersWsTest {
private static final TestAction TEST_ACTION_1 = new TestAction();
private static final TestAction TEST_ACTION_2 = new TestAction();
private final UsersWs underTest = new UsersWs(List.of(TEST_ACTION_1, TEST_ACTION_2));
@Test
public void define_ws() {
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller(UsersWs.API_USERS);
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo(UsersWs.SINCE_VERSION);
assertThat(controller.description()).isEqualTo(UsersWs.DESCRIPTION);
}
private static class TestAction implements BaseUsersWsAction {
@Override
public void define(WebService.NewController context) {
context.createAction(randomAlphanumeric(10)).setHandler(ServletFilterHandler.INSTANCE);
}
}
}
| 2,044 | 34.877193 | 93 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/GroupServiceTest.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.usergroups.ws;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.sonar.api.security.DefaultGroups;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.permission.AuthorizationDao;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.permission.template.PermissionTemplateDao;
import org.sonar.db.qualitygate.QualityGateGroupPermissionsDao;
import org.sonar.db.qualityprofile.QProfileEditGroupsDao;
import org.sonar.db.scim.ScimGroupDao;
import org.sonar.db.user.ExternalGroupDao;
import org.sonar.db.user.GroupDao;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.RoleDao;
import org.sonar.db.user.UserGroupDao;
import org.sonar.server.exceptions.BadRequestException;
import static java.lang.String.format;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(DataProviderRunner.class)
public class GroupServiceTest {
private static final String GROUP_NAME = "GROUP_NAME";
private static final String GROUP_UUID = "GROUP_UUID";
private static final String DEFAULT_GROUP_NAME = "sonar-users";
private static final String DEFAULT_GROUP_UUID = "DEFAULT_GROUP_UUID";
@Mock
private DbSession dbSession;
@Mock
private DbClient dbClient;
@Mock
private UuidFactory uuidFactory;
@InjectMocks
private GroupService groupService;
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Before
public void setUp() {
mockNeededDaos();
}
private void mockNeededDaos() {
when(dbClient.authorizationDao()).thenReturn(mock(AuthorizationDao.class));
when(dbClient.roleDao()).thenReturn(mock(RoleDao.class));
when(dbClient.permissionTemplateDao()).thenReturn(mock(PermissionTemplateDao.class));
when(dbClient.userGroupDao()).thenReturn(mock(UserGroupDao.class));
when(dbClient.qProfileEditGroupsDao()).thenReturn(mock(QProfileEditGroupsDao.class));
when(dbClient.qualityGateGroupPermissionsDao()).thenReturn(mock(QualityGateGroupPermissionsDao.class));
when(dbClient.scimGroupDao()).thenReturn(mock(ScimGroupDao.class));
when(dbClient.externalGroupDao()).thenReturn(mock(ExternalGroupDao.class));
when(dbClient.groupDao()).thenReturn(mock(GroupDao.class));
}
@Test
public void findGroupDtoOrThrow_whenGroupExists_returnsIt() {
GroupDto groupDto = mockGroupDto();
when(dbClient.groupDao().selectByName(dbSession, GROUP_NAME))
.thenReturn(Optional.of(groupDto));
assertThat(groupService.findGroup(dbSession, GROUP_NAME)).contains(groupDto);
}
@Test
public void findGroupDtoOrThrow_whenGroupDoesntExist_throw() {
when(dbClient.groupDao().selectByName(dbSession, GROUP_NAME))
.thenReturn(Optional.empty());
assertThat(groupService.findGroup(dbSession, GROUP_NAME)).isEmpty();
}
@Test
public void delete_whenNotDefaultAndNotLastAdminGroup_deleteGroup() {
GroupDto groupDto = mockGroupDto();
when(dbClient.groupDao().selectByName(dbSession, DefaultGroups.USERS))
.thenReturn(Optional.of(new GroupDto().setUuid("another_group_uuid")));
when(dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingGroup(dbSession, GlobalPermission.ADMINISTER.getKey(), groupDto.getUuid()))
.thenReturn(2);
groupService.delete(dbSession, groupDto);
verifyGroupDelete(dbSession, groupDto);
}
@Test
public void delete_whenDefaultGroup_throwAndDontDeleteGroup() {
GroupDto groupDto = mockGroupDto();
when(dbClient.groupDao().selectByName(dbSession, DefaultGroups.USERS))
.thenReturn(Optional.of(groupDto));
assertThatThrownBy(() -> groupService.delete(dbSession, groupDto))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(format("Default group '%s' cannot be used to perform this action", GROUP_NAME));
verifyNoGroupDelete(dbSession, groupDto);
}
@Test
public void delete_whenLastAdminGroup_throwAndDontDeleteGroup() {
GroupDto groupDto = mockGroupDto();
when(dbClient.groupDao().selectByName(dbSession, DefaultGroups.USERS))
.thenReturn(Optional.of(new GroupDto().setUuid("another_group_uuid"))); // We must pass the default group check
when(dbClient.authorizationDao().countUsersWithGlobalPermissionExcludingGroup(dbSession, GlobalPermission.ADMINISTER.getKey(), groupDto.getUuid()))
.thenReturn(0);
assertThatThrownBy(() -> groupService.delete(dbSession, groupDto))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The last system admin group cannot be deleted");
verifyNoGroupDelete(dbSession, groupDto);
}
@Test
public void updateGroup_updatesGroupNameAndDescription() {
GroupDto group = mockGroupDto();
GroupDto groupWithUpdatedName = mockGroupDto();
mockDefaultGroup();
when(dbClient.groupDao().update(dbSession, group)).thenReturn(groupWithUpdatedName);
groupService.updateGroup(dbSession, group, "new-name", "New Description");
verify(group).setName("new-name");
verify(groupWithUpdatedName).setDescription("New Description");
verify(dbClient.groupDao()).update(dbSession, group);
verify(dbClient.groupDao()).update(dbSession, groupWithUpdatedName);
}
@Test
public void updateGroup_updatesGroupName() {
GroupDto group = mockGroupDto();
mockDefaultGroup();
groupService.updateGroup(dbSession, group, "new-name");
verify(group).setName("new-name");
verify(dbClient.groupDao()).update(dbSession, group);
}
@Test
public void updateGroup_whenGroupIsDefault_throws() {
GroupDto defaultGroup = mockDefaultGroup();
when(dbClient.groupDao().selectByName(dbSession, DEFAULT_GROUP_NAME)).thenReturn(Optional.of(defaultGroup));
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> groupService.updateGroup(dbSession, defaultGroup, "new-name", "New Description"))
.withMessage("Default group 'sonar-users' cannot be used to perform this action");
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> groupService.updateGroup(dbSession, defaultGroup, "new-name"))
.withMessage("Default group 'sonar-users' cannot be used to perform this action");
}
@Test
public void updateGroup_whenGroupNameDoesntChange_succeedsWithDescription() {
GroupDto group = mockGroupDto();
mockDefaultGroup();
groupService.updateGroup(dbSession, group, group.getName(), "New Description");
verify(group).setDescription("New Description");
verify(dbClient.groupDao()).update(dbSession, group);
}
@Test
public void updateGroup_whenGroupNameDoesntChange_succeeds() {
GroupDto group = mockGroupDto();
mockDefaultGroup();
assertThatNoException()
.isThrownBy(() -> groupService.updateGroup(dbSession, group, group.getName()));
verify(dbClient.groupDao(), never()).update(dbSession, group);
}
@Test
public void updateGroup_whenGroupExist_throws() {
GroupDto group = mockGroupDto();
GroupDto group2 = mockGroupDto();
mockDefaultGroup();
String group2Name = GROUP_NAME + "2";
when(dbClient.groupDao().selectByName(dbSession, group2Name)).thenReturn(Optional.of(group2));
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> groupService.updateGroup(dbSession, group, group2Name, "New Description"))
.withMessage("Group '" + group2Name + "' already exists");
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> groupService.updateGroup(dbSession, group, group2Name))
.withMessage("Group '" + group2Name + "' already exists");
}
@Test
@UseDataProvider("invalidGroupNames")
public void updateGroup_whenGroupNameIsInvalid_throws(String groupName, String errorMessage) {
GroupDto group = mockGroupDto();
mockDefaultGroup();
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> groupService.updateGroup(dbSession, group, groupName, "New Description"))
.withMessage(errorMessage);
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> groupService.updateGroup(dbSession, group, groupName))
.withMessage(errorMessage);
}
@Test
public void createGroup_whenNameAndDescriptionIsProvided_createsGroup() {
when(uuidFactory.create()).thenReturn("1234");
groupService.createGroup(dbSession, "Name", "Description");
ArgumentCaptor<GroupDto> groupCaptor = ArgumentCaptor.forClass(GroupDto.class);
verify(dbClient.groupDao()).insert(eq(dbSession), groupCaptor.capture());
GroupDto createdGroup = groupCaptor.getValue();
assertThat(createdGroup.getName()).isEqualTo("Name");
assertThat(createdGroup.getDescription()).isEqualTo("Description");
assertThat(createdGroup.getUuid()).isEqualTo("1234");
}
@Test
public void createGroup_whenGroupExist_throws() {
GroupDto group = mockGroupDto();
when(dbClient.groupDao().selectByName(dbSession, GROUP_NAME)).thenReturn(Optional.of(group));
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> groupService.createGroup(dbSession, GROUP_NAME, "New Description"))
.withMessage("Group '" + GROUP_NAME + "' already exists");
}
@Test
@UseDataProvider("invalidGroupNames")
public void createGroup_whenGroupNameIsInvalid_throws(String groupName, String errorMessage) {
mockDefaultGroup();
assertThatExceptionOfType(BadRequestException.class)
.isThrownBy(() -> groupService.createGroup(dbSession, groupName, "Description"))
.withMessage(errorMessage);
}
@DataProvider
public static Object[][] invalidGroupNames() {
return new Object[][] {
{"", "Group name cannot be empty"},
{randomAlphanumeric(256), "Group name cannot be longer than 255 characters"},
{"Anyone", "Anyone group cannot be used"},
};
}
private static GroupDto mockGroupDto() {
GroupDto groupDto = mock(GroupDto.class);
when(groupDto.getName()).thenReturn(GROUP_NAME);
when(groupDto.getUuid()).thenReturn(GROUP_UUID);
return groupDto;
}
private GroupDto mockDefaultGroup() {
GroupDto defaultGroup = mock(GroupDto.class);
when(defaultGroup.getName()).thenReturn(DEFAULT_GROUP_NAME);
when(defaultGroup.getUuid()).thenReturn(DEFAULT_GROUP_UUID);
when(dbClient.groupDao().selectByName(dbSession, DEFAULT_GROUP_NAME)).thenReturn(Optional.of(defaultGroup));
return defaultGroup;
}
private void verifyNoGroupDelete(DbSession dbSession, GroupDto groupDto) {
verify(dbClient.roleDao(), never()).deleteGroupRolesByGroupUuid(dbSession, groupDto.getUuid());
verify(dbClient.permissionTemplateDao(), never()).deleteByGroup(dbSession, groupDto.getUuid(), groupDto.getName());
verify(dbClient.userGroupDao(), never()).deleteByGroupUuid(dbSession, groupDto.getUuid(), groupDto.getName());
verify(dbClient.qProfileEditGroupsDao(), never()).deleteByGroup(dbSession, groupDto);
verify(dbClient.qualityGateGroupPermissionsDao(), never()).deleteByGroup(dbSession, groupDto);
verify(dbClient.scimGroupDao(), never()).deleteByGroupUuid(dbSession, groupDto.getUuid());
verify(dbClient.groupDao(), never()).deleteByUuid(dbSession, groupDto.getUuid(), groupDto.getName());
}
private void verifyGroupDelete(DbSession dbSession, GroupDto groupDto) {
verify(dbClient.roleDao()).deleteGroupRolesByGroupUuid(dbSession, groupDto.getUuid());
verify(dbClient.permissionTemplateDao()).deleteByGroup(dbSession, groupDto.getUuid(), groupDto.getName());
verify(dbClient.userGroupDao()).deleteByGroupUuid(dbSession, groupDto.getUuid(), groupDto.getName());
verify(dbClient.qProfileEditGroupsDao()).deleteByGroup(dbSession, groupDto);
verify(dbClient.qualityGateGroupPermissionsDao()).deleteByGroup(dbSession, groupDto);
verify(dbClient.scimGroupDao()).deleteByGroupUuid(dbSession, groupDto.getUuid());
verify(dbClient.externalGroupDao()).deleteByGroupUuid(dbSession, groupDto.getUuid());
verify(dbClient.groupDao()).deleteByUuid(dbSession, groupDto.getUuid(), groupDto.getName());
}
}
| 13,851 | 40.22619 | 151 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/GroupWsRefTest.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.usergroups.ws;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.usergroups.ws.GroupWsRef.fromName;
public class GroupWsRefTest {
@Test
public void test_ref_by_id() {
GroupWsRef ref = GroupWsRef.fromUuid("10");
assertThat(ref.hasUuid()).isTrue();
assertThat(ref.getUuid()).isEqualTo("10");
assertThat(ref.isAnyone()).isFalse();
}
@Test
public void test_ref_by_name() {
GroupWsRef ref = fromName("the-group");
assertThat(ref.hasUuid()).isFalse();
assertThat(ref.getName()).isEqualTo("the-group");
assertThat(ref.isAnyone()).isFalse();
}
@Test
public void test_equals_and_hashCode() {
GroupWsRef refId1 = GroupWsRef.fromUuid("10");
GroupWsRef refId2 = GroupWsRef.fromUuid("11");
assertThat(refId1)
.isEqualTo(refId1)
.isEqualTo(GroupWsRef.fromUuid("10"))
.hasSameHashCodeAs(GroupWsRef.fromUuid("10"))
.isNotEqualTo(refId2);
GroupWsRef refName1 = fromName("the-group");
GroupWsRef refName2 = fromName("the-group2");
GroupWsRef refName3 = fromName("the-group2");
assertThat(refName1)
.isEqualTo(refName1)
.isEqualTo(fromName("the-group"))
.hasSameHashCodeAs(fromName("the-group"))
.isNotEqualTo(refName2);
assertThat(refName2).isEqualTo(refName3);
}
@Test
public void test_toString() {
GroupWsRef refId = GroupWsRef.fromUuid("10");
assertThat(refId).hasToString("GroupWsRef{uuid=10, name='null'}");
}
@Test
public void reference_anyone_by_its_name() {
GroupWsRef ref = GroupWsRef.fromName("Anyone");
assertThat(ref.getName()).isEqualTo("Anyone");
assertThat(ref.isAnyone()).isTrue();
// case-insensitive
ref = GroupWsRef.fromName("anyone");
assertThat(ref.getName()).isEqualTo("anyone");
assertThat(ref.isAnyone()).isTrue();
}
}
| 2,744 | 31.294118 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UserGroupsModuleTest.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.usergroups.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class UserGroupsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new UserGroupsModule().configure(container);
assertThat(container.getAddedObjects()).isNotEmpty();
}
}
| 1,272 | 35.371429 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UserGroupsWsTest.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.usergroups.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 UserGroupsWsTest {
private UserGroupsWs underTest = new UserGroupsWs(new UserGroupsWsAction() {
@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/user_groups");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
assertThat(controller.since()).isEqualTo("5.2");
assertThat(controller.actions()).hasSize(1);
}
}
| 1,842 | 31.910714 | 78 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/UserTokenWsModuleTest.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.usertoken.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import org.sonar.server.usertoken.UserTokenModule;
import static org.assertj.core.api.Assertions.assertThat;
public class UserTokenWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new UserTokenModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(7);
}
}
| 1,320 | 35.694444 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/UserTokensWsTest.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.usertoken.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 UserTokensWsTest {
private UserTokensWs underTest = new UserTokensWs(new UserTokensWsAction() {
@Override
public void define(WebService.NewController context) {
context.createAction("foo").setHandler(this);
}
@Override
public void handle(Request request, Response response) {
}
});
@Test
public void is_defined() {
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/user_tokens");
assertThat(controller).isNotNull();
assertThat(controller.since()).isEqualTo("5.3");
assertThat(controller.description()).isNotEmpty();
assertThat(controller.actions()).hasSize(1);
}
}
| 1,833 | 31.75 | 78 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/util/TypeValidationsTesting.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.util;
import java.util.Arrays;
public class TypeValidationsTesting {
private TypeValidationsTesting() {
// utility class
}
public static TypeValidations newFullTypeValidations() {
return new TypeValidations(Arrays.asList(
new BooleanTypeValidation(),
new IntegerTypeValidation(),
new LongTypeValidation(),
new FloatTypeValidation(),
new StringTypeValidation(),
new StringListTypeValidation(),
new MetricLevelTypeValidation()
));
}
}
| 1,368 | 32.390244 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/webhook/ws/NetworkInterfaceProviderTest.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.webhook.ws;
import java.net.SocketException;
import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class NetworkInterfaceProviderTest {
private NetworkInterfaceProvider underTest = new NetworkInterfaceProvider();
@Test
public void itGetsListOfNetworkInterfaceAddresses() throws SocketException {
assertThat(underTest.getNetworkInterfaceAddresses())
.isInstanceOf(List.class)
.hasSizeGreaterThan(0);
}
}
| 1,356 | 34.710526 | 78 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/webhook/ws/WebhookSupportTest.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.webhook.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.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import okhttp3.HttpUrl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.Configuration;
import org.sonar.server.user.UserSession;
import static java.util.Optional.of;
import static org.assertj.core.api.Assertions.assertThatCode;
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;
@RunWith(DataProviderRunner.class)
public class WebhookSupportTest {
private final Configuration configuration = mock(Configuration.class);
private final NetworkInterfaceProvider networkInterfaceProvider = mock(NetworkInterfaceProvider.class);
private final WebhookSupport underTest = new WebhookSupport(mock(UserSession.class), configuration, networkInterfaceProvider);
@DataProvider
public static Object[][] validUrls() {
return new Object[][] {
{"https://some.valid.address.com/random_webhook"},
{"https://248.235.76.254/some_webhook"},
{"https://248.235.76.254:8454/some_webhook"},
// local addresses are allowed too
{"https://192.168.0.1/some_webhook"},
{"https://192.168.0.1:8888/some_webhook"},
{"https://10.15.15.15/some_webhook"},
{"https://10.15.15.15:7777/some_webhook"},
{"https://172.16.16.16/some_webhook"},
{"https://172.16.16.16:9999/some_webhook"},
};
}
@DataProvider
public static Object[][] loopbackUrls() {
return new Object[][] {
{"https://0.0.0.0/some_webhook"},
{"https://0.0.0.0:8888/some_webhook"},
{"https://127.0.0.1/some_webhook"},
{"https://127.0.0.1:7777/some_webhook"},
{"https://localhost/some_webhook"},
{"https://localhost:9999/some_webhook"},
{"https://192.168.1.21/"},
};
}
@Before
public void prepare() throws IOException {
InetAddress inetAddress = InetAddress.getByName(HttpUrl.parse("https://192.168.1.21/").host());
when(networkInterfaceProvider.getNetworkInterfaceAddresses())
.thenReturn(ImmutableList.of(inetAddress));
}
@Test
@UseDataProvider("validUrls")
public void checkUrlPatternSuccessfulForValidAddress(String url) {
assertThatCode(() -> underTest.checkUrlPattern(url, "msg")).doesNotThrowAnyException();
}
@Test
@UseDataProvider("loopbackUrls")
public void checkUrlPatternFailsForLoopbackAddress(String url) {
assertThatThrownBy(() -> underTest.checkUrlPattern(url, "msg"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid URL: loopback and wildcard addresses are not allowed for webhooks.");
}
@Test
@UseDataProvider("loopbackUrls")
public void checkUrlPatternSuccessfulForLoopbackAddressWhenSonarValidateWebhooksPropertyDisabled(String url) {
when(configuration.getBoolean("sonar.validateWebhooks")).thenReturn(of(false));
assertThatCode(() -> underTest.checkUrlPattern(url, "msg")).doesNotThrowAnyException();
}
@Test
public void itThrowsIllegalExceptionIfGettingNetworkInterfaceAddressesFails() throws SocketException {
when(networkInterfaceProvider.getNetworkInterfaceAddresses()).thenThrow(new SocketException());
assertThatThrownBy(() -> underTest.checkUrlPattern("https://sonarsource.com", "msg"))
.hasMessageContaining("Can not retrieve a network interfaces")
.isInstanceOf(IllegalStateException.class);
verify(networkInterfaceProvider).getNetworkInterfaceAddresses();
}
}
| 4,681 | 37.694215 | 128 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/webhook/ws/WebhooksWsModuleTest.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.webhook.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class WebhooksWsModuleTest {
private final WebhooksWsModule underTest = new WebhooksWsModule();
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
underTest.configure(container);
assertThat(container.getAddedObjects()).isNotEmpty();
}
}
| 1,326 | 34.864865 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/webhook/ws/WebhooksWsTest.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.webhook.ws;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.user.UserSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class WebhooksWsTest {
@Test
public void test_definition() {
WebhooksWsAction action = newFakeAction();
WebhooksWs underTest = new WebhooksWs(action);
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/webhooks");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
assertThat(controller.since()).isEqualTo("6.2");
}
private static WebhooksWsAction newFakeAction() {
return new WebhookDeliveriesAction(mock(DbClient.class), mock(UserSession.class), mock(ComponentFinder.class));
}
}
| 1,836 | 34.326923 | 115 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/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.ws.ws;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.ws.TestRequest;
import static org.sonar.test.JsonAssert.assertJson;
public class ListActionTest {
private WebService.Context context = new WebService.Context();
private ListAction underTest = new ListAction();
private WebService.Action action;
@Before
public void setUp() throws Exception {
WebService.NewController newController = context.createController("api/webservices")
.setDescription("Get information on the web api supported on this instance.")
.setSince("4.2");
for (WebServicesWsAction wsWsAction : Arrays.asList(underTest, new ResponseExampleAction(), new ChangeLogAction())) {
wsWsAction.define(newController);
wsWsAction.setContext(context);
}
newController.done();
action = context.controller("api/webservices").action("list");
}
@Test
public void list() {
new MetricWs().define(context);
String response = newRequest().execute().getInput();
assertJson(response).withStrictArrayOrder().isSimilarTo(getClass().getResource("list-example.json"));
}
@Test
public void list_including_internals() {
MetricWs metricWs = new MetricWs();
metricWs.define(context);
newRequest()
.setParam("include_internals", "true")
.execute()
.assertJson(getClass(), "list_including_internals.json");
}
public TestRequest newRequest() {
TestRequest request = new TestRequest();
request.setAction(action);
return request;
}
class ChangeLogAction implements WebServicesWsAction {
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("action")
.setHandler(this);
action.setChangelog(new Change("1.0", "Initial"), new Change("2.0", "Second"), new Change("10.0", "Ten"));
}
@Override
public void handle(Request request, Response response) throws Exception {
}
@Override
public void setContext(WebService.Context context) {
}
}
}
| 3,130 | 30.626263 | 121 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/MetricWs.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.ws.ws;
import com.google.common.io.Resources;
import org.sonar.api.server.ws.Change;
import org.sonar.api.server.ws.WebService;
class MetricWs implements WebService {
@Override
public void define(Context context) {
NewController newController = context
.createController("api/metric")
.setDescription("Metrics")
.setSince("3.2");
// action with default values
newController.createAction("show")
.setSince("3.2")
.setDescription("Show Description")
.setResponseExample(getClass().getResource("web-services-ws-test.txt"))
.setHandler((request, response) -> {
});
// action with a lot of overridden values
NewAction create = newController.createAction("create")
.setPost(true)
.setDescription("Create metric")
.setSince("4.1")
.setDeprecatedSince("5.3")
.setResponseExample(Resources.getResource(getClass(), "ListActionTest/metrics_example.json"))
.setChangelog(
new Change("4.5", "Deprecate database ID in response"),
new Change("6.0", "Remove database ID from response"),
new Change("6.6", "Requires 'Administer System' permission instead of 'Administer Quality Profiles'"))
.setHandler((request, response) -> {
});
create
.createParam("severity")
.setDescription("Severity")
.setSince("4.4")
.setDeprecatedSince("5.2")
.setDeprecatedKey("old_severity", "4.6")
.setRequired(false)
.setPossibleValues("BLOCKER", "INFO")
.setExampleValue("INFO")
.setDefaultValue("BLOCKER");
create.createParam("name");
create.createParam("internal").setInternal(true);
create
.createParam("constrained_string_param")
.setMaximumLength(64)
.setMinimumLength(3);
create
.createParam("constrained_numeric_param")
.setMaximumValue(12);
newController.createAction("internal_action")
.setDescription("Internal Action Description")
.setResponseExample(getClass().getResource("web-services-ws-test.txt"))
.setSince("5.3")
.setInternal(true)
.setHandler((request, response) -> {
});
newController.done();
}
}
| 3,052 | 33.303371 | 110 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/ResponseExampleActionTest.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.ws.ws;
import com.google.common.collect.Iterables;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.ws.TestRequest;
public class ResponseExampleActionTest {
private WebService.Context context = new WebService.Context();
private ResponseExampleAction underTest = new ResponseExampleAction();
private WebService.Action action;
@Before
public void setUp() {
WebService.NewController newController = context.createController("api/ws");
underTest.define(newController);
newController.done();
action = Iterables.get(context.controller("api/ws").actions(), 0);
underTest.setContext(context);
}
@Test
public void response_example() {
MetricWs metricWs = new MetricWs();
metricWs.define(context);
newRequest()
.setParam("controller", "api/metric")
.setParam("action", "create")
.execute()
.assertJson(getClass(), "response_example.json");
}
public TestRequest newRequest() {
TestRequest request = new TestRequest();
request.setAction(action);
return request;
}
}
| 1,985 | 31.557377 | 80 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/WebServicesWsModuleTest.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.ws.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class WebServicesWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new WebServicesWsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(3);
}
}
| 1,268 | 35.257143 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ws/ws/WebServicesWsTest.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.ws.ws;
import java.util.Arrays;
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 WebServicesWsTest {
private DummyWebServicesWsAction dummyWebServicesWsAction = new DummyWebServicesWsAction();
private WebServicesWs underTest = new WebServicesWs(Arrays.asList(dummyWebServicesWsAction));
@Test
public void define_ws() {
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/webservices");
assertThat(controller).isNotNull();
assertThat(controller.path()).isEqualTo("api/webservices");
assertThat(controller.since()).isEqualTo("4.2");
assertThat(controller.description()).isNotEmpty();
assertThat(controller.actions()).hasSize(1);
assertThat(dummyWebServicesWsAction.context).isNotNull();
}
private static class DummyWebServicesWsAction implements WebServicesWsAction {
private WebService.Context context;
@Override
public void setContext(WebService.Context context) {
this.context = context;
}
@Override
public void define(WebService.NewController context) {
context.createAction("foo").setHandler(this);
}
@Override
public void handle(Request request, Response response) {
}
}
}
| 2,319 | 31.676056 | 95 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/testFixtures/java/org/sonar/server/component/TestComponentFinder.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.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ResourceTypesRule;
public class TestComponentFinder extends ComponentFinder {
private TestComponentFinder(DbClient dbClient, ResourceTypes resourceTypes) {
super(dbClient, resourceTypes);
}
public static TestComponentFinder from(DbTester dbTester) {
return new TestComponentFinder(dbTester.getDbClient(), new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT));
}
}
| 1,450 | 38.216216 | 122 | java |
sonarqube | sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/CacheWriter.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.ws;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import org.apache.commons.io.IOUtils;
/**
* Writer that writes only when closing the resource
*/
class CacheWriter extends Writer {
private final StringWriter bufferWriter;
private final Writer outputWriter;
private boolean isClosed;
CacheWriter(Writer outputWriter) {
this.bufferWriter = new StringWriter();
this.outputWriter = outputWriter;
this.isClosed = false;
}
@Override
public void write(char[] cbuf, int off, int len) {
bufferWriter.write(cbuf, off, len);
}
@Override
public void flush() {
bufferWriter.flush();
}
@Override
public void close() throws IOException {
if (isClosed) {
return;
}
IOUtils.write(bufferWriter.toString(), outputWriter);
outputWriter.close();
this.isClosed = true;
}
}
| 1,737 | 27.032258 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/DefaultLocalResponse.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.ws;
import com.google.common.base.Throwables;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.CheckForNull;
import org.apache.commons.io.IOUtils;
import org.sonar.api.server.ws.LocalConnector;
import org.sonar.api.server.ws.Response;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.api.utils.text.XmlWriter;
import org.sonarqube.ws.MediaTypes;
public class DefaultLocalResponse implements Response, LocalConnector.LocalResponse {
private final InMemoryStream stream = new InMemoryStream();
private final ByteArrayOutputStream output = new ByteArrayOutputStream();
private final Map<String, String> headers = new HashMap<>();
@Override
public int getStatus() {
return stream().status();
}
@Override
public String getMediaType() {
return stream().mediaType();
}
@Override
public byte[] getBytes() {
return output.toByteArray();
}
public class InMemoryStream implements Response.Stream {
private String mediaType;
private int status = 200;
@CheckForNull
public String mediaType() {
return mediaType;
}
public int status() {
return status;
}
@Override
public Response.Stream setMediaType(String s) {
this.mediaType = s;
return this;
}
@Override
public Response.Stream setStatus(int i) {
this.status = i;
return this;
}
@Override
public OutputStream output() {
return output;
}
}
@Override
public JsonWriter newJsonWriter() {
stream.setMediaType(MediaTypes.JSON);
return JsonWriter.of(new OutputStreamWriter(output, StandardCharsets.UTF_8));
}
@Override
public XmlWriter newXmlWriter() {
stream.setMediaType(MediaTypes.XML);
return XmlWriter.of(new OutputStreamWriter(output, StandardCharsets.UTF_8));
}
@Override
public InMemoryStream stream() {
return stream;
}
@Override
public Response noContent() {
stream().setStatus(HttpURLConnection.HTTP_NO_CONTENT);
IOUtils.closeQuietly(output);
return this;
}
public String outputAsString() {
return new String(output.toByteArray(), StandardCharsets.UTF_8);
}
@Override
public Response setHeader(String name, String value) {
headers.put(name, value);
return this;
}
@Override
public Collection<String> getHeaderNames() {
return headers.keySet();
}
@Override
public String getHeader(String name) {
return headers.get(name);
}
public byte[] getFlushedOutput() {
try {
output.flush();
return output.toByteArray();
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
}
| 3,755 | 24.55102 | 85 | java |
sonarqube | sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/JsonWriterUtils.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.ws;
import java.util.Collection;
import java.util.Date;
import javax.annotation.Nullable;
import org.sonar.api.utils.text.JsonWriter;
public class JsonWriterUtils {
private JsonWriterUtils() {
// Utility class
}
public static void writeIfNeeded(JsonWriter json, @Nullable String value, String field, @Nullable Collection<String> fields) {
if (isFieldNeeded(field, fields)) {
json.prop(field, value);
}
}
public static void writeIfNeeded(JsonWriter json, @Nullable Boolean value, String field, @Nullable Collection<String> fields) {
if (isFieldNeeded(field, fields)) {
json.prop(field, value);
}
}
public static void writeIfNeeded(JsonWriter json, @Nullable Integer value, String field, @Nullable Collection<String> fields) {
if (isFieldNeeded(field, fields)) {
json.prop(field, value);
}
}
public static void writeIfNeeded(JsonWriter json, @Nullable Long value, String field, @Nullable Collection<String> fields) {
if (isFieldNeeded(field, fields)) {
json.prop(field, value);
}
}
public static void writeIfNeeded(JsonWriter json, @Nullable Date value, String field, @Nullable Collection<String> fields) {
if (isFieldNeeded(field, fields)) {
json.propDateTime(field, value);
}
}
public static boolean isFieldNeeded(String field, @Nullable Collection<String> fields) {
return fields == null || fields.isEmpty() || fields.contains(field);
}
}
| 2,323 | 33.686567 | 129 | java |
sonarqube | sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/KeyExamples.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.ws;
public class KeyExamples {
public static final String KEY_APPLICATION_EXAMPLE_001 = "my_app";
public static final String KEY_FILE_EXAMPLE_001 = "my_project:/src/foo/Bar.php";
public static final String KEY_FILE_EXAMPLE_002 = "another_project:/src/foo/Foo.php";
public static final String KEY_PROJECT_EXAMPLE_001 = "my_project";
public static final String KEY_PROJECT_EXAMPLE_002 = "another_project";
public static final String KEY_PROJECT_EXAMPLE_003 = "third_project";
public static final String KEY_ORG_EXAMPLE_001 = "my-org";
public static final String KEY_ORG_EXAMPLE_002 = "foo-company";
public static final String KEY_BRANCH_EXAMPLE_001 = "feature/my_branch";
public static final String KEY_PULL_REQUEST_EXAMPLE_001 = "5461";
public static final String NAME_WEBHOOK_EXAMPLE_001 = "My Webhook";
public static final String URL_WEBHOOK_EXAMPLE_001 = "https://www.my-webhook-listener.com/sonar";
public static final String PROJECT_BADGE_TOKEN_EXAMPLE = "8bb493196edb5896ccb64582499895f187a2ae8f";
private KeyExamples() {
// prevent instantiation
}
}
| 1,965 | 41.73913 | 102 | java |
sonarqube | sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/LocalRequestAdapter.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.ws;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.sonar.api.server.ws.LocalConnector;
import org.sonar.api.impl.ws.ValidatingRequest;
public class LocalRequestAdapter extends ValidatingRequest {
private final LocalConnector.LocalRequest localRequest;
public LocalRequestAdapter(LocalConnector.LocalRequest localRequest) {
this.localRequest = localRequest;
}
@Override
protected String readParam(String key) {
return localRequest.getParam(key);
}
@Override
public Map<String, String[]> getParams() {
return localRequest.getParameterMap();
}
@Override
protected List<String> readMultiParam(String key) {
return localRequest.getMultiParam(key);
}
@Override
protected InputStream readInputStreamParam(String key) {
String value = readParam(key);
if (value == null) {
return null;
}
return new ByteArrayInputStream(value.getBytes(StandardCharsets.UTF_8));
}
@Override
protected Part readPart(String key) {
throw new UnsupportedOperationException("reading part is not supported yet by local WS calls");
}
@Override
public boolean hasParam(String key) {
return localRequest.hasParam(key);
}
@Override
public String getPath() {
return localRequest.getPath();
}
@Override
public String method() {
return localRequest.getMethod();
}
@Override
public String getMediaType() {
return localRequest.getMediaType();
}
@Override
public Optional<String> header(String name) {
return localRequest.getHeader(name);
}
}
| 2,553 | 26.462366 | 99 | java |
sonarqube | sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/MessageFormattingUtils.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.ws;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.db.protobuf.DbIssues;
import org.sonarqube.ws.Common;
public class MessageFormattingUtils {
private MessageFormattingUtils() {
}
public static List<Common.MessageFormatting> dbMessageFormattingToWs(@Nullable DbIssues.MessageFormattings dbFormattings) {
if (dbFormattings == null) {
return List.of();
}
return dbMessageFormattingListToWs(dbFormattings.getMessageFormattingList());
}
public static List<Common.MessageFormatting> dbMessageFormattingListToWs(@Nullable List<DbIssues.MessageFormatting> dbFormattings) {
if (dbFormattings == null) {
return List.of();
}
return dbFormattings.stream()
.map(f -> Common.MessageFormatting.newBuilder()
.setStart(f.getStart())
.setEnd(f.getEnd())
.setType(Common.MessageFormattingType.valueOf(f.getType().name())).build())
.toList();
}
}
| 1,813 | 33.884615 | 134 | java |
sonarqube | sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/RemovedWebServiceHandler.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.ws;
import com.google.common.io.Resources;
import java.net.URL;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.RequestHandler;
import org.sonar.api.server.ws.Response;
import org.sonar.server.exceptions.ServerException;
import static java.net.HttpURLConnection.HTTP_GONE;
/**
* Used to declare web services that are removed
*/
public enum RemovedWebServiceHandler implements RequestHandler {
INSTANCE;
@Override
public void handle(Request request, Response response) {
throw new ServerException(HTTP_GONE, String.format("The web service '%s' doesn't exist anymore, please read its documentation to use alternatives", request.getPath()));
}
public URL getResponseExample() {
return Resources.getResource(RemovedWebServiceHandler.class, "removed-ws-example.json");
}
}
| 1,687 | 34.914894 | 172 | java |
sonarqube | sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/RequestVerifier.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.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.exceptions.ServerException;
import static javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED;
public class RequestVerifier {
private RequestVerifier() {
// static methods only
}
public static void verifyRequest(WebService.Action action, Request request) {
switch (request.method()) {
case "GET":
if (action.isPost()) {
throw new ServerException(SC_METHOD_NOT_ALLOWED, "HTTP method POST is required");
}
break;
case "POST":
if (!action.isPost()) {
throw new ServerException(SC_METHOD_NOT_ALLOWED, "HTTP method GET is required");
}
break;
default:
throw new ServerException(SC_METHOD_NOT_ALLOWED, String.format("HTTP method %s is not allowed", request.method()));
}
}
}
| 1,775 | 34.52 | 123 | java |
sonarqube | sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/ServletFilterHandler.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.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.RequestHandler;
import org.sonar.api.server.ws.Response;
/**
* Used to declare web services that are implemented by a servlet filter.
*/
public class ServletFilterHandler implements RequestHandler {
public static final RequestHandler INSTANCE = new ServletFilterHandler();
private ServletFilterHandler() {
// Nothing
}
@Override
public void handle(Request request, Response response) {
throw new UnsupportedOperationException("This web service is implemented as a servlet filter");
}
}
| 1,457 | 32.906977 | 99 | java |
sonarqube | sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/ServletRequest.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.ws;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.HttpHeaders;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import org.sonar.api.impl.ws.PartImpl;
import org.sonar.api.impl.ws.ValidatingRequest;
import org.sonar.api.server.http.HttpRequest;
import org.slf4j.LoggerFactory;
import org.sonar.server.http.JavaxHttpRequest;
import org.sonarqube.ws.MediaTypes;
import static com.google.common.base.MoreObjects.firstNonNull;
import static java.util.Collections.emptyList;
import static java.util.Locale.ENGLISH;
import static org.apache.commons.lang.StringUtils.substringAfterLast;
import static org.apache.tomcat.util.http.fileupload.FileUploadBase.MULTIPART;
public class ServletRequest extends ValidatingRequest {
static final Map<String, String> SUPPORTED_MEDIA_TYPES_BY_URL_SUFFIX = ImmutableMap.of(
"json", MediaTypes.JSON,
"protobuf", MediaTypes.PROTOBUF,
"text", MediaTypes.TXT);
private final HttpServletRequest source;
public ServletRequest(HttpRequest source) {
this.source = ((JavaxHttpRequest) source).getDelegate();
}
@Override
public String method() {
return source.getMethod();
}
@Override
public String getMediaType() {
return firstNonNull(
mediaTypeFromUrl(source.getRequestURI()),
firstNonNull(
acceptedContentTypeInResponse(),
MediaTypes.DEFAULT));
}
@Override
public BufferedReader getReader() {
try {
return source.getReader();
} catch (IOException e) {
throw new IllegalStateException("Failed to read", e);
}
}
@Override
public boolean hasParam(String key) {
return source.getParameterMap().containsKey(key);
}
@Override
public String readParam(String key) {
return source.getParameter(key);
}
@Override
public Map<String, String[]> getParams() {
return source.getParameterMap();
}
@Override
public List<String> readMultiParam(String key) {
String[] values = source.getParameterValues(key);
return values == null ? emptyList() : ImmutableList.copyOf(values);
}
@Override
protected InputStream readInputStreamParam(String key) {
Part part = readPart(key);
return (part == null) ? null : part.getInputStream();
}
@Override
@CheckForNull
public Part readPart(String key) {
try {
if (!isMultipartContent()) {
return null;
}
javax.servlet.http.Part part = source.getPart(key);
if (part == null || part.getSize() == 0) {
return null;
}
return new PartImpl(part.getInputStream(), part.getSubmittedFileName());
} catch (Exception e) {
LoggerFactory.getLogger(ServletRequest.class).warn("Can't read file part for parameter " + key, e);
return null;
}
}
public AsyncContext startAsync() {
return source.startAsync();
}
private boolean isMultipartContent() {
String contentType = source.getContentType();
return contentType != null && contentType.toLowerCase(ENGLISH).startsWith(MULTIPART);
}
@Override
public String toString() {
StringBuffer url = source.getRequestURL();
String query = source.getQueryString();
if (query != null) {
url.append("?").append(query);
}
return url.toString();
}
@CheckForNull
private String acceptedContentTypeInResponse() {
return source.getHeader(HttpHeaders.ACCEPT);
}
@CheckForNull
private static String mediaTypeFromUrl(String url) {
String formatSuffix = substringAfterLast(url, ".");
return SUPPORTED_MEDIA_TYPES_BY_URL_SUFFIX.get(formatSuffix.toLowerCase(ENGLISH));
}
@Override
public String getPath() {
return source.getRequestURI().replaceFirst(source.getContextPath(), "");
}
@Override
public Optional<String> header(String name) {
return Optional.ofNullable(source.getHeader(name));
}
@Override
public Map<String, String> getHeaders() {
ImmutableMap.Builder<String, String> mapBuilder = ImmutableMap.builder();
Enumeration<String> headerNames = source.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
mapBuilder.put(headerName, source.getHeader(headerName));
}
return mapBuilder.build();
}
}
| 5,405 | 29.201117 | 105 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.