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-server-common/src/test/java/org/sonar/server/notification/EmailRecipientTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.notification;
import org.junit.Test;
import org.sonar.server.notification.NotificationManager.EmailRecipient;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class EmailRecipientTest {
@Test
public void constructor_fails_with_NPE_if_login_is_null() {
String email = randomAlphabetic(12);
assertThatThrownBy(() -> new EmailRecipient(null, email))
.isInstanceOf(NullPointerException.class)
.hasMessage("login can't be null");
}
@Test
public void constructor_fails_with_NPE_if_email_is_null() {
String login = randomAlphabetic(12);
assertThatThrownBy(() -> new EmailRecipient(login, null))
.isInstanceOf(NullPointerException.class)
.hasMessage("email can't be null");
}
@Test
public void equals_is_based_on_login_and_email() {
String login = randomAlphabetic(11);
String email = randomAlphabetic(12);
EmailRecipient underTest = new EmailRecipient(login, email);
assertThat(underTest)
.isEqualTo(new EmailRecipient(login, email))
.isNotNull()
.isNotEqualTo(new Object())
.isNotEqualTo(new EmailRecipient(email, login))
.isNotEqualTo(new EmailRecipient(randomAlphabetic(5), email))
.isNotEqualTo(new EmailRecipient(login, randomAlphabetic(5)))
.isNotEqualTo(new EmailRecipient(randomAlphabetic(5), randomAlphabetic(6)));
}
@Test
public void hashcode_is_based_on_login_and_email() {
String login = randomAlphabetic(11);
String email = randomAlphabetic(12);
EmailRecipient underTest = new EmailRecipient(login, email);
assertThat(underTest.hashCode())
.isEqualTo(new EmailRecipient(login, email).hashCode())
.isNotEqualTo(new Object().hashCode())
.isNotEqualTo(new EmailRecipient(email, login).hashCode())
.isNotEqualTo(new EmailRecipient(randomAlphabetic(5), email).hashCode())
.isNotEqualTo(new EmailRecipient(login, randomAlphabetic(5)).hashCode())
.isNotEqualTo(new EmailRecipient(randomAlphabetic(5), randomAlphabetic(6)).hashCode());
}
@Test
public void verify_to_String() {
String login = randomAlphabetic(11);
String email = randomAlphabetic(12);
assertThat(new EmailRecipient(login, email)).hasToString("EmailRecipient{'" + login + "':'" + email + "'}");
}
}
| 3,291 | 36.409091 | 112 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationDispatcherMetadataTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.notification;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class NotificationDispatcherMetadataTest {
private NotificationDispatcherMetadata metadata;
@Before
public void init() {
metadata = NotificationDispatcherMetadata.create("NewViolations").setProperty("global", "true");
}
@Test
public void shouldReturnDispatcherKey() {
assertThat(metadata.getDispatcherKey()).isEqualTo("NewViolations");
}
@Test
public void shouldReturnProperty() {
assertThat(metadata.getProperty("global")).isEqualTo("true");
assertThat(metadata.getProperty("per-project")).isNull();
}
}
| 1,543 | 31.851064 | 100 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationDispatcherTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.notification;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sonar.api.notifications.Notification;
import org.sonar.api.notifications.NotificationChannel;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class NotificationDispatcherTest {
@Mock
private NotificationChannel channel;
@Mock
private Notification notification;
@Mock
private NotificationDispatcher.Context context;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
when(notification.getType()).thenReturn("event1");
}
@Test
public void defaultMethods() {
NotificationDispatcher dispatcher = new FakeGenericNotificationDispatcher();
assertThat(dispatcher.getKey(), is("FakeGenericNotificationDispatcher"));
assertThat(dispatcher.toString(), is("FakeGenericNotificationDispatcher"));
}
@Test
public void shouldAlwaysRunDispatchForGenericDispatcher() {
NotificationDispatcher dispatcher = new FakeGenericNotificationDispatcher();
dispatcher.performDispatch(notification, context);
verify(context, times(1)).addUser("user1", channel);
}
@Test
public void shouldNotAlwaysRunDispatchForSpecificDispatcher() {
NotificationDispatcher dispatcher = new FakeSpecificNotificationDispatcher();
// a "event1" notif is sent
dispatcher.performDispatch(notification, context);
verify(context, never()).addUser("user1", channel);
// now, a "specific-event" notif is sent
when(notification.getType()).thenReturn("specific-event");
dispatcher.performDispatch(notification, context);
verify(context, times(1)).addUser("user1", channel);
}
class FakeGenericNotificationDispatcher extends NotificationDispatcher {
@Override
public void dispatch(Notification notification, Context context) {
context.addUser("user1", channel);
}
}
class FakeSpecificNotificationDispatcher extends NotificationDispatcher {
public FakeSpecificNotificationDispatcher() {
super("specific-event");
}
@Override
public void dispatch(Notification notification, Context context) {
context.addUser("user1", channel);
}
}
}
| 3,278 | 31.147059 | 81 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationServiceTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.notification;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.notifications.Notification;
import org.sonar.db.DbClient;
import org.sonar.db.property.PropertiesDao;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
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 NotificationServiceTest {
private final DbClient dbClient = mock(DbClient.class);
private final PropertiesDao propertiesDao = mock(PropertiesDao.class);
@Before
public void wire_mocks() {
when(dbClient.propertiesDao()).thenReturn(propertiesDao);
}
@Test
public void deliverEmails_fails_with_IAE_if_type_of_collection_is_Notification() {
NotificationHandler handler = getMockOfNotificationHandlerForType(Notification1.class);
List<Notification> notifications = IntStream.range(0, 10)
.mapToObj(i -> new Notification("i"))
.toList();
NotificationService underTest = new NotificationService(dbClient, new NotificationHandler[]{handler});
assertThatThrownBy(() -> underTest.deliverEmails(notifications))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Type of notification objects must be a subtype of Notification");
}
@Test
public void deliverEmails_collection_has_no_effect_if_no_handler_nor_dispatcher() {
List<Notification> notifications = IntStream.range(0, 10)
.mapToObj(i -> mock(Notification.class))
.toList();
NotificationService underTest = new NotificationService(dbClient);
assertThat(underTest.deliverEmails(notifications)).isZero();
verifyNoInteractions(dbClient);
}
@Test
public void deliverEmails_collection_has_no_effect_if_no_handler() {
NotificationDispatcher dispatcher = mock(NotificationDispatcher.class);
List<Notification> notifications = IntStream.range(0, 10)
.mapToObj(i -> mock(Notification.class))
.toList();
NotificationService underTest = new NotificationService(dbClient, new NotificationDispatcher[]{dispatcher});
assertThat(underTest.deliverEmails(notifications)).isZero();
verifyNoInteractions(dispatcher);
verifyNoInteractions(dbClient);
}
@Test
public void deliverEmails_collection_returns_0_if_collection_is_empty() {
NotificationHandler<Notification1> handler1 = getMockOfNotificationHandlerForType(Notification1.class);
NotificationHandler<Notification2> handler2 = getMockOfNotificationHandlerForType(Notification2.class);
NotificationService underTest = new NotificationService(dbClient,
new NotificationHandler[]{handler1, handler2});
assertThat(underTest.deliverEmails(Collections.emptyList())).isZero();
verifyNoInteractions(handler1, handler2);
}
@Test
public void deliverEmails_collection_returns_0_if_no_handler_for_the_notification_class() {
NotificationHandler<Notification1> handler1 = getMockOfNotificationHandlerForType(Notification1.class);
NotificationHandler<Notification2> handler2 = getMockOfNotificationHandlerForType(Notification2.class);
List<Notification1> notification1s = IntStream.range(0, 10)
.mapToObj(i -> new Notification1())
.toList();
List<Notification2> notification2s = IntStream.range(0, 10)
.mapToObj(i -> new Notification2())
.toList();
NotificationService noHandler = new NotificationService(dbClient);
NotificationService onlyHandler1 = new NotificationService(dbClient, new NotificationHandler[]{handler1});
NotificationService onlyHandler2 = new NotificationService(dbClient, new NotificationHandler[]{handler2});
assertThat(noHandler.deliverEmails(notification1s)).isZero();
assertThat(noHandler.deliverEmails(notification2s)).isZero();
assertThat(onlyHandler1.deliverEmails(notification2s)).isZero();
assertThat(onlyHandler2.deliverEmails(notification1s)).isZero();
verify(handler1, times(0)).deliver(anyCollection());
verify(handler2, times(0)).deliver(anyCollection());
}
@Test
public void deliverEmails_collection_calls_deliver_method_of_handler_for_notification_class_and_returns_its_output() {
NotificationHandler<Notification1> handler1 = getMockOfNotificationHandlerForType(Notification1.class);
NotificationHandler<Notification2> handler2 = getMockOfNotificationHandlerForType(Notification2.class);
List<Notification1> notification1s = IntStream.range(0, 10)
.mapToObj(i -> new Notification1())
.toList();
List<Notification2> notification2s = IntStream.range(0, 10)
.mapToObj(i -> new Notification2())
.toList();
NotificationService onlyHandler1 = new NotificationService(dbClient, new NotificationHandler[]{handler1});
NotificationService onlyHandler2 = new NotificationService(dbClient, new NotificationHandler[]{handler2});
NotificationService bothHandlers = new NotificationService(dbClient, new NotificationHandler[]{handler1, handler2});
int expected = notification1s.size() - 1;
when(handler1.deliver(notification1s)).thenReturn(expected);
assertThat(onlyHandler1.deliverEmails(notification1s)).isEqualTo(expected);
verify(handler1, times(1)).deliver(notification1s);
verify(handler2, times(0)).deliver(anyCollection());
expected = notification2s.size() - 2;
when(handler2.deliver(notification2s)).thenReturn(expected);
assertThat(onlyHandler2.deliverEmails(notification2s)).isEqualTo(expected);
verify(handler2, times(1)).deliver(notification2s);
verify(handler1, times(1)).deliver(anyCollection());
expected = notification1s.size() - 1;
when(handler1.deliver(notification1s)).thenReturn(expected);
assertThat(bothHandlers.deliverEmails(notification1s)).isEqualTo(expected);
verify(handler1, times(2)).deliver(notification1s);
verify(handler2, times(1)).deliver(anyCollection());
expected = notification2s.size() - 2;
when(handler2.deliver(notification2s)).thenReturn(expected);
assertThat(bothHandlers.deliverEmails(notification2s)).isEqualTo(expected);
verify(handler2, times(2)).deliver(notification2s);
verify(handler1, times(2)).deliver(anyCollection());
}
@Test
public void deliver_calls_deliver_method_on_each_handler_for_notification_class_and_returns_sum_of_their_outputs() {
NotificationHandler<Notification1> handler1A = getMockOfNotificationHandlerForType(Notification1.class);
NotificationHandler<Notification1> handler1B = getMockOfNotificationHandlerForType(Notification1.class);
NotificationHandler<Notification2> handler2 = getMockOfNotificationHandlerForType(Notification2.class);
List<Notification1> notification1s = IntStream.range(0, 10)
.mapToObj(i -> new Notification1())
.toList();
List<Notification2> notification2s = IntStream.range(0, 10)
.mapToObj(i -> new Notification2())
.toList();
NotificationService onlyHandler1A = new NotificationService(dbClient, new NotificationHandler[]{handler1A});
NotificationService onlyHandler1B = new NotificationService(dbClient, new NotificationHandler[]{handler1B});
NotificationService bothHandlers = new NotificationService(dbClient, new NotificationHandler[]{handler1A, handler1B});
NotificationService allHandlers = new NotificationService(dbClient, new NotificationHandler[]{handler1A, handler1B, handler2});
int expected = notification1s.size() - 1;
when(onlyHandler1A.deliverEmails(notification1s)).thenReturn(expected);
assertThat(onlyHandler1A.deliverEmails(notification1s)).isEqualTo(expected);
verify(handler1A, times(1)).deliver(notification1s);
verify(handler1B, times(0)).deliver(anyCollection());
verify(handler2, times(0)).deliver(anyCollection());
expected = notification1s.size() - 1;
when(handler1B.deliver(notification1s)).thenReturn(expected);
assertThat(onlyHandler1B.deliverEmails(notification1s)).isEqualTo(expected);
verify(handler1B, times(1)).deliver(notification1s);
verify(handler1A, times(1)).deliver(anyCollection());
verify(handler2, times(0)).deliver(anyCollection());
expected = notification1s.size() - 1;
int expected2 = notification1s.size() - 2;
when(handler1A.deliver(notification1s)).thenReturn(expected);
when(handler1B.deliver(notification1s)).thenReturn(expected2);
assertThat(bothHandlers.deliverEmails(notification1s)).isEqualTo(expected + expected2);
verify(handler1A, times(2)).deliver(notification1s);
verify(handler1B, times(2)).deliver(notification1s);
verify(handler2, times(0)).deliver(anyCollection());
expected = notification2s.size() - 2;
when(handler2.deliver(notification2s)).thenReturn(expected);
assertThat(allHandlers.deliverEmails(notification2s)).isEqualTo(expected);
verify(handler2, times(1)).deliver(notification2s);
verify(handler1A, times(2)).deliver(anyCollection());
verify(handler1B, times(2)).deliver(anyCollection());
}
@Test
public void hasProjectSubscribersForType_returns_false_if_there_are_no_handler() {
String projectUuid = randomAlphabetic(7);
NotificationService underTest = new NotificationService(dbClient);
assertThat(underTest.hasProjectSubscribersForTypes(projectUuid, ImmutableSet.of(Notification1.class))).isFalse();
assertThat(underTest.hasProjectSubscribersForTypes(projectUuid, ImmutableSet.of(Notification2.class))).isFalse();
}
@Test
public void hasProjectSubscribersForType_checks_property_for_each_dispatcher_key_supporting_Notification_type() {
String dispatcherKey1A = randomAlphabetic(5);
String dispatcherKey1B = randomAlphabetic(6);
String projectUuid = randomAlphabetic(7);
NotificationHandler<Notification1> handler1A = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A)));
NotificationHandler<Notification1> handler1B = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1B.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1B)));
NotificationHandler<Notification2> handler2 = getMockOfNotificationHandlerForType(Notification2.class);
when(handler2.getMetadata()).thenReturn(Optional.empty());
boolean expected = true;
when(propertiesDao.hasProjectNotificationSubscribersForDispatchers(projectUuid, ImmutableSet.of(dispatcherKey1A, dispatcherKey1B)))
.thenReturn(expected);
NotificationService underTest = new NotificationService(dbClient, new NotificationHandler[]{handler1A, handler1B, handler2});
boolean flag = underTest.hasProjectSubscribersForTypes(projectUuid, ImmutableSet.of(Notification1.class));
verify(propertiesDao).hasProjectNotificationSubscribersForDispatchers(projectUuid, ImmutableSet.of(dispatcherKey1A, dispatcherKey1B));
verifyNoMoreInteractions(propertiesDao);
assertThat(flag).isEqualTo(expected);
flag = underTest.hasProjectSubscribersForTypes(projectUuid, ImmutableSet.of(Notification1.class, Notification2.class));
verify(propertiesDao, times(2)).hasProjectNotificationSubscribersForDispatchers(projectUuid, ImmutableSet.of(dispatcherKey1A, dispatcherKey1B));
verifyNoMoreInteractions(propertiesDao);
assertThat(flag).isEqualTo(expected);
}
@Test
public void hasProjectSubscribersForType_checks_property_for_each_dispatcher_key_supporting_Notification_types() {
String dispatcherKey1A = randomAlphabetic(5);
String dispatcherKey1B = randomAlphabetic(6);
String dispatcherKey2 = randomAlphabetic(7);
String projectUuid = randomAlphabetic(8);
NotificationHandler<Notification1> handler1A = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A)));
NotificationHandler<Notification1> handler1B = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1B.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1B)));
NotificationHandler<Notification2> handler2 = getMockOfNotificationHandlerForType(Notification2.class);
when(handler2.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey2)));
boolean expected1 = false;
when(propertiesDao.hasProjectNotificationSubscribersForDispatchers(projectUuid, ImmutableSet.of(dispatcherKey1A, dispatcherKey1B, dispatcherKey2)))
.thenReturn(expected1);
boolean expected2 = true;
when(propertiesDao.hasProjectNotificationSubscribersForDispatchers(projectUuid, ImmutableSet.of(dispatcherKey2)))
.thenReturn(expected2);
NotificationService underTest = new NotificationService(dbClient, new NotificationHandler[]{handler1A, handler1B, handler2});
boolean flag = underTest.hasProjectSubscribersForTypes(projectUuid, ImmutableSet.of(Notification1.class, Notification2.class));
verify(propertiesDao).hasProjectNotificationSubscribersForDispatchers(projectUuid, ImmutableSet.of(dispatcherKey1A, dispatcherKey1B, dispatcherKey2));
verifyNoMoreInteractions(propertiesDao);
assertThat(flag).isEqualTo(expected1);
flag = underTest.hasProjectSubscribersForTypes(projectUuid, ImmutableSet.of(Notification2.class));
verify(propertiesDao).hasProjectNotificationSubscribersForDispatchers(projectUuid, ImmutableSet.of(dispatcherKey1A, dispatcherKey1B, dispatcherKey2));
verify(propertiesDao).hasProjectNotificationSubscribersForDispatchers(projectUuid, ImmutableSet.of(dispatcherKey2));
verifyNoMoreInteractions(propertiesDao);
assertThat(flag).isEqualTo(expected2);
}
@Test
public void hasProjectSubscribersForType_returns_false_if_set_is_empty() {
String dispatcherKey1A = randomAlphabetic(5);
String dispatcherKey1B = randomAlphabetic(6);
String projectUuid = randomAlphabetic(7);
NotificationHandler<Notification1> handler1A = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A)));
NotificationHandler<Notification1> handler1B = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1B.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1B)));
NotificationHandler<Notification2> handler2 = getMockOfNotificationHandlerForType(Notification2.class);
when(handler2.getMetadata()).thenReturn(Optional.empty());
NotificationService underTest = new NotificationService(dbClient, new NotificationHandler[]{handler1A, handler1B, handler2});
boolean flag = underTest.hasProjectSubscribersForTypes(projectUuid, ImmutableSet.of());
assertThat(flag).isFalse();
verify(propertiesDao).hasProjectNotificationSubscribersForDispatchers(projectUuid, ImmutableSet.of());
verifyNoMoreInteractions(propertiesDao);
}
@Test
public void hasProjectSubscribersForType_returns_false_for_type_which_have_no_handler() {
String dispatcherKey1A = randomAlphabetic(5);
String dispatcherKey1B = randomAlphabetic(6);
String projectUuid = randomAlphabetic(7);
NotificationHandler<Notification1> handler1A = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1A.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1A)));
NotificationHandler<Notification1> handler1B = getMockOfNotificationHandlerForType(Notification1.class);
when(handler1B.getMetadata()).thenReturn(Optional.of(NotificationDispatcherMetadata.create(dispatcherKey1B)));
NotificationService underTest = new NotificationService(dbClient, new NotificationHandler[]{handler1A, handler1B});
boolean flag = underTest.hasProjectSubscribersForTypes(projectUuid, ImmutableSet.of(Notification2.class));
assertThat(flag).isFalse();
verify(propertiesDao).hasProjectNotificationSubscribersForDispatchers(projectUuid, ImmutableSet.of());
verifyNoMoreInteractions(propertiesDao);
}
private static final class Notification1 extends Notification {
public Notification1() {
super("1");
}
}
private <T extends Notification> NotificationHandler<T> getMockOfNotificationHandlerForType(Class<T> notificationClass) {
NotificationHandler mock = mock(NotificationHandler.class);
when(mock.getNotificationClass()).thenReturn(notificationClass);
return mock;
}
private static final class Notification2 extends Notification {
public Notification2() {
super("2");
}
}
}
| 17,964 | 49.605634 | 154 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/notification/email/EmailNotificationChannelTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.notification.email;
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.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.mail.EmailException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.event.Level;
import org.sonar.api.config.EmailSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.server.issue.notification.EmailMessage;
import org.sonar.server.issue.notification.EmailTemplate;
import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest;
import org.subethamail.wiser.Wiser;
import org.subethamail.wiser.WiserMessage;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static junit.framework.Assert.fail;
import static org.apache.commons.lang.RandomStringUtils.random;
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;
@RunWith(DataProviderRunner.class)
public class EmailNotificationChannelTest {
private static final String SUBJECT_PREFIX = "[SONARQUBE]";
@Rule
public LogTester logTester = new LogTester();
private Wiser smtpServer;
private EmailSettings configuration;
private EmailNotificationChannel underTest;
@Before
public void setUp() {
logTester.setLevel(LoggerLevel.DEBUG);
smtpServer = new Wiser(0);
smtpServer.start();
configuration = mock(EmailSettings.class);
underTest = new EmailNotificationChannel(configuration, null, null);
}
@After
public void tearDown() {
smtpServer.stop();
}
@Test
public void isActivated_returns_true_if_smpt_host_is_not_empty() {
when(configuration.getSmtpHost()).thenReturn(random(5));
assertThat(underTest.isActivated()).isTrue();
}
@Test
public void isActivated_returns_false_if_smpt_host_is_null() {
when(configuration.getSmtpHost()).thenReturn(null);
assertThat(underTest.isActivated()).isFalse();
}
@Test
public void isActivated_returns_false_if_smpt_host_is_empty() {
when(configuration.getSmtpHost()).thenReturn("");
assertThat(underTest.isActivated()).isFalse();
}
@Test
public void shouldSendTestEmail() throws Exception {
configure();
underTest.sendTestEmail("user@nowhere", "Test Message from SonarQube", "This is a test message from SonarQube.");
List<WiserMessage> messages = smtpServer.getMessages();
assertThat(messages).hasSize(1);
MimeMessage email = messages.get(0).getMimeMessage();
assertThat(email.getHeader("Content-Type", null)).isEqualTo("text/plain; charset=UTF-8");
assertThat(email.getHeader("From", ",")).isEqualTo("SonarQube from NoWhere <server@nowhere>");
assertThat(email.getHeader("To", null)).isEqualTo("<user@nowhere>");
assertThat(email.getHeader("Subject", null)).isEqualTo("[SONARQUBE] Test Message from SonarQube");
assertThat((String) email.getContent()).startsWith("This is a test message from SonarQube.\r\n\r\nMail sent from: http://nemo.sonarsource.org");
}
@Test
public void sendTestEmailShouldSanitizeLog() throws Exception {
logTester.setLevel(LoggerLevel.TRACE);
configure();
underTest.sendTestEmail("user@nowhere", "Test Message from SonarQube", "This is a message \n containing line breaks \r that should be sanitized when logged.");
assertThat(logTester.logs(Level.TRACE)).isNotEmpty()
.contains("Sending email: This is a message _ containing line breaks _ that should be sanitized when logged.__Mail sent from: http://nemo.sonarsource.org");
}
@Test
public void shouldThrowAnExceptionWhenUnableToSendTestEmail() {
configure();
smtpServer.stop();
try {
underTest.sendTestEmail("user@nowhere", "Test Message from SonarQube", "This is a test message from SonarQube.");
fail();
} catch (EmailException e) {
// expected
}
}
@Test
public void shouldNotSendEmailWhenHostnameNotConfigured() {
EmailMessage emailMessage = new EmailMessage()
.setTo("user@nowhere")
.setSubject("Foo")
.setPlainTextMessage("Bar");
boolean delivered = underTest.deliver(emailMessage);
assertThat(smtpServer.getMessages()).isEmpty();
assertThat(delivered).isFalse();
}
@Test
public void shouldSendThreadedEmail() throws Exception {
configure();
EmailMessage emailMessage = new EmailMessage()
.setMessageId("reviews/view/1")
.setFrom("Full Username")
.setTo("user@nowhere")
.setSubject("Review #3")
.setPlainTextMessage("I'll take care of this violation.");
boolean delivered = underTest.deliver(emailMessage);
List<WiserMessage> messages = smtpServer.getMessages();
assertThat(messages).hasSize(1);
MimeMessage email = messages.get(0).getMimeMessage();
assertThat(email.getHeader("Content-Type", null)).isEqualTo("text/plain; charset=UTF-8");
assertThat(email.getHeader("In-Reply-To", null)).isEqualTo("<reviews/view/1@nemo.sonarsource.org>");
assertThat(email.getHeader("References", null)).isEqualTo("<reviews/view/1@nemo.sonarsource.org>");
assertThat(email.getHeader("List-ID", null)).isEqualTo("SonarQube <sonar.nemo.sonarsource.org>");
assertThat(email.getHeader("List-Archive", null)).isEqualTo("http://nemo.sonarsource.org");
assertThat(email.getHeader("From", ",")).isEqualTo("\"Full Username (SonarQube from NoWhere)\" <server@nowhere>");
assertThat(email.getHeader("To", null)).isEqualTo("<user@nowhere>");
assertThat(email.getHeader("Subject", null)).isEqualTo("[SONARQUBE] Review #3");
assertThat((String) email.getContent()).startsWith("I'll take care of this violation.");
assertThat(delivered).isTrue();
}
@Test
public void shouldSendNonThreadedEmail() throws Exception {
configure();
EmailMessage emailMessage = new EmailMessage()
.setTo("user@nowhere")
.setSubject("Foo")
.setPlainTextMessage("Bar");
boolean delivered = underTest.deliver(emailMessage);
List<WiserMessage> messages = smtpServer.getMessages();
assertThat(messages).hasSize(1);
MimeMessage email = messages.get(0).getMimeMessage();
assertThat(email.getHeader("Content-Type", null)).isEqualTo("text/plain; charset=UTF-8");
assertThat(email.getHeader("In-Reply-To", null)).isNull();
assertThat(email.getHeader("References", null)).isNull();
assertThat(email.getHeader("List-ID", null)).isEqualTo("SonarQube <sonar.nemo.sonarsource.org>");
assertThat(email.getHeader("List-Archive", null)).isEqualTo("http://nemo.sonarsource.org");
assertThat(email.getHeader("From", null)).isEqualTo("SonarQube from NoWhere <server@nowhere>");
assertThat(email.getHeader("To", null)).isEqualTo("<user@nowhere>");
assertThat(email.getHeader("Subject", null)).isEqualTo("[SONARQUBE] Foo");
assertThat((String) email.getContent()).startsWith("Bar");
assertThat(delivered).isTrue();
}
@Test
public void shouldNotThrowAnExceptionWhenUnableToSendEmail() {
configure();
smtpServer.stop();
EmailMessage emailMessage = new EmailMessage()
.setTo("user@nowhere")
.setSubject("Foo")
.setPlainTextMessage("Bar");
boolean delivered = underTest.deliver(emailMessage);
assertThat(delivered).isFalse();
}
@Test
public void shouldSendTestEmailWithSTARTTLS() {
smtpServer.getServer().setEnableTLS(true);
smtpServer.getServer().setRequireTLS(true);
configure();
when(configuration.getSecureConnection()).thenReturn("STARTTLS");
try {
underTest.sendTestEmail("user@nowhere", "Test Message from SonarQube", "This is a test message from SonarQube.");
fail("An SSL exception was expected a a proof that STARTTLS is enabled");
} catch (EmailException e) {
// We don't have a SSL certificate so we are expecting a SSL error
assertThat(e.getCause().getMessage()).isEqualTo("Could not convert socket to TLS");
}
}
@Test
public void deliverAll_has_no_effect_if_set_is_empty() {
EmailSettings emailSettings = mock(EmailSettings.class);
EmailNotificationChannel underTest = new EmailNotificationChannel(emailSettings, null, null);
int count = underTest.deliverAll(Collections.emptySet());
assertThat(count).isZero();
verifyNoInteractions(emailSettings);
assertThat(smtpServer.getMessages()).isEmpty();
}
@Test
public void deliverAll_has_no_effect_if_smtp_host_is_null() {
EmailSettings emailSettings = mock(EmailSettings.class);
when(emailSettings.getSmtpHost()).thenReturn(null);
Set<EmailDeliveryRequest> requests = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> new EmailDeliveryRequest("foo" + i + "@moo", mock(Notification.class)))
.collect(toSet());
EmailNotificationChannel underTest = new EmailNotificationChannel(emailSettings, null, null);
int count = underTest.deliverAll(requests);
assertThat(count).isZero();
verify(emailSettings).getSmtpHost();
verifyNoMoreInteractions(emailSettings);
assertThat(smtpServer.getMessages()).isEmpty();
}
@Test
@UseDataProvider("emptyStrings")
public void deliverAll_ignores_requests_which_recipient_is_empty(String emptyString) {
EmailSettings emailSettings = mock(EmailSettings.class);
when(emailSettings.getSmtpHost()).thenReturn(null);
Set<EmailDeliveryRequest> requests = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> new EmailDeliveryRequest(emptyString, mock(Notification.class)))
.collect(toSet());
EmailNotificationChannel underTest = new EmailNotificationChannel(emailSettings, null, null);
int count = underTest.deliverAll(requests);
assertThat(count).isZero();
verify(emailSettings).getSmtpHost();
verifyNoMoreInteractions(emailSettings);
assertThat(smtpServer.getMessages()).isEmpty();
}
@Test
public void deliverAll_returns_count_of_request_for_which_at_least_one_formatter_accept_it() throws MessagingException, IOException {
String recipientEmail = "foo@donut";
configure();
Notification notification1 = mock(Notification.class);
Notification notification2 = mock(Notification.class);
Notification notification3 = mock(Notification.class);
EmailTemplate template1 = mock(EmailTemplate.class);
EmailTemplate template3 = mock(EmailTemplate.class);
EmailMessage emailMessage1 = new EmailMessage().setTo(recipientEmail).setSubject("sub11").setPlainTextMessage("msg11");
EmailMessage emailMessage3 = new EmailMessage().setTo(recipientEmail).setSubject("sub3").setPlainTextMessage("msg3");
when(template1.format(notification1)).thenReturn(emailMessage1);
when(template3.format(notification3)).thenReturn(emailMessage3);
Set<EmailDeliveryRequest> requests = Stream.of(notification1, notification2, notification3)
.map(t -> new EmailDeliveryRequest(recipientEmail, t))
.collect(toSet());
EmailNotificationChannel underTest = new EmailNotificationChannel(configuration, new EmailTemplate[] {template1, template3}, null);
int count = underTest.deliverAll(requests);
assertThat(count).isEqualTo(2);
assertThat(smtpServer.getMessages()).hasSize(2);
Map<String, MimeMessage> messagesBySubject = smtpServer.getMessages().stream()
.map(t -> {
try {
return t.getMimeMessage();
} catch (MessagingException e) {
throw new RuntimeException(e);
}
})
.collect(toMap(t -> {
try {
return t.getSubject();
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}, t -> t));
assertThat((String) messagesBySubject.get(SUBJECT_PREFIX + " " + emailMessage1.getSubject()).getContent())
.contains(emailMessage1.getMessage());
assertThat((String) messagesBySubject.get(SUBJECT_PREFIX + " " + emailMessage3.getSubject()).getContent())
.contains(emailMessage3.getMessage());
}
@Test
public void deliverAll_ignores_multiple_templates_by_notification_and_takes_the_first_one_only() throws MessagingException, IOException {
String recipientEmail = "foo@donut";
configure();
Notification notification1 = mock(Notification.class);
EmailTemplate template11 = mock(EmailTemplate.class);
EmailTemplate template12 = mock(EmailTemplate.class);
EmailMessage emailMessage11 = new EmailMessage().setTo(recipientEmail).setSubject("sub11").setPlainTextMessage("msg11");
EmailMessage emailMessage12 = new EmailMessage().setTo(recipientEmail).setSubject("sub12").setPlainTextMessage("msg12");
when(template11.format(notification1)).thenReturn(emailMessage11);
when(template12.format(notification1)).thenReturn(emailMessage12);
EmailDeliveryRequest request = new EmailDeliveryRequest(recipientEmail, notification1);
EmailNotificationChannel underTest = new EmailNotificationChannel(configuration, new EmailTemplate[] {template11, template12}, null);
int count = underTest.deliverAll(Collections.singleton(request));
assertThat(count).isOne();
assertThat(smtpServer.getMessages()).hasSize(1);
assertThat((String) smtpServer.getMessages().iterator().next().getMimeMessage().getContent())
.contains(emailMessage11.getMessage());
}
@DataProvider
public static Object[][] emptyStrings() {
return new Object[][] {
{""},
{" "},
{" \n "}
};
}
private void configure() {
when(configuration.getSmtpHost()).thenReturn("localhost");
when(configuration.getSmtpPort()).thenReturn(smtpServer.getServer().getPort());
when(configuration.getFrom()).thenReturn("server@nowhere");
when(configuration.getFromName()).thenReturn("SonarQube from NoWhere");
when(configuration.getPrefix()).thenReturn(SUBJECT_PREFIX);
when(configuration.getServerBaseURL()).thenReturn("http://nemo.sonarsource.org");
}
}
| 15,443 | 39.21875 | 163 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.permission.index;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexType;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Fail.fail;
@RunWith(DataProviderRunner.class)
public class AuthorizationDocTest {
@Test
public void idOf_returns_argument_with_a_prefix() {
String s = randomAlphabetic(12);
assertThat(AuthorizationDoc.idOf(s)).isEqualTo("auth_" + s);
}
@Test
public void idOf_fails_with_NPE_if_argument_is_null() {
assertThatThrownBy(() -> AuthorizationDoc.idOf(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("entityUuid can't be null");
}
@Test
public void projectUuidOf_fails_with_NPE_if_argument_is_null() {
assertThatThrownBy(() -> AuthorizationDoc.entityUuidOf(null))
.isInstanceOf(NullPointerException.class);
}
@Test
public void projectUuidOf_returns_substring_if_starts_with_id_prefix() {
assertThat(AuthorizationDoc.entityUuidOf("auth_")).isEmpty();
String id = randomAlphabetic(1 + new Random().nextInt(10));
assertThat(AuthorizationDoc.entityUuidOf("auth_" + id)).isEqualTo(id);
}
@Test
public void projectUuidOf_returns_argument_if_does_not_starts_with_id_prefix() {
String id = randomAlphabetic(1 + new Random().nextInt(10));
assertThat(AuthorizationDoc.entityUuidOf(id)).isEqualTo(id);
assertThat(AuthorizationDoc.entityUuidOf("")).isEmpty();
}
@Test
public void getId_fails_with_NPE_if_IndexPermissions_has_null_projectUuid() {
IndexPermissions dto = new IndexPermissions(null, null);
IndexType.IndexMainType mainType = IndexType.main(Index.simple("foo"), "bar");
AuthorizationDoc underTest = AuthorizationDoc.fromDto(mainType, dto);
assertThatThrownBy(() -> underTest.getId())
.isInstanceOf(NullPointerException.class)
.hasMessage("entityUuid can't be null");
}
@Test
@UseDataProvider("dtos")
public void getId_returns_projectUuid_with_a_prefix(IndexPermissions dto) {
AuthorizationDoc underTest = AuthorizationDoc.fromDto(IndexType.main(Index.simple("foo"), "bar"), dto);
assertThat(underTest.getId()).isEqualTo("auth_" + dto.getEntityUuid());
}
@Test
@UseDataProvider("dtos")
public void getRouting_returns_projectUuid(IndexPermissions dto) {
AuthorizationDoc underTest = AuthorizationDoc.fromDto(IndexType.main(Index.simple("foo"), "bar"), dto);
assertThat(underTest.getRouting()).contains(dto.getEntityUuid());
}
@Test
public void fromDto_of_allowAnyone_is_false_and_no_user_nor_group() {
IndexPermissions underTest = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
AuthorizationDoc doc = AuthorizationDoc.fromDto(IndexType.main(Index.simple("foo"), "bar"), underTest);
boolean auth_allowAnyone = doc.getField("auth_allowAnyone");
assertThat(auth_allowAnyone).isFalse();
List<Integer> userIds = doc.getField("auth_userIds");
assertThat(userIds).isEmpty();
List<Integer> groupIds = doc.getField("auth_groupIds");
assertThat(groupIds).isEmpty();
}
@Test
public void fromDto_defines_userIds_and_groupIds_if_allowAnyone_is_false() {
IndexPermissions underTest = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(underTest::addUserUuid);
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(underTest::addGroupUuid);
AuthorizationDoc doc = AuthorizationDoc.fromDto(IndexType.main(Index.simple("foo"), "bar"), underTest);
boolean auth_allowAnyone = doc.getField("auth_allowAnyone");
assertThat(auth_allowAnyone).isFalse();
List<String> userUuids = doc.getField("auth_userIds");
assertThat(userUuids).isEqualTo(underTest.getUserUuids());
List<String> groupUuids = doc.getField("auth_groupIds");
assertThat(groupUuids).isEqualTo(underTest.getGroupUuids());
}
@Test
public void fromDto_ignores_userIds_and_groupUuids_if_allowAnyone_is_true() {
IndexPermissions underTest = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(underTest::addUserUuid);
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(underTest::addGroupUuid);
underTest.allowAnyone();
AuthorizationDoc doc = AuthorizationDoc.fromDto(IndexType.main(Index.simple("foo"), "bar"), underTest);
boolean auth_allowAnyone = doc.getField("auth_allowAnyone");
assertThat(auth_allowAnyone).isTrue();
try {
doc.getField("auth_userIds");
fail("should have thrown IllegalStateException");
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Field auth_userIds not specified in query options");
}
try {
doc.getField("auth_groupUuids");
fail("should have thrown IllegalStateException");
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Field auth_groupUuids not specified in query options");
}
}
@DataProvider
public static Object[][] dtos() {
IndexPermissions allowAnyone = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
allowAnyone.allowAnyone();
IndexPermissions someUserIds = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(someUserIds::addUserUuid);
IndexPermissions someGroupUuids = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(someGroupUuids::addGroupUuid);
IndexPermissions someGroupUuidAndUserIs = new IndexPermissions(randomAlphabetic(3), randomAlphabetic(4));
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(String::valueOf).forEach(someGroupUuidAndUserIs::addUserUuid);
IntStream.range(0, 1 + new Random().nextInt(5)).mapToObj(Integer::toString).forEach(someGroupUuidAndUserIs::addGroupUuid);
return new Object[][] {
{allowAnyone},
{someUserIds},
{someGroupUuids},
{someGroupUuidAndUserIs}
};
}
}
| 7,531 | 41.553672 | 126 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/platform/DefaultNodeInformationTest.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;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultNodeInformationTest {
private MapSettings settings = new MapSettings();
@Test
public void cluster_is_disabled_by_default() {
DefaultNodeInformation underTest = new DefaultNodeInformation(settings.asConfig());
assertThat(underTest.isStandalone()).isTrue();
assertThat(underTest.isStartupLeader()).isTrue();
}
@Test
public void node_is_startup_leader_in_cluster() {
settings.setProperty("sonar.cluster.enabled", "true");
settings.setProperty("sonar.cluster.web.startupLeader", "true");
DefaultNodeInformation underTest = new DefaultNodeInformation(settings.asConfig());
assertThat(underTest.isStandalone()).isFalse();
assertThat(underTest.isStartupLeader()).isTrue();
}
@Test
public void node_is_startup_follower_by_default_in_cluster() {
settings.setProperty("sonar.cluster.enabled", "true");
DefaultNodeInformation underTest = new DefaultNodeInformation(settings.asConfig());
assertThat(underTest.isStandalone()).isFalse();
assertThat(underTest.isStartupLeader()).isFalse();
}
@Test
public void node_is_startup_follower_in_cluster() {
settings.setProperty("sonar.cluster.enabled", "true");
settings.setProperty("sonar.cluster.web.startupLeader", "false");
DefaultNodeInformation underTest = new DefaultNodeInformation(settings.asConfig());
assertThat(underTest.isStandalone()).isFalse();
assertThat(underTest.isStartupLeader()).isFalse();
}
@Test
public void getNodeName_whenNotACluster_isEmpty() {
settings.setProperty("sonar.cluster.enabled", "false");
settings.setProperty("sonar.cluster.node.name", "nameIgnored");
DefaultNodeInformation underTest = new DefaultNodeInformation(settings.asConfig());
assertThat(underTest.getNodeName()).isEmpty();
}
@Test
public void getNodeName_whenClusterAndNameNotDefined_fallbacksToDefaultName() {
settings.setProperty("sonar.cluster.enabled", "true");
settings.removeProperty("sonar.cluster.node.name");
DefaultNodeInformation underTest = new DefaultNodeInformation(settings.asConfig());
assertThat(underTest.getNodeName()).isNotEmpty();
String nodeNameFirstCallToGetNodeName = underTest.getNodeName().get();
assertThat(nodeNameFirstCallToGetNodeName).startsWith("sonarqube-");
String nodeNameSecondCallToGetNodeName = underTest.getNodeName().get();
assertThat(nodeNameFirstCallToGetNodeName).isEqualTo(nodeNameSecondCallToGetNodeName);
}
@Test
public void getNodeName_whenClusterAndNameDefined_returnName() {
String nodeName = "nodeName1";
settings.setProperty("sonar.cluster.enabled", "true");
settings.setProperty("sonar.cluster.node.name", nodeName);
DefaultNodeInformation underTest = new DefaultNodeInformation(settings.asConfig());
assertThat(underTest.getNodeName()).isNotEmpty();
assertThat(underTest.getNodeName().get()).startsWith(nodeName);
}
}
| 3,937 | 35.12844 | 90 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/platform/OfficialDistributionTest.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;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class OfficialDistributionTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private ServerFileSystem serverFileSystem = mock(ServerFileSystem.class);
private OfficialDistribution underTest = new OfficialDistribution(serverFileSystem);
@Test
public void official_distribution() throws Exception {
File rootDir = temp.newFolder();
FileUtils.write(new File(rootDir, OfficialDistribution.BRANDING_FILE_PATH), "1.2");
when(serverFileSystem.getHomeDir()).thenReturn(rootDir);
assertThat(underTest.check()).isTrue();
}
@Test
public void not_an_official_distribution() throws Exception {
File rootDir = temp.newFolder();
// branding file is missing
when(serverFileSystem.getHomeDir()).thenReturn(rootDir);
assertThat(underTest.check()).isFalse();
}
}
| 1,990 | 33.327586 | 87 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerFileSystemImplTest.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;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.config.Configuration;
import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
public class ServerFileSystemImplTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
private ServerFileSystemImpl underTest;
private File homeDir;
private File tempDir;
private File dataDir;
@Before
public void before() throws IOException {
DumpMapConfiguration configuration = new DumpMapConfiguration();
homeDir = temporaryFolder.newFolder();
tempDir = temporaryFolder.newFolder();
dataDir = temporaryFolder.newFolder();
configuration.put("sonar.path.home", homeDir.toPath().toString());
configuration.put("sonar.path.temp", tempDir.toPath().toString());
configuration.put("sonar.path.data", dataDir.toPath().toString());
underTest = new ServerFileSystemImpl(configuration);
}
@Test
public void start_should_log() {
underTest.start();
underTest.stop();
assertThat(logTester.logs())
.contains("SonarQube home: " + homeDir.toPath().toString());
}
@Test
public void verify_values_set() {
assertThat(underTest.getHomeDir()).isEqualTo(homeDir);
assertThat(underTest.getTempDir()).isEqualTo(tempDir);
assertThat(underTest.getDeployedPluginsDir()).isEqualTo(new File(dataDir.getAbsolutePath() + "/web/deploy/plugins"));
assertThat(underTest.getDownloadedPluginsDir()).isEqualTo(new File(homeDir.getAbsolutePath() + "/extensions/downloads"));
assertThat(underTest.getInstalledBundledPluginsDir()).isEqualTo(new File(homeDir.getAbsolutePath() + "/lib/extensions"));
assertThat(underTest.getInstalledExternalPluginsDir()).isEqualTo(new File(homeDir.getAbsolutePath() + "/extensions/plugins"));
assertThat(underTest.getPluginIndex()).isEqualTo(new File(dataDir.getAbsolutePath() + "/web/deploy/plugins/index.txt"));
assertThat(underTest.getUninstalledPluginsDir()).isEqualTo(new File(tempDir.getAbsolutePath() + "/uninstalled-plugins"));
}
private static class DumpMapConfiguration implements Configuration {
private final Map<String, String> keyValues = new HashMap<>();
public Configuration put(String key, String value) {
keyValues.put(key, value.trim());
return this;
}
@Override
public Optional<String> get(String key) {
return Optional.ofNullable(keyValues.get(key));
}
@Override
public boolean hasKey(String key) {
throw new UnsupportedOperationException("hasKey not implemented");
}
@Override
public String[] getStringArray(String key) {
throw new UnsupportedOperationException("getStringArray not implemented");
}
}
}
| 3,874 | 34.550459 | 130 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerImplTest.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;
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.Version;
import org.sonar.core.platform.SonarQubeVersion;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ServerImplTest {
private final MapSettings settings = new MapSettings();
private final StartupMetadata state = mock(StartupMetadata.class);
private final UrlSettings urlSettings = mock(UrlSettings.class);
private final SonarQubeVersion sonarQubeVersion = mock(SonarQubeVersion.class);
private final ServerImpl underTest = new ServerImpl(settings.asConfig(), state, urlSettings, sonarQubeVersion);
@Test
public void test_url_information() {
when(urlSettings.getContextPath()).thenReturn("/foo");
when(urlSettings.getBaseUrl()).thenReturn("http://localhost:9000/foo");
when(urlSettings.isSecured()).thenReturn(false);
assertThat(underTest.getContextPath()).isEqualTo("/foo");
assertThat(underTest.getPublicRootUrl()).isEqualTo("http://localhost:9000/foo");
assertThat(underTest.isSecured()).isFalse();
}
@Test
public void test_startup_information() {
long time = 123_456_789L;
when(state.getStartedAt()).thenReturn(time);
assertThat(underTest.getStartedAt().getTime()).isEqualTo(time);
}
@Test
public void test_id() {
settings.setProperty(CoreProperties.SERVER_ID, "foo");
assertThat(underTest.getId()).isEqualTo("foo");
assertThat(underTest.getPermanentServerId()).isEqualTo("foo");
}
@Test
public void test_getVersion() {
Version version = Version.create(6, 1);
when(sonarQubeVersion.get()).thenReturn(version);
assertThat(underTest.getVersion()).isEqualTo(version.toString());
}
}
| 2,711 | 35.648649 | 113 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerLifecycleNotifierTest.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;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.platform.Server;
import org.sonar.api.platform.ServerStartHandler;
import org.sonar.api.platform.ServerStopHandler;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
public class ServerLifecycleNotifierTest {
private Server server;
private ServerStartHandler start1;
private ServerStartHandler start2;
private ServerStopHandler stop1;
private ServerStopHandler stop2;
@Before
public void before() {
server = new FakeServer();
start1 = mock(ServerStartHandler.class);
start2 = mock(ServerStartHandler.class);
stop1 = mock(ServerStopHandler.class);
stop2 = mock(ServerStopHandler.class);
}
/**
* see the explanation in the method ServerLifecycleNotifier.start()
*/
@Test
public void doNotNotifyWithTheStartMethod() {
ServerLifecycleNotifier notifier = new ServerLifecycleNotifier(server, new ServerStartHandler[] {start1, start2}, new ServerStopHandler[] {stop2});
notifier.start();
verify(start1, never()).onServerStart(server);
verify(start2, never()).onServerStart(server);
verify(stop1, never()).onServerStop(server);
}
@Test
public void notifyOnStart() {
ServerLifecycleNotifier notifier = new ServerLifecycleNotifier(server, new ServerStartHandler[] {start1, start2}, new ServerStopHandler[] {stop2});
notifier.notifyStart();
verify(start1).onServerStart(server);
verify(start2).onServerStart(server);
verify(stop1, never()).onServerStop(server);
}
@Test
public void notifyOnStop() {
ServerLifecycleNotifier notifier = new ServerLifecycleNotifier(server, new ServerStartHandler[] {start1, start2}, new ServerStopHandler[] {stop1, stop2});
notifier.stop();
verify(start1, never()).onServerStart(server);
verify(start2, never()).onServerStart(server);
verify(stop1).onServerStop(server);
verify(stop2).onServerStop(server);
}
@Test
public void null_handler_param_wont_lead_to_NPE() {
ServerLifecycleNotifier notifier = new ServerLifecycleNotifier(server, null, null);
assertThatNoException().isThrownBy(notifier::notifyStart);
assertThatNoException().isThrownBy(notifier::stop);
}
}
class FakeServer extends Server {
@Override
public String getId() {
return null;
}
@Override
public String getVersion() {
return null;
}
@Override
public Date getStartedAt() {
return null;
}
@Override
public String getContextPath() {
return null;
}
@Override
public String getPublicRootUrl() {
return null;
}
@Override
public boolean isSecured() {
return false;
}
@Override
public String getPermanentServerId() {
return null;
}
}
| 3,761 | 27.938462 | 158 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/platform/TempFolderProviderTest.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;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.utils.TempFolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TempFolderProviderTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private final TempFolderProvider underTest = new TempFolderProvider();
@Test
public void existing_temp_dir() throws Exception {
ServerFileSystem fs = mock(ServerFileSystem.class);
File tmpDir = temp.newFolder();
when(fs.getTempDir()).thenReturn(tmpDir);
TempFolder folder = underTest.provide(fs);
assertThat(folder).isNotNull();
File newDir = folder.newDir();
assertThat(newDir).exists().isDirectory();
assertThat(newDir.getParentFile().getCanonicalPath()).startsWith(tmpDir.getCanonicalPath());
}
@Test
public void create_temp_dir_if_missing() throws Exception {
ServerFileSystem fs = mock(ServerFileSystem.class);
File tmpDir = temp.newFolder();
when(fs.getTempDir()).thenReturn(tmpDir);
FileUtils.forceDelete(tmpDir);
TempFolder folder = underTest.provide(fs);
assertThat(folder).isNotNull();
File newDir = folder.newDir();
assertThat(newDir).exists().isDirectory();
assertThat(newDir.getParentFile().getCanonicalPath()).startsWith(tmpDir.getCanonicalPath());
}
}
| 2,360 | 34.772727 | 96 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/platform/UrlSettingsTest.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;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import org.sonar.core.config.CorePropertyDefinitions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.CoreProperties.SERVER_BASE_URL;
public class UrlSettingsTest {
private static final String HOST_PROPERTY = "sonar.web.host";
private static final String PORT_PORPERTY = "sonar.web.port";
private static final String CONTEXT_PROPERTY = "sonar.web.context";
private final MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, CorePropertyDefinitions.all()));
@Test
public void use_default_context_path() {
assertThat(underTest().getContextPath()).isEmpty();
}
@Test
public void default_url() {
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:9000");
}
@Test
public void base_url_is_configured() {
settings.setProperty("sonar.core.serverBaseURL", "http://mydomain.com");
assertThat(underTest().getBaseUrl()).isEqualTo("http://mydomain.com");
}
@Test
public void remove_trailing_slash() {
settings.setProperty("sonar.core.serverBaseURL", "http://mydomain.com/");
assertThat(underTest().getBaseUrl()).isEqualTo("http://mydomain.com");
}
@Test
public void is_secured_on_https_server() {
settings.setProperty("sonar.core.serverBaseURL", "https://mydomain.com");
assertThat(underTest().isSecured()).isTrue();
}
@Test
public void is_not_secured_if_http() {
settings.setProperty("sonar.core.serverBaseURL", "http://mydomain.com");
assertThat(underTest().isSecured()).isFalse();
}
@Test
public void context_path_is_configured() {
settings.setProperty(CONTEXT_PROPERTY, "/my_path");
assertThat(underTest().getContextPath()).isEqualTo("/my_path");
}
@Test
public void sanitize_context_path_from_settings() {
settings.setProperty(CONTEXT_PROPERTY, "/my_path///");
assertThat(underTest().getContextPath()).isEqualTo("/my_path");
}
@Test
public void base_url_is_http_localhost_9000_when_serverBaseUrl_is_null() {
settings.setProperty(SERVER_BASE_URL, (String) null);
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:9000");
}
@Test
public void base_url_is_serverBaseUrl_if_non_empty() {
String serverBaseUrl = "whatever";
settings.setProperty(SERVER_BASE_URL, serverBaseUrl);
assertThat(underTest().getBaseUrl()).isEqualTo(serverBaseUrl);
}
@Test
public void base_url_is_http_localhost_9000_when_serverBaseUrl_is_empty() {
settings.setProperty(SERVER_BASE_URL, "");
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:9000");
}
@Test
public void base_url_is_http_localhost_9000_when_host_set_to_0_0_0_0() {
settings.setProperty(HOST_PROPERTY, "0.0.0.0");
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:9000");
}
@Test
public void base_url_is_http_specified_host_9000_when_host_is_set() {
settings.setProperty(HOST_PROPERTY, "my_host");
assertThat(underTest().getBaseUrl()).isEqualTo("http://my_host:9000");
}
@Test
public void base_url_is_http_localhost_specified_port_when_port_is_set() {
settings.setProperty(PORT_PORPERTY, 951);
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:951");
}
@Test
public void base_url_is_http_localhost_no_port_when_port_is_80() {
settings.setProperty(PORT_PORPERTY, 80);
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost");
}
@Test
public void base_url_is_http_localhost_9000_when_port_is_0() {
settings.setProperty(PORT_PORPERTY, 0);
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:9000");
}
@Test
public void base_url_is_http_localhost_9000_when_port_is_negative() {
settings.setProperty(PORT_PORPERTY, -23);
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:9000");
}
@Test
public void getBaseUrl_throws_when_port_not_an_int() {
settings.setProperty(PORT_PORPERTY, "not a number");
assertThatThrownBy(() -> underTest().getBaseUrl())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("The property 'sonar.web.port' is not an int value");
}
@Test
public void base_url_is_http_localhost_900_specified_context_when_context_is_set() {
settings.setProperty(CONTEXT_PROPERTY, "sdsd");
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:9000sdsd");
}
@Test
public void base_url_is_http_specified_host_no_port_when_host_is_set_and_port_is_80() {
settings.setProperty(HOST_PROPERTY, "foo");
settings.setProperty(PORT_PORPERTY, 80);
assertThat(underTest().getBaseUrl()).isEqualTo("http://foo");
}
@Test
public void getBaseUrl_does_not_cache_returned_value() {
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:9000");
settings.setProperty(HOST_PROPERTY, "foo");
assertThat(underTest().getBaseUrl()).isEqualTo("http://foo:9000");
settings.setProperty(PORT_PORPERTY, 666);
assertThat(underTest().getBaseUrl()).isEqualTo("http://foo:666");
settings.setProperty(CONTEXT_PROPERTY, "/bar");
assertThat(underTest().getBaseUrl()).isEqualTo("http://foo:666/bar");
}
private UrlSettings underTest() {
return new UrlSettings(settings.asConfig());
}
}
| 6,374 | 32.031088 | 129 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/platform/monitoring/LoggingSectionTest.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.monitoring;
import java.io.File;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
import org.sonar.server.log.ServerLogging;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs;
public class LoggingSectionTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private SonarRuntime runtime = mock(SonarRuntime.class);
private ServerLogging logging = mock(ServerLogging.class);
private File logDir;
private LoggingSection underTest = new LoggingSection(runtime, logging);
@Before
public void setUp() throws Exception {
logDir = temp.newFolder();
when(logging.getLogsDir()).thenReturn(logDir);
when(logging.getRootLoggerLevel()).thenReturn(LoggerLevel.DEBUG);
}
@Test
public void return_logging_attributes_of_compute_engine() {
when(runtime.getSonarQubeSide()).thenReturn(SonarQubeSide.COMPUTE_ENGINE);
ProtobufSystemInfo.Section section = underTest.toProtobuf();
assertThat(section.getName()).isEqualTo("Compute Engine Logging");
assertThatAttributeIs(section, "Logs Dir", logDir.getAbsolutePath());
assertThatAttributeIs(section, "Logs Level", "DEBUG");
}
@Test
public void return_logging_attributes_of_web_server() {
when(runtime.getSonarQubeSide()).thenReturn(SonarQubeSide.SERVER);
ProtobufSystemInfo.Section section = underTest.toProtobuf();
assertThat(section.getName()).isEqualTo("Web Logging");
assertThatAttributeIs(section, "Logs Dir", logDir.getAbsolutePath());
assertThatAttributeIs(section, "Logs Level", "DEBUG");
}
}
| 2,829 | 36.733333 | 91 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/platform/monitoring/cluster/ProcessInfoProviderTest.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.monitoring.cluster;
import java.util.List;
import org.junit.Test;
import org.sonar.process.systeminfo.SystemInfoSection;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
import static org.assertj.core.api.Assertions.assertThat;
public class ProcessInfoProviderTest {
@Test
public void remove_global_sections_from_results() {
ProcessInfoProvider underTest = new ProcessInfoProvider(new SystemInfoSection[]{
new TestGlobalSystemInfoSection("foo"),
new TestSystemInfoSection("bar")});
underTest.start();
List<ProtobufSystemInfo.Section> sections = ProcessInfoProvider.provide().getSectionsList();
assertThat(sections).extracting(ProtobufSystemInfo.Section::getName).containsExactly("bar");
underTest.stop();
}
@Test
public void merge_sections() {
ProcessInfoProvider underTest = new ProcessInfoProvider(new SystemInfoSection[]{
new TestSystemInfoSection("foo"),
new TestSystemInfoSection("bar")});
underTest.start();
List<ProtobufSystemInfo.Section> sections = ProcessInfoProvider.provide().getSectionsList();
assertThat(sections).extracting(ProtobufSystemInfo.Section::getName)
.containsExactlyInAnyOrder("foo", "bar");
underTest.stop();
}
@Test
public void empty_result_is_returned_if_not_started_yet() {
ProcessInfoProvider underTest = new ProcessInfoProvider(new SystemInfoSection[]{
new TestSystemInfoSection("foo"),
new TestSystemInfoSection("bar")});
assertThat(ProcessInfoProvider.provide().getSectionsCount()).isZero();
underTest.start();
assertThat(ProcessInfoProvider.provide().getSectionsCount()).isEqualTo(2);
underTest.stop();
assertThat(ProcessInfoProvider.provide().getSectionsCount()).isZero();
}
}
| 2,644 | 34.743243 | 96 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/platform/serverid/JdbcUrlSanitizerTest.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.serverid;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class JdbcUrlSanitizerTest {
private JdbcUrlSanitizer underTest = new JdbcUrlSanitizer();
@Test
public void sanitize_h2_url() {
verifyJdbcUrl("jdbc:h2:tcp://dbserv:8084/~/sample", "jdbc:h2:tcp://dbserv:8084/~/sample");
verifyJdbcUrl("jdbc:h2:tcp://localhost/mem:test", "jdbc:h2:tcp://localhost/mem:test");
verifyJdbcUrl("jdbc:h2:tcp://localhost/mem:TEST", "jdbc:h2:tcp://localhost/mem:test");
}
@Test
public void sanitize_oracle_url() {
verifyJdbcUrl("sonar.jdbc.url=jdbc:oracle:thin:@localhost:1521/XE", "sonar.jdbc.url=jdbc:oracle:thin:@localhost:1521/xe");
verifyJdbcUrl("sonar.jdbc.url=jdbc:oracle:thin:@localhost/XE", "sonar.jdbc.url=jdbc:oracle:thin:@localhost/xe");
verifyJdbcUrl("sonar.jdbc.url=jdbc:oracle:thin:@localhost/XE?foo", "sonar.jdbc.url=jdbc:oracle:thin:@localhost/xe");
verifyJdbcUrl("sonar.jdbc.url=jdbc:oracle:thin:@LOCALHOST/XE?foo", "sonar.jdbc.url=jdbc:oracle:thin:@localhost/xe");
}
@Test
public void sanitize_sqlserver_url() {
// see examples listed at https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url
verifyJdbcUrl("jdbc:sqlserver://localhost;user=MyUserName;password=*****;", "jdbc:sqlserver://localhost");
verifyJdbcUrl("jdbc:sqlserver://;servername=server_name;integratedSecurity=true;authenticationScheme=JavaKerberos", "jdbc:sqlserver://server_name");
verifyJdbcUrl("jdbc:sqlserver://localhost;integratedSecurity=true;", "jdbc:sqlserver://localhost");
verifyJdbcUrl("jdbc:sqlserver://localhost;databaseName=AdventureWorks;integratedSecurity=true;", "jdbc:sqlserver://localhost/adventureworks");
verifyJdbcUrl("jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks;integratedSecurity=true;", "jdbc:sqlserver://localhost:1433/adventureworks");
verifyJdbcUrl("jdbc:sqlserver://localhost;databaseName=AdventureWorks;integratedSecurity=true;applicationName=MyApp;", "jdbc:sqlserver://localhost/adventureworks");
verifyJdbcUrl("jdbc:sqlserver://localhost;instanceName=instance1;integratedSecurity=true;", "jdbc:sqlserver://localhost");
verifyJdbcUrl("jdbc:sqlserver://;serverName=3ffe:8311:eeee:f70f:0:5eae:10.203.31.9\\\\instance1;integratedSecurity=true;", "jdbc:sqlserver://3ffe:8311:eeee:f70f:0:5eae:10.203.31.9\\\\instance1");
// test parameter aliases
verifyJdbcUrl("jdbc:sqlserver://;server=server_name", "jdbc:sqlserver://server_name");
verifyJdbcUrl("jdbc:sqlserver://;server=server_name;portNumber=1234", "jdbc:sqlserver://server_name:1234");
verifyJdbcUrl("jdbc:sqlserver://;server=server_name;port=1234", "jdbc:sqlserver://server_name:1234");
// case-insensitive
verifyJdbcUrl("jdbc:sqlserver://LOCALHOST;user=MyUserName;password=*****;", "jdbc:sqlserver://localhost");
}
@Test
public void sanitize_postgres_url() {
verifyJdbcUrl("jdbc:postgresql://localhost/sonar", "jdbc:postgresql://localhost/sonar");
verifyJdbcUrl("jdbc:postgresql://localhost:1234/sonar", "jdbc:postgresql://localhost:1234/sonar");
verifyJdbcUrl("jdbc:postgresql://localhost:1234/sonar?foo", "jdbc:postgresql://localhost:1234/sonar");
// case-insensitive
verifyJdbcUrl("jdbc:postgresql://localhost:1234/SONAR?foo", "jdbc:postgresql://localhost:1234/sonar");
}
private void verifyJdbcUrl(String url, String expectedResult) {
assertThat(underTest.sanitize(url)).isEqualTo(expectedResult);
}
}
| 4,368 | 52.280488 | 199 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/platform/serverid/ServerIdChecksumTest.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.serverid;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.process.ProcessProperties.Property.JDBC_URL;
public class ServerIdChecksumTest {
@Test
public void compute_throws_ISE_if_jdbcUrl_property_is_not_set() {
ServerIdChecksum underTest = new ServerIdChecksum(new MapSettings().asConfig(), null /*doesn't matter*/);
assertThatThrownBy(() -> underTest.computeFor("foo"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Missing JDBC URL");
}
@Test
public void test_checksum() {
assertThat(computeFor("id1", "url1"))
.isNotEmpty()
.isEqualTo(computeFor("id1", "url1"))
.isNotEqualTo(computeFor("id1", "url2"))
.isNotEqualTo(computeFor("id2", "url1"))
.isNotEqualTo(computeFor("id2", "url2"));
}
private String computeFor(String serverId, String jdbcUrl) {
MapSettings settings = new MapSettings();
JdbcUrlSanitizer jdbcUrlSanitizer = mock(JdbcUrlSanitizer.class);
when(jdbcUrlSanitizer.sanitize(jdbcUrl)).thenReturn("_" + jdbcUrl);
ServerIdChecksum underTest = new ServerIdChecksum(settings.asConfig(), jdbcUrlSanitizer);
settings.setProperty(JDBC_URL.getKey(), jdbcUrl);
return underTest.computeFor(serverId);
}
}
| 2,352 | 37.57377 | 109 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/plugins/InstalledPluginReferentialFactoryTest.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;
import org.junit.Test;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class InstalledPluginReferentialFactoryTest {
@Test
public void should_create_plugin_referential() {
PluginInfo info = new PluginInfo("foo");
PluginRepository pluginRepository = mock(PluginRepository.class);
when(pluginRepository.getPluginInfos()).thenReturn(newArrayList(info));
InstalledPluginReferentialFactory factory = new InstalledPluginReferentialFactory(pluginRepository);
assertThat(factory.getInstalledPluginReferential()).isNull();
factory.start();
assertThat(factory.getInstalledPluginReferential()).isNotNull();
assertThat(factory.getInstalledPluginReferential().getPlugins()).hasSize(1);
}
@Test
public void should_encapsulate_exception() {
PluginRepository pluginRepository = mock(PluginRepository.class);
when(pluginRepository.getPluginInfos()).thenThrow(new IllegalArgumentException());
InstalledPluginReferentialFactory factory = new InstalledPluginReferentialFactory(pluginRepository);
assertThatThrownBy(factory::start)
.isInstanceOf(RuntimeException.class);
}
}
| 2,318 | 40.410714 | 104 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/plugins/PluginReferentialMetadataConverterTest.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;
import org.junit.Test;
import org.sonar.core.platform.PluginInfo;
import org.sonar.updatecenter.common.PluginReferential;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
public class PluginReferentialMetadataConverterTest {
@Test
public void should_convert_info_to_plugin_referential() {
PluginInfo info = new PluginInfo("foo");
PluginReferential pluginReferential = PluginReferentialMetadataConverter.getInstalledPluginReferential(newArrayList(info));
assertThat(pluginReferential).isNotNull();
assertThat(pluginReferential.getPlugins()).hasSize(1);
assertThat(pluginReferential.getPlugins().get(0).getKey()).isEqualTo("foo");
}
}
| 1,611 | 37.380952 | 127 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/plugins/PluginRequirementsValidatorTest.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;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginInfo.RequiredPlugin;
import org.sonar.updatecenter.common.Version;
import static org.assertj.core.api.Assertions.assertThat;
public class PluginRequirementsValidatorTest {
@Rule
public LogTester logTester = new LogTester();
@Test
public void unloadIncompatiblePlugins_removes_incompatible_plugins() {
PluginInfo pluginE = new PluginInfo("pluginE");
PluginInfo pluginD = new PluginInfo("pluginD")
.setBasePlugin("pluginC");
PluginInfo pluginC = new PluginInfo("pluginC")
.setBasePlugin("pluginB");
PluginInfo pluginB = new PluginInfo("pluginB")
.addRequiredPlugin(RequiredPlugin.parse("pluginA:1.0"));
Map<String, PluginInfo> plugins = new HashMap<>();
plugins.put(pluginB.getKey(), pluginB);
plugins.put(pluginC.getKey(), pluginC);
plugins.put(pluginD.getKey(), pluginD);
plugins.put(pluginE.getKey(), pluginE);
PluginRequirementsValidator.unloadIncompatiblePlugins(plugins);
assertThat(plugins).contains(Map.entry(pluginE.getKey(), pluginE));
}
@Test
public void isCompatible_verifies_base_plugin_existence() {
PluginInfo pluginWithoutBase = new PluginInfo("plugin-without-base-plugin")
.setBasePlugin("not-existing-base-plugin");
PluginInfo basePlugin = new PluginInfo("base-plugin");
PluginInfo pluginWithBase = new PluginInfo("plugin-with-base-plugin")
.setBasePlugin("base-plugin");
Map<String, PluginInfo> plugins = new HashMap<>();
plugins.put(pluginWithoutBase.getKey(), pluginWithoutBase);
plugins.put(basePlugin.getKey(), basePlugin);
plugins.put(pluginWithBase.getKey(), pluginWithBase);
var underTest = new PluginRequirementsValidator<>(plugins);
assertThat(underTest.isCompatible(pluginWithoutBase)).isFalse();
assertThat(underTest.isCompatible(pluginWithBase)).isTrue();
assertThat(logTester.logs(Level.WARN))
.contains("Plugin plugin-without-base-plugin [plugin-without-base-plugin] is ignored"
+ " because its base plugin [not-existing-base-plugin] is not installed");
}
@Test
public void isCompatible_verifies_required_plugin_existence() {
PluginInfo requiredPlugin = new PluginInfo("required")
.setVersion(Version.create("1.2"));
PluginInfo pluginWithRequired = new PluginInfo("plugin-with-required-plugin")
.addRequiredPlugin(RequiredPlugin.parse("required:1.2"));
PluginInfo pluginWithoutRequired = new PluginInfo("plugin-without-required-plugin")
.addRequiredPlugin(RequiredPlugin.parse("notexistingrequired:1.0"));
Map<String, PluginInfo> plugins = new HashMap<>();
plugins.put(requiredPlugin.getKey(), requiredPlugin);
plugins.put(pluginWithRequired.getKey(), pluginWithRequired);
plugins.put(pluginWithoutRequired.getKey(), pluginWithoutRequired);
var underTest = new PluginRequirementsValidator<>(plugins);
assertThat(underTest.isCompatible(pluginWithoutRequired)).isFalse();
assertThat(underTest.isCompatible(pluginWithRequired)).isTrue();
assertThat(logTester.logs(Level.WARN))
.contains("Plugin plugin-without-required-plugin [plugin-without-required-plugin] is ignored"
+ " because the required plugin [notexistingrequired] is not installed");
}
@Test
public void isCompatible_verifies_required_plugins_version() {
PluginInfo requiredPlugin = new PluginInfo("required")
.setVersion(Version.create("1.2"));
PluginInfo pluginWithRequired = new PluginInfo("plugin-with-required-plugin")
.addRequiredPlugin(RequiredPlugin.parse("required:0.8"));
PluginInfo pluginWithoutRequired = new PluginInfo("plugin-without-required-plugin")
.addRequiredPlugin(RequiredPlugin.parse("required:1.5"));
Map<String, PluginInfo> plugins = new HashMap<>();
plugins.put(requiredPlugin.getKey(), requiredPlugin);
plugins.put(pluginWithRequired.getKey(), pluginWithRequired);
plugins.put(pluginWithoutRequired.getKey(), pluginWithoutRequired);
var underTest = new PluginRequirementsValidator<>(plugins);
assertThat(underTest.isCompatible(pluginWithoutRequired)).isFalse();
assertThat(underTest.isCompatible(pluginWithRequired)).isTrue();
assertThat(logTester.logs(Level.WARN))
.contains("Plugin plugin-without-required-plugin [plugin-without-required-plugin] is ignored"
+ " because the version 1.5 of required plugin [required] is not installed");
}
}
| 5,519 | 42.125 | 99 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/plugins/ServerExtensionInstallerTest.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;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.sonar.api.Plugin;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
import org.sonar.api.config.Configuration;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.Version;
import org.sonar.core.platform.ListContainer;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ServerExtensionInstallerTest {
private SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.parse("8.0"), SonarQubeSide.SERVER, SonarEdition.COMMUNITY);
private TestPluginRepository pluginRepository = new TestPluginRepository();
private TestServerExtensionInstaller underTest = new TestServerExtensionInstaller(sonarRuntime, pluginRepository);
@Test
public void add_plugin_to_container() {
PluginInfo fooPluginInfo = newPlugin("foo", "Foo");
Plugin fooPlugin = mock(Plugin.class);
pluginRepository.add(fooPluginInfo, fooPlugin);
ListContainer componentContainer = new ListContainer();
underTest.installExtensions(componentContainer);
assertThat(componentContainer.getAddedObjects()).contains(fooPlugin);
}
private static PluginInfo newPlugin(String key, String name) {
PluginInfo plugin = mock(PluginInfo.class);
when(plugin.getKey()).thenReturn(key);
when(plugin.getName()).thenReturn(name);
return plugin;
}
private static class TestPluginRepository implements PluginRepository {
private final Map<String, PluginInfo> pluginsInfoMap = new HashMap<>();
private final Map<String, Plugin> pluginsMap = new HashMap<>();
void add(PluginInfo pluginInfo, Plugin plugin) {
pluginsInfoMap.put(pluginInfo.getKey(), pluginInfo);
pluginsMap.put(pluginInfo.getKey(), plugin);
}
@Override
public Collection<PluginInfo> getPluginInfos() {
return pluginsInfoMap.values();
}
@Override
public PluginInfo getPluginInfo(String key) {
if (!pluginsMap.containsKey(key)) {
throw new IllegalArgumentException();
}
return pluginsInfoMap.get(key);
}
@Override
public Plugin getPluginInstance(String key) {
if (!pluginsMap.containsKey(key)) {
throw new IllegalArgumentException();
}
return pluginsMap.get(key);
}
@Override
public Collection<Plugin> getPluginInstances() {
return pluginsMap.values();
}
@Override
public boolean hasPlugin(String key) {
return pluginsMap.containsKey(key);
}
}
private static class TestServerExtensionInstaller extends ServerExtensionInstaller {
protected TestServerExtensionInstaller(SonarRuntime sonarRuntime, PluginRepository pluginRepository) {
super(mock(Configuration.class), sonarRuntime, pluginRepository, singleton(ServerSide.class));
}
}
}
| 4,036 | 33.801724 | 136 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/project/DefaultBranchNameResolverTest.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;
import java.util.Optional;
import org.junit.Test;
import org.sonar.api.config.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.core.config.CorePropertyDefinitions.SONAR_PROJECTCREATION_MAINBRANCHNAME;
public class DefaultBranchNameResolverTest {
@Test
public void getEffectiveMainBranchName_givenEmptyConfiguration_returnMain() {
Configuration config = mock(Configuration.class);
DefaultBranchNameResolver defaultBranchNameResolver = new DefaultBranchNameResolver(config);
String effectiveMainBranchName = defaultBranchNameResolver.getEffectiveMainBranchName();
assertThat(effectiveMainBranchName).isEqualTo("main");
}
@Test
public void getEffectiveMainBranchName_givenDevelopInConfiguration_returnDevelop() {
Configuration config = mock(Configuration.class);
when(config.get(SONAR_PROJECTCREATION_MAINBRANCHNAME)).thenReturn(Optional.of("develop"));
DefaultBranchNameResolver defaultBranchNameResolver = new DefaultBranchNameResolver(config);
String effectiveMainBranchName = defaultBranchNameResolver.getEffectiveMainBranchName();
assertThat(effectiveMainBranchName).isEqualTo("develop");
}
}
| 2,155 | 40.461538 | 97 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/project/ProjectTest.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;
import org.junit.Test;
import org.sonar.db.entity.EntityDto;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ProjectTest {
@Test
public void test_bean_without_description() {
Project project1 = new Project("U1", "K1", "N1", null, emptyList());
Project project2 = new Project("U1", "K1", "N1", null, emptyList());
assertThat(project1.getUuid()).isEqualTo(project2.getUuid()).isEqualTo("U1");
assertThat(project1.getKey()).isEqualTo(project2.getKey()).isEqualTo("K1");
assertThat(project1.getName()).isEqualTo(project2.getName()).isEqualTo("N1");
assertThat(project1.getDescription()).isEqualTo(project2.getDescription()).isNull();
assertThat(project1.toString())
.isEqualTo(project2.toString())
.isEqualTo("Project{uuid='U1', key='K1', name='N1', description=null}");
}
@Test
public void test_bean_with_description() {
Project project1 = new Project("U1", "K1", "N1", "D1", emptyList());
assertThat(project1.getUuid()).isEqualTo("U1");
assertThat(project1.getKey()).isEqualTo("K1");
assertThat(project1.getName()).isEqualTo("N1");
assertThat(project1.getDescription()).isEqualTo("D1");
assertThat(project1.toString())
.isEqualTo(project1.toString())
.isEqualTo("Project{uuid='U1', key='K1', name='N1', description='D1'}");
}
@Test
public void from_whenPortfolioPassed_shouldNotReturnNullFields() {
EntityDto entity = mock(EntityDto.class);
when(entity.getUuid()).thenReturn("U1");
when(entity.getKey()).thenReturn("K1");
when(entity.getName()).thenReturn("N1");
when(entity.getDescription()).thenReturn("D1");
Project underTest = Project.from(entity);
assertThat(underTest.getUuid()).isEqualTo("U1");
assertThat(underTest.getKey()).isEqualTo("K1");
assertThat(underTest.getName()).isEqualTo("N1");
assertThat(underTest.getDescription()).isEqualTo("D1");
assertThat(underTest.toString())
.isEqualTo(underTest.toString())
.isEqualTo("Project{uuid='U1', key='K1', name='N1', description='D1'}");
}
@Test
public void test_equals_and_hashCode() {
Project project1 = new Project("U1", "K1", "N1", null, emptyList());
Project project2 = new Project("U1", "K1", "N1", "D1", emptyList());
assertThat(project1).isEqualTo(project1)
.isNotNull()
.isNotEqualTo(new Object())
.isEqualTo(new Project("U1", "K1", "N1", null, emptyList()))
.isNotEqualTo(new Project("U1", "K2", "N1", null, emptyList()))
.isNotEqualTo(new Project("U1", "K1", "N2", null, emptyList()))
.isEqualTo(project2);
assertThat(project1).hasSameHashCodeAs(project1);
assertThat(project1.hashCode()).isNotEqualTo(new Object().hashCode());
assertThat(project1).hasSameHashCodeAs(new Project("U1", "K1", "N1", null, emptyList()));
assertThat(project1.hashCode()).isNotEqualTo(new Project("U1", "K2", "N1", null, emptyList()).hashCode());
assertThat(project1.hashCode()).isNotEqualTo(new Project("U1", "K1", "N2", null, emptyList()).hashCode());
assertThat(project1).hasSameHashCodeAs(project2);
}
}
| 4,123 | 39.038835 | 110 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/property/InternalPropertiesImplTest.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.property;
import java.util.Optional;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.junit.Before;
import org.junit.Test;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.property.InternalPropertiesDao;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class InternalPropertiesImplTest {
private static final String EMPTY_STRING = "";
public static final String SOME_VALUE = "a value";
public static final String SOME_KEY = "some key";
private DbClient dbClient = mock(DbClient.class);
private DbSession dbSession = mock(DbSession.class);
private InternalPropertiesDao internalPropertiesDao = mock(InternalPropertiesDao.class);
private InternalPropertiesImpl underTest = new InternalPropertiesImpl(dbClient);
@Before
public void setUp() {
when(dbClient.openSession(false)).thenReturn(dbSession);
when(dbClient.internalPropertiesDao()).thenReturn(internalPropertiesDao);
}
@Test
public void reads_throws_IAE_if_key_is_null() {
expectKeyNullOrEmptyIAE(() -> underTest.read(null));
}
@Test
public void reads_throws_IAE_if_key_is_empty() {
expectKeyNullOrEmptyIAE(() -> underTest.read(EMPTY_STRING));
}
@Test
public void reads_returns_optional_from_DAO() {
Optional<String> value = Optional.of("bablabla");
when(internalPropertiesDao.selectByKey(dbSession, SOME_KEY)).thenReturn(value);
assertThat(underTest.read(SOME_KEY)).isSameAs(value);
}
@Test
public void write_throws_IAE_if_key_is_null() {
expectKeyNullOrEmptyIAE(() -> underTest.write(null, SOME_VALUE));
}
@Test
public void writes_throws_IAE_if_key_is_empty() {
expectKeyNullOrEmptyIAE(() -> underTest.write(EMPTY_STRING, SOME_VALUE));
}
@Test
public void write_calls_dao_saveAsEmpty_when_value_is_null() {
underTest.write(SOME_KEY, null);
verify(internalPropertiesDao).saveAsEmpty(dbSession, SOME_KEY);
verify(dbSession).commit();
}
@Test
public void write_calls_dao_saveAsEmpty_when_value_is_empty() {
underTest.write(SOME_KEY, EMPTY_STRING);
verify(internalPropertiesDao).saveAsEmpty(dbSession, SOME_KEY);
verify(dbSession).commit();
}
@Test
public void write_calls_dao_save_when_value_is_neither_null_nor_empty() {
underTest.write(SOME_KEY, SOME_VALUE);
verify(internalPropertiesDao).save(dbSession, SOME_KEY, SOME_VALUE);
verify(dbSession).commit();
}
private void expectKeyNullOrEmptyIAE(ThrowingCallable callback) {
assertThatThrownBy(callback)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("key can't be null nor empty");
}
}
| 3,720 | 32.223214 | 90 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/ConditionComparatorTest.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 java.util.Arrays;
import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.RELIABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.SQALE_RATING_KEY;
public class ConditionComparatorTest {
@Test
public void sort_by_hardcoded_metric_keys_then_alphabetically() {
ConditionComparator<String> comparator = new ConditionComparator<>(x -> x);
List<String> conditions = Arrays.asList(NEW_DUPLICATED_LINES_DENSITY_KEY, RELIABILITY_RATING_KEY, "rule1", SQALE_RATING_KEY, "abc",
NEW_SECURITY_RATING_KEY, "metric", NEW_COVERAGE_KEY);
conditions.sort(comparator);
assertThat(conditions).contains(RELIABILITY_RATING_KEY, NEW_SECURITY_RATING_KEY, SQALE_RATING_KEY,
NEW_COVERAGE_KEY, "abc", "metric", "rule1");
}
}
| 1,966 | 43.704545 | 135 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/ConditionEvaluatorTest.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 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 javax.annotation.Nullable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.measures.Metric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.measures.Metric.ValueType.BOOL;
import static org.sonar.api.measures.Metric.ValueType.DATA;
import static org.sonar.api.measures.Metric.ValueType.DISTRIB;
import static org.sonar.api.measures.Metric.ValueType.STRING;
@RunWith(DataProviderRunner.class)
public class ConditionEvaluatorTest {
@Test
public void GREATER_THAN_double() {
test(new FakeMeasure(10.1d), Condition.Operator.GREATER_THAN, "10.2", EvaluatedCondition.EvaluationStatus.OK, "10.1");
test(new FakeMeasure(10.2d), Condition.Operator.GREATER_THAN, "10.2", EvaluatedCondition.EvaluationStatus.OK, "10.2");
test(new FakeMeasure(10.3d), Condition.Operator.GREATER_THAN, "10.2", EvaluatedCondition.EvaluationStatus.ERROR, "10.3");
}
@Test
public void LESS_THAN_double() {
test(new FakeMeasure(10.1d), Condition.Operator.LESS_THAN, "10.2", EvaluatedCondition.EvaluationStatus.ERROR, "10.1");
test(new FakeMeasure(10.2d), Condition.Operator.LESS_THAN, "10.2", EvaluatedCondition.EvaluationStatus.OK, "10.2");
test(new FakeMeasure(10.3d), Condition.Operator.LESS_THAN, "10.2", EvaluatedCondition.EvaluationStatus.OK, "10.3");
}
@Test
public void GREATER_THAN_int() {
test(new FakeMeasure(10), Condition.Operator.GREATER_THAN, "9", EvaluatedCondition.EvaluationStatus.ERROR, "10");
test(new FakeMeasure(10), Condition.Operator.GREATER_THAN, "10", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10), Condition.Operator.GREATER_THAN, "11", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10), Condition.Operator.GREATER_THAN, "9", EvaluatedCondition.EvaluationStatus.ERROR, "10");
test(new FakeMeasure(10), Condition.Operator.GREATER_THAN, "10", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10), Condition.Operator.GREATER_THAN, "11", EvaluatedCondition.EvaluationStatus.OK, "10");
}
@Test
public void LESS_THAN_int() {
test(new FakeMeasure(10), Condition.Operator.LESS_THAN, "9", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10), Condition.Operator.LESS_THAN, "10", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10), Condition.Operator.LESS_THAN, "11", EvaluatedCondition.EvaluationStatus.ERROR, "10");
test(new FakeMeasure(10), Condition.Operator.LESS_THAN, "9", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10), Condition.Operator.LESS_THAN, "10", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10), Condition.Operator.LESS_THAN, "11", EvaluatedCondition.EvaluationStatus.ERROR, "10");
}
@Test
public void GREATER_THAN_long() {
test(new FakeMeasure(10L), Condition.Operator.GREATER_THAN, "9", EvaluatedCondition.EvaluationStatus.ERROR, "10");
test(new FakeMeasure(10L), Condition.Operator.GREATER_THAN, "10", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10L), Condition.Operator.GREATER_THAN, "11", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10L), Condition.Operator.GREATER_THAN, "9", EvaluatedCondition.EvaluationStatus.ERROR, "10");
test(new FakeMeasure(10L), Condition.Operator.GREATER_THAN, "10", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10L), Condition.Operator.GREATER_THAN, "11", EvaluatedCondition.EvaluationStatus.OK, "10");
}
@Test
public void LESS_THAN_long() {
test(new FakeMeasure(10L), Condition.Operator.LESS_THAN, "9", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10L), Condition.Operator.LESS_THAN, "10", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10L), Condition.Operator.LESS_THAN, "11", EvaluatedCondition.EvaluationStatus.ERROR, "10");
test(new FakeMeasure(10L), Condition.Operator.LESS_THAN, "9", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10L), Condition.Operator.LESS_THAN, "10", EvaluatedCondition.EvaluationStatus.OK, "10");
test(new FakeMeasure(10L), Condition.Operator.LESS_THAN, "11", EvaluatedCondition.EvaluationStatus.ERROR, "10");
}
@Test
public void evaluate_throws_IAE_if_fail_to_parse_threshold() {
assertThatThrownBy(() -> test(new FakeMeasure(10), Condition.Operator.LESS_THAN, "9bar", EvaluatedCondition.EvaluationStatus.ERROR, "10da"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Quality Gate: unable to parse threshold '9bar' to compare against foo");
}
@Test
public void no_value_present() {
test(new FakeMeasure((Integer) null), Condition.Operator.LESS_THAN, "9", EvaluatedCondition.EvaluationStatus.OK, null);
test(null, Condition.Operator.LESS_THAN, "9", EvaluatedCondition.EvaluationStatus.OK, null);
}
@Test
@UseDataProvider("unsupportedMetricTypes")
public void fail_when_condition_is_on_unsupported_metric(Metric.ValueType metricType) {
assertThatThrownBy(() -> test(new FakeMeasure(metricType), Condition.Operator.LESS_THAN, "9", EvaluatedCondition.EvaluationStatus.OK, "10"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("Condition is not allowed for type %s", metricType));
}
@DataProvider
public static Object[][] unsupportedMetricTypes() {
return new Object[][] {
{BOOL},
{STRING},
{DATA},
{DISTRIB}
};
}
private void test(@Nullable QualityGateEvaluator.Measure measure, Condition.Operator operator, String errorThreshold, EvaluatedCondition.EvaluationStatus expectedStatus,
@Nullable String expectedValue) {
Condition condition = new Condition("foo", operator, errorThreshold);
EvaluatedCondition result = ConditionEvaluator.evaluate(condition, new FakeMeasures(measure));
assertThat(result.getStatus()).isEqualTo(expectedStatus);
if (expectedValue == null) {
assertThat(result.getValue()).isNotPresent();
} else {
assertThat(result.getValue()).hasValue(expectedValue);
}
}
private static class FakeMeasures implements QualityGateEvaluator.Measures {
private final QualityGateEvaluator.Measure measure;
FakeMeasures(@Nullable QualityGateEvaluator.Measure measure) {
this.measure = measure;
}
@Override
public Optional<QualityGateEvaluator.Measure> get(String metricKey) {
return Optional.ofNullable(measure);
}
}
}
| 7,701 | 48.057325 | 171 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/ConditionTest.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 java.util.Arrays;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ConditionTest {
private static final String METRIC_KEY = "metric_key";
private static final Condition.Operator OPERATOR = Condition.Operator.GREATER_THAN;
private static final String ERROR_THRESHOLD = "2";
private Condition underTest = new Condition(METRIC_KEY, OPERATOR, ERROR_THRESHOLD);
@Test
public void constructor_throws_NPE_if_metricKey_is_null() {
assertThatThrownBy(() -> new Condition(null, OPERATOR, ERROR_THRESHOLD))
.isInstanceOf(NullPointerException.class)
.hasMessage("metricKey can't be null");
}
@Test
public void constructor_throws_NPE_if_operator_is_null() {
assertThatThrownBy(() -> new Condition(METRIC_KEY, null, ERROR_THRESHOLD))
.isInstanceOf(NullPointerException.class)
.hasMessage("operator can't be null");
}
@Test
public void constructor_throws_NPE_if_errorThreshold_is_null() {
assertThatThrownBy(() -> new Condition(METRIC_KEY, OPERATOR, null))
.isInstanceOf(NullPointerException.class)
.hasMessage("errorThreshold can't be null");
}
@Test
public void verify_getters() {
assertThat(underTest.getMetricKey()).isEqualTo(METRIC_KEY);
assertThat(underTest.getOperator()).isEqualTo(OPERATOR);
assertThat(underTest.getErrorThreshold()).contains(ERROR_THRESHOLD);
}
@Test
public void toString_is_override() {
assertThat(underTest.toString())
.isEqualTo("Condition{metricKey='metric_key', operator=GREATER_THAN, errorThreshold='2'}");
}
@Test
public void equals_is_based_on_all_fields() {
assertThat(underTest)
.isEqualTo(underTest)
.isNotNull()
.isNotEqualTo(new Object())
.isEqualTo(new Condition(METRIC_KEY, OPERATOR, ERROR_THRESHOLD))
.isNotEqualTo(new Condition("other_metric_key", OPERATOR, ERROR_THRESHOLD));
Arrays.stream(Condition.Operator.values())
.filter(s -> !OPERATOR.equals(s))
.forEach(otherOperator -> assertThat(underTest)
.isNotEqualTo(new Condition(METRIC_KEY, otherOperator, ERROR_THRESHOLD)));
assertThat(underTest).isNotEqualTo(new Condition(METRIC_KEY, OPERATOR, "other_error_threshold"));
}
@Test
public void hashcode_is_based_on_all_fields() {
assertThat(underTest).hasSameHashCodeAs(underTest);
assertThat(underTest.hashCode()).isNotEqualTo(new Object().hashCode());
assertThat(underTest).hasSameHashCodeAs(new Condition(METRIC_KEY, OPERATOR, ERROR_THRESHOLD));
assertThat(underTest.hashCode()).isNotEqualTo(new Condition("other_metric_key", OPERATOR, ERROR_THRESHOLD).hashCode());
Arrays.stream(Condition.Operator.values())
.filter(s -> !OPERATOR.equals(s))
.forEach(otherOperator -> assertThat(underTest.hashCode())
.isNotEqualTo(new Condition(METRIC_KEY, otherOperator, ERROR_THRESHOLD).hashCode()));
assertThat(underTest.hashCode()).isNotEqualTo(new Condition(METRIC_KEY, OPERATOR, "other_error_threshold").hashCode());
}
}
| 3,980 | 40.041237 | 123 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedConditionTest.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 static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.qualitygate.Condition.Operator.GREATER_THAN;
import static org.sonar.server.qualitygate.EvaluatedCondition.EvaluationStatus.ERROR;
import static org.sonar.server.qualitygate.EvaluatedCondition.EvaluationStatus.OK;
public class EvaluatedConditionTest {
private static final Condition CONDITION_1 = new Condition("metricKey", GREATER_THAN, "2");
private EvaluatedCondition underTest = new EvaluatedCondition(CONDITION_1, ERROR, "value");
@Test
public void constructor_throws_NPE_if_condition_is_null() {
assertThatThrownBy(() -> new EvaluatedCondition(null, ERROR, "value"))
.isInstanceOf(NullPointerException.class)
.hasMessage("condition can't be null");
}
@Test
public void constructor_throws_NPE_if_EvaluationStatus_is_null() {
assertThatThrownBy(() -> new EvaluatedCondition(CONDITION_1, null, "value"))
.isInstanceOf(NullPointerException.class)
.hasMessage("status can't be null");
}
@Test
public void constructor_accepts_null_value() {
EvaluatedCondition underTest = new EvaluatedCondition(CONDITION_1, ERROR, null);
assertThat(underTest.getValue()).isEmpty();
}
@Test
public void verify_getters() {
EvaluatedCondition underTest = new EvaluatedCondition(CONDITION_1, ERROR, "value");
assertThat(underTest.getCondition()).isEqualTo(CONDITION_1);
assertThat(underTest.getStatus()).isEqualTo(ERROR);
assertThat(underTest.getValue()).contains("value");
}
@Test
public void override_toString() {
assertThat(underTest).hasToString("EvaluatedCondition{condition=" +
"Condition{metricKey='metricKey', operator=GREATER_THAN, errorThreshold='2'}, " +
"status=ERROR, value='value'}");
}
@Test
public void toString_does_not_quote_null_value() {
EvaluatedCondition underTest = new EvaluatedCondition(CONDITION_1, ERROR, null);
assertThat(underTest).hasToString("EvaluatedCondition{condition=" +
"Condition{metricKey='metricKey', operator=GREATER_THAN, errorThreshold='2'}, " +
"status=ERROR, value=null}");
}
@Test
public void equals_is_based_on_all_fields() {
assertThat(underTest)
.isEqualTo(underTest)
.isEqualTo(new EvaluatedCondition(CONDITION_1, ERROR, "value"))
.isNotNull()
.isNotEqualTo(new Object())
.isNotEqualTo(new EvaluatedCondition(new Condition("other_metric", GREATER_THAN, "a"), ERROR, "value"))
.isNotEqualTo(new EvaluatedCondition(CONDITION_1, OK, "value"))
.isNotEqualTo(new EvaluatedCondition(CONDITION_1, ERROR, null))
.isNotEqualTo(new EvaluatedCondition(CONDITION_1, ERROR, "other_value"));
}
@Test
public void hashcode_is_based_on_all_fields() {
assertThat(underTest)
.hasSameHashCodeAs(underTest)
.hasSameHashCodeAs(new EvaluatedCondition(CONDITION_1, ERROR, "value"));
assertThat(underTest.hashCode()).isNotEqualTo(new Object().hashCode())
.isNotEqualTo(new EvaluatedCondition(new Condition("other_metric", GREATER_THAN, "a"), ERROR, "value").hashCode())
.isNotEqualTo(new EvaluatedCondition(CONDITION_1, OK, "value").hashCode())
.isNotEqualTo(new EvaluatedCondition(CONDITION_1, ERROR, null).hashCode())
.isNotEqualTo(new EvaluatedCondition(CONDITION_1, ERROR, "other_value").hashCode());
}
}
| 4,328 | 39.839623 | 120 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedQualityGateTest.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 com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric.Level;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.server.qualitygate.EvaluatedQualityGate.newBuilder;
public class EvaluatedQualityGateTest {
private static final String QUALITY_GATE_ID = "qg_id";
private static final String QUALITY_GATE_NAME = "qg_name";
private static final QualityGate NO_CONDITION_QUALITY_GATE = new QualityGate(QUALITY_GATE_ID, QUALITY_GATE_NAME, emptySet());
private static final Condition CONDITION_1 = new Condition("metric_key_1", Condition.Operator.LESS_THAN, "2");
private static final Condition CONDITION_2 = new Condition("a_metric", Condition.Operator.GREATER_THAN, "6");
private static final Condition CONDITION_3 = new Condition(CoreMetrics.NEW_MAINTAINABILITY_RATING_KEY, Condition.Operator.GREATER_THAN, "6");
private static final QualityGate ONE_CONDITION_QUALITY_GATE = new QualityGate(QUALITY_GATE_ID, QUALITY_GATE_NAME, singleton(CONDITION_1));
private static final QualityGate ALL_CONDITIONS_QUALITY_GATE = new QualityGate(QUALITY_GATE_ID, QUALITY_GATE_NAME,
new HashSet<>(Arrays.asList(CONDITION_1, CONDITION_2, CONDITION_3)));
private final Random random = new Random();
private final Level randomStatus = Level.values()[random.nextInt(Level.values().length)];
private final EvaluatedCondition.EvaluationStatus randomEvaluationStatus = EvaluatedCondition.EvaluationStatus.values()[random
.nextInt(EvaluatedCondition.EvaluationStatus.values().length)];
private final String randomValue = random.nextBoolean() ? null : RandomStringUtils.randomAlphanumeric(3);
private EvaluatedQualityGate.Builder builder = newBuilder();
@Test
public void build_fails_with_NPE_if_status_not_set() {
builder.setQualityGate(NO_CONDITION_QUALITY_GATE);
assertThatThrownBy(() -> builder.build())
.isInstanceOf(NullPointerException.class)
.hasMessage("status can't be null");
}
@Test
public void addCondition_fails_with_NPE_if_condition_is_null() {
assertThatThrownBy(() -> builder.addEvaluatedCondition(null, EvaluatedCondition.EvaluationStatus.ERROR, "a_value"))
.isInstanceOf(NullPointerException.class)
.hasMessage("condition can't be null");
}
@Test
public void addCondition_fails_with_NPE_if_status_is_null() {
assertThatThrownBy(() -> builder.addEvaluatedCondition(new Condition("metric_key", Condition.Operator.LESS_THAN, "2"), null, "a_value"))
.isInstanceOf(NullPointerException.class)
.hasMessage("status can't be null");
}
@Test
public void addCondition_accepts_null_value() {
builder.addEvaluatedCondition(CONDITION_1, EvaluatedCondition.EvaluationStatus.NO_VALUE, null);
assertThat(builder.getEvaluatedConditions())
.containsOnly(new EvaluatedCondition(CONDITION_1, EvaluatedCondition.EvaluationStatus.NO_VALUE, null));
}
@Test
public void getEvaluatedConditions_returns_empty_with_no_condition_added_to_builder() {
assertThat(builder.getEvaluatedConditions()).isEmpty();
}
@Test
public void build_fails_with_IAE_if_condition_added_and_no_on_QualityGate() {
builder.setQualityGate(NO_CONDITION_QUALITY_GATE)
.setStatus(randomStatus)
.addEvaluatedCondition(CONDITION_1, randomEvaluationStatus, randomValue);
assertThatThrownBy(() -> builder.build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Evaluation provided for unknown conditions: [" + CONDITION_1 + "]");
}
@Test
public void build_fails_with_IAE_if_condition_is_missing_for_one_defined_in_QualityGate() {
builder.setQualityGate(ONE_CONDITION_QUALITY_GATE)
.setStatus(randomStatus);
assertThatThrownBy(() -> builder.build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Evaluation missing for the following conditions: [" + CONDITION_1 + "]");
}
@Test
public void getEvaluatedConditions_is_sorted() {
EvaluatedQualityGate underTest = builder
.setQualityGate(ALL_CONDITIONS_QUALITY_GATE)
.setStatus(randomStatus)
.addEvaluatedCondition(CONDITION_1, randomEvaluationStatus, randomValue)
.addEvaluatedCondition(CONDITION_2, randomEvaluationStatus, randomValue)
.addEvaluatedCondition(CONDITION_3, randomEvaluationStatus, randomValue)
.build();
assertThat(underTest.getQualityGate()).isEqualTo(ALL_CONDITIONS_QUALITY_GATE);
assertThat(underTest.getStatus()).isEqualTo(randomStatus);
assertThat(underTest.getEvaluatedConditions()).extracting(c -> c.getCondition().getMetricKey())
.contains(CONDITION_3.getMetricKey(), CONDITION_2.getMetricKey(), CONDITION_1.getMetricKey());
}
@Test
public void verify_getters() {
EvaluatedQualityGate underTest = builder
.setQualityGate(ONE_CONDITION_QUALITY_GATE)
.setStatus(randomStatus)
.addEvaluatedCondition(CONDITION_1, randomEvaluationStatus, randomValue)
.build();
assertThat(underTest.getQualityGate()).isEqualTo(ONE_CONDITION_QUALITY_GATE);
assertThat(underTest.getStatus()).isEqualTo(randomStatus);
assertThat(underTest.getEvaluatedConditions())
.containsOnly(new EvaluatedCondition(CONDITION_1, randomEvaluationStatus, randomValue));
}
@Test
public void verify_getters_when_no_condition() {
EvaluatedQualityGate underTest = builder
.setQualityGate(NO_CONDITION_QUALITY_GATE)
.setStatus(randomStatus)
.build();
assertThat(underTest.getQualityGate()).isEqualTo(NO_CONDITION_QUALITY_GATE);
assertThat(underTest.getStatus()).isEqualTo(randomStatus);
assertThat(underTest.getEvaluatedConditions()).isEmpty();
}
@Test
public void verify_getters_when_multiple_conditions() {
QualityGate qualityGate = new QualityGate(QUALITY_GATE_ID, QUALITY_GATE_NAME, ImmutableSet.of(CONDITION_1, CONDITION_2));
EvaluatedQualityGate underTest = builder
.setQualityGate(qualityGate)
.setStatus(randomStatus)
.addEvaluatedCondition(CONDITION_1, randomEvaluationStatus, randomValue)
.addEvaluatedCondition(CONDITION_2, EvaluatedCondition.EvaluationStatus.ERROR, "bad")
.build();
assertThat(underTest.getQualityGate()).isEqualTo(qualityGate);
assertThat(underTest.getStatus()).isEqualTo(randomStatus);
assertThat(underTest.getEvaluatedConditions()).containsOnly(
new EvaluatedCondition(CONDITION_1, randomEvaluationStatus, randomValue),
new EvaluatedCondition(CONDITION_2, EvaluatedCondition.EvaluationStatus.ERROR, "bad"));
}
@Test
public void equals_is_based_on_all_fields() {
EvaluatedQualityGate.Builder builder = this.builder
.setQualityGate(ONE_CONDITION_QUALITY_GATE)
.setStatus(Level.ERROR)
.addEvaluatedCondition(CONDITION_1, EvaluatedCondition.EvaluationStatus.ERROR, "foo");
EvaluatedQualityGate underTest = builder.build();
assertThat(underTest)
.isEqualTo(builder.build())
.isNotSameAs(builder.build())
.isNotNull()
.isNotEqualTo(new Object())
.isNotEqualTo(builder.setQualityGate(new QualityGate("other_id", QUALITY_GATE_NAME, singleton(CONDITION_1))).build())
.isNotEqualTo(builder.setQualityGate(ONE_CONDITION_QUALITY_GATE).setStatus(Level.OK).build())
.isNotEqualTo(newBuilder()
.setQualityGate(ONE_CONDITION_QUALITY_GATE)
.setStatus(Level.ERROR)
.addEvaluatedCondition(CONDITION_1, EvaluatedCondition.EvaluationStatus.OK, "foo")
.build());
}
@Test
public void hashcode_is_based_on_all_fields() {
EvaluatedQualityGate.Builder builder = this.builder
.setQualityGate(ONE_CONDITION_QUALITY_GATE)
.setStatus(Level.ERROR)
.addEvaluatedCondition(CONDITION_1, EvaluatedCondition.EvaluationStatus.ERROR, "foo");
EvaluatedQualityGate underTest = builder.build();
assertThat(underTest).hasSameHashCodeAs(builder.build());
assertThat(underTest.hashCode()).isNotSameAs(builder.build().hashCode());
assertThat(underTest.hashCode()).isNotEqualTo(new Object().hashCode());
assertThat(underTest.hashCode()).isNotEqualTo(builder.setQualityGate(new QualityGate("other_id", QUALITY_GATE_NAME, singleton(CONDITION_1))).build().hashCode());
assertThat(underTest.hashCode()).isNotEqualTo(builder.setQualityGate(ONE_CONDITION_QUALITY_GATE).setStatus(Level.OK).build().hashCode());
assertThat(underTest.hashCode()).isNotEqualTo(newBuilder()
.setQualityGate(ONE_CONDITION_QUALITY_GATE)
.setStatus(Level.ERROR)
.addEvaluatedCondition(CONDITION_1, EvaluatedCondition.EvaluationStatus.OK, "foo")
.build().hashCode());
}
}
| 9,845 | 44.795349 | 165 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/FakeMeasure.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 java.util.Optional;
import java.util.OptionalDouble;
import javax.annotation.Nullable;
import org.sonar.api.measures.Metric;
public class FakeMeasure implements QualityGateEvaluator.Measure {
private Double value;
private Metric.ValueType valueType;
private FakeMeasure() {
// nothing to do
}
public FakeMeasure(Metric.ValueType valueType) {
this.valueType = valueType;
}
public FakeMeasure(@Nullable Double value) {
this.value = value;
this.valueType = Metric.ValueType.FLOAT;
}
public FakeMeasure(@Nullable Integer value) {
this.value = value == null ? null : value.doubleValue();
this.valueType = Metric.ValueType.INT;
}
public FakeMeasure(@Nullable Long value) {
this.value = value == null ? null : value.doubleValue();
this.valueType = Metric.ValueType.MILLISEC;
}
@Override
public Metric.ValueType getType() {
return valueType;
}
@Override
public OptionalDouble getValue() {
return value == null ? OptionalDouble.empty() : OptionalDouble.of(value);
}
@Override
public Optional<String> getStringValue() {
return Optional.empty();
}
}
| 2,024 | 28.347826 | 77 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/QualityGateEvaluatorImplTest.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 com.google.common.collect.ImmutableSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.ConfigurationBridge;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.measures.Metric;
import static java.util.Collections.singleton;
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.measures.CoreMetrics.NEW_DUPLICATED_LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_MAINTAINABILITY_RATING_KEY;
public class QualityGateEvaluatorImplTest {
private final MapSettings settings = new MapSettings();
private final Configuration configuration = new ConfigurationBridge(settings);
private final QualityGateEvaluator underTest = new QualityGateEvaluatorImpl();
@Test
public void getMetricKeys_includes_by_default_new_lines() {
QualityGate gate = mock(QualityGate.class);
assertThat(underTest.getMetricKeys(gate)).containsExactly(NEW_LINES_KEY);
}
@Test
public void getMetricKeys_includes_metrics_from_qgate() {
Set<String> metricKeys = ImmutableSet.of("foo", "bar", "baz");
Set<Condition> conditions = metricKeys.stream().map(key -> {
Condition condition = mock(Condition.class);
when(condition.getMetricKey()).thenReturn(key);
return condition;
}).collect(Collectors.toSet());
QualityGate gate = mock(QualityGate.class);
when(gate.getConditions()).thenReturn(conditions);
assertThat(underTest.getMetricKeys(gate)).containsAll(metricKeys);
}
@Test
public void evaluated_conditions_are_sorted() {
Set<String> metricKeys = ImmutableSet.of("foo", "bar", NEW_MAINTAINABILITY_RATING_KEY);
Set<Condition> conditions = metricKeys.stream().map(key -> {
Condition condition = mock(Condition.class);
when(condition.getMetricKey()).thenReturn(key);
return condition;
}).collect(Collectors.toSet());
QualityGate gate = mock(QualityGate.class);
when(gate.getConditions()).thenReturn(conditions);
QualityGateEvaluator.Measures measures = mock(QualityGateEvaluator.Measures.class);
assertThat(underTest.evaluate(gate, measures, configuration).getEvaluatedConditions()).extracting(x -> x.getCondition().getMetricKey())
.containsExactly(NEW_MAINTAINABILITY_RATING_KEY, "bar", "foo");
}
@Test
public void evaluate_is_OK_for_empty_qgate() {
QualityGate gate = mock(QualityGate.class);
QualityGateEvaluator.Measures measures = mock(QualityGateEvaluator.Measures.class);
EvaluatedQualityGate evaluatedQualityGate = underTest.evaluate(gate, measures, configuration);
assertThat(evaluatedQualityGate.getStatus()).isEqualTo(Metric.Level.OK);
}
@Test
public void evaluate_is_ERROR() {
Condition condition = new Condition(NEW_MAINTAINABILITY_RATING_KEY, Condition.Operator.GREATER_THAN, "0");
QualityGate gate = mock(QualityGate.class);
when(gate.getConditions()).thenReturn(singleton(condition));
QualityGateEvaluator.Measures measures = key -> Optional.of(new FakeMeasure(1));
assertThat(underTest.evaluate(gate, measures, configuration).getStatus()).isEqualTo(Metric.Level.ERROR);
}
@Test
public void evaluate_for_small_changes() {
Condition condition = new Condition(NEW_DUPLICATED_LINES_KEY, Condition.Operator.GREATER_THAN, "0");
Map<String, QualityGateEvaluator.Measure> notSmallChange = new HashMap<>();
notSmallChange.put(NEW_DUPLICATED_LINES_KEY, new FakeMeasure(1));
notSmallChange.put(NEW_LINES_KEY, new FakeMeasure(1000));
Map<String, QualityGateEvaluator.Measure> smallChange = new HashMap<>();
smallChange.put(NEW_DUPLICATED_LINES_KEY, new FakeMeasure(1));
smallChange.put(NEW_LINES_KEY, new FakeMeasure(10));
QualityGate gate = mock(QualityGate.class);
when(gate.getConditions()).thenReturn(singleton(condition));
QualityGateEvaluator.Measures notSmallChangeMeasures = key -> Optional.ofNullable(notSmallChange.get(key));
QualityGateEvaluator.Measures smallChangeMeasures = key -> Optional.ofNullable(smallChange.get(key));
settings.setProperty(CoreProperties.QUALITY_GATE_IGNORE_SMALL_CHANGES, true);
assertThat(underTest.evaluate(gate, notSmallChangeMeasures, configuration).getStatus()).isEqualTo(Metric.Level.ERROR);
assertThat(underTest.evaluate(gate, smallChangeMeasures, configuration).getStatus()).isEqualTo(Metric.Level.OK);
settings.setProperty(CoreProperties.QUALITY_GATE_IGNORE_SMALL_CHANGES, false);
assertThat(underTest.evaluate(gate, smallChangeMeasures, configuration).getStatus()).isEqualTo(Metric.Level.ERROR);
}
}
| 5,796 | 43.937984 | 139 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/QualityGateTest.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 com.google.common.collect.ImmutableSet;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Test;
import static java.util.Collections.emptySet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class QualityGateTest {
private static final String QUALIGATE_ID = "qg_id";
private static final String QUALIGATE_NAME = "qg_name";
private static final Condition CONDITION_1 = new Condition("m1", Condition.Operator.GREATER_THAN, "1");
private static final Condition CONDITION_2 = new Condition("m2", Condition.Operator.LESS_THAN, "2");
private QualityGate underTest = new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, ImmutableSet.of(CONDITION_1, CONDITION_2));
@Test
public void constructor_fails_with_NPE_if_id_is_null() {
assertThatThrownBy(() -> new QualityGate(null, "name", emptySet()))
.isInstanceOf(NullPointerException.class)
.hasMessage("id can't be null");
}
@Test
public void constructor_fails_with_NPE_if_name_is_null() {
assertThatThrownBy(() -> new QualityGate("id", null, emptySet()))
.isInstanceOf(NullPointerException.class)
.hasMessage("name can't be null");
}
@Test
public void constructor_fails_with_NPE_if_conditions_is_null() {
assertThatThrownBy(() -> new QualityGate("id", "name", null))
.isInstanceOf(NullPointerException.class)
.hasMessage("conditions can't be null");
}
@Test
public void constructor_fails_with_NPE_if_conditions_contains_null() {
Random random = new Random();
Set<Condition> conditions = Stream.of(
IntStream.range(0, random.nextInt(5))
.mapToObj(i -> new Condition("m_before_" + i, Condition.Operator.GREATER_THAN, "10")),
Stream.of((Condition) null),
IntStream.range(0, random.nextInt(5))
.mapToObj(i -> new Condition("m_after_" + i, Condition.Operator.GREATER_THAN, "10")))
.flatMap(s -> s)
.collect(Collectors.toSet());
assertThatThrownBy(() -> new QualityGate("id", "name", conditions))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("condition can't be null");
}
@Test
public void verify_getters() {
assertThat(underTest.getId()).isEqualTo(QUALIGATE_ID);
assertThat(underTest.getName()).isEqualTo(QUALIGATE_NAME);
assertThat(underTest.getConditions()).containsOnly(CONDITION_1, CONDITION_2);
}
@Test
public void toString_is_override() {
QualityGate underTest = new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, ImmutableSet.of(CONDITION_2));
assertThat(underTest).hasToString("QualityGate{id=qg_id, name='qg_name', conditions=[" +
"Condition{metricKey='m2', operator=LESS_THAN, errorThreshold='2'}" +
"]}");
}
@Test
public void equals_is_based_on_all_fields() {
assertThat(underTest)
.isEqualTo(underTest)
.isEqualTo(new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, ImmutableSet.of(CONDITION_2, CONDITION_1)))
.isNotNull()
.isNotEqualTo(new Object())
.isNotEqualTo(new QualityGate("other_id", QUALIGATE_NAME, ImmutableSet.of(CONDITION_2, CONDITION_1)))
.isNotEqualTo(new QualityGate(QUALIGATE_ID, "other_name", ImmutableSet.of(CONDITION_2, CONDITION_1)))
.isNotEqualTo(new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, emptySet()))
.isNotEqualTo(new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, ImmutableSet.of(CONDITION_1)))
.isNotEqualTo(new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, ImmutableSet.of(CONDITION_2)))
.isNotEqualTo(
new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, ImmutableSet.of(CONDITION_1, CONDITION_2, new Condition("new", Condition.Operator.GREATER_THAN, "a"))));
}
@Test
public void hashcode_is_based_on_all_fields() {
assertThat(underTest)
.hasSameHashCodeAs(underTest)
.hasSameHashCodeAs(new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, ImmutableSet.of(CONDITION_2, CONDITION_1)));
assertThat(underTest.hashCode()).isNotEqualTo(new Object().hashCode())
.isNotEqualTo(new QualityGate("other_id", QUALIGATE_NAME, ImmutableSet.of(CONDITION_2, CONDITION_1)).hashCode())
.isNotEqualTo(new QualityGate(QUALIGATE_ID, "other_name", ImmutableSet.of(CONDITION_2, CONDITION_1)).hashCode())
.isNotEqualTo(new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, emptySet()).hashCode())
.isNotEqualTo(new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, ImmutableSet.of(CONDITION_1)).hashCode())
.isNotEqualTo(new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, ImmutableSet.of(CONDITION_2)).hashCode())
.isNotEqualTo(
new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, ImmutableSet.of(CONDITION_1, CONDITION_2, new Condition("new", Condition.Operator.GREATER_THAN, "a"))).hashCode());
}
}
| 5,755 | 43.96875 | 169 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/notification/QGChangeEmailTemplateTest.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.notification;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.EmailSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.server.issue.notification.EmailMessage;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(DataProviderRunner.class)
public class QGChangeEmailTemplateTest {
private QGChangeEmailTemplate template;
@Before
public void setUp() {
EmailSettings configuration = mock(EmailSettings.class);
when(configuration.getServerBaseURL()).thenReturn("http://nemo.sonarsource.org");
template = new QGChangeEmailTemplate(configuration);
}
@Test
public void shouldNotFormatIfNotCorrectNotification() {
Notification notification = new Notification("other-notif");
EmailMessage message = template.format(notification);
assertThat(message, nullValue());
}
@Test
public void shouldFormatAlertWithSeveralMessages() {
Notification notification = createNotification("Failed", "violations > 4, coverage < 75%", "ERROR", "false");
EmailMessage message = template.format(notification);
assertThat(message.getMessageId(), is("alerts/45"));
assertThat(message.getSubject(), is("Quality gate status changed on \"Foo\""));
assertThat(message.getMessage(), is("" +
"Project: Foo\n" +
"Version: V1-SNAP\n" +
"Quality gate status: Failed\n" +
"\n" +
"Quality gate thresholds:\n" +
" - violations > 4\n" +
" - coverage < 75%\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/dashboard?id=org.sonar.foo:foo"));
}
@Test
public void shouldFormatAlertWithSeveralMessagesOnBranch() {
Notification notification = createNotification("Failed", "violations > 4, coverage < 75%", "ERROR", "false")
.setFieldValue("branch", "feature");
EmailMessage message = template.format(notification);
assertThat(message.getMessageId(), is("alerts/45"));
assertThat(message.getSubject(), is("Quality gate status changed on \"Foo (feature)\""));
assertThat(message.getMessage(), is("" +
"Project: Foo\n" +
"Branch: feature\n" +
"Version: V1-SNAP\n" +
"Quality gate status: Failed\n" +
"\n" +
"Quality gate thresholds:\n" +
" - violations > 4\n" +
" - coverage < 75%\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/dashboard?id=org.sonar.foo:foo&branch=feature"));
}
@Test
public void shouldFormatNewAlertWithSeveralMessages() {
Notification notification = createNotification("Failed", "violations > 4, coverage < 75%", "ERROR", "true");
EmailMessage message = template.format(notification);
assertThat(message.getMessageId(), is("alerts/45"));
assertThat(message.getSubject(), is("New quality gate threshold reached on \"Foo\""));
assertThat(message.getMessage(), is("" +
"Project: Foo\n" +
"Version: V1-SNAP\n" +
"Quality gate status: Failed\n" +
"\n" +
"New quality gate thresholds:\n" +
" - violations > 4\n" +
" - coverage < 75%\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/dashboard?id=org.sonar.foo:foo"));
}
@Test
public void shouldFormatNewAlertWithOneMessage() {
Notification notification = createNotification("Failed", "violations > 4", "ERROR", "true");
EmailMessage message = template.format(notification);
assertThat(message.getMessageId(), is("alerts/45"));
assertThat(message.getSubject(), is("New quality gate threshold reached on \"Foo\""));
assertThat(message.getMessage(), is("" +
"Project: Foo\n" +
"Version: V1-SNAP\n" +
"Quality gate status: Failed\n" +
"\n" +
"New quality gate threshold: violations > 4\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/dashboard?id=org.sonar.foo:foo"));
}
@Test
public void shouldFormatNewAlertWithoutVersion() {
Notification notification = createNotification("Failed", "violations > 4", "ERROR", "true")
.setFieldValue("projectVersion", null);
EmailMessage message = template.format(notification);
assertThat(message.getMessageId(), is("alerts/45"));
assertThat(message.getSubject(), is("New quality gate threshold reached on \"Foo\""));
assertThat(message.getMessage(), is("" +
"Project: Foo\n" +
"Quality gate status: Failed\n" +
"\n" +
"New quality gate threshold: violations > 4\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/dashboard?id=org.sonar.foo:foo"));
}
@Test
public void shouldFormatBackToGreenMessage() {
Notification notification = createNotification("Passed", "", "OK", "false");
EmailMessage message = template.format(notification);
assertThat(message.getMessageId(), is("alerts/45"));
assertThat(message.getSubject(), is("\"Foo\" is back to green"));
assertThat(message.getMessage(), is("" +
"Project: Foo\n" +
"Version: V1-SNAP\n" +
"Quality gate status: Passed\n" +
"\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/dashboard?id=org.sonar.foo:foo"));
}
@Test
public void shouldFormatNewAlertWithOneMessageOnBranch() {
Notification notification = createNotification("Failed", "violations > 4", "ERROR", "true")
.setFieldValue("branch", "feature");
EmailMessage message = template.format(notification);
assertThat(message.getMessageId(), is("alerts/45"));
assertThat(message.getSubject(), is("New quality gate threshold reached on \"Foo (feature)\""));
assertThat(message.getMessage(), is("" +
"Project: Foo\n" +
"Branch: feature\n" +
"Version: V1-SNAP\n" +
"Quality gate status: Failed\n" +
"\n" +
"New quality gate threshold: violations > 4\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/dashboard?id=org.sonar.foo:foo&branch=feature"));
}
@Test
public void shouldFormatBackToGreenMessageOnBranch() {
Notification notification = createNotification("Passed", "", "OK", "false")
.setFieldValue("branch", "feature");
EmailMessage message = template.format(notification);
assertThat(message.getMessageId(), is("alerts/45"));
assertThat(message.getSubject(), is("\"Foo (feature)\" is back to green"));
assertThat(message.getMessage(), is("" +
"Project: Foo\n" +
"Branch: feature\n" +
"Version: V1-SNAP\n" +
"Quality gate status: Passed\n" +
"\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/dashboard?id=org.sonar.foo:foo&branch=feature"));
}
@DataProvider
public static Object[][] alertTextAndFormattedText() {
return new Object[][] {
{"violations > 0", "violations > 0"},
{"violations > 1", "violations > 1"},
{"violations > 4", "violations > 4"},
{"violations > 5", "violations > 5"},
{"violations > 6", "violations > 6"},
{"violations > 10", "violations > 10"},
{"Code Coverage < 0%", "Code Coverage < 0%"},
{"Code Coverage < 1%", "Code Coverage < 1%"},
{"Code Coverage < 50%", "Code Coverage < 50%"},
{"Code Coverage < 100%", "Code Coverage < 100%"},
{"Custom metric with big number > 100000000000", "Custom metric with big number > 100000000000"},
{"Custom metric with negative number > -1", "Custom metric with negative number > -1"},
{"custom metric condition not met", "custom metric condition not met"},
{"Security Review Rating > 1", "Security Review Rating worse than A"},
{"Security Review Rating on New Code > 4", "Security Review Rating on New Code worse than D"},
{"Security Rating > 1", "Security Rating worse than A"},
{"Maintainability Rating > 3", "Maintainability Rating worse than C"},
{"Reliability Rating > 4", "Reliability Rating worse than D" }
};
}
@UseDataProvider("alertTextAndFormattedText")
@Test
public void shouldFormatNewAlertWithThresholdProperlyFormatted(String alertText, String expectedFormattedAlertText) {
Notification notification = createNotification("Failed", alertText, "ERROR", "true");
EmailMessage message = template.format(notification);
assertThat(message.getMessageId(), is("alerts/45"));
assertThat(message.getSubject(), is("New quality gate threshold reached on \"Foo\""));
assertThat(message.getMessage(), is("" +
"Project: Foo\n" +
"Version: V1-SNAP\n" +
"Quality gate status: Failed\n" +
"\n" +
"New quality gate threshold: " + expectedFormattedAlertText + "\n" +
"\n" +
"More details at: http://nemo.sonarsource.org/dashboard?id=org.sonar.foo:foo"));
}
private Notification createNotification(String alertName, String alertText, String alertLevel, String isNewAlert) {
return new Notification("alerts")
.setFieldValue("projectName", "Foo")
.setFieldValue("projectKey", "org.sonar.foo:foo")
.setFieldValue("projectId", "45")
.setFieldValue("projectVersion", "V1-SNAP")
.setFieldValue("alertName", alertName)
.setFieldValue("alertText", alertText)
.setFieldValue("alertLevel", alertLevel)
.setFieldValue("isNewAlert", isNewAlert)
.setFieldValue("ratingMetrics", "Maintainability Rating,Reliability Rating on New Code," +
"Maintainability Rating on New Code,Reliability Rating," +
"Security Rating on New Code,Security Review Rating," +
"Security Review Rating on New Code,Security Rating");
}
}
| 10,770 | 39.799242 | 119 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/notification/QGChangeNotificationHandlerTest.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.notification;
import java.util.Collections;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.server.notification.NotificationDispatcherMetadata;
import org.sonar.server.notification.NotificationManager;
import org.sonar.server.notification.email.EmailNotificationChannel;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
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;
import static org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION;
import static org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION;
import static org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER;
public class QGChangeNotificationHandlerTest {
private static final String QG_CHANGE_DISPATCHER_KEY = "NewAlerts";
private NotificationManager notificationManager = mock(NotificationManager.class);
private EmailNotificationChannel emailNotificationChannel = mock(EmailNotificationChannel.class);
private QGChangeNotificationHandler underTest = new QGChangeNotificationHandler(notificationManager, emailNotificationChannel);
@Test
public void getMetadata_returns_same_instance_as_static_method() {
assertThat(underTest.getMetadata()).containsSame(QGChangeNotificationHandler.newMetadata());
}
@Test
public void verify_qgChange_notification_dispatcher_key() {
NotificationDispatcherMetadata metadata = QGChangeNotificationHandler.newMetadata();
assertThat(metadata.getDispatcherKey()).isEqualTo(QG_CHANGE_DISPATCHER_KEY);
}
@Test
public void qgChange_notification_is_enable_at_global_level() {
NotificationDispatcherMetadata metadata = QGChangeNotificationHandler.newMetadata();
assertThat(metadata.getProperty(GLOBAL_NOTIFICATION)).isEqualTo("true");
}
@Test
public void qgChange_notification_is_enable_at_project_level() {
NotificationDispatcherMetadata metadata = QGChangeNotificationHandler.newMetadata();
assertThat(metadata.getProperty(PER_PROJECT_NOTIFICATION)).isEqualTo("true");
}
@Test
public void getNotificationClass_is_QGChangeNotification() {
assertThat(underTest.getNotificationClass()).isEqualTo(QGChangeNotification.class);
}
@Test
public void deliver_has_no_effect_if_notifications_is_empty() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
int deliver = underTest.deliver(Collections.emptyList());
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager, emailNotificationChannel);
}
@Test
public void deliver_has_no_effect_if_emailNotificationChannel_is_disabled() {
when(emailNotificationChannel.isActivated()).thenReturn(false);
Set<QGChangeNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> mock(QGChangeNotification.class))
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
notifications.forEach(Mockito::verifyNoInteractions);
}
@Test
public void deliver_has_no_effect_if_no_notification_has_projectKey() {
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<QGChangeNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> newNotification(null))
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verifyNoInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
notifications.forEach(notification -> {
verify(notification).getProjectKey();
verifyNoMoreInteractions(notification);
});
}
@Test
public void deliver_has_no_effect_if_no_notification_has_subscribed_recipients_to_QGChange_notifications() {
String projectKey = randomAlphabetic(12);
QGChangeNotification notification = newNotification(projectKey);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emptySet());
int deliver = underTest.deliver(Collections.singleton(notification));
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_ignores_notification_without_projectKey() {
String projectKey = randomAlphabetic(10);
Set<QGChangeNotification> withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(projectKey))
.collect(toSet());
Set<QGChangeNotification> noProjectKey = IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(null))
.collect(toSet());
Set<NotificationManager.EmailRecipient> emailRecipients = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> "user_" + i)
.map(login -> new NotificationManager.EmailRecipient(login, emailOf(login)))
.collect(toSet());
Set<EmailNotificationChannel.EmailDeliveryRequest> expectedRequests = emailRecipients.stream()
.flatMap(emailRecipient -> withProjectKey.stream().map(notif -> new EmailNotificationChannel.EmailDeliveryRequest(emailRecipient.email(), notif)))
.collect(toSet());
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emailRecipients);
Set<QGChangeNotification> notifications = Stream.of(withProjectKey.stream(), noProjectKey.stream())
.flatMap(t -> t)
.collect(toSet());
int deliver = underTest.deliver(notifications);
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(expectedRequests);
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_QGChange_notifications() {
String projectKey1 = randomAlphabetic(10);
String projectKey2 = randomAlphabetic(11);
Set<QGChangeNotification> notifications1 = randomSetOfNotifications(projectKey1);
Set<QGChangeNotification> notifications2 = randomSetOfNotifications(projectKey2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
Set<NotificationManager.EmailRecipient> emailRecipients1 = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> "user1_" + i)
.map(login -> new NotificationManager.EmailRecipient(login, emailOf(login)))
.collect(toSet());
Set<NotificationManager.EmailRecipient> emailRecipients2 = IntStream.range(0, 1 + new Random().nextInt(10))
.mapToObj(i -> "user2_" + i)
.map(login -> new NotificationManager.EmailRecipient(login, emailOf(login)))
.collect(toSet());
when(notificationManager.findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey1, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emailRecipients1);
when(notificationManager.findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey2, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emailRecipients2);
Set<EmailNotificationChannel.EmailDeliveryRequest> expectedRequests = Stream.concat(
emailRecipients1.stream()
.flatMap(emailRecipient -> notifications1.stream().map(notif -> new EmailNotificationChannel.EmailDeliveryRequest(emailRecipient.email(), notif))),
emailRecipients2.stream()
.flatMap(emailRecipient -> notifications2.stream().map(notif -> new EmailNotificationChannel.EmailDeliveryRequest(emailRecipient.email(), notif))))
.collect(toSet());
int deliver = underTest.deliver(Stream.concat(notifications1.stream(), notifications2.stream()).collect(toSet()));
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey1, ALL_MUST_HAVE_ROLE_USER);
verify(notificationManager).findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey2, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verify(emailNotificationChannel).deliverAll(expectedRequests);
verifyNoMoreInteractions(emailNotificationChannel);
}
@Test
public void deliver_send_notifications_to_all_subscribers_of_all_projects() {
String projectKey1 = randomAlphabetic(10);
String projectKey2 = randomAlphabetic(11);
Set<QGChangeNotification> notifications1 = randomSetOfNotifications(projectKey1);
Set<QGChangeNotification> notifications2 = randomSetOfNotifications(projectKey2);
when(emailNotificationChannel.isActivated()).thenReturn(true);
when(notificationManager.findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey1, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emptySet());
when(notificationManager.findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey2, ALL_MUST_HAVE_ROLE_USER))
.thenReturn(emptySet());
int deliver = underTest.deliver(Stream.concat(notifications1.stream(), notifications2.stream()).collect(toSet()));
assertThat(deliver).isZero();
verify(notificationManager).findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey1, ALL_MUST_HAVE_ROLE_USER);
verify(notificationManager).findSubscribedEmailRecipients(QG_CHANGE_DISPATCHER_KEY, projectKey2, ALL_MUST_HAVE_ROLE_USER);
verifyNoMoreInteractions(notificationManager);
verify(emailNotificationChannel).isActivated();
verifyNoMoreInteractions(emailNotificationChannel);
}
private static Set<QGChangeNotification> randomSetOfNotifications(@Nullable String projectKey) {
return IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newNotification(projectKey))
.collect(Collectors.toSet());
}
private static QGChangeNotification newNotification(@Nullable String projectKey) {
QGChangeNotification notification = mock(QGChangeNotification.class);
when(notification.getProjectKey()).thenReturn(projectKey);
return notification;
}
private static String emailOf(String assignee1) {
return assignee1 + "@giraffe";
}
}
| 12,294 | 47.027344 | 155 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualityprofile/ActiveRuleChangeTest.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 org.junit.Test;
import org.sonar.api.rule.RuleKey;
import org.sonar.core.util.Uuids;
import org.sonar.db.qualityprofile.ActiveRuleKey;
import org.sonar.db.qualityprofile.QProfileChangeDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.rule.RuleDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.qualityprofile.QualityProfileTesting.newQualityProfileDto;
import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.ACTIVATED;
public class ActiveRuleChangeTest {
private static final String A_USER_UUID = "A_USER_UUID";
@Test
public void toDto() {
QProfileDto profile = newQualityProfileDto();
ActiveRuleKey key = ActiveRuleKey.of(profile, RuleKey.of("P1", "R1"));
String ruleUuid = Uuids.createFast();
ActiveRuleChange underTest = new ActiveRuleChange(ACTIVATED, key, new RuleDto().setUuid(ruleUuid));
QProfileChangeDto result = underTest.toDto(A_USER_UUID);
assertThat(result.getChangeType()).isEqualTo(ACTIVATED.name());
assertThat(result.getRulesProfileUuid()).isEqualTo(profile.getRulesProfileUuid());
assertThat(result.getUserUuid()).isEqualTo(A_USER_UUID);
assertThat(result.getDataAsMap()).containsEntry("ruleUuid", ruleUuid);
}
}
| 2,148 | 39.54717 | 103 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/qualityprofile/QualityProfileTest.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.util.Date;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class QualityProfileTest {
private static final String SOME_QP_KEY = "qpKey";
private static final String SOME_QP_NAME = "qpName";
private static final String SOME_LANGUAGE_KEY = "languageKey";
private static final Date SOME_DATE = DateUtils.parseDateTimeQuietly("2010-05-18T15:50:45+0100");
private static final QualityProfile QUALITY_PROFILE = new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, SOME_LANGUAGE_KEY, SOME_DATE);
@Test
public void constructor_throws_NPE_if_qkKey_arg_is_null() {
assertThatThrownBy(() -> new QualityProfile(null, SOME_QP_NAME, SOME_LANGUAGE_KEY, SOME_DATE))
.isInstanceOf(NullPointerException.class);
}
@Test
public void constructor_throws_NPE_if_qpName_arg_is_null() {
assertThatThrownBy(() -> {
new QualityProfile(SOME_QP_KEY, null, SOME_LANGUAGE_KEY, SOME_DATE);
})
.isInstanceOf(NullPointerException.class);
}
@Test
public void constructor_throws_NPE_if_languageKey_arg_is_null() {
assertThatThrownBy(() -> {
new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, null, SOME_DATE);
})
.isInstanceOf(NullPointerException.class);
}
@Test
public void constructor_throws_NPE_if_rulesUpdatedAt_arg_is_null() {
assertThatThrownBy(() -> {
new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, SOME_LANGUAGE_KEY, null);
})
.isInstanceOf(NullPointerException.class);
}
@Test
public void verify_properties() {
assertThat(QUALITY_PROFILE.getQpKey()).isEqualTo(SOME_QP_KEY);
assertThat(QUALITY_PROFILE.getQpName()).isEqualTo(SOME_QP_NAME);
assertThat(QUALITY_PROFILE.getLanguageKey()).isEqualTo(SOME_LANGUAGE_KEY);
assertThat(QUALITY_PROFILE.getRulesUpdatedAt()).isEqualTo(SOME_DATE);
}
@Test
public void verify_getRulesUpdatedAt_keeps_object_immutable() {
assertThat(QUALITY_PROFILE.getRulesUpdatedAt()).isNotSameAs(SOME_DATE);
}
@Test
public void verify_equals() {
assertThat(QUALITY_PROFILE)
.isEqualTo(new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, SOME_LANGUAGE_KEY, SOME_DATE))
.isEqualTo(QUALITY_PROFILE)
.isNotNull();
}
@Test
public void verify_toString() {
assertThat(QUALITY_PROFILE).hasToString("QualityProfile{key=qpKey, name=qpName, language=languageKey, rulesUpdatedAt=1274194245000}");
}
}
| 3,391 | 35.085106 | 138 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/rule/CommonRuleKeysTest.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 org.junit.Test;
import org.sonar.test.TestUtils;
import static org.assertj.core.api.Assertions.assertThat;
public class CommonRuleKeysTest {
@Test
public void wonderful_test_for_commonRepositoryForLang() {
assertThat(CommonRuleKeys.commonRepositoryForLang("java")).isEqualTo("common-java");
}
@Test
public void wonderful_test_to_verify_that_this_class_is_an_helper_class() {
assertThat(TestUtils.hasOnlyPrivateConstructors(CommonRuleKeys.class)).isTrue();
}
}
| 1,367 | 33.2 | 88 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/rule/RuleDescriptionFormatterTest.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 org.junit.Test;
import org.sonar.api.rules.RuleType;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ASSESS_THE_PROBLEM_SECTION_KEY;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ROOT_CAUSE_SECTION_KEY;
import static org.sonar.db.rule.RuleDescriptionSectionDto.DEFAULT_KEY;
import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection;
import static org.sonar.db.rule.RuleDto.Format.HTML;
import static org.sonar.db.rule.RuleDto.Format.MARKDOWN;
public class RuleDescriptionFormatterTest {
private static final RuleDescriptionSectionDto HTML_SECTION = createDefaultRuleDescriptionSection("uuid", "<span class=\"example\">*md* ``description``</span>");
private static final RuleDescriptionSectionDto MARKDOWN_SECTION = createDefaultRuleDescriptionSection("uuid", "*md* ``description``");
private static final RuleDescriptionFormatter ruleDescriptionFormatter = new RuleDescriptionFormatter();
@Test
public void getMarkdownDescriptionAsHtml() {
RuleDto rule = new RuleDto().setDescriptionFormat(MARKDOWN).addRuleDescriptionSectionDto(MARKDOWN_SECTION).setType(RuleType.BUG);
String html = ruleDescriptionFormatter.getDescriptionAsHtml(rule);
assertThat(html).isEqualTo("<strong>md</strong> <code>description</code>");
}
@Test
public void getHtmlDescriptionAsIs() {
RuleDto rule = new RuleDto().setDescriptionFormat(RuleDto.Format.HTML).addRuleDescriptionSectionDto(HTML_SECTION).setType(RuleType.BUG);
String html = ruleDescriptionFormatter.getDescriptionAsHtml(rule);
assertThat(html).isEqualTo(HTML_SECTION.getContent());
}
@Test
public void getDescriptionAsHtml_ignoresAdvancedSections() {
var section1 = createRuleDescriptionSection(ROOT_CAUSE_SECTION_KEY, "<div>Root is Root</div>");
var section2 = createRuleDescriptionSection(ASSESS_THE_PROBLEM_SECTION_KEY, "<div>This is not a problem</div>");
var defaultRuleDescriptionSection = createDefaultRuleDescriptionSection("uuid_432", "default description");
RuleDto rule = new RuleDto().setDescriptionFormat(RuleDto.Format.HTML)
.setType(RuleType.SECURITY_HOTSPOT)
.addRuleDescriptionSectionDto(section1)
.addRuleDescriptionSectionDto(section2)
.addRuleDescriptionSectionDto(defaultRuleDescriptionSection);
String html = ruleDescriptionFormatter.getDescriptionAsHtml(rule);
assertThat(html).isEqualTo(defaultRuleDescriptionSection.getContent());
}
@Test
public void handleEmptyDescription() {
RuleDto rule = new RuleDto().setDescriptionFormat(RuleDto.Format.HTML).setType(RuleType.BUG);
String result = ruleDescriptionFormatter.getDescriptionAsHtml(rule);
assertThat(result).isNull();
}
@Test
public void handleNullDescriptionFormat() {
RuleDescriptionSectionDto sectionWithNullFormat = createDefaultRuleDescriptionSection("uuid", "whatever");
RuleDto rule = new RuleDto().addRuleDescriptionSectionDto(sectionWithNullFormat).setType(RuleType.BUG);
String result = ruleDescriptionFormatter.getDescriptionAsHtml(rule);
assertThat(result).isNull();
}
@Test
public void toHtmlWithNullFormat() {
RuleDescriptionSectionDto section = createRuleDescriptionSection(DEFAULT_KEY, "whatever");
String result = ruleDescriptionFormatter.toHtml(null, section);
assertThat(result).isEqualTo(section.getContent());
}
@Test
public void toHtmlWithMarkdownFormat() {
String result = ruleDescriptionFormatter.toHtml(MARKDOWN, MARKDOWN_SECTION);
assertThat(result).isEqualTo("<strong>md</strong> <code>description</code>");
}
@Test
public void toHtmlWithHtmlFormat() {
String result = ruleDescriptionFormatter.toHtml(HTML, HTML_SECTION);
assertThat(result).isEqualTo(HTML_SECTION.getContent());
}
private static RuleDescriptionSectionDto createRuleDescriptionSection(String key, String content) {
return RuleDescriptionSectionDto.builder().key(key).content(content).build();
}
}
| 5,054 | 46.242991 | 163 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleDocTest.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.index;
import org.junit.Test;
import org.sonar.db.rule.RuleDescriptionSectionContextDto;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleForIndexingDto;
import org.sonar.server.security.SecurityStandards;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.db.rule.RuleTesting.newRule;
import static org.sonar.db.rule.RuleTesting.newRuleWithoutDescriptionSection;
import static org.sonar.markdown.Markdown.convertToHtml;
import static org.sonar.server.security.SecurityStandards.fromSecurityStandards;
public class RuleDocTest {
@Test
public void ruleDocOf_mapsFieldCorrectly() {
RuleDto ruleDto = newRule();
RuleForIndexingDto ruleForIndexingDto = RuleForIndexingDto.fromRuleDto(ruleDto);
ruleForIndexingDto.setTemplateRuleKey("templateKey");
ruleForIndexingDto.setTemplateRepository("repoKey");
SecurityStandards securityStandards = fromSecurityStandards(ruleDto.getSecurityStandards());
RuleDoc ruleDoc = RuleDoc.createFrom(ruleForIndexingDto, securityStandards);
assertThat(ruleDoc.getId()).isEqualTo(ruleDto.getUuid());
assertThat(ruleDoc.key()).isEqualTo(ruleForIndexingDto.getRuleKey());
assertThat(ruleDoc.repository()).isEqualTo(ruleForIndexingDto.getRepository());
assertThat(ruleDoc.internalKey()).isEqualTo(ruleForIndexingDto.getInternalKey());
assertThat(ruleDoc.isExternal()).isEqualTo(ruleForIndexingDto.isExternal());
assertThat(ruleDoc.language()).isEqualTo(ruleForIndexingDto.getLanguage());
assertThat(ruleDoc.getCwe()).isEqualTo(securityStandards.getCwe());
assertThat(ruleDoc.getOwaspTop10()).isEqualTo(securityStandards.getOwaspTop10());
assertThat(ruleDoc.getOwaspTop10For2021()).isEqualTo(securityStandards.getOwaspTop10For2021());
assertThat(ruleDoc.getSansTop25()).isEqualTo(securityStandards.getSansTop25());
assertThat(ruleDoc.getSonarSourceSecurityCategory()).isEqualTo(securityStandards.getSqCategory());
assertThat(ruleDoc.name()).isEqualTo(ruleForIndexingDto.getName());
assertThat(ruleDoc.ruleKey()).isEqualTo(ruleForIndexingDto.getPluginRuleKey());
assertThat(ruleDoc.severity()).isEqualTo(ruleForIndexingDto.getSeverityAsString());
assertThat(ruleDoc.status()).isEqualTo(ruleForIndexingDto.getStatus());
assertThat(ruleDoc.type().name()).isEqualTo(ruleForIndexingDto.getTypeAsRuleType().name());
assertThat(ruleDoc.createdAt()).isEqualTo(ruleForIndexingDto.getCreatedAt());
assertThat(ruleDoc.getTags())
.containsAll(ruleForIndexingDto.getSystemTags())
.containsAll(ruleForIndexingDto.getTags())
.hasSize(ruleForIndexingDto.getSystemTags().size() + ruleForIndexingDto.getTags().size());
assertThat(ruleDoc.updatedAt()).isEqualTo(ruleForIndexingDto.getUpdatedAt());
assertThat(ruleDoc.templateKey().repository()).isEqualTo(ruleForIndexingDto.getTemplateRepository());
assertThat(ruleDoc.templateKey().rule()).isEqualTo(ruleForIndexingDto.getTemplateRuleKey());
}
@Test
public void ruleDocOf_whenGivenNoHtmlSections_hasEmptyStringInHtmlDescription() {
RuleDto ruleDto = newRuleWithoutDescriptionSection();
ruleDto.setDescriptionFormat(RuleDto.Format.HTML);
RuleForIndexingDto ruleForIndexingDto = RuleForIndexingDto.fromRuleDto(ruleDto);
SecurityStandards securityStandards = fromSecurityStandards(ruleDto.getSecurityStandards());
RuleDoc ruleDoc = RuleDoc.createFrom(ruleForIndexingDto, securityStandards);
assertThat(ruleDoc.htmlDescription()).isEmpty();
}
@Test
public void ruleDocOf_whenGivenMultipleHtmlSections_hasConcatenationInHtmlDescription() {
RuleDescriptionSectionDto section1 = buildRuleDescriptionSectionDto("section1", "<p>html content 1</p>");
RuleDescriptionSectionDto section2 = buildRuleDescriptionSectionDto("section2", "<p>html content 2</p>");
RuleDescriptionSectionDto section3ctx1 = buildRuleDescriptionSectionDtoWithContext("section3", "<p>html content 3.1</p>", "ctx1");
RuleDescriptionSectionDto section3ctx2 = buildRuleDescriptionSectionDtoWithContext("section3", "<p>html content 3.2</p>", "ctx2");
RuleDto ruleDto = newRule(section1, section2, section3ctx1, section3ctx2);
ruleDto.setDescriptionFormat(RuleDto.Format.HTML);
RuleForIndexingDto ruleForIndexingDto = RuleForIndexingDto.fromRuleDto(ruleDto);
SecurityStandards securityStandards = fromSecurityStandards(ruleDto.getSecurityStandards());
RuleDoc ruleDoc = RuleDoc.createFrom(ruleForIndexingDto, securityStandards);
assertThat(ruleDoc.htmlDescription())
.contains(section1.getContent())
.contains(section2.getContent())
.contains(section3ctx1.getContent())
.contains(section3ctx2.getContent())
.hasSameSizeAs(section1.getContent() + " " + section2.getContent() + " " + section3ctx1.getContent() + " " + section3ctx2.getContent());
}
@Test
public void ruleDocOf_whenGivenMultipleMarkdownSections_transformToHtmlAndConcatenatesInHtmlDescription() {
RuleDescriptionSectionDto section1 = buildRuleDescriptionSectionDto("section1", "*html content 1*");
RuleDescriptionSectionDto section2 = buildRuleDescriptionSectionDto("section2", "*html content 2*");
RuleDto ruleDto = newRule(section1, section2);
ruleDto.setDescriptionFormat(RuleDto.Format.MARKDOWN);
RuleForIndexingDto ruleForIndexingDto = RuleForIndexingDto.fromRuleDto(ruleDto);
SecurityStandards securityStandards = fromSecurityStandards(ruleDto.getSecurityStandards());
RuleDoc ruleDoc = RuleDoc.createFrom(ruleForIndexingDto, securityStandards);
assertThat(ruleDoc.htmlDescription())
.contains(convertToHtml(section1.getContent()))
.contains(convertToHtml(section2.getContent()))
.hasSameSizeAs(convertToHtml(section1.getContent()) + " " + convertToHtml(section2.getContent()));
}
private static RuleDescriptionSectionDto buildRuleDescriptionSectionDto(String key, String content) {
return RuleDescriptionSectionDto.builder().key(key).content(content).build();
}
private static RuleDescriptionSectionDto buildRuleDescriptionSectionDtoWithContext(String key, String content, String contextKey) {
return RuleDescriptionSectionDto.builder().key(key).content(content).context(RuleDescriptionSectionContextDto.of(contextKey, contextKey)).build();
}
}
| 7,224 | 53.323308 | 150 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/security/SecurityReviewRatingTest.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.security;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.data.Offset;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.server.measure.Rating;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.measure.Rating.A;
import static org.sonar.server.measure.Rating.B;
import static org.sonar.server.measure.Rating.C;
import static org.sonar.server.measure.Rating.D;
import static org.sonar.server.measure.Rating.E;
import static org.sonar.server.security.SecurityReviewRating.computePercent;
import static org.sonar.server.security.SecurityReviewRating.computeRating;
@RunWith(DataProviderRunner.class)
public class SecurityReviewRatingTest {
private static final Offset<Double> DOUBLE_OFFSET = Offset.offset(0.01d);
@DataProvider
public static Object[][] values() {
List<Object[]> res = new ArrayList<>();
res.add(new Object[] {100.0, A});
res.add(new Object[] {90.0, A});
res.add(new Object[] {80.0, A});
res.add(new Object[] {75.0, B});
res.add(new Object[] {70.0, B});
res.add(new Object[] {60, C});
res.add(new Object[] {50.0, C});
res.add(new Object[] {40.0, D});
res.add(new Object[] {30.0, D});
res.add(new Object[] {29.9, E});
return res.toArray(new Object[res.size()][2]);
}
@Test
@UseDataProvider("values")
public void compute_rating(double percent, Rating expectedRating) {
assertThat(computeRating(percent)).isEqualTo(expectedRating);
}
@Test
public void compute_percent() {
assertThat(computePercent(0, 0)).isEmpty();
assertThat(computePercent(0, 10)).contains(100.0);
assertThat(computePercent(1, 3)).contains(75.0);
assertThat(computePercent(3, 4).get()).isEqualTo(57.14, DOUBLE_OFFSET);
assertThat(computePercent(10, 10)).contains(50.0);
assertThat(computePercent(10, 0)).contains(0.0);
}
}
| 2,943 | 36.74359 | 76 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/security/SecurityStandardsTest.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.security;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
import org.sonar.api.server.rule.RulesDefinition.OwaspAsvsVersion;
import org.sonar.server.security.SecurityStandards.OwaspAsvs;
import org.sonar.server.security.SecurityStandards.PciDss;
import org.sonar.server.security.SecurityStandards.SQCategory;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.sonar.server.security.SecurityStandards.CWES_BY_SQ_CATEGORY;
import static org.sonar.server.security.SecurityStandards.OWASP_ASVS_REQUIREMENTS_BY_LEVEL;
import static org.sonar.server.security.SecurityStandards.SQ_CATEGORY_KEYS_ORDERING;
import static org.sonar.server.security.SecurityStandards.fromSecurityStandards;
import static org.sonar.server.security.SecurityStandards.getRequirementsForCategoryAndLevel;
public class SecurityStandardsTest {
@Test
public void fromSecurityStandards_from_empty_set_has_SQCategory_OTHERS() {
SecurityStandards securityStandards = fromSecurityStandards(emptySet());
assertThat(securityStandards.getStandards()).isEmpty();
assertThat(securityStandards.getSqCategory()).isEqualTo(SQCategory.OTHERS);
assertThat(securityStandards.getIgnoredSQCategories()).isEmpty();
}
@Test
public void fromSecurityStandards_from_empty_set_has_unkwown_cwe_standard() {
SecurityStandards securityStandards = fromSecurityStandards(emptySet());
assertThat(securityStandards.getStandards()).isEmpty();
assertThat(securityStandards.getCwe()).containsOnly("unknown");
}
@Test
public void fromSecurityStandards_from_empty_set_has_no_OwaspTop10_standard() {
SecurityStandards securityStandards = fromSecurityStandards(emptySet());
assertThat(securityStandards.getStandards()).isEmpty();
assertThat(securityStandards.getOwaspTop10()).isEmpty();
}
@Test
public void fromSecurityStandards_from_empty_set_has_no_SansTop25_standard() {
SecurityStandards securityStandards = fromSecurityStandards(emptySet());
assertThat(securityStandards.getStandards()).isEmpty();
assertThat(securityStandards.getSansTop25()).isEmpty();
}
@Test
public void fromSecurityStandards_from_empty_set_has_no_CweTop25_standard() {
SecurityStandards securityStandards = fromSecurityStandards(emptySet());
assertThat(securityStandards.getStandards()).isEmpty();
assertThat(securityStandards.getCweTop25()).isEmpty();
}
@Test
public void fromSecurityStandards_finds_SQCategory_from_any_if_the_mapped_CWE_standard() {
CWES_BY_SQ_CATEGORY.forEach((sqCategory, cwes) -> {
cwes.forEach(cwe -> {
SecurityStandards securityStandards = fromSecurityStandards(singleton("cwe:" + cwe));
assertThat(securityStandards.getSqCategory()).isEqualTo(sqCategory);
});
});
}
@Test
public void fromSecurityStandards_finds_SQCategory_from_multiple_of_the_mapped_CWE_standard() {
CWES_BY_SQ_CATEGORY.forEach((sqCategory, cwes) -> {
SecurityStandards securityStandards = fromSecurityStandards(cwes.stream().map(t -> "cwe:" + t).collect(toSet()));
assertThat(securityStandards.getSqCategory()).isEqualTo(sqCategory);
});
}
@Test
public void fromSecurityStandards_finds_SQCategory_first_in_order_when_CWEs_map_to_multiple_SQCategories() {
EnumSet<SQCategory> sqCategories = EnumSet.allOf(SQCategory.class);
sqCategories.remove(SQCategory.OTHERS);
while (!sqCategories.isEmpty()) {
SQCategory expected = sqCategories.stream().min(SQ_CATEGORY_KEYS_ORDERING.onResultOf(SQCategory::getKey)).get();
SQCategory[] expectedIgnored = sqCategories.stream().filter(t -> t != expected).toArray(SQCategory[]::new);
Set<String> cwes = sqCategories.stream()
.flatMap(t -> CWES_BY_SQ_CATEGORY.get(t).stream().map(e -> "cwe:" + e))
.collect(Collectors.toSet());
SecurityStandards securityStandards = fromSecurityStandards(cwes);
assertThat(securityStandards.getSqCategory()).isEqualTo(expected);
assertThat(securityStandards.getIgnoredSQCategories()).containsOnly(expectedIgnored);
sqCategories.remove(expected);
}
}
@Test
public void pciDss_categories_check() {
List<String> pciDssCategories = Arrays.stream(PciDss.values()).map(PciDss::category).toList();
assertThat(pciDssCategories).hasSize(12).containsExactly("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12");
}
@Test
public void owaspAsvs_categories_check() {
List<String> owaspAsvsCategories = Arrays.stream(OwaspAsvs.values()).map(OwaspAsvs::category).toList();
assertThat(owaspAsvsCategories).hasSize(14).containsExactly("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14");
}
@Test
public void owaspAsvs40_requirements_distribution_by_level_check() {
assertTrue(OWASP_ASVS_REQUIREMENTS_BY_LEVEL.containsKey(OwaspAsvsVersion.V4_0));
assertTrue(OWASP_ASVS_REQUIREMENTS_BY_LEVEL.get(OwaspAsvsVersion.V4_0).containsKey(1));
assertTrue(OWASP_ASVS_REQUIREMENTS_BY_LEVEL.get(OwaspAsvsVersion.V4_0).containsKey(2));
assertTrue(OWASP_ASVS_REQUIREMENTS_BY_LEVEL.get(OwaspAsvsVersion.V4_0).containsKey(3));
assertEquals(135, OWASP_ASVS_REQUIREMENTS_BY_LEVEL.get(OwaspAsvsVersion.V4_0).get(1).size());
assertEquals(266, OWASP_ASVS_REQUIREMENTS_BY_LEVEL.get(OwaspAsvsVersion.V4_0).get(2).size());
assertEquals(286, OWASP_ASVS_REQUIREMENTS_BY_LEVEL.get(OwaspAsvsVersion.V4_0).get(3).size());
}
@Test
public void owaspAsvs40_requirements_by_category_and_level_check() {
assertEquals(0, getRequirementsForCategoryAndLevel(OwaspAsvs.C1, 1).size());
assertEquals(31, getRequirementsForCategoryAndLevel(OwaspAsvs.C2, 1).size());
assertEquals(12, getRequirementsForCategoryAndLevel(OwaspAsvs.C3, 1).size());
assertEquals(9, getRequirementsForCategoryAndLevel(OwaspAsvs.C4, 1).size());
assertEquals(27, getRequirementsForCategoryAndLevel(OwaspAsvs.C5, 1).size());
assertEquals(1, getRequirementsForCategoryAndLevel(OwaspAsvs.C6, 1).size());
assertEquals(3, getRequirementsForCategoryAndLevel(OwaspAsvs.C7, 1).size());
assertEquals(7, getRequirementsForCategoryAndLevel(OwaspAsvs.C8, 1).size());
assertEquals(3, getRequirementsForCategoryAndLevel(OwaspAsvs.C9, 1).size());
assertEquals(3, getRequirementsForCategoryAndLevel(OwaspAsvs.C10, 1).size());
assertEquals(5, getRequirementsForCategoryAndLevel(OwaspAsvs.C11, 1).size());
assertEquals(11, getRequirementsForCategoryAndLevel(OwaspAsvs.C12, 1).size());
assertEquals(7, getRequirementsForCategoryAndLevel(OwaspAsvs.C13, 1).size());
assertEquals(16, getRequirementsForCategoryAndLevel(OwaspAsvs.C14, 1).size());
}
}
| 7,863 | 44.988304 | 139 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/setting/ChildSettingsTest.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 java.util.Collections;
import java.util.Date;
import java.util.Optional;
import java.util.Random;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ChildSettingsTest {
private static final Random RANDOM = new Random();
private MapSettings parent = new MapSettings();
private ChildSettings underTest = new ChildSettings(parent);
@Test
public void childSettings_should_retrieve_parent_settings() {
String multipleValuesKey = randomAlphanumeric(19);
PropertyDefinition multipleValues = PropertyDefinition.builder(multipleValuesKey).multiValues(true).build();
MapSettings parent = new MapSettings(new PropertyDefinitions(System2.INSTANCE, Collections.singletonList(multipleValues)));
ChildSettings underTest = new ChildSettings(parent);
parent.setProperty(randomAlphanumeric(10), randomAlphanumeric(20));
parent.setProperty(randomAlphanumeric(11), RANDOM.nextLong());
parent.setProperty(randomAlphanumeric(12), RANDOM.nextDouble());
parent.setProperty(randomAlphanumeric(13), RANDOM.nextFloat());
parent.setProperty(randomAlphanumeric(14), RANDOM.nextBoolean());
parent.setProperty(randomAlphanumeric(15), RANDOM.nextInt());
parent.setProperty(randomAlphanumeric(16), new Date(RANDOM.nextInt()));
parent.setProperty(randomAlphanumeric(17), new Date(RANDOM.nextInt()), true);
parent.setProperty(randomAlphanumeric(18), new Date(RANDOM.nextInt()), false);
parent.setProperty(multipleValuesKey, new String[] {randomAlphanumeric(10), randomAlphanumeric(20)});
assertThat(underTest.getProperties()).isEqualTo(parent.getProperties());
}
@Test
public void set_will_throw_NPE_if_key_is_null() {
assertThatThrownBy(() -> underTest.set(null, ""))
.isInstanceOf(NullPointerException.class)
.hasMessage("key can't be null");
}
@Test
public void set_will_throw_NPE_if_value_is_null() {
assertThatThrownBy(() -> underTest.set(randomAlphanumeric(10), null))
.isInstanceOf(NullPointerException.class)
.hasMessage("value can't be null");
}
@Test
public void childSettings_override_parent() {
String key = randomAlphanumeric(10);
parent.setProperty(key, randomAlphanumeric(20));
underTest.setProperty(key, randomAlphanumeric(10));
Optional<String> result = underTest.get(key);
assertThat(result).isPresent();
assertThat(result.get()).isNotEqualTo(parent.getString(key));
}
@Test
public void remove_should_not_throw_exception_if_key_is_not_present() {
underTest.remove(randomAlphanumeric(90));
}
@Test
public void remove_should_remove_value() {
String key = randomAlphanumeric(10);
String childValue = randomAlphanumeric(10);
underTest.set(key, childValue);
assertThat(underTest.get(key)).isEqualTo(Optional.of(childValue));
underTest.remove(key);
assertThat(underTest.get(key)).isEmpty();
}
@Test
public void remove_should_retrieve_parent_value() {
String key = randomAlphanumeric(10);
String childValue = randomAlphanumeric(10);
String parentValue = randomAlphanumeric(10);
parent.setProperty(key, parentValue);
underTest.set(key, childValue);
assertThat(underTest.get(key)).isEqualTo(Optional.of(childValue));
underTest.remove(key);
assertThat(underTest.get(key)).isEqualTo(Optional.of(parentValue));
}
}
| 4,582 | 36.876033 | 127 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/setting/DatabaseSettingsEnablerTest.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.junit.After;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class DatabaseSettingsEnablerTest {
private ThreadLocalSettings settings = mock(ThreadLocalSettings.class);
private DatabaseSettingLoader loader = mock(DatabaseSettingLoader.class);
private DatabaseSettingsEnabler underTest = new DatabaseSettingsEnabler(settings, loader);
@After
public void tearDown() {
underTest.stop();
}
@Test
public void change_loader_at_startup() {
underTest.start();
verify(settings).setSettingLoader(loader);
}
}
| 1,489 | 30.702128 | 92 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/setting/NopSettingLoaderTest.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.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class NopSettingLoaderTest {
private NopSettingLoader underTest = new NopSettingLoader();
@Test
public void do_nothing() {
assertThat(underTest.load("foo")).isNull();
assertThat(underTest.loadAll()).isEmpty();
}
}
| 1,201 | 31.486486 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/setting/ThreadLocalSettingsTest.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 com.google.common.collect.ImmutableMap;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import javax.annotation.Nullable;
import org.apache.ibatis.exceptions.PersistenceException;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.Property;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.System2;
import org.sonar.core.config.CorePropertyDefinitions;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ThreadLocalSettingsTest {
private static final String A_KEY = "a_key";
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private MapSettingLoader dbSettingLoader = new MapSettingLoader();
private ThreadLocalSettings underTest = null;
private System2 system = mock(System2.class);
@After
public void tearDown() {
if (underTest != null) {
underTest.unload();
}
}
@Test
public void can_not_add_property_if_no_cache() {
underTest = create(system, Collections.emptyMap());
underTest.set("foo", "wiz");
assertThat(underTest.get("foo")).isNotPresent();
}
@Test
public void can_not_remove_system_property_if_no_cache() {
underTest = create(system, ImmutableMap.of("foo", "bar"));
underTest.remove("foo");
assertThat(underTest.get("foo")).hasValue("bar");
}
@Test
public void add_property_to_cache() {
underTest = create(system, Collections.emptyMap());
underTest.load();
underTest.set("foo", "bar");
assertThat(underTest.get("foo")).hasValue("bar");
underTest.unload();
// no more cache
assertThat(underTest.get("foo")).isNotPresent();
}
@Test
public void remove_property_from_cache() {
underTest = create(system, Collections.emptyMap());
underTest.load();
underTest.set("foo", "bar");
assertThat(underTest.get("foo")).hasValue("bar");
underTest.remove("foo");
assertThat(underTest.get("foo")).isNotPresent();
underTest.unload();
// no more cache
assertThat(underTest.get("foo")).isNotPresent();
}
/**
* SONAR-8216 System info page fails when a setting is defined both in sonar.properties and in DB
*/
@Test
public void getProperties_does_not_fail_on_duplicated_key() {
insertPropertyIntoDb("foo", "from_db");
underTest = create(system, ImmutableMap.of("foo", "from_system"));
assertThat(underTest.get("foo")).hasValue("from_system");
assertThat(underTest.getProperties()).containsEntry("foo", "from_system");
}
@Test
public void load_encryption_secret_key_from_system_properties() throws Exception {
File secretKey = temp.newFile();
underTest = create(system, ImmutableMap.of("foo", "bar", "sonar.secretKeyPath", secretKey.getAbsolutePath()));
assertThat(underTest.getEncryption().hasSecretKey()).isTrue();
}
@Test
public void encryption_secret_key_is_undefined_by_default() {
underTest = create(system, ImmutableMap.of("foo", "bar", "sonar.secretKeyPath", "unknown/path/to/sonar-secret.txt"));
assertThat(underTest.getEncryption().hasSecretKey()).isFalse();
}
private ThreadLocalSettings create(System2 system, Map<String, String> systemProps) {
PropertyDefinitions definitions = new PropertyDefinitions(system);
definitions.addComponents(CorePropertyDefinitions.all());
definitions.addComponent(new AnnotatedTestClass());
Properties p = new Properties();
p.putAll(systemProps);
return new ThreadLocalSettings(definitions, p, dbSettingLoader);
}
@Test
public void load_system_properties() {
underTest = create(system, ImmutableMap.of("foo", "1", "bar", "2"));
assertThat(underTest.get("foo")).hasValue("1");
assertThat(underTest.get("missing")).isNotPresent();
assertThat(underTest.getProperties()).containsOnly(entry("foo", "1"), entry("bar", "2"));
}
@Test
public void load_core_properties_from_environment() {
when(system.envVariable("SONAR_FORCEAUTHENTICATION")).thenReturn("true");
when(system.envVariable("SONAR_ANNOTATION_TEST_PROP")).thenReturn("113");
underTest = create(system, ImmutableMap.of());
assertThat(underTest.get("sonar.forceAuthentication")).hasValue("true");
assertThat(underTest.get("sonar.annotation.test.prop")).hasValue("113");
assertThat(underTest.get("missing")).isNotPresent();
assertThat(underTest.getProperties()).containsOnly(entry("sonar.forceAuthentication", "true"), entry("sonar.annotation.test.prop", "113"));
}
@Test
public void database_properties_are_not_cached_by_default() {
insertPropertyIntoDb("foo", "from db");
underTest = create(system, Collections.emptyMap());
assertThat(underTest.get("foo")).hasValue("from db");
deletePropertyFromDb("foo");
// no cache, change is visible immediately
assertThat(underTest.get("foo")).isNotPresent();
}
@Test
public void system_settings_have_precedence_over_database() {
insertPropertyIntoDb("foo", "from db");
underTest = create(system, ImmutableMap.of("foo", "from system"));
assertThat(underTest.get("foo")).hasValue("from system");
}
@Test
public void getProperties_are_all_properties_with_value() {
insertPropertyIntoDb("db", "from db");
insertPropertyIntoDb("empty", "");
underTest = create(system, ImmutableMap.of("system", "from system"));
assertThat(underTest.getProperties()).containsOnly(entry("system", "from system"), entry("db", "from db"), entry("empty", ""));
}
@Test
public void getProperties_is_not_cached_in_thread_cache() {
insertPropertyIntoDb("foo", "bar");
underTest = create(system, Collections.emptyMap());
underTest.load();
assertThat(underTest.getProperties())
.containsOnly(entry("foo", "bar"));
insertPropertyIntoDb("foo2", "bar2");
assertThat(underTest.getProperties())
.containsOnly(entry("foo", "bar"), entry("foo2", "bar2"));
underTest.unload();
assertThat(underTest.getProperties())
.containsOnly(entry("foo", "bar"), entry("foo2", "bar2"));
}
@Test
public void load_creates_a_thread_specific_cache() throws InterruptedException {
insertPropertyIntoDb(A_KEY, "v1");
underTest = create(system, Collections.emptyMap());
underTest.load();
assertThat(underTest.get(A_KEY)).hasValue("v1");
deletePropertyFromDb(A_KEY);
// the main thread still has "v1" in cache, but not new thread
assertThat(underTest.get(A_KEY)).hasValue("v1");
verifyValueInNewThread(underTest, null);
insertPropertyIntoDb(A_KEY, "v2");
// the main thread still has the old value "v1" in cache, but new thread loads "v2"
assertThat(underTest.get(A_KEY)).hasValue("v1");
verifyValueInNewThread(underTest, "v2");
underTest.unload();
}
@Test
public void load_invalidates_cache_if_unload_has_not_been_called() {
underTest = create(system, emptyMap());
underTest.load();
underTest.set("foo", "bar");
// unload() is not called
underTest.load();
assertThat(underTest.get("foo")).isEmpty();
}
@Test
public void keep_in_thread_cache_the_fact_that_a_property_is_not_in_db() {
underTest = create(system, Collections.emptyMap());
underTest.load();
assertThat(underTest.get(A_KEY)).isNotPresent();
insertPropertyIntoDb(A_KEY, "bar");
// do not execute new SQL request, cache contains the information of missing property
assertThat(underTest.get(A_KEY)).isNotPresent();
underTest.unload();
}
@Test
public void change_setting_loader() {
underTest = new ThreadLocalSettings(new PropertyDefinitions(system), new Properties());
assertThat(underTest.getSettingLoader()).isNotNull();
SettingLoader newLoader = mock(SettingLoader.class);
underTest.setSettingLoader(newLoader);
assertThat(underTest.getSettingLoader()).isSameAs(newLoader);
}
@Test
public void cache_db_calls_if_property_is_not_persisted() {
underTest = create(system, Collections.emptyMap());
underTest.load();
assertThat(underTest.get(A_KEY)).isNotPresent();
assertThat(underTest.get(A_KEY)).isNotPresent();
underTest.unload();
}
@Test
public void getProperties_return_empty_if_DB_error_on_first_call_ever_out_of_thread_cache() {
SettingLoader settingLoaderMock = mock(SettingLoader.class);
PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB");
doThrow(toBeThrown).when(settingLoaderMock).loadAll();
underTest = new ThreadLocalSettings(new PropertyDefinitions(system), new Properties(), settingLoaderMock);
assertThat(underTest.getProperties())
.isEmpty();
}
@Test
public void getProperties_returns_empty_if_DB_error_on_first_call_ever_in_thread_cache() {
SettingLoader settingLoaderMock = mock(SettingLoader.class);
PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB");
doThrow(toBeThrown).when(settingLoaderMock).loadAll();
underTest = new ThreadLocalSettings(new PropertyDefinitions(system), new Properties(), settingLoaderMock);
underTest.load();
assertThat(underTest.getProperties())
.isEmpty();
}
@Test
public void getProperties_return_properties_from_previous_thread_cache_if_DB_error_on_not_first_call() {
String key = randomAlphanumeric(3);
String value1 = randomAlphanumeric(4);
String value2 = randomAlphanumeric(5);
SettingLoader settingLoaderMock = mock(SettingLoader.class);
PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB");
doAnswer(invocationOnMock -> ImmutableMap.of(key, value1))
.doThrow(toBeThrown)
.doAnswer(invocationOnMock -> ImmutableMap.of(key, value2))
.when(settingLoaderMock)
.loadAll();
underTest = new ThreadLocalSettings(new PropertyDefinitions(system), new Properties(), settingLoaderMock);
underTest.load();
assertThat(underTest.getProperties())
.containsOnly(entry(key, value1));
underTest.unload();
underTest.load();
assertThat(underTest.getProperties())
.containsOnly(entry(key, value1));
underTest.unload();
underTest.load();
assertThat(underTest.getProperties())
.containsOnly(entry(key, value2));
underTest.unload();
}
@Test
public void get_returns_empty_if_DB_error_on_first_call_ever_out_of_thread_cache() {
SettingLoader settingLoaderMock = mock(SettingLoader.class);
PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB");
String key = randomAlphanumeric(3);
doThrow(toBeThrown).when(settingLoaderMock).load(key);
underTest = new ThreadLocalSettings(new PropertyDefinitions(system), new Properties(), settingLoaderMock);
assertThat(underTest.get(key)).isEmpty();
}
@Test
public void get_returns_empty_if_DB_error_on_first_call_ever_in_thread_cache() {
SettingLoader settingLoaderMock = mock(SettingLoader.class);
PersistenceException toBeThrown = new PersistenceException("Faking an error connecting to DB");
String key = randomAlphanumeric(3);
doThrow(toBeThrown).when(settingLoaderMock).load(key);
underTest = new ThreadLocalSettings(new PropertyDefinitions(system), new Properties(), settingLoaderMock);
underTest.load();
assertThat(underTest.get(key)).isEmpty();
}
private void insertPropertyIntoDb(String key, String value) {
dbSettingLoader.put(key, value);
}
private void deletePropertyFromDb(String key) {
dbSettingLoader.remove(key);
}
private void verifyValueInNewThread(ThreadLocalSettings settings, @Nullable String expectedValue) throws InterruptedException {
CacheCaptorThread captor = new CacheCaptorThread();
captor.verifyValue(settings, expectedValue);
}
private static class CacheCaptorThread extends Thread {
private final CountDownLatch latch = new CountDownLatch(1);
private ThreadLocalSettings settings;
private String value;
void verifyValue(ThreadLocalSettings settings, @Nullable String expectedValue) throws InterruptedException {
this.settings = settings;
this.start();
this.latch.await(5, SECONDS);
assertThat(value).isEqualTo(expectedValue);
}
@Override
public void run() {
try {
settings.load();
value = settings.get(A_KEY).orElse(null);
latch.countDown();
} finally {
settings.unload();
}
}
}
private static class MapSettingLoader implements SettingLoader {
private final Map<String, String> map = new HashMap<>();
public MapSettingLoader put(String key, String value) {
map.put(key, value);
return this;
}
public MapSettingLoader remove(String key) {
map.remove(key);
return this;
}
@Override
public String load(String key) {
return map.get(key);
}
@Override
public Map<String, String> loadAll() {
return unmodifiableMap(map);
}
}
@org.sonar.api.Properties({
@Property(
key = "sonar.annotation.test.prop",
defaultValue = "60",
name = "Test annotation property",
global = false)
})
class AnnotatedTestClass {
}
}
| 14,649 | 32.678161 | 143 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/telemetry/TelemetryDataJsonWriterTest.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.telemetry;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.codec.digest.DigestUtils;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.core.platform.EditionProvider;
import org.sonar.core.telemetry.TelemetryExtension;
import org.sonar.db.user.UserTelemetryDto;
import static java.util.stream.Collectors.joining;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.PREVIOUS_VERSION;
import static org.sonar.test.JsonAssert.assertJson;
@RunWith(DataProviderRunner.class)
public class TelemetryDataJsonWriterTest {
private final Random random = new Random();
private final TelemetryExtension extension = mock(TelemetryExtension.class);
private final System2 system2 = mock(System2.class);
private final TelemetryDataJsonWriter underTest = new TelemetryDataJsonWriter(List.of(extension), system2);
private static final int NCD_ID = 12345;
private static final TelemetryData.NewCodeDefinition NCD_INSTANCE =
new TelemetryData.NewCodeDefinition(PREVIOUS_VERSION.name(), "", "instance");
private static final TelemetryData.NewCodeDefinition NCD_PROJECT =
new TelemetryData.NewCodeDefinition(NUMBER_OF_DAYS.name(), "30", "project");
@Test
public void write_server_id_version_and_sequence() {
TelemetryData data = telemetryBuilder().build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"id": "%s",
"version": "%s",
"messageSequenceNumber": %s
}
""".formatted(data.getServerId(), data.getVersion(), data.getMessageSequenceNumber()));
}
@Test
public void does_not_write_edition_if_null() {
TelemetryData data = telemetryBuilder().build();
String json = writeTelemetryData(data);
assertThat(json).doesNotContain("edition");
}
@Test
@UseDataProvider("allEditions")
public void writes_edition_if_non_null(EditionProvider.Edition edition) {
TelemetryData data = telemetryBuilder()
.setEdition(edition)
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"edition": "%s"
}
""".formatted(edition.name().toLowerCase(Locale.ENGLISH)));
}
@Test
public void writes_default_qg() {
TelemetryData data = telemetryBuilder()
.setDefaultQualityGate("default-qg")
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"defaultQualityGate": "%s"
}
""".formatted(data.getDefaultQualityGate()));
}
@Test
public void writes_database() {
String name = randomAlphabetic(12);
String version = randomAlphabetic(10);
TelemetryData data = telemetryBuilder()
.setDatabase(new TelemetryData.Database(name, version))
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"database": {
"name": "%s",
"version": "%s"
}
}
""".formatted(name, version));
}
@Test
public void writes_no_plugins() {
TelemetryData data = telemetryBuilder()
.setPlugins(Collections.emptyMap())
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"plugins": []
}
""");
}
@Test
public void writes_all_plugins() {
Map<String, String> plugins = IntStream.range(0, 1 + random.nextInt(10))
.boxed()
.collect(Collectors.toMap(i -> "P" + i, i1 -> "V" + i1));
TelemetryData data = telemetryBuilder()
.setPlugins(plugins)
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"plugins": [%s]
}
""".formatted(plugins.entrySet().stream().map(e -> "{\"name\":\"" + e.getKey() + "\",\"version\":\"" + e.getValue() + "\"}").collect(joining(","))));
}
@Test
public void does_not_write_installation_date_if_null() {
TelemetryData data = telemetryBuilder()
.setInstallationDate(null)
.build();
String json = writeTelemetryData(data);
assertThat(json).doesNotContain("installationDate");
}
@Test
public void write_installation_date_in_utc_format() {
TelemetryData data = telemetryBuilder()
.setInstallationDate(1_000L)
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"installationDate":"1970-01-01T00:00:01+0000"
}
""");
}
@Test
public void does_not_write_installation_version_if_null() {
TelemetryData data = telemetryBuilder()
.setInstallationVersion(null)
.build();
String json = writeTelemetryData(data);
assertThat(json).doesNotContain("installationVersion");
}
@Test
public void write_installation_version() {
String installationVersion = randomAlphabetic(5);
TelemetryData data = telemetryBuilder()
.setInstallationVersion(installationVersion)
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"installationVersion": "%s"
}
""".formatted(installationVersion));
}
@Test
@UseDataProvider("getFeatureFlagEnabledStates")
public void write_container_flag(boolean isIncontainer) {
TelemetryData data = telemetryBuilder()
.setInContainer(isIncontainer)
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"container": %s
}
""".formatted(isIncontainer));
}
@DataProvider
public static Object[][] getManagedInstanceData() {
return new Object[][] {
{true, "scim"},
{true, "github"},
{true, "gitlab"},
{false, null},
};
}
@Test
@UseDataProvider("getManagedInstanceData")
public void writeTelemetryData_encodesCorrectlyManagedInstanceInformation(boolean isManaged, String provider) {
TelemetryData data = telemetryBuilder()
.setManagedInstanceInformation(new TelemetryData.ManagedInstanceInformation(isManaged, provider))
.build();
String json = writeTelemetryData(data);
if (isManaged) {
assertJson(json).isSimilarTo("""
{
"managedInstanceInformation": {
"isManaged": true,
"provider": "%s"
}
}
""".formatted(provider));
} else {
assertJson(json).isSimilarTo("""
{
"managedInstanceInformation": {
"isManaged": false
}
}
""");
}
}
@Test
public void writeTelemetryData_shouldWriteCloudUsage() {
TelemetryData data = telemetryBuilder().build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"cloudUsage": {
"kubernetes": true,
"kubernetesVersion": "1.27",
"kubernetesPlatform": "linux/amd64",
"kubernetesProvider": "5.4.181-99.354.amzn2.x86_64",
"officialHelmChart": "10.1.0",
"officialImage": false,
"containerRuntime": "docker"
}
}
""");
}
@Test
public void writes_has_unanalyzed_languages() {
TelemetryData data = telemetryBuilder()
.setHasUnanalyzedC(true)
.setHasUnanalyzedCpp(false)
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"hasUnanalyzedC": true,
"hasUnanalyzedCpp": false,
}
""");
}
@Test
public void writes_security_custom_config() {
TelemetryData data = telemetryBuilder()
.setCustomSecurityConfigs(Set.of("php", "java"))
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"customSecurityConfig": ["php", "java"]
}
""");
}
@Test
public void writes_local_timestamp() {
when(system2.now()).thenReturn(1000L);
TelemetryData data = telemetryBuilder().build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"localTimestamp": "1970-01-01T00:00:01+0000"
}
""");
}
@Test
public void writes_all_users_with_anonymous_md5_uuids() {
TelemetryData data = telemetryBuilder()
.setUsers(attachUsers())
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"users": [
{
"userUuid": "%s",
"status": "active",
"identityProvider": "gitlab",
"lastActivity": "1970-01-01T00:00:00+0000",
"lastSonarlintActivity": "1970-01-01T00:00:00+0000",
"managed": true
},
{
"userUuid": "%s",
"status": "inactive",
"identityProvider": "gitlab",
"lastActivity": "1970-01-01T00:00:00+0000",
"lastSonarlintActivity": "1970-01-01T00:00:00+0000",
"managed": false
},
{
"userUuid": "%s",
"status": "active",
"identityProvider": "gitlab",
"lastActivity": "1970-01-01T00:00:00+0000",
"lastSonarlintActivity": "1970-01-01T00:00:00+0000",
"managed": true
}
]
}
"""
.formatted(DigestUtils.sha3_224Hex("uuid-0"), DigestUtils.sha3_224Hex("uuid-1"), DigestUtils.sha3_224Hex("uuid-2")));
}
@Test
public void writes_all_projects() {
TelemetryData data = telemetryBuilder()
.setProjects(attachProjects())
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"projects": [
{
"projectUuid": "uuid-0",
"lastAnalysis": "1970-01-01T00:00:00+0000",
"language": "lang-0",
"loc": 2
},
{
"projectUuid": "uuid-1",
"lastAnalysis": "1970-01-01T00:00:00+0000",
"language": "lang-1",
"loc": 4
},
{
"projectUuid": "uuid-2",
"lastAnalysis": "1970-01-01T00:00:00+0000",
"language": "lang-2",
"loc": 6
}
]
}
""");
}
@Test
public void writeTelemetryData_whenAnalyzedLanguages_shouldwriteAllProjectsStats() {
TelemetryData data = telemetryBuilder()
.setProjectStatistics(attachProjectStatsWithMetrics())
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"projects-general-stats": [
{
"projectUuid": "uuid-0",
"branchCount": 2,
"pullRequestCount": 2,
"qualityGate": "qg-0",
"scm": "scm-0",
"ci": "ci-0",
"devopsPlatform": "devops-0",
"bugs": 2,
"vulnerabilities": 3,
"securityHotspots": 4,
"technicalDebt": 60,
"developmentCost": 30,
"ncdId": 12345
},
{
"projectUuid": "uuid-1",
"branchCount": 4,
"pullRequestCount": 4,
"qualityGate": "qg-1",
"scm": "scm-1",
"ci": "ci-1",
"devopsPlatform": "devops-1",
"bugs": 4,
"vulnerabilities": 6,
"securityHotspots": 8,
"technicalDebt": 120,
"developmentCost": 60,
"ncdId": 12345
},
{
"projectUuid": "uuid-2",
"branchCount": 6,
"pullRequestCount": 6,
"qualityGate": "qg-2",
"scm": "scm-2",
"ci": "ci-2",
"devopsPlatform": "devops-2",
"bugs": 6,
"vulnerabilities": 9,
"securityHotspots": 12,
"technicalDebt": 180,
"developmentCost": 90,
"ncdId": 12345
}
]
}
"""
);
}
@Test
public void writes_all_projects_stats_with_unanalyzed_languages() {
TelemetryData data = telemetryBuilder()
.setProjectStatistics(attachProjectStats())
.build();
String json = writeTelemetryData(data);
assertThat(json).doesNotContain("hasUnanalyzedC", "hasUnanalyzedCpp");
}
@Test
public void writes_all_projects_stats_without_missing_metrics() {
TelemetryData data = telemetryBuilder()
.setProjectStatistics(attachProjectStats())
.build();
String json = writeTelemetryData(data);
assertThat(json).doesNotContain("bugs", "vulnerabilities", "securityHotspots", "technicalDebt", "developmentCost");
}
@Test
public void writes_all_quality_gates() {
TelemetryData data = telemetryBuilder()
.setQualityGates(attachQualityGates())
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"quality-gates": [
{
"uuid": "uuid-0",
"caycStatus": "non-compliant"
},
{
"uuid": "uuid-1",
"caycStatus": "compliant"
},
{
"uuid": "uuid-2",
"caycStatus": "over-compliant"
}
]
}
"""
);
}
@Test
public void writes_all_branches() {
TelemetryData data = telemetryBuilder()
.setBranches(attachBranches())
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"branches": [
{
"projectUuid": "projectUuid1",
"branchUuid": "branchUuid1",
"ncdId": 12345,
"greenQualityGateCount": 1,
"analysisCount": 2,
"excludeFromPurge": true
},
{
"projectUuid": "projectUuid2",
"branchUuid": "branchUuid2",
"ncdId": 12345,
"greenQualityGateCount": 0,
"analysisCount": 2,
"excludeFromPurge": true
}
]
}
""");
}
@Test
public void writes_new_code_definitions() {
TelemetryData data = telemetryBuilder()
.setNewCodeDefinitions(attachNewCodeDefinitions())
.build();
String json = writeTelemetryData(data);
assertJson(json).isSimilarTo("""
{
"new-code-definitions": [
{
"ncdId": %s,
"type": "%s",
"value": "%s",
"scope": "%s"
},
{
"ncdId": %s,
"type": "%s",
"value": "%s",
"scope": "%s"
},
]
}
""".formatted(NCD_INSTANCE.hashCode(), NCD_INSTANCE.type(), NCD_INSTANCE.value(), NCD_INSTANCE.scope(), NCD_PROJECT.hashCode(),
NCD_PROJECT.type(), NCD_PROJECT.value(), NCD_PROJECT.scope()));
}
@Test
public void writes_instance_new_code_definition() {
TelemetryData data = telemetryBuilder().build();
String json = writeTelemetryData(data);
assertThat(json).contains("ncdId");
}
private static TelemetryData.Builder telemetryBuilder() {
return TelemetryData.builder()
.setServerId("foo")
.setVersion("bar")
.setMessageSequenceNumber(1L)
.setPlugins(Collections.emptyMap())
.setManagedInstanceInformation(new TelemetryData.ManagedInstanceInformation(false, null))
.setCloudUsage(new TelemetryData.CloudUsage(true, "1.27", "linux/amd64", "5.4.181-99.354.amzn2.x86_64", "10.1.0", "docker", false))
.setDatabase(new TelemetryData.Database("H2", "11"))
.setNcdId(NCD_ID);
}
@NotNull
private static List<UserTelemetryDto> attachUsers() {
return IntStream.range(0, 3)
.mapToObj(
i -> new UserTelemetryDto().setUuid("uuid-" + i).setActive(i % 2 == 0).setLastConnectionDate(1L)
.setLastSonarlintConnectionDate(2L).setExternalIdentityProvider("gitlab").setScimUuid(i % 2 == 0 ? "scim-uuid-" + i : null))
.toList();
}
private static List<TelemetryData.Project> attachProjects() {
return IntStream.range(0, 3).mapToObj(i -> new TelemetryData.Project("uuid-" + i, 1L, "lang-" + i, (i + 1L) * 2L)).toList();
}
private static List<TelemetryData.ProjectStatistics> attachProjectStatsWithMetrics() {
return IntStream.range(0, 3).mapToObj(i -> getProjectStatisticsWithMetricBuilder(i).build()).toList();
}
private static List<TelemetryData.ProjectStatistics> attachProjectStats() {
return IntStream.range(0, 3).mapToObj(i -> getProjectStatisticsBuilder(i).build()).toList();
}
private static TelemetryData.ProjectStatistics.Builder getProjectStatisticsBuilder(int i) {
return new TelemetryData.ProjectStatistics.Builder()
.setProjectUuid("uuid-" + i)
.setBranchCount((i + 1L) * 2L)
.setPRCount((i + 1L) * 2L)
.setQG("qg-" + i).setCi("ci-" + i)
.setScm("scm-" + i)
.setDevops("devops-" + i)
.setNcdId(NCD_ID);
}
private static TelemetryData.ProjectStatistics.Builder getProjectStatisticsWithMetricBuilder(int i) {
return getProjectStatisticsBuilder(i)
.setBugs((i + 1L) * 2)
.setVulnerabilities((i + 1L) * 3)
.setSecurityHotspots((i + 1L) * 4)
.setDevelopmentCost((i + 1L) * 30d)
.setTechnicalDebt((i + 1L) * 60d);
}
private List<TelemetryData.QualityGate> attachQualityGates() {
return List.of(new TelemetryData.QualityGate("uuid-0", "non-compliant"),
new TelemetryData.QualityGate("uuid-1", "compliant"),
new TelemetryData.QualityGate("uuid-2", "over-compliant"));
}
private List<TelemetryData.Branch> attachBranches() {
return List.of(new TelemetryData.Branch("projectUuid1", "branchUuid1", NCD_ID, 1, 2, true),
new TelemetryData.Branch("projectUuid2", "branchUuid2", NCD_ID, 0, 2, true));
}
private List<TelemetryData.NewCodeDefinition> attachNewCodeDefinitions() {
return List.of(NCD_INSTANCE, NCD_PROJECT);
}
@DataProvider
public static Object[][] allEditions() {
return Arrays.stream(EditionProvider.Edition.values())
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
}
private String writeTelemetryData(TelemetryData data) {
StringWriter jsonString = new StringWriter();
try (JsonWriter json = JsonWriter.of(jsonString)) {
underTest.writeTelemetryData(json, data);
}
return jsonString.toString();
}
@DataProvider
public static Set<Boolean> getFeatureFlagEnabledStates() {
return Set.of(true, false);
}
}
| 20,033 | 28.119186 | 155 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/util/AbstractStoppableExecutorServiceTest.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 com.google.common.collect.ImmutableList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AbstractStoppableExecutorServiceTest {
private static final Callable<String> SOME_CALLABLE = () -> null;
private static final Runnable SOME_RUNNABLE = () -> {
};
private static final String SOME_STRING = "some string";
private static final long SOME_LONG = 100L;
private static final int TIMEOUT = 5;
private static final TimeUnit TIMEOUT_UNIT = TimeUnit.SECONDS;
private ExecutorService executorService = mock(ExecutorService.class);
private InOrder inOrder = Mockito.inOrder(executorService);
private AbstractStoppableExecutorService underTest = new AbstractStoppableExecutorService(executorService) {
};
public static final ImmutableList<Callable<String>> CALLABLES = ImmutableList.of(SOME_CALLABLE);
@Test
public void stop_calls_shutdown_and_verify_termination() throws InterruptedException {
when(executorService.awaitTermination(TIMEOUT, TIMEOUT_UNIT)).thenReturn(true);
underTest.stop();
inOrder.verify(executorService).shutdown();
inOrder.verify(executorService).awaitTermination(TIMEOUT, TIMEOUT_UNIT);
inOrder.verifyNoMoreInteractions();
}
@Test
public void stop_calls_shutdown_then_shutdownNow_if_not_terminated_and_check_termination_again() throws InterruptedException {
when(executorService.awaitTermination(TIMEOUT, TIMEOUT_UNIT)).thenReturn(false).thenReturn(true);
underTest.stop();
inOrder.verify(executorService).shutdown();
inOrder.verify(executorService).awaitTermination(TIMEOUT, TIMEOUT_UNIT);
inOrder.verify(executorService).shutdownNow();
inOrder.verify(executorService).awaitTermination(TIMEOUT, TIMEOUT_UNIT);
inOrder.verifyNoMoreInteractions();
}
@Test
public void stop_calls_shutdownnow_if_interrupted_exception_is_raised() throws InterruptedException {
when(executorService.awaitTermination(TIMEOUT, TIMEOUT_UNIT)).thenThrow(new InterruptedException());
underTest.stop();
inOrder.verify(executorService).shutdown();
inOrder.verify(executorService).awaitTermination(TIMEOUT, TIMEOUT_UNIT);
inOrder.verify(executorService).shutdownNow();
inOrder.verifyNoMoreInteractions();
}
@Test
public void shutdown_delegates_to_executorService() {
underTest.shutdown();
inOrder.verify(executorService).shutdown();
inOrder.verifyNoMoreInteractions();
}
@Test
public void shutdownNow_delegates_to_executorService() {
underTest.shutdownNow();
inOrder.verify(executorService).shutdownNow();
inOrder.verifyNoMoreInteractions();
}
@Test
public void isShutdown_delegates_to_executorService() {
underTest.isShutdown();
inOrder.verify(executorService).isShutdown();
inOrder.verifyNoMoreInteractions();
}
@Test
public void isTerminated_delegates_to_executorService() {
underTest.isTerminated();
inOrder.verify(executorService).isTerminated();
inOrder.verifyNoMoreInteractions();
}
@Test
public void awaitTermination_delegates_to_executorService() throws InterruptedException {
underTest.awaitTermination(SOME_LONG, SECONDS);
inOrder.verify(executorService).awaitTermination(SOME_LONG, SECONDS);
inOrder.verifyNoMoreInteractions();
}
@Test
public void submit_callable_delegates_to_executorService() {
underTest.submit(SOME_CALLABLE);
inOrder.verify(executorService).submit(SOME_CALLABLE);
inOrder.verifyNoMoreInteractions();
}
@Test
public void submit_runnable_delegates_to_executorService() {
underTest.submit(SOME_RUNNABLE);
inOrder.verify(executorService).submit(SOME_RUNNABLE);
inOrder.verifyNoMoreInteractions();
}
@Test
public void submit_runnable_with_result_delegates_to_executorService() {
underTest.submit(SOME_RUNNABLE, SOME_STRING);
inOrder.verify(executorService).submit(SOME_RUNNABLE, SOME_STRING);
inOrder.verifyNoMoreInteractions();
}
@Test
public void invokeAll_delegates_to_executorService() throws InterruptedException {
underTest.invokeAll(CALLABLES);
inOrder.verify(executorService).invokeAll(CALLABLES);
inOrder.verifyNoMoreInteractions();
}
@Test
public void invokeAll1_delegates_to_executorService() throws InterruptedException {
underTest.invokeAll(CALLABLES, SOME_LONG, SECONDS);
inOrder.verify(executorService).invokeAll(CALLABLES, SOME_LONG, SECONDS);
inOrder.verifyNoMoreInteractions();
}
@Test
public void invokeAny_delegates_to_executorService() throws ExecutionException, InterruptedException {
underTest.invokeAny(CALLABLES);
inOrder.verify(executorService).invokeAny(CALLABLES);
inOrder.verifyNoMoreInteractions();
}
@Test
public void invokeAny1_delegates_to_executorService() throws InterruptedException, ExecutionException, TimeoutException {
underTest.invokeAny(CALLABLES, SOME_LONG, SECONDS);
inOrder.verify(executorService).invokeAny(CALLABLES, SOME_LONG, SECONDS);
inOrder.verifyNoMoreInteractions();
}
@Test
public void execute_delegates_to_executorService() {
underTest.execute(SOME_RUNNABLE);
inOrder.verify(executorService).execute(SOME_RUNNABLE);
inOrder.verifyNoMoreInteractions();
}
}
| 6,486 | 32.786458 | 128 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/util/OkHttpClientProviderTest.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.io.IOException;
import java.util.Base64;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.Version;
import org.sonar.core.platform.SonarQubeVersion;
import static org.assertj.core.api.Assertions.assertThat;
public class OkHttpClientProviderTest {
private final MapSettings settings = new MapSettings();
private final SonarQubeVersion sonarQubeVersion = new SonarQubeVersion(Version.parse("6.2"));
private final OkHttpClientProvider underTest = new OkHttpClientProvider();
@Rule
public MockWebServer server = new MockWebServer();
@Test
public void get_returns_a_OkHttpClient_with_default_configuration() throws Exception {
OkHttpClient client = underTest.provide(settings.asConfig(), sonarQubeVersion);
assertThat(client.connectTimeoutMillis()).isEqualTo(10_000);
assertThat(client.readTimeoutMillis()).isEqualTo(10_000);
assertThat(client.proxy()).isNull();
RecordedRequest recordedRequest = call(client);
assertThat(recordedRequest.getHeader("User-Agent")).isEqualTo("SonarQube/6.2");
assertThat(recordedRequest.getHeader("Proxy-Authorization")).isNull();
}
@Test
public void get_returns_a_OkHttpClient_with_proxy_authentication() throws Exception {
settings.setProperty("http.proxyUser", "the-login");
settings.setProperty("http.proxyPassword", "the-password");
OkHttpClient client = underTest.provide(settings.asConfig(), sonarQubeVersion);
Response response = new Response.Builder().protocol(Protocol.HTTP_1_1).request(new Request.Builder().url("http://foo").build()).code(407)
.message("").build();
Request request = client.proxyAuthenticator().authenticate(null, response);
assertThat(request.header("Proxy-Authorization")).isEqualTo("Basic " + Base64.getEncoder().encodeToString("the-login:the-password".getBytes()));
}
private RecordedRequest call(OkHttpClient client) throws IOException, InterruptedException {
server.enqueue(new MockResponse().setBody("pong"));
client.newCall(new Request.Builder().url(server.url("/ping")).build()).execute();
return server.takeRequest();
}
}
| 3,291 | 39.641975 | 148 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/util/Paths2ImplTest.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 com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.net.URI;
import java.nio.file.Paths;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.assertj.core.api.Assertions.assertThat;
import static java.nio.file.Path.of;
@RunWith(DataProviderRunner.class)
public class Paths2ImplTest {
@Test
public void getInstance_returns_the_same_object_for_every_call() {
assertThat(Paths2Impl.getInstance())
.isSameAs(Paths2Impl.getInstance())
.isSameAs(Paths2Impl.getInstance());
}
@Test
@UseDataProvider("getStringParameters")
public void get_String_returns_result_of_Paths_get(String first, String... others) {
assertThat(Paths2Impl.getInstance().get(first, others))
.isEqualTo(Paths.get(first, others));
}
@DataProvider
public static Object[][] getStringParameters() {
return new Object[][] {
{"a", new String[] {}},
{"a", new String[] {"b"}},
{"a", new String[] {"b", "c"}}
};
}
@Test
@UseDataProvider("getURIParameter")
public void get_URI_returns_result_of_Paths_get(URI uri) {
assertThat(Paths2Impl.getInstance().get(uri))
.isEqualTo(Paths.get(uri));
}
@DataProvider
public static Object[][] getURIParameter() {
return new Object[][] {
{URI.create("file:///")},
{URI.create("file:///a")},
{URI.create("file:///b/c")}
};
}
@Test
@UseDataProvider("getStringParameters")
public void exists_returns_result_of_Paths_exists(String first, String... others) {
assertThat(Paths2Impl.getInstance().exists(first, others))
.isEqualTo(of(first, others).toFile().exists());
}
}
| 2,641 | 31.617284 | 86 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/view/index/ViewIndexDefinitionTest.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.view.index;
import org.junit.Test;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.newindex.NewIndex;
import static org.assertj.core.api.Assertions.assertThat;
public class ViewIndexDefinitionTest {
IndexDefinition.IndexDefinitionContext underTest = new IndexDefinition.IndexDefinitionContext();
@Test
public void define() {
ViewIndexDefinition def = new ViewIndexDefinition(new MapSettings().asConfig());
def.define(underTest);
assertThat(underTest.getIndices()).hasSize(1);
NewIndex index = underTest.getIndices().get("views");
assertThat(index.getMainType())
.isEqualTo(IndexType.main(Index.simple("views"), "view"));
assertThat(index.getRelationsStream()).isEmpty();
assertThat(index.getSetting("index.number_of_shards")).isEqualTo("5");
assertThat(index.getSetting("index.number_of_replicas")).isEqualTo("0");
}
}
| 1,885 | 36.72 | 98 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/AnalysisTest.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;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class AnalysisTest {
@Test
public void constructor_throws_NPE_when_uuid_is_null() {
assertThatThrownBy(() -> new Analysis(null, 1_990L, "abcde"))
.isInstanceOf(NullPointerException.class)
.hasMessage("uuid must not be null");
}
@Test
public void test_bean() {
Analysis analysis = new Analysis("u1", 1_990L, "abcde");
assertThat(analysis.getUuid()).isEqualTo("u1");
assertThat(analysis.getDate()).isEqualTo(1_990L);
assertThat(analysis.getRevision()).hasValue("abcde");
analysis = new Analysis("u1", 1_990L, null);
assertThat(analysis.getRevision()).isEmpty();
}
}
| 1,654 | 33.479167 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/BranchTest.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;
import java.util.Random;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class BranchTest {
private Branch underTest = new Branch(true, "b", Branch.Type.BRANCH);
@Test
public void constructor_throws_NPE_if_type_is_null() {
assertThatThrownBy(() -> new Branch(new Random().nextBoolean(), "s", null))
.isInstanceOf(NullPointerException.class)
.hasMessage("type can't be null");
}
@Test
public void verify_getters() {
assertThat(underTest.isMain()).isTrue();
assertThat(underTest.getName()).contains("b");
assertThat(underTest.getType()).isEqualTo(Branch.Type.BRANCH);
Branch underTestWithNull = new Branch(false, null, Branch.Type.BRANCH);
assertThat(underTestWithNull.isMain()).isFalse();
assertThat(underTestWithNull.getName()).isEmpty();
assertThat(underTestWithNull.getType()).isEqualTo(Branch.Type.BRANCH);
}
}
| 1,863 | 34.846154 | 79 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/CeTaskTest.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;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class CeTaskTest {
private final CeTask underTest = new CeTask("A", CeTask.Status.SUCCESS);
@Test
public void constructor_throws_NPE_if_id_is_null() {
assertThatThrownBy(() -> new CeTask(null, CeTask.Status.SUCCESS))
.isInstanceOf(NullPointerException.class)
.hasMessage("id can't be null");
}
@Test
public void constructor_throws_NPE_if_status_is_null() {
assertThatThrownBy(() -> new CeTask("B", null))
.isInstanceOf(NullPointerException.class)
.hasMessage("status can't be null");
}
@Test
public void verify_getters() {
assertThat(underTest.id()).isEqualTo("A");
assertThat(underTest.status()).isEqualTo(CeTask.Status.SUCCESS);
}
}
| 1,733 | 33 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/HttpUrlHelperTest.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;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import okhttp3.HttpUrl;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.apache.commons.lang.StringUtils.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.webhook.HttpUrlHelper.obfuscateCredentials;
@RunWith(DataProviderRunner.class)
public class HttpUrlHelperTest {
@Test
@UseDataProvider("obfuscateCredentialsUseCases")
public void verify_obfuscateCredentials(String originalUrl, String expectedUrl) {
assertThat(obfuscateCredentials(originalUrl, HttpUrl.parse(originalUrl)))
.isEqualTo(obfuscateCredentials(originalUrl))
.isEqualTo(expectedUrl);
}
@DataProvider
public static Object[][] obfuscateCredentialsUseCases() {
List<Object[]> rows = new ArrayList<>();
for (String before : Arrays.asList("http://", "https://")) {
for (String host : Arrays.asList("foo", "127.0.0.1", "[2001:db8:85a3:0:0:8a2e:370:7334]", "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]")) {
for (String port : Arrays.asList("", ":123")) {
for (String after : Arrays.asList("", "/", "/bar", "/bar/", "?", "?a=b", "?a=b&c=d")) {
for (String username : Arrays.asList("", "us", "a b", "a%20b")) {
for (String password : Arrays.asList("", "pwd", "pwd%20k", "pwd k", "c:d")) {
if (username.isEmpty()) {
String url = before + host + port + after;
rows.add(new Object[] {url, url});
} else if (password.isEmpty()) {
String url = before + username + '@' + host + port + after;
String expected = before + repeat("*", username.length()) + '@' + host + port + after;
rows.add(new Object[] {url, expected});
} else {
String url = before + username + ':' + password + '@' + host + port + after;
String expected = before + repeat("*", username.length()) + ':' + repeat("*", password.length()) + '@' + host + port + after;
rows.add(new Object[] {url, expected});
}
}
}
}
}
}
}
return rows.toArray(new Object[0][]);
}
}
| 3,340 | 41.833333 | 143 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/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;
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,353 | 34.631579 | 78 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/ProjectAnalysisTest.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;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import org.junit.Test;
import org.sonar.api.measures.Metric;
import org.sonar.server.qualitygate.EvaluatedQualityGate;
import org.sonar.server.qualitygate.QualityGate;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ProjectAnalysisTest {
private final CeTask ceTask = new CeTask("id", CeTask.Status.SUCCESS);
private final Project project = new Project("uuid", "key", "name");
private final Analysis analysis = new Analysis("analysis_uuid", 1_500L, "sha1");
private final Branch branch = new Branch(true, "name", Branch.Type.BRANCH);
private final EvaluatedQualityGate qualityGate = EvaluatedQualityGate.newBuilder()
.setQualityGate(new QualityGate("id", "name", emptySet()))
.setStatus(Metric.Level.ERROR)
.build();
private final Map<String, String> properties = ImmutableMap.of("a", "b");
private ProjectAnalysis underTest = new ProjectAnalysis(project, ceTask, analysis, branch, qualityGate, 1L, properties);
@Test
public void constructor_throws_NPE_if_project_is_null() {
assertThatThrownBy(() -> {
new ProjectAnalysis(null,
ceTask,
analysis,
branch,
qualityGate,
1L,
emptyMap());
})
.isInstanceOf(NullPointerException.class)
.hasMessage("project can't be null");
}
@Test
public void constructor_throws_NPE_if_properties_is_null() {
assertThatThrownBy(() -> {
new ProjectAnalysis(project,
ceTask,
analysis,
branch,
qualityGate,
1L,
null);
})
.isInstanceOf(NullPointerException.class)
.hasMessage("properties can't be null");
}
@Test
public void verify_getters() {
assertThat(underTest.getCeTask()).containsSame(ceTask);
assertThat(underTest.getProject()).isSameAs(project);
assertThat(underTest.getBranch()).containsSame(branch);
assertThat(underTest.getQualityGate()).containsSame(qualityGate);
assertThat(underTest.getProperties()).isEqualTo(properties);
assertThat(underTest.getAnalysis()).contains(analysis);
ProjectAnalysis underTestWithNulls = new ProjectAnalysis(project, null, null, null, null, null, emptyMap());
assertThat(underTestWithNulls.getCeTask()).isEmpty();
assertThat(underTestWithNulls.getBranch()).isEmpty();
assertThat(underTestWithNulls.getQualityGate()).isEmpty();
assertThat(underTestWithNulls.getProperties()).isEmpty();
assertThat(underTestWithNulls.getAnalysis()).isEmpty();
}
@Test
public void defines_equals_based_on_all_fields() {
assertThat(underTest)
.isEqualTo(underTest)
.isEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, qualityGate, 1L, properties))
.isNotNull()
.isNotEqualTo(new Object())
.isNotEqualTo(new ProjectAnalysis(project, new CeTask("2", CeTask.Status.SUCCESS), analysis, branch, qualityGate, 1L, properties))
.isNotEqualTo(new ProjectAnalysis(new Project("A", "B", "C"), ceTask, analysis, branch, qualityGate, 1L, properties))
.isNotEqualTo(new ProjectAnalysis(new Project("A", "B", "C"), ceTask, analysis, branch, qualityGate, 1L, properties))
.isNotEqualTo(new ProjectAnalysis(project, null, null, null, qualityGate, 1L, properties))
.isNotEqualTo(new ProjectAnalysis(project, ceTask, null, null, qualityGate, 1L, properties))
.isNotEqualTo(new ProjectAnalysis(project, ceTask, new Analysis("foo", 1_500L, "sha1"), null, qualityGate, 1L, properties))
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, null, qualityGate, 1L, properties))
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, new Branch(false, "B", Branch.Type.BRANCH), qualityGate, 1L, properties))
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, null, 1L, properties));
EvaluatedQualityGate otherQualityGate = EvaluatedQualityGate.newBuilder()
.setQualityGate(new QualityGate("A", "B", emptySet()))
.setStatus(Metric.Level.ERROR)
.build();
assertThat(underTest)
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, otherQualityGate, 1L, properties))
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, qualityGate, null, properties))
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, qualityGate, 2L, properties))
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, qualityGate, 1L, emptyMap()))
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, qualityGate, 1L, ImmutableMap.of("A", "B")));
}
@Test
public void defines_hashcode_based_on_all_fields() {
assertThat(underTest)
.hasSameHashCodeAs(underTest)
.hasSameHashCodeAs(new ProjectAnalysis(project, ceTask, analysis, branch, qualityGate, 1L, properties));
assertThat(underTest.hashCode())
.isNotEqualTo(new Object().hashCode())
.isNotEqualTo(new ProjectAnalysis(project, new CeTask("2", CeTask.Status.SUCCESS), analysis, branch, qualityGate, 1L, properties).hashCode())
.isNotEqualTo(new ProjectAnalysis(new Project("A", "B", "C"), ceTask, analysis, branch, qualityGate, 1L, properties).hashCode())
.isNotEqualTo(new ProjectAnalysis(new Project("A", "B", "C"), ceTask, analysis, branch, qualityGate, 1L, properties).hashCode())
.isNotEqualTo(new ProjectAnalysis(project, null, null, null, qualityGate, 1L, properties).hashCode())
.isNotEqualTo(new ProjectAnalysis(project, ceTask, null, null, qualityGate, 1L, properties).hashCode())
.isNotEqualTo(new ProjectAnalysis(project, ceTask, new Analysis("foo", 1_500L, "sha1"), null, qualityGate, 1L, properties).hashCode())
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, null, qualityGate, 1L, properties).hashCode())
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, new Branch(false, "B", Branch.Type.BRANCH), qualityGate, 1L, properties).hashCode())
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, null, 1L, properties).hashCode());
EvaluatedQualityGate otherQualityGate = EvaluatedQualityGate.newBuilder()
.setQualityGate(new QualityGate("A", "B", emptySet()))
.setStatus(Metric.Level.ERROR)
.build();
assertThat(underTest.hashCode())
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, otherQualityGate, 1L, properties).hashCode())
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, this.qualityGate, null, properties).hashCode())
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, this.qualityGate, 2L, properties).hashCode())
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, this.qualityGate, 1L, emptyMap()).hashCode())
.isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, this.qualityGate, 1L, ImmutableMap.of("B", "C")).hashCode());
}
@Test
public void verify_toString() {
assertThat(underTest).hasToString(
"ProjectAnalysis{project=Project{uuid='uuid', key='key', name='name'}, ceTask=CeTask{id='id', status=SUCCESS}, branch=Branch{main=true, name='name', type=BRANCH}, qualityGate=EvaluatedQualityGate{qualityGate=QualityGate{id=id, name='name', conditions=[]}, status=ERROR, evaluatedConditions=[]}, updatedAt=1, properties={a=b}, analysis=Analysis{uuid='analysis_uuid', date=1500, revision=sha1}}");
}
}
| 8,500 | 52.465409 | 401 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/TestWebhookCaller.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;
import java.util.LinkedList;
import java.util.Queue;
import javax.annotation.Nullable;
import static java.util.Objects.requireNonNull;
public class TestWebhookCaller implements WebhookCaller {
private final Queue<Item> deliveries = new LinkedList<>();
private int countSent = 0;
public TestWebhookCaller enqueueSuccess(long at, int httpCode, int durationMs) {
deliveries.add(new Item(at, httpCode, durationMs, null));
return this;
}
public TestWebhookCaller enqueueFailure(long at, Throwable t) {
deliveries.add(new Item(at, null, null, t));
return this;
}
@Override
public WebhookDelivery call(Webhook webhook, WebhookPayload payload) {
Item item = requireNonNull(deliveries.poll(), "Queue is empty");
countSent++;
return new WebhookDelivery.Builder()
.setAt(item.at)
.setHttpStatus(item.httpCode)
.setDurationInMs(item.durationMs)
.setError(item.throwable)
.setPayload(payload)
.setWebhook(webhook)
.build();
}
public int countSent() {
return countSent;
}
private static class Item {
final long at;
final Integer httpCode;
final Integer durationMs;
final Throwable throwable;
Item(long at, @Nullable Integer httpCode, @Nullable Integer durationMs, @Nullable Throwable throwable) {
this.at = at;
this.httpCode = httpCode;
this.durationMs = durationMs;
this.throwable = throwable;
}
}
}
| 2,322 | 29.973333 | 108 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookCallerImplTest.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;
import com.google.common.collect.ImmutableList;
import java.net.InetAddress;
import java.util.Optional;
import okhttp3.Credentials;
import okhttp3.HttpUrl;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.mockito.Mockito;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.Version;
import org.sonar.core.platform.SonarQubeVersion;
import org.sonar.server.util.OkHttpClientProvider;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.sonar.api.CoreProperties.SONAR_VALIDATE_WEBHOOKS_PROPERTY;
public class WebhookCallerImplTest {
private static final long NOW = 1_500_000_000_000L;
private static final String PROJECT_UUID = "P_UUID1";
private static final String WEBHOOK_UUID = "WH_UUID1";
private static final String CE_TASK_UUID = "CE_UUID1";
private static final String SOME_JSON = "{\"payload\": {}}";
private static final WebhookPayload PAYLOAD = new WebhookPayload("P1", SOME_JSON);
@Rule
public MockWebServer server = new MockWebServer();
@Rule
public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60));
Configuration configuration = Mockito.mock(Configuration.class);
NetworkInterfaceProvider networkInterfaceProvider = Mockito.mock(NetworkInterfaceProvider.class);
private System2 system = new TestSystem2().setNow(NOW);
@Test
public void post_payload_to_http_server() throws Exception {
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, randomAlphanumeric(40),
"my-webhook", server.url("/ping").toString(), null);
server.enqueue(new MockResponse().setBody("pong").setResponseCode(201));
WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD);
assertThat(delivery.getHttpStatus()).hasValue(201);
assertThat(delivery.getWebhook().getUuid()).isEqualTo(WEBHOOK_UUID);
assertThat(delivery.getDurationInMs().get()).isNotNegative();
assertThat(delivery.getError()).isEmpty();
assertThat(delivery.getAt()).isEqualTo(NOW);
assertThat(delivery.getWebhook()).isSameAs(webhook);
assertThat(delivery.getPayload()).isSameAs(PAYLOAD);
RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo("POST");
assertThat(recordedRequest.getPath()).isEqualTo("/ping");
assertThat(recordedRequest.getBody().readUtf8()).isEqualTo(PAYLOAD.getJson());
assertThat(recordedRequest.getHeader("User-Agent")).isEqualTo("SonarQube/6.2");
assertThat(recordedRequest.getHeader("Content-Type")).isEqualTo("application/json; charset=utf-8");
assertThat(recordedRequest.getHeader("X-SonarQube-Project")).isEqualTo(PAYLOAD.getProjectKey());
assertThat(recordedRequest.getHeader("X-Sonar-Webhook-HMAC-SHA256")).isNull();
}
@Test
public void sign_payload_if_secret_is_set() throws Exception {
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID, randomAlphanumeric(40),
"my-webhook", server.url("/ping").toString(), "my_secret");
server.enqueue(new MockResponse().setBody("pong").setResponseCode(201));
newSender(false).call(webhook, PAYLOAD);
RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getHeader("X-Sonar-Webhook-HMAC-SHA256")).isEqualTo("ef35d3420a3df3d05f8f7eb3b53384abc41395f164245d6c7e78a70e61703dde");
}
@Test
public void silently_catch_error_when_external_server_does_not_answer() throws Exception {
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
randomAlphanumeric(40), "my-webhook", server.url("/ping").toString(), null);
server.shutdown();
WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD);
assertThat(delivery.getHttpStatus()).isEmpty();
assertThat(delivery.getDurationInMs().get()).isNotNegative();
// message can be "Connection refused" or "connect timed out"
assertThat(delivery.getErrorMessage().get()).matches("(.*Connection refused.*)|(.*connect timed out.*)");
assertThat(delivery.getAt()).isEqualTo(NOW);
assertThat(delivery.getWebhook()).isSameAs(webhook);
assertThat(delivery.getPayload()).isSameAs(PAYLOAD);
}
@Test
public void silently_catch_error_when_url_is_incorrect() {
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
randomAlphanumeric(40), "my-webhook", "this_is_not_an_url", null);
WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD);
assertThat(delivery.getHttpStatus()).isEmpty();
assertThat(delivery.getDurationInMs().get()).isNotNegative();
assertThat(delivery.getError().get()).isInstanceOf(IllegalArgumentException.class);
assertThat(delivery.getErrorMessage()).contains("Webhook URL is not valid: this_is_not_an_url");
assertThat(delivery.getAt()).isEqualTo(NOW);
assertThat(delivery.getWebhook()).isSameAs(webhook);
assertThat(delivery.getPayload()).isSameAs(PAYLOAD);
}
/**
* SONAR-8799
*/
@Test
public void redirects_should_be_followed_with_POST_method() throws Exception {
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
randomAlphanumeric(40), "my-webhook", server.url("/redirect").toString(), null);
// /redirect redirects to /target
server.enqueue(new MockResponse().setResponseCode(307).setHeader("Location", server.url("target")));
server.enqueue(new MockResponse().setResponseCode(200));
WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD);
assertThat(delivery.getHttpStatus()).contains(200);
assertThat(delivery.getDurationInMs().get()).isNotNegative();
assertThat(delivery.getError()).isEmpty();
assertThat(delivery.getAt()).isEqualTo(NOW);
assertThat(delivery.getWebhook()).isSameAs(webhook);
assertThat(delivery.getPayload()).isSameAs(PAYLOAD);
takeAndVerifyPostRequest("/redirect");
takeAndVerifyPostRequest("/target");
}
@Test
public void credentials_are_propagated_to_POST_redirects() throws Exception {
HttpUrl url = server.url("/redirect").newBuilder().username("theLogin").password("thePassword").build();
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
randomAlphanumeric(40), "my-webhook", url.toString(), null);
// /redirect redirects to /target
server.enqueue(new MockResponse().setResponseCode(307).setHeader("Location", server.url("target")));
server.enqueue(new MockResponse().setResponseCode(200));
WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD);
assertThat(delivery.getHttpStatus()).contains(200);
RecordedRequest redirectedRequest = takeAndVerifyPostRequest("/redirect");
assertThat(redirectedRequest.getHeader("Authorization")).isEqualTo(Credentials.basic(url.username(), url.password()));
RecordedRequest targetRequest = takeAndVerifyPostRequest("/target");
assertThat(targetRequest.getHeader("Authorization")).isEqualTo(Credentials.basic(url.username(), url.password()));
}
@Test
public void redirects_throws_ISE_if_header_Location_is_missing() {
HttpUrl url = server.url("/redirect");
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
randomAlphanumeric(40), "my-webhook", url.toString(), null);
server.enqueue(new MockResponse().setResponseCode(307));
WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD);
Throwable error = delivery.getError().get();
assertThat(error)
.isInstanceOf(IllegalStateException.class)
.hasMessage("Missing HTTP header 'Location' in redirect of " + url);
}
@Test
public void redirects_throws_ISE_if_header_Location_does_not_relate_to_a_supported_protocol() {
HttpUrl url = server.url("/redirect");
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
randomAlphanumeric(40), "my-webhook", url.toString(), null);
server.enqueue(new MockResponse().setResponseCode(307).setHeader("Location", "ftp://foo"));
WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD);
Throwable error = delivery.getError().get();
assertThat(error)
.isInstanceOf(IllegalStateException.class)
.hasMessage("Unsupported protocol in redirect of " + url + " to ftp://foo");
}
@Test
public void send_basic_authentication_header_if_url_contains_credentials() throws Exception {
HttpUrl url = server.url("/ping").newBuilder().username("theLogin").password("thePassword").build();
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
randomAlphanumeric(40), "my-webhook", url.toString(), null);
server.enqueue(new MockResponse().setBody("pong"));
WebhookDelivery delivery = newSender(false).call(webhook, PAYLOAD);
assertThat(delivery.getWebhook().getUrl())
.isEqualTo(url.toString())
.contains("://theLogin:thePassword@");
RecordedRequest recordedRequest = takeAndVerifyPostRequest("/ping");
assertThat(recordedRequest.getHeader("Authorization")).isEqualTo(Credentials.basic(url.username(), url.password()));
}
@Test
public void silently_catch_error_when_url_is_localhost(){
String url = server.url("/").toString();
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
randomAlphanumeric(40), "my-webhook", url, null);
WebhookDelivery delivery = newSender(true).call(webhook, PAYLOAD);
assertThat(delivery.getHttpStatus()).isEmpty();
assertThat(delivery.getDurationInMs().get()).isNotNegative();
assertThat(delivery.getError().get()).isInstanceOf(IllegalArgumentException.class);
assertThat(delivery.getErrorMessage()).contains("Invalid URL: loopback and wildcard addresses are not allowed for webhooks.");
assertThat(delivery.getAt()).isEqualTo(NOW);
assertThat(delivery.getWebhook()).isSameAs(webhook);
assertThat(delivery.getPayload()).isSameAs(PAYLOAD);
}
@Test
public void silently_catch_error_when_url_is_local_network_interface() throws Exception {
String url = "https://localhost";
InetAddress inetAddress = InetAddress.getByName(HttpUrl.parse(url).host());
when(networkInterfaceProvider.getNetworkInterfaceAddresses())
.thenReturn(ImmutableList.of(inetAddress));
Webhook webhook = new Webhook(WEBHOOK_UUID, PROJECT_UUID, CE_TASK_UUID,
randomAlphanumeric(40), "my-webhook", url, null);
WebhookDelivery delivery = newSender(true).call(webhook, PAYLOAD);
assertThat(delivery.getHttpStatus()).isEmpty();
assertThat(delivery.getDurationInMs().get()).isNotNegative();
assertThat(delivery.getError().get()).isInstanceOf(IllegalArgumentException.class);
assertThat(delivery.getErrorMessage()).contains("Invalid URL: loopback and wildcard addresses are not allowed for webhooks.");
assertThat(delivery.getAt()).isEqualTo(NOW);
assertThat(delivery.getWebhook()).isSameAs(webhook);
assertThat(delivery.getPayload()).isSameAs(PAYLOAD);
}
private RecordedRequest takeAndVerifyPostRequest(String expectedPath) throws Exception {
RecordedRequest request = server.takeRequest();
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getPath()).isEqualTo(expectedPath);
assertThat(request.getHeader("User-Agent")).isEqualTo("SonarQube/6.2");
return request;
}
private WebhookCaller newSender(boolean validateWebhook) {
SonarQubeVersion version = new SonarQubeVersion(Version.parse("6.2"));
when(configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY))
.thenReturn(Optional.of(validateWebhook));
WebhookCustomDns webhookCustomDns = new WebhookCustomDns(configuration, networkInterfaceProvider);
return new WebhookCallerImpl(system, new OkHttpClientProvider().provide(new MapSettings().asConfig(), version), webhookCustomDns);
}
}
| 13,153 | 44.202749 | 151 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookCustomDnsTest.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;
import com.google.common.collect.ImmutableList;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Optional;
import okhttp3.HttpUrl;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.config.Configuration;
import static org.mockito.Mockito.when;
import static org.sonar.api.CoreProperties.SONAR_VALIDATE_WEBHOOKS_PROPERTY;
public class WebhookCustomDnsTest {
private static final String INVALID_URL = "Invalid URL: loopback and wildcard addresses are not allowed for webhooks.";
private Configuration configuration = Mockito.mock(Configuration.class);
private NetworkInterfaceProvider networkInterfaceProvider = Mockito.mock(NetworkInterfaceProvider.class);
private WebhookCustomDns underTest = new WebhookCustomDns(configuration, networkInterfaceProvider);
@Test
public void lookup_fail_on_localhost() {
when(configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY))
.thenReturn(Optional.of(true));
Assertions.assertThatThrownBy(() -> underTest.lookup("localhost"))
.hasMessageContaining(INVALID_URL)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void lookup_fail_on_127_0_0_1() {
when(configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY))
.thenReturn(Optional.of(true));
Assertions.assertThatThrownBy(() -> underTest.lookup("127.0.0.1"))
.hasMessageContaining(INVALID_URL)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void lookup_fail_on_192_168_1_21() throws UnknownHostException, SocketException {
InetAddress inetAddress = InetAddress.getByName(HttpUrl.parse("https://192.168.1.21/").host());
when(configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY))
.thenReturn(Optional.of(true));
when(networkInterfaceProvider.getNetworkInterfaceAddresses())
.thenReturn(ImmutableList.of(inetAddress));
Assertions.assertThatThrownBy(() -> underTest.lookup("192.168.1.21"))
.hasMessageContaining(INVALID_URL)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void lookup_fail_on_ipv6_local_case_insensitive() throws UnknownHostException, SocketException {
Optional<InetAddress> inet6Address = Collections.list(NetworkInterface.getNetworkInterfaces())
.stream()
.flatMap(ni -> Collections.list(ni.getInetAddresses()).stream())
.filter(i -> i instanceof Inet6Address).findAny();
if (!inet6Address.isPresent()) {
return;
}
String differentCaseAddress = getDifferentCaseInetAddress(inet6Address.get());
when(configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY))
.thenReturn(Optional.of(true));
when(networkInterfaceProvider.getNetworkInterfaceAddresses())
.thenReturn(ImmutableList.of(inet6Address.get()));
Assertions.assertThatThrownBy(() -> underTest.lookup(differentCaseAddress))
.hasMessageContaining(INVALID_URL)
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void lookup_fail_on_network_interface_throwing_socket_exception() throws SocketException {
when(networkInterfaceProvider.getNetworkInterfaceAddresses())
.thenThrow(new SocketException());
Assertions.assertThatThrownBy(() -> underTest.lookup("sonarsource.com"))
.hasMessageContaining("Network interfaces could not be fetched.")
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void lookup_dont_fail_on_localhost_if_validation_disabled() throws UnknownHostException {
when(configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY))
.thenReturn(Optional.of(false));
Assertions.assertThat(underTest.lookup("localhost"))
.extracting(InetAddress::toString)
.containsExactlyInAnyOrder("localhost/127.0.0.1");
}
@Test
public void lookup_dont_fail_on_classic_host_with_validation_enabled() throws UnknownHostException {
when(configuration.getBoolean(SONAR_VALIDATE_WEBHOOKS_PROPERTY))
.thenReturn(Optional.of(true));
Assertions.assertThat(underTest.lookup("sonarsource.com").toString()).contains("sonarsource.com/");
}
private String getDifferentCaseInetAddress(InetAddress inetAddress) {
StringBuilder differentCaseAddress = new StringBuilder();
String address = inetAddress.getHostAddress();
int i;
for (i = 0; i < address.length(); i++) {
char c = address.charAt(i);
if (Character.isAlphabetic(c)) {
differentCaseAddress.append(Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c));
break;
} else {
differentCaseAddress.append(c);
}
}
if (i < address.length() - 1) {
differentCaseAddress.append(address.substring(i + 1));
}
return differentCaseAddress.toString();
}
}
| 5,834 | 36.645161 | 121 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookDeliveryTest.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;
import java.io.IOException;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class WebhookDeliveryTest {
@Test
public void isSuccess_returns_false_if_failed_to_send_http_request() {
WebhookDelivery delivery = newBuilderTemplate()
.setError(new IOException("Fail to connect"))
.build();
assertThat(delivery.isSuccess()).isFalse();
}
@Test
public void isSuccess_returns_false_if_http_response_returns_error_status() {
WebhookDelivery delivery = newBuilderTemplate()
.setHttpStatus(404)
.build();
assertThat(delivery.isSuccess()).isFalse();
}
@Test
public void isSuccess_returns_true_if_http_response_returns_2xx_code() {
WebhookDelivery delivery = newBuilderTemplate()
.setHttpStatus(204)
.build();
assertThat(delivery.isSuccess()).isTrue();
}
@Test
public void getErrorMessage_returns_empty_if_no_error() {
WebhookDelivery delivery = newBuilderTemplate().build();
assertThat(delivery.getErrorMessage()).isEmpty();
}
@Test
public void getErrorMessage_returns_root_cause_message_if_error() {
Exception rootCause = new IOException("fail to connect");
Exception cause = new IOException("nested", rootCause);
WebhookDelivery delivery = newBuilderTemplate()
.setError(cause)
.build();
assertThat(delivery.getErrorMessage()).contains("fail to connect");
}
private static WebhookDelivery.Builder newBuilderTemplate() {
return new WebhookDelivery.Builder()
.setWebhook(mock(Webhook.class))
.setPayload(mock(WebhookPayload.class))
.setAt(1_000L);
}
}
| 2,563 | 29.891566 | 79 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookModuleTest.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;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class WebhookModuleTest {
private WebhookModule underTest = new WebhookModule();
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
underTest.configure(container);
assertThat(container.getAddedObjects().size()).isNotZero();
}
}
| 1,317 | 31.95 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookPayloadFactoryImplTest.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;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.measures.Metric;
import org.sonar.api.platform.Server;
import org.sonar.api.utils.System2;
import org.sonar.server.qualitygate.Condition;
import org.sonar.server.qualitygate.EvaluatedCondition;
import org.sonar.server.qualitygate.EvaluatedQualityGate;
import org.sonar.server.qualitygate.QualityGate;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
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 WebhookPayloadFactoryImplTest {
private static final String PROJECT_KEY = "P1";
private Server server = mock(Server.class);
private System2 system2 = mock(System2.class);
private WebhookPayloadFactory underTest = new WebhookPayloadFactoryImpl(server, system2);
@Before
public void setUp() {
when(server.getPublicRootUrl()).thenReturn("http://foo");
when(system2.now()).thenReturn(1_500_999L);
}
@Test
public void create_payload_for_successful_analysis() {
CeTask task = new CeTask("#1", CeTask.Status.SUCCESS);
Condition condition = new Condition("coverage", Condition.Operator.GREATER_THAN, "70.0");
EvaluatedQualityGate gate = EvaluatedQualityGate.newBuilder()
.setQualityGate(new QualityGate("G1", "Gate One", singleton(condition)))
.setStatus(Metric.Level.ERROR)
.addEvaluatedCondition(condition, EvaluatedCondition.EvaluationStatus.ERROR, "74.0")
.build();
ProjectAnalysis analysis = newAnalysis(task, gate, null, 1_500_000_000_000L, emptyMap());
WebhookPayload payload = underTest.create(analysis);
assertThat(payload.getProjectKey()).isEqualTo(PROJECT_KEY);
assertJson(payload.getJson())
.isSimilarTo("{" +
" \"serverUrl\": \"http://foo\"," +
" \"taskId\": \"#1\"," +
" \"status\": \"SUCCESS\"," +
" \"analysedAt\": \"2017-07-14T04:40:00+0200\"," +
" \"revision\": \"sha1\"," +
" \"changedAt\": \"2017-07-14T04:40:00+0200\"," +
" \"project\": {" +
" \"key\": \"P1\"," +
" \"name\": \"Project One\"," +
" \"url\": \"http://foo/dashboard?id=P1\"" +
" }," +
" \"qualityGate\": {" +
" \"name\": \"Gate One\"," +
" \"status\": \"ERROR\"," +
" \"conditions\": [" +
" {" +
" \"metric\": \"coverage\"," +
" \"operator\": \"GREATER_THAN\"," +
" \"value\": \"74.0\"," +
" \"status\": \"ERROR\"," +
" \"errorThreshold\": \"70.0\"" +
" }" +
" ]" +
" }," +
" \"properties\": {" +
" }" +
"}");
}
@Test
public void create_payload_with_gate_conditions_without_value() {
CeTask task = new CeTask("#1", CeTask.Status.SUCCESS);
Condition condition = new Condition("coverage", Condition.Operator.GREATER_THAN, "70.0");
EvaluatedQualityGate gate = EvaluatedQualityGate.newBuilder()
.setQualityGate(new QualityGate("G1", "Gate One", singleton(condition)))
.setStatus(Metric.Level.ERROR)
.addEvaluatedCondition(condition, EvaluatedCondition.EvaluationStatus.NO_VALUE, null)
.build();
ProjectAnalysis analysis = newAnalysis(task, gate, null, 1_500_000_000_000L, emptyMap());
WebhookPayload payload = underTest.create(analysis);
assertThat(payload.getProjectKey()).isEqualTo(PROJECT_KEY);
assertJson(payload.getJson())
.isSimilarTo("{" +
" \"serverUrl\": \"http://foo\"," +
" \"taskId\": \"#1\"," +
" \"status\": \"SUCCESS\"," +
" \"analysedAt\": \"2017-07-14T04:40:00+0200\"," +
" \"revision\": \"sha1\"," +
" \"changedAt\": \"2017-07-14T04:40:00+0200\"," +
" \"project\": {" +
" \"key\": \"P1\"," +
" \"name\": \"Project One\"," +
" \"url\": \"http://foo/dashboard?id=P1\"" +
" }," +
" \"qualityGate\": {" +
" \"name\": \"Gate One\"," +
" \"status\": \"ERROR\"," +
" \"conditions\": [" +
" {" +
" \"metric\": \"coverage\"," +
" \"operator\": \"GREATER_THAN\"," +
" \"status\": \"NO_VALUE\"," +
" \"errorThreshold\": \"70.0\"" +
" }" +
" ]" +
" }" +
"}");
}
@Test
public void create_payload_with_analysis_properties() {
CeTask task = new CeTask("#1", CeTask.Status.SUCCESS);
EvaluatedQualityGate gate = EvaluatedQualityGate.newBuilder()
.setQualityGate(new QualityGate("G1", "Gate One", emptySet()))
.setStatus(Metric.Level.ERROR)
.build();
Map<String, String> scannerProperties = ImmutableMap.of(
"sonar.analysis.foo", "bar",
"sonar.analysis.buildNumber", "B123",
"not.prefixed.with.sonar.analysis", "should be ignored",
"ignored", "should be ignored too");
ProjectAnalysis analysis = newAnalysis(task, gate, null, 1_500_000_000_000L, scannerProperties);
WebhookPayload payload = underTest.create(analysis);
assertJson(payload.getJson())
.isSimilarTo("{" +
" \"serverUrl\": \"http://foo\"," +
" \"taskId\": \"#1\"," +
" \"status\": \"SUCCESS\"," +
" \"analysedAt\": \"2017-07-14T04:40:00+0200\"," +
" \"revision\": \"sha1\"," +
" \"changedAt\": \"2017-07-14T04:40:00+0200\"," +
" \"project\": {" +
" \"key\": \"P1\"," +
" \"name\": \"Project One\"," +
" \"url\": \"http://foo/dashboard?id=P1\"" +
" }," +
" \"qualityGate\": {" +
" \"name\": \"Gate One\"," +
" \"status\": \"ERROR\"," +
" \"conditions\": [" +
" ]" +
" }," +
" \"properties\": {" +
" \"sonar.analysis.foo\": \"bar\"," +
" \"sonar.analysis.buildNumber\": \"B123\"" +
" }" +
"}");
assertThat(payload.getJson())
.doesNotContain("not.prefixed.with.sonar.analysis")
.doesNotContain("ignored");
}
@Test
public void create_payload_for_failed_analysis() {
CeTask ceTask = new CeTask("#1", CeTask.Status.FAILED);
ProjectAnalysis analysis = newAnalysis(ceTask, null, null, 1_500_000_000_000L, emptyMap());
WebhookPayload payload = underTest.create(analysis);
assertThat(payload.getProjectKey()).isEqualTo(PROJECT_KEY);
assertJson(payload.getJson())
.isSimilarTo("{" +
" \"serverUrl\": \"http://foo\"," +
" \"taskId\": \"#1\"," +
" \"status\": \"FAILED\"," +
" \"changedAt\": \"2017-07-14T04:40:00+0200\"," +
" \"project\": {" +
" \"key\": \"P1\"," +
" \"name\": \"Project One\"," +
" \"url\": \"http://foo/dashboard?id=P1\"" +
" }," +
" \"properties\": {" +
" }" +
"}");
}
@Test
public void create_payload_for_no_analysis_date() {
CeTask ceTask = new CeTask("#1", CeTask.Status.FAILED);
ProjectAnalysis analysis = newAnalysis(ceTask, null, null, null, emptyMap());
WebhookPayload payload = underTest.create(analysis);
assertThat(payload.getProjectKey()).isEqualTo(PROJECT_KEY);
assertJson(payload.getJson())
.isSimilarTo("{" +
" \"serverUrl\": \"http://foo\"," +
" \"taskId\": \"#1\"," +
" \"status\": \"FAILED\"," +
" \"changedAt\": \"1970-01-01T01:25:00+0100\"," +
" \"project\": {" +
" \"key\": \"P1\"," +
" \"name\": \"Project One\"" +
" }," +
" \"properties\": {" +
" }" +
"}");
}
@Test
public void create_payload_on_pull_request() {
CeTask task = new CeTask("#1", CeTask.Status.SUCCESS);
ProjectAnalysis analysis = newAnalysis(task, null, new Branch(false, "pr/foo", Branch.Type.PULL_REQUEST), 1_500_000_000_000L, emptyMap());
WebhookPayload payload = underTest.create(analysis);
assertJson(payload.getJson())
.isSimilarTo("{" +
"\"branch\": {" +
" \"name\": \"pr/foo\"," +
" \"type\": \"PULL_REQUEST\"," +
" \"isMain\": false," +
" \"url\": \"http://foo/dashboard?id=P1&pullRequest=pr%2Ffoo\"" +
"}" +
"}");
}
@Test
public void create_without_ce_task() {
ProjectAnalysis analysis = newAnalysis(null, null, null, null, emptyMap());
WebhookPayload payload = underTest.create(analysis);
String json = payload.getJson();
assertThat(json).doesNotContain("taskId");
assertJson(json)
.isSimilarTo("{" +
" \"serverUrl\": \"http://foo\"," +
" \"status\": \"SUCCESS\"," +
" \"changedAt\": \"1970-01-01T01:25:00+0100\"," +
" \"project\": {" +
" \"key\": \"P1\"," +
" \"name\": \"Project One\"" +
" }," +
" \"properties\": {" +
" }" +
"}");
}
@Test
public void create_payload_on_branch() {
CeTask task = new CeTask("#1", CeTask.Status.SUCCESS);
ProjectAnalysis analysis = newAnalysis(task, null, new Branch(false, "feature/foo", Branch.Type.BRANCH), 1_500_000_000_000L, emptyMap());
WebhookPayload payload = underTest.create(analysis);
assertJson(payload.getJson())
.isSimilarTo("{" +
"\"branch\": {" +
" \"name\": \"feature/foo\"" +
" \"type\": \"BRANCH\"" +
" \"isMain\": false," +
" \"url\": \"http://foo/dashboard?id=P1&branch=feature%2Ffoo\"" +
"}" +
"}");
}
@Test
public void create_payload_on_main_branch_without_name() {
CeTask task = new CeTask("#1", CeTask.Status.SUCCESS);
ProjectAnalysis analysis = newAnalysis(task, null, new Branch(true, null, Branch.Type.BRANCH), 1_500_000_000_000L, emptyMap());
WebhookPayload payload = underTest.create(analysis);
assertJson(payload.getJson())
.isSimilarTo("{" +
"\"branch\": {" +
" \"type\": \"BRANCH\"" +
" \"isMain\": true," +
" \"url\": \"http://foo/dashboard?id=P1\"" +
"}" +
"}");
}
private static ProjectAnalysis newAnalysis(@Nullable CeTask task, @Nullable EvaluatedQualityGate gate,
@Nullable Branch branch, @Nullable Long analysisDate, Map<String, String> scannerProperties) {
return new ProjectAnalysis(new Project("P1_UUID", PROJECT_KEY, "Project One"), task, analysisDate == null ? null : new Analysis("A_UUID1", analysisDate, "sha1"), branch,
gate, analysisDate, scannerProperties);
}
}
| 11,697 | 36.614148 | 173 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookTest.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;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class WebhookTest {
@Test
public void webhook_with_only_required_fields() {
Webhook underTest = new Webhook("a_uuid", "a_project_uuid", null, null, "a_name", "an_url", null);
assertThat(underTest.getUuid()).isEqualTo("a_uuid");
assertThat(underTest.getProjectUuid()).isEqualTo("a_project_uuid");
assertThat(underTest.getCeTaskUuid()).isEmpty();
assertThat(underTest.getAnalysisUuid()).isEmpty();
assertThat(underTest.getName()).isEqualTo("a_name");
assertThat(underTest.getUrl()).isEqualTo("an_url");
assertThat(underTest.getSecret()).isEmpty();
}
@Test
public void webhook_with_all_fields() {
Webhook underTest = new Webhook("a_uuid", "a_component_uuid", "a_task_uuid", "an_analysis", "a_name", "an_url", "a_secret");
assertThat(underTest.getUuid()).isEqualTo("a_uuid");
assertThat(underTest.getProjectUuid()).isEqualTo("a_component_uuid");
assertThat(underTest.getCeTaskUuid()).hasValue("a_task_uuid");
assertThat(underTest.getAnalysisUuid()).hasValue("an_analysis");
assertThat(underTest.getName()).isEqualTo("a_name");
assertThat(underTest.getUrl()).isEqualTo("an_url");
assertThat(underTest.getSecret()).hasValue("a_secret");
}
}
| 2,183 | 39.444444 | 128 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/es/EsTester.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.es;
import com.google.common.base.Throwables;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import org.apache.commons.lang.reflect.ConstructorUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.analysis.common.CommonAnalysisPlugin;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.discovery.DiscoveryModule;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.http.BindHttpException;
import org.elasticsearch.http.HttpTransportSettings;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.indices.recovery.RecoverySettings;
import org.elasticsearch.join.ParentJoinPlugin;
import org.elasticsearch.node.InternalSettingsPreparer;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeValidationException;
import org.elasticsearch.reindex.ReindexPlugin;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.Netty4Plugin;
import org.junit.rules.ExternalResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.server.component.index.ComponentIndexDefinition;
import org.sonar.server.es.IndexDefinition.IndexDefinitionContext;
import org.sonar.server.es.IndexType.IndexRelationType;
import org.sonar.server.es.newindex.BuiltIndex;
import org.sonar.server.es.newindex.NewIndex;
import org.sonar.server.issue.index.IssueIndexDefinition;
import org.sonar.server.measure.index.ProjectMeasuresIndexDefinition;
import org.sonar.server.rule.index.RuleIndexDefinition;
import org.sonar.server.view.index.ViewIndexDefinition;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Lists.newArrayList;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.sonar.server.es.Index.ALL_INDICES;
import static org.sonar.server.es.IndexType.FIELD_INDEX_TYPE;
import static org.sonar.server.es.newindex.DefaultIndexSettings.REFRESH_IMMEDIATE;
public class EsTester extends ExternalResource {
private static final int MIN_PORT = 1;
private static final int MAX_PORT = 49151;
private static final int MIN_NON_ROOT_PORT = 1025;
private static final Logger LOG = LoggerFactory.getLogger(EsTester.class);
static {
System.setProperty("log4j.shutdownHookEnabled", "false");
// we can not shutdown logging when tests are running or the next test that runs within the
// same JVM will try to initialize logging after a security manager has been installed and
// this will fail
System.setProperty("es.log4j.shutdownEnabled", "false");
System.setProperty("log4j2.disable.jmx", "true");
System.setProperty("log4j.skipJansi", "true"); // jython has this crazy shaded Jansi version that log4j2 tries to load
if (!Strings.hasLength(System.getProperty("tests.es.logger.level"))) {
System.setProperty("tests.es.logger.level", "WARN");
}
}
private static final Node SHARED_NODE = createNode();
private static final EsClient ES_REST_CLIENT = createEsRestClient(SHARED_NODE);
private static final AtomicBoolean CORE_INDICES_CREATED = new AtomicBoolean(false);
private static final Set<String> CORE_INDICES_NAMES = new HashSet<>();
private final boolean isCustom;
private EsTester(boolean isCustom) {
this.isCustom = isCustom;
}
/**
* New instance which contains the core indices (rules, issues, ...).
*/
public static EsTester create() {
if (!CORE_INDICES_CREATED.get()) {
List<BuiltIndex> createdIndices = createIndices(
ComponentIndexDefinition.createForTest(),
IssueIndexDefinition.createForTest(),
ProjectMeasuresIndexDefinition.createForTest(),
RuleIndexDefinition.createForTest(),
ViewIndexDefinition.createForTest());
CORE_INDICES_CREATED.set(true);
createdIndices.stream().map(t -> t.getMainType().getIndex().getName()).forEach(CORE_INDICES_NAMES::add);
}
return new EsTester(false);
}
/**
* New instance which contains the specified indices. Note that
* core indices may exist.
*/
public static EsTester createCustom(IndexDefinition... definitions) {
createIndices(definitions);
return new EsTester(true);
}
public void recreateIndexes() {
deleteIndexIfExists(ALL_INDICES.getName());
CORE_INDICES_CREATED.set(false);
create();
}
@Override
protected void after() {
if (isCustom) {
// delete non-core indices
String[] existingIndices = getIndicesNames();
Stream.of(existingIndices)
.filter(i -> !CORE_INDICES_NAMES.contains(i))
.forEach(EsTester::deleteIndexIfExists);
}
deleteAllDocumentsInIndexes();
}
private void deleteAllDocumentsInIndexes() {
try {
ES_REST_CLIENT.nativeClient()
.deleteByQuery(new DeleteByQueryRequest(ALL_INDICES.getName()).setQuery(QueryBuilders.matchAllQuery()).setRefresh(true).setWaitForActiveShards(1), RequestOptions.DEFAULT);
ES_REST_CLIENT.forcemerge(new ForceMergeRequest());
} catch (IOException e) {
throw new IllegalStateException("Could not delete data from _all indices", e);
}
}
private static String[] getIndicesNames() {
String[] existingIndices;
try {
existingIndices = ES_REST_CLIENT.nativeClient().indices().get(new GetIndexRequest(ALL_INDICES.getName()), RequestOptions.DEFAULT).getIndices();
} catch (ElasticsearchStatusException e) {
if (e.status().getStatus() == 404) {
existingIndices = new String[0];
} else {
throw e;
}
} catch (IOException e) {
throw new IllegalStateException("Could not get indicies", e);
}
return existingIndices;
}
private static EsClient createEsRestClient(Node sharedNode) {
assertThat(sharedNode.isClosed()).isFalse();
String host = sharedNode.settings().get(HttpTransportSettings.SETTING_HTTP_BIND_HOST.getKey());
Integer port = sharedNode.settings().getAsInt(HttpTransportSettings.SETTING_HTTP_PORT.getKey(), -1);
return new EsClient(new HttpHost(host, port));
}
public EsClient client() {
return ES_REST_CLIENT;
}
public RestHighLevelClient nativeClient() {
return ES_REST_CLIENT.nativeClient();
}
public void putDocuments(IndexType indexType, BaseDoc... docs) {
BulkRequest bulk = new BulkRequest()
.setRefreshPolicy(REFRESH_IMMEDIATE);
for (BaseDoc doc : docs) {
bulk.add(doc.toIndexRequest());
}
BulkResponse bulkResponse = ES_REST_CLIENT.bulk(bulk);
if (bulkResponse.hasFailures()) {
fail("Bulk indexing of documents failed: " + bulkResponse.buildFailureMessage());
}
}
public void putDocuments(IndexType indexType, Map<String, Object>... docs) {
try {
BulkRequest bulk = new BulkRequest()
.setRefreshPolicy(REFRESH_IMMEDIATE);
for (Map<String, Object> doc : docs) {
IndexType.IndexMainType mainType = indexType.getMainType();
bulk.add(new IndexRequest(mainType.getIndex().getName())
.source(doc));
}
BulkResponse bulkResponse = ES_REST_CLIENT.bulk(bulk);
if (bulkResponse.hasFailures()) {
throw new IllegalStateException(bulkResponse.buildFailureMessage());
}
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public long countDocuments(Index index) {
SearchRequest searchRequest = EsClient.prepareSearch(index.getName())
.source(new SearchSourceBuilder()
.query(QueryBuilders.matchAllQuery())
.size(0));
return ES_REST_CLIENT.search(searchRequest)
.getHits().getTotalHits().value;
}
public long countDocuments(IndexType indexType) {
SearchRequest searchRequest = EsClient.prepareSearch(indexType.getMainType())
.source(new SearchSourceBuilder()
.query(getDocumentsQuery(indexType))
.size(0));
return ES_REST_CLIENT.search(searchRequest)
.getHits().getTotalHits().value;
}
/**
* Get all the indexed documents (no paginated results). Results are converted to BaseDoc objects.
* Results are not sorted.
*/
public <E extends BaseDoc> List<E> getDocuments(IndexType indexType, final Class<E> docClass) {
List<SearchHit> hits = getDocuments(indexType);
return new ArrayList<>(Collections2.transform(hits, input -> {
try {
return (E) ConstructorUtils.invokeConstructor(docClass, input.getSourceAsMap());
} catch (Exception e) {
throw Throwables.propagate(e);
}
}));
}
/**
* Get all the indexed documents (no paginated results) of the specified type. Results are not sorted.
*/
public List<SearchHit> getDocuments(IndexType indexType) {
IndexType.IndexMainType mainType = indexType.getMainType();
SearchRequest searchRequest = EsClient.prepareSearch(mainType.getIndex().getName())
.source(new SearchSourceBuilder()
.query(getDocumentsQuery(indexType)));
return getDocuments(searchRequest);
}
private List<SearchHit> getDocuments(SearchRequest req) {
req.scroll(new TimeValue(60000));
req.source()
.size(100)
.sort("_doc", SortOrder.ASC);
SearchResponse response = ES_REST_CLIENT.search(req);
List<SearchHit> result = newArrayList();
while (true) {
Iterables.addAll(result, response.getHits());
response = ES_REST_CLIENT.scroll(new SearchScrollRequest(response.getScrollId()).scroll(new TimeValue(600000)));
// Break condition: No hits are returned
if (response.getHits().getHits().length == 0) {
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
clearScrollRequest.addScrollId(response.getScrollId());
ES_REST_CLIENT.clearScroll(clearScrollRequest);
break;
}
}
return result;
}
private QueryBuilder getDocumentsQuery(IndexType indexType) {
if (!indexType.getMainType().getIndex().acceptsRelations()) {
return matchAllQuery();
}
if (indexType instanceof IndexRelationType) {
return new TermQueryBuilder(FIELD_INDEX_TYPE, ((IndexRelationType) indexType).getName());
}
if (indexType instanceof IndexType.IndexMainType) {
return new TermQueryBuilder(FIELD_INDEX_TYPE, ((IndexType.IndexMainType) indexType).getType());
}
throw new IllegalArgumentException("Unsupported IndexType " + indexType.getClass());
}
/**
* Get a list of a specific field from all indexed documents.
*/
public <T> List<T> getDocumentFieldValues(IndexType indexType, final String fieldNameToReturn) {
return getDocuments(indexType)
.stream()
.map(input -> (T) input.getSourceAsMap().get(fieldNameToReturn))
.toList();
}
public List<String> getIds(IndexType indexType) {
return getDocuments(indexType).stream().map(SearchHit::getId).toList();
}
public void lockWrites(IndexType index) {
setIndexSettings(index.getMainType().getIndex().getName(), ImmutableMap.of("index.blocks.write", "true"));
}
public void unlockWrites(IndexType index) {
setIndexSettings(index.getMainType().getIndex().getName(), ImmutableMap.of("index.blocks.write", "false"));
}
private void setIndexSettings(String index, Map<String, Object> settings) {
AcknowledgedResponse response = null;
try {
response = ES_REST_CLIENT.nativeClient().indices()
.putSettings(new UpdateSettingsRequest(index).settings(settings), RequestOptions.DEFAULT);
} catch (IOException e) {
throw new IllegalStateException("Could not update index settings", e);
}
checkState(response.isAcknowledged());
}
private static void deleteIndexIfExists(String name) {
try {
AcknowledgedResponse response = ES_REST_CLIENT.nativeClient().indices().delete(new DeleteIndexRequest(name), RequestOptions.DEFAULT);
checkState(response.isAcknowledged(), "Fail to drop the index " + name);
} catch (ElasticsearchStatusException e) {
if (e.status().getStatus() == 404) {
// ignore, index not found
} else {
throw e;
}
} catch (IOException e) {
throw new IllegalStateException("Could not delete index", e);
}
}
private static List<BuiltIndex> createIndices(IndexDefinition... definitions) {
IndexDefinitionContext context = new IndexDefinitionContext();
Stream.of(definitions).forEach(d -> d.define(context));
List<BuiltIndex> result = new ArrayList<>();
for (NewIndex newIndex : context.getIndices().values()) {
BuiltIndex index = newIndex.build();
String indexName = index.getMainType().getIndex().getName();
deleteIndexIfExists(indexName);
// create index
Settings.Builder settings = Settings.builder();
settings.put(index.getSettings());
CreateIndexResponse indexResponse = createIndex(indexName, settings);
if (!indexResponse.isAcknowledged()) {
throw new IllegalStateException("Failed to create index " + indexName);
}
waitForClusterYellowStatus(indexName);
// create types
String typeName = index.getMainType().getType();
putIndexMapping(index, indexName, typeName);
waitForClusterYellowStatus(indexName);
result.add(index);
}
return result;
}
private static void waitForClusterYellowStatus(String indexName) {
try {
ES_REST_CLIENT.nativeClient().cluster().health(new ClusterHealthRequest(indexName).waitForStatus(ClusterHealthStatus.YELLOW), RequestOptions.DEFAULT);
} catch (IOException e) {
throw new IllegalStateException("Could not query for index health status");
}
}
private static void putIndexMapping(BuiltIndex index, String indexName, String typeName) {
try {
AcknowledgedResponse mappingResponse = ES_REST_CLIENT.nativeClient().indices().putMapping(new PutMappingRequest(indexName)
.type(typeName)
.source(index.getAttributes()), RequestOptions.DEFAULT);
if (!mappingResponse.isAcknowledged()) {
throw new IllegalStateException("Failed to create type " + typeName);
}
} catch (IOException e) {
throw new IllegalStateException("Could not query for put index mapping");
}
}
private static CreateIndexResponse createIndex(String indexName, Settings.Builder settings) {
CreateIndexResponse indexResponse;
try {
indexResponse = ES_REST_CLIENT.nativeClient().indices()
.create(new CreateIndexRequest(indexName).settings(settings), RequestOptions.DEFAULT);
} catch (IOException e) {
throw new IllegalStateException("Could not create index");
}
return indexResponse;
}
private static Node createNode() {
try {
Path tempDir = Files.createTempDirectory("EsTester");
tempDir.toFile().deleteOnExit();
int i = 10;
while (i > 0) {
int httpPort = getNextAvailable();
try {
Node node = startNode(tempDir, httpPort);
LOG.info("EsTester running ElasticSearch on HTTP port {}", httpPort);
return node;
} catch (BindHttpException e) {
i--;
}
}
} catch (Exception e) {
throw new IllegalStateException("Fail to start embedded Elasticsearch", e);
}
throw new IllegalStateException("Failed to find an open port to connect EsTester's Elasticsearch instance after 10 attempts");
}
private static Node startNode(Path tempDir, int httpPort) throws NodeValidationException {
Settings settings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), tempDir)
.put("node.name", "EsTester")
.put(NodeEnvironment.MAX_LOCAL_STORAGE_NODES_SETTING.getKey(), Integer.MAX_VALUE)
.put("logger.level", "INFO")
.put("action.auto_create_index", false)
// allows to drop all indices at once using `_all`
// this parameter will default to true in ES 8.X
.put("action.destructive_requires_name", false)
// Default the watermarks to absurdly low to prevent the tests
// from failing on nodes without enough disk space
.put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK_SETTING.getKey(), "1b")
.put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK_SETTING.getKey(), "1b")
.put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_FLOOD_STAGE_WATERMARK_SETTING.getKey(), "1b")
// always reduce this - it can make tests really slow
.put(RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING.getKey(), TimeValue.timeValueMillis(20))
.put(HttpTransportSettings.SETTING_HTTP_PORT.getKey(), httpPort)
.put(HttpTransportSettings.SETTING_HTTP_BIND_HOST.getKey(), "localhost")
.put(DiscoveryModule.DISCOVERY_TYPE_SETTING.getKey(), "single-node")
.build();
Node node = new Node(InternalSettingsPreparer.prepareEnvironment(settings, Collections.emptyMap(), null, null),
ImmutableList.of(
CommonAnalysisPlugin.class,
ReindexPlugin.class,
// Netty4Plugin provides http and tcp transport
Netty4Plugin.class,
// install ParentJoin plugin required to create field of type "join"
ParentJoinPlugin.class),
true) {
};
return node.start();
}
public static int getNextAvailable() {
Random random = new Random();
int maxAttempts = 10;
int i = maxAttempts;
while (i > 0) {
int port = MIN_NON_ROOT_PORT + random.nextInt(MAX_PORT - MIN_NON_ROOT_PORT);
if (available(port)) {
return port;
}
i--;
}
throw new NoSuchElementException(format("Could not find an available port in %s attempts", maxAttempts));
}
private static boolean available(int port) {
checkArgument(validPort(port), "Invalid port: %s", port);
try (ServerSocket ss = new ServerSocket(port)) {
ss.setReuseAddress(true);
try (DatagramSocket ds = new DatagramSocket(port)) {
ds.setReuseAddress(true);
}
return true;
} catch (IOException var13) {
return false;
}
}
private static boolean validPort(int fromPort) {
return fromPort >= MIN_PORT && fromPort <= MAX_PORT;
}
}
| 21,434 | 37.972727 | 179 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/es/FakeDoc.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.es;
import java.util.HashMap;
import static org.sonar.server.es.newindex.FakeIndexDefinition.INT_FIELD;
import static org.sonar.server.es.newindex.FakeIndexDefinition.TYPE_FAKE;
public class FakeDoc extends BaseDoc {
public FakeDoc() {
super(TYPE_FAKE, new HashMap<>());
}
@Override
public String getId() {
return null;
}
public int getInt() {
return getField(INT_FIELD);
}
public FakeDoc setInt(int i) {
setField(INT_FIELD, i);
return this;
}
}
| 1,358 | 28.543478 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/es/TestIndexers.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.es;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import java.util.Collection;
import org.sonar.db.DbSession;
import static org.assertj.core.api.Assertions.assertThat;
public class TestIndexers implements Indexers {
private final ListMultimap<String, EntityEvent> entityCalls = ArrayListMultimap.create();
private final ListMultimap<String, BranchEvent> branchCalls = ArrayListMultimap.create();
@Override
public void commitAndIndexOnEntityEvent(DbSession dbSession, Collection<String> entityUuids, EntityEvent cause) {
dbSession.commit();
entityUuids.forEach(entityUuid -> entityCalls.put(entityUuid, cause));
}
@Override
public void commitAndIndexOnBranchEvent(DbSession dbSession, Collection<String> branchUuids, BranchEvent cause) {
dbSession.commit();
branchUuids.forEach(branchUuid -> branchCalls.put(branchUuid, cause));
}
public boolean hasBeenCalledForEntity(String entityUuid, EntityEvent expectedCause) {
assertThat(branchCalls.keySet()).isEmpty();
return entityCalls.get(entityUuid).contains(expectedCause);
}
public boolean hasBeenCalledForEntity(String projectUuid) {
assertThat(branchCalls.keySet()).isEmpty();
return entityCalls.containsKey(projectUuid);
}
public boolean hasBeenCalledForBranch(String branchUuid, BranchEvent expectedCause) {
assertThat(entityCalls.keySet()).isEmpty();
return branchCalls.get(branchUuid).contains(expectedCause);
}
public boolean hasBeenCalledForBranch(String branchUuid) {
assertThat(entityCalls.keySet()).isEmpty();
return branchCalls.containsKey(branchUuid);
}
}
| 2,527 | 37.30303 | 115 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/es/newindex/FakeIndexDefinition.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.es.newindex;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.server.es.FakeDoc;
import org.sonar.server.es.Index;
import org.sonar.server.es.IndexDefinition;
import org.sonar.server.es.IndexType;
import org.sonar.server.es.IndexType.IndexMainType;
import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder;
public class FakeIndexDefinition implements IndexDefinition {
public static final String INDEX = "fakes";
public static final String TYPE = "fake";
public static final Index DESCRIPTOR = Index.simple(INDEX);
public static final IndexMainType TYPE_FAKE = IndexType.main(DESCRIPTOR, TYPE);
public static final IndexMainType EXCPECTED_TYPE_FAKE = IndexType.main(DESCRIPTOR, "_doc");
public static final String INT_FIELD = "intField";
private int replicas = 0;
public FakeIndexDefinition setReplicas(int replicas) {
this.replicas = replicas;
return this;
}
@Override
public void define(IndexDefinitionContext context) {
NewIndex index = context.create(DESCRIPTOR, newBuilder(new MapSettings().asConfig()).build());
index.getSettings().put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, replicas);
index.getSettings().put("index.refresh_interval", "-1");
index.createTypeMapping(TYPE_FAKE)
.createIntegerField(INT_FIELD);
}
public static FakeDoc newDoc(int value) {
return new FakeDoc().setInt(value);
}
}
| 2,335 | 37.295082 | 98 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/es/textsearch/ComponentTextSearchFeatureRule.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.es.textsearch;
import org.junit.rules.ExternalResource;
public class ComponentTextSearchFeatureRule extends ExternalResource {
private ComponentTextSearchFeature[] features;
@Override
protected void before() {
features = ComponentTextSearchFeatureRepertoire.values();
}
public ComponentTextSearchFeature[] get() {
return features;
}
public void set(ComponentTextSearchFeature... features) {
this.features = features;
}
}
| 1,323 | 31.292683 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/issue/IssueDocTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.HashMap;
import org.sonar.api.resources.Scopes;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.core.util.Uuids;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.issue.index.IssueDoc;
import org.sonar.server.issue.index.IssueScope;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.math.RandomUtils.nextInt;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
public class IssueDocTesting {
public static IssueDoc newDoc(ComponentDto componentDto, String projectUuid) {
return newDoc(Uuids.createFast(), projectUuid, componentDto);
}
public static IssueDoc newDocForProject(ComponentDto project) {
return newDocForProject(Uuids.createFast(), project);
}
public static IssueDoc newDoc(String key, String projectUuid, ComponentDto componentDto) {
return newDoc()
.setKey(key)
.setBranchUuid(componentDto.branchUuid())
.setComponentUuid(componentDto.uuid())
.setProjectUuid(projectUuid)
// File path make no sens on modules and projects
.setFilePath(!componentDto.scope().equals(Scopes.PROJECT) ? componentDto.path() : null)
.setIsMainBranch(componentDto.branchUuid().equals(projectUuid))
.setFuncCreationDate(Date.from(LocalDateTime.of(1970, 1, 1, 1, 1).toInstant(ZoneOffset.UTC)));
}
public static IssueDoc newDocForProject(String key, ComponentDto project) {
return newDoc()
.setKey(key)
.setBranchUuid(project.branchUuid())
.setComponentUuid(project.uuid())
.setProjectUuid(project.branchUuid())
// File path make no sens on modules and projects
.setFilePath(!project.scope().equals(Scopes.PROJECT) ? project.path() : null)
.setIsMainBranch(true)
.setFuncCreationDate(Date.from(LocalDateTime.of(1970, 1, 1, 1, 1).toInstant(ZoneOffset.UTC)));
}
public static IssueDoc newDoc() {
IssueDoc doc = new IssueDoc(new HashMap<>());
doc.setKey(Uuids.createFast());
doc.setRuleUuid(Uuids.createFast());
doc.setType(RuleType.CODE_SMELL);
doc.setAssigneeUuid("assignee_uuid_" + randomAlphabetic(26));
doc.setAuthorLogin("author_" + randomAlphabetic(5));
doc.setScope(IssueScope.MAIN);
doc.setLanguage("language_" + randomAlphabetic(5));
doc.setComponentUuid(Uuids.createFast());
doc.setFilePath("filePath_" + randomAlphabetic(5));
doc.setDirectoryPath("directory_" + randomAlphabetic(5));
doc.setProjectUuid(Uuids.createFast());
doc.setLine(nextInt(1_000) + 1);
doc.setStatus(STATUS_OPEN);
doc.setResolution(null);
doc.setSeverity(Severity.ALL.get(nextInt(Severity.ALL.size())));
doc.setEffort((long) nextInt(10));
doc.setFuncCreationDate(new Date(System.currentTimeMillis() - 2_000));
doc.setFuncUpdateDate(new Date(System.currentTimeMillis() - 1_000));
doc.setFuncCloseDate(null);
return doc;
}
}
| 3,912 | 39.760417 | 100 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/issue/notification/IssuesChangesNotificationBuilderTesting.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue.notification;
import java.util.Random;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.AnalysisChange;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Rule;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.sonar.api.rules.RuleType.BUG;
import static org.sonar.api.rules.RuleType.CODE_SMELL;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.api.rules.RuleType.VULNERABILITY;
public class IssuesChangesNotificationBuilderTesting {
private static final RuleType[] RULE_TYPES = {CODE_SMELL, BUG, VULNERABILITY, SECURITY_HOTSPOT};
private IssuesChangesNotificationBuilderTesting() {
}
public static Rule ruleOf(RuleDto rule) {
return new Rule(rule.getKey(), RuleType.valueOfNullable(rule.getType()), rule.getName());
}
public static User userOf(UserDto changeAuthor) {
return new User(changeAuthor.getUuid(), changeAuthor.getLogin(), changeAuthor.getName());
}
public static Project projectBranchOf(DbTester db, ComponentDto branch) {
BranchDto branchDto = db.getDbClient().branchDao().selectByUuid(db.getSession(), branch.uuid()).get();
checkArgument(!branchDto.isMain(), "should be a branch");
return new Project.Builder(branch.uuid())
.setKey(branch.getKey())
.setProjectName(branch.name())
.setBranchName(branchDto.getKey())
.build();
}
public static Project projectOf(ComponentDto project) {
return new Project.Builder(project.uuid())
.setKey(project.getKey())
.setProjectName(project.name())
.build();
}
static ChangedIssue newChangedIssue(String key, Project project, Rule rule) {
return new ChangedIssue.Builder(key)
.setNewStatus(randomAlphabetic(19))
.setProject(project)
.setRule(rule)
.build();
}
static ChangedIssue newChangedIssue(String key, String status, Project project, String ruleName, RuleType ruleType) {
return newChangedIssue(key, status, project, newRule(ruleName, ruleType));
}
static ChangedIssue newChangedIssue(String key, String status, Project project, Rule rule) {
return new ChangedIssue.Builder(key)
.setNewStatus(status)
.setProject(project)
.setRule(rule)
.build();
}
static Rule newRule(String ruleName, RuleType ruleType) {
return new Rule(RuleKey.of(randomAlphabetic(6), randomAlphabetic(7)), ruleType, ruleName);
}
static Rule newRandomNotAHotspotRule(String ruleName) {
return newRule(ruleName, randomRuleTypeHotspotExcluded());
}
static Rule newSecurityHotspotRule(String ruleName) {
return newRule(ruleName, SECURITY_HOTSPOT);
}
static Project newProject(String uuid) {
return new Project.Builder(uuid).setProjectName(uuid + "_name").setKey(uuid + "_key").build();
}
static Project newBranch(String uuid, String branchName) {
return new Project.Builder(uuid).setProjectName(uuid + "_name").setKey(uuid + "_key").setBranchName(branchName).build();
}
static UserChange newUserChange() {
return new UserChange(new Random().nextLong(), new User(randomAlphabetic(4), randomAlphabetic(5), randomAlphabetic(6)));
}
static AnalysisChange newAnalysisChange() {
return new AnalysisChange(new Random().nextLong());
}
static RuleType randomRuleTypeHotspotExcluded() {
return RULE_TYPES[new Random().nextInt(RULE_TYPES.length - 1)];
}
}
| 4,981 | 37.921875 | 124 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/l18n/I18nRule.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.l18n;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.sonar.core.i18n.I18n;
public class I18nRule implements TestRule, I18n {
private final Map<String, String> messages = new HashMap<>();
public I18nRule put(String key, String value) {
messages.put(key, value);
return this;
}
@Override
public Statement apply(final Statement statement, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
statement.evaluate();
} finally {
messages.clear();
}
}
};
}
public void setProjectPermissions() {
put("projects_role.admin", "Administer");
put("projects_role.admin.desc", "Ability to access project settings and perform administration tasks. " +
"(Users will also need \"Browse\" permission)");
put("projects_role.issueadmin", "Administer Issues");
put("projects_role.issueadmin.desc", "Grants the permission to perform advanced editing on issues: marking an issue " +
"False Positive / Won't Fix or changing an Issue's severity. (Users will also need \"Browse\" permission)");
put("projects_role.securityhotspotadmin", "Administer Security Hotspots");
put("projects_role.securityhotspotadmin.desc", "Detect a Vulnerability from a \"Security Hotspot\". Reject, clear, accept, reopen a \"Security Hotspot\" (users also need \"Browse\" permissions).");
put("projects_role.applicationcreator", "Create Applications");
put("projects_role.applicationcreator.desc", "Allow to create applications for non system administrator.");
put("projects_role.portfoliocreator", "Create Portfolios");
put("projects_role.portfoliocreator.desc", "Allow to create portfolios for non system administrator.");
put("projects_role.user", "Browse");
put("projects_role.user.desc", "Ability to access a project, browse its measures, and create/edit issues for it.");
put("projects_role.codeviewer", "See Source Code");
put("projects_role.codeviewer.desc", "Ability to view the project's source code. (Users will also need \"Browse\" permission)");
put("projects_role.scan", "Execute Analysis");
put("projects_role.scan.desc",
"Ability to execute analyses, and to get all settings required to perform the analysis, even the secured ones like the scm account password, the jira account password, and so on.");
}
@Override
public String message(Locale locale, String key, @Nullable String defaultValue, Object... parameters) {
String messageInMap = messages.get(key);
String message = messageInMap != null ? messageInMap : defaultValue;
return formatMessage(message, parameters);
}
@CheckForNull
private static String formatMessage(@Nullable String message, Object... parameters) {
if (message == null || parameters.length == 0) {
return message;
}
return MessageFormat.format(message.replaceAll("'", "''"), parameters);
}
@Override
public String age(Locale locale, long durationInMillis) {
throw new UnsupportedOperationException();
}
@Override
public String age(Locale locale, Date fromDate, Date toDate) {
throw new UnsupportedOperationException();
}
@Override
public String ageFromNow(Locale locale, Date date) {
throw new UnsupportedOperationException();
}
@Override
public String formatDateTime(Locale locale, Date date) {
throw new UnsupportedOperationException();
}
@Override
public String formatDate(Locale locale, Date date) {
throw new UnsupportedOperationException();
}
@Override
public String formatDouble(Locale locale, Double value) {
return String.valueOf(value);
}
@Override
public String formatInteger(Locale locale, Integer value) {
return String.valueOf(value);
}
}
| 4,950 | 37.379845 | 201 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/platform/monitoring/SystemInfoTesting.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.monitoring;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.process.systeminfo.SystemInfoUtils.attribute;
public class SystemInfoTesting {
private SystemInfoTesting() {
// do not instantiate
}
public static void assertThatAttributeIs(ProtobufSystemInfo.Section section, String key, String expectedValue) {
ProtobufSystemInfo.Attribute value = attribute(section, key);
assertThat(value).as(key).isNotNull();
assertThat(value.getStringValue()).isEqualTo(expectedValue);
}
public static void assertThatAttributeIs(ProtobufSystemInfo.Section section, String key, boolean expectedValue) {
ProtobufSystemInfo.Attribute value = attribute(section, key);
assertThat(value).as(key).isNotNull();
assertThat(value.getBooleanValue()).isEqualTo(expectedValue);
}
public static void assertThatAttributeIs(ProtobufSystemInfo.Section section, String key, long expectedValue) {
ProtobufSystemInfo.Attribute value = attribute(section, key);
assertThat(value).as(key).isNotNull();
assertThat(value.getLongValue()).isEqualTo(expectedValue);
}
public static void assertThatAttributeDoesNotExist(ProtobufSystemInfo.Section section, String key) {
ProtobufSystemInfo.Attribute value = attribute(section, key);
assertThat(value).as(key).isNull();
}
}
| 2,277 | 39.678571 | 115 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/platform/monitoring/cluster/TestGlobalSystemInfoSection.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.monitoring.cluster;
import org.sonar.process.systeminfo.Global;
import org.sonar.process.systeminfo.SystemInfoSection;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
class TestGlobalSystemInfoSection implements SystemInfoSection, Global {
private final String name;
TestGlobalSystemInfoSection(String name) {
this.name = name;
}
@Override
public ProtobufSystemInfo.Section toProtobuf() {
return ProtobufSystemInfo.Section.newBuilder().setName(name).build();
}
}
| 1,381 | 35.368421 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/platform/monitoring/cluster/TestSystemInfoSection.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.monitoring.cluster;
import org.sonar.process.systeminfo.SystemInfoSection;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
class TestSystemInfoSection implements SystemInfoSection {
private final String name;
TestSystemInfoSection(String name) {
this.name = name;
}
@Override
public ProtobufSystemInfo.Section toProtobuf() {
return ProtobufSystemInfo.Section.newBuilder().setName(name).build();
}
}
| 1,317 | 34.621622 | 75 | java |
sonarqube | sonarqube-master/server/sonar-server-common/src/testFixtures/java/org/sonar/server/source/index/FileSourceTesting.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.index;
import java.util.Arrays;
import org.sonar.db.protobuf.DbFileSources;
public class FileSourceTesting {
private FileSourceTesting() {
// only static stuff
}
/**
* Generate predefined fake data. Result is mutable.
*/
public static DbFileSources.Data.Builder newFakeData(int numberOfLines) {
DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder();
for (int i = 1; i <= numberOfLines; i++) {
dataBuilder.addLinesBuilder()
.setLine(i)
.setScmRevision("REVISION_" + i)
.setScmAuthor("AUTHOR_" + i)
.setScmDate(1_500_000_000_00L + i)
.setSource("SOURCE_" + i)
.setLineHits(i)
.setConditions(i + 1)
.setCoveredConditions(i + 2)
.setHighlighting("HIGHLIGHTING_" + i)
.setSymbols("SYMBOLS_" + i)
.addAllDuplication(Arrays.asList(i))
.setIsNewLine(true)
.build();
}
return dataBuilder;
}
}
| 1,829 | 31.678571 | 77 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/it/java/org/sonar/server/plugins/DetectPluginChangeIT.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;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.Plugin;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.plugin.PluginType;
import org.sonar.db.DbTester;
import org.sonar.db.plugin.PluginDto;
import org.sonar.server.plugins.PluginFilesAndMd5.FileAndMd5;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DetectPluginChangeIT {
@Rule
public DbTester dbTester = DbTester.create();
private final ServerPluginRepository pluginRepository = new ServerPluginRepository();
private final DetectPluginChange detectPluginChange = new DetectPluginChange(pluginRepository, dbTester.getDbClient());
@Test
public void detect_changed_plugin() {
addPluginToDb("plugin1", "hash1", PluginDto.Type.BUNDLED);
addPluginToFs("plugin1", "hash2", PluginType.BUNDLED);
detectPluginChange.start();
assertThat(detectPluginChange.anyPluginChanged()).isTrue();
}
@Test
public void detect_changed_type() {
addPluginToDb("plugin1", "hash1", PluginDto.Type.BUNDLED);
addPluginToFs("plugin1", "hash1", PluginType.EXTERNAL);
detectPluginChange.start();
assertThat(detectPluginChange.anyPluginChanged()).isTrue();
}
@Test
public void detect_new_plugin() {
addPluginToDb("plugin1", "hash1", PluginDto.Type.BUNDLED);
addPluginToFs("plugin2", "hash1", PluginType.BUNDLED);
detectPluginChange.start();
assertThat(detectPluginChange.anyPluginChanged()).isTrue();
}
@Test
public void detect_removed_plugin() {
addPluginToDb("plugin1", "hash1", PluginDto.Type.BUNDLED, true);
addPluginToFs("plugin1", "hash1", PluginType.BUNDLED);
detectPluginChange.start();
assertThat(detectPluginChange.anyPluginChanged()).isTrue();
}
@Test
public void detect_missing_plugin() {
addPluginToDb("plugin1", "hash1", PluginDto.Type.BUNDLED);
detectPluginChange.start();
assertThat(detectPluginChange.anyPluginChanged()).isTrue();
}
@Test
public void detect_no_changes() {
addPluginToDb("plugin1", "hash1", PluginDto.Type.BUNDLED);
addPluginToFs("plugin1", "hash1", PluginType.BUNDLED);
addPluginToDb("plugin2", "hash2", PluginDto.Type.EXTERNAL);
addPluginToFs("plugin2", "hash2", PluginType.EXTERNAL);
detectPluginChange.start();
assertThat(detectPluginChange.anyPluginChanged()).isFalse();
}
@Test
public void fail_if_start_twice() {
detectPluginChange.start();
assertThrows(IllegalStateException.class, detectPluginChange::start);
}
@Test
public void fail_if_not_started() {
assertThrows(NullPointerException.class, detectPluginChange::anyPluginChanged);
}
private void addPluginToDb(String key, String hash, PluginDto.Type type) {
addPluginToDb(key, hash, type, false);
}
private void addPluginToDb(String key, String hash, PluginDto.Type type, boolean removed) {
dbTester.pluginDbTester().insertPlugin(p -> p.setKee(key).setFileHash(hash).setType(type).setRemoved(removed));
}
private void addPluginToFs(String key, String hash, PluginType type) {
PluginInfo pluginInfo = new PluginInfo(key);
Plugin plugin = mock(Plugin.class);
FileAndMd5 fileAndMd5 = mock(FileAndMd5.class);
when(fileAndMd5.getMd5()).thenReturn(hash);
ServerPlugin serverPlugin = new ServerPlugin(pluginInfo, type, plugin, fileAndMd5, null);
pluginRepository.addPlugin(serverPlugin);
}
}
| 4,393 | 33.598425 | 121 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/it/java/org/sonar/server/rule/CachingRuleFinderIT.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 java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleQuery;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleDao;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleParamDto;
import org.sonar.db.rule.RuleTesting;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
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.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class CachingRuleFinderIT {
@org.junit.Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = dbTester.getDbClient();
private final AlwaysIncreasingSystem2 system2 = new AlwaysIncreasingSystem2();
private RuleDto[] ruleDtos;
private RuleParamDto[] ruleParams;
private CachingRuleFinder underTest;
private RuleDescriptionFormatter ruleDescriptionFormatter = new RuleDescriptionFormatter();
@Before()
public void setUp() {
Consumer<RuleDto> setUpdatedAt = rule -> rule.setUpdatedAt(system2.now());
this.ruleDtos = new RuleDto[] {
dbTester.rules().insert(setUpdatedAt),
dbTester.rules().insert(setUpdatedAt),
dbTester.rules().insert(setUpdatedAt),
dbTester.rules().insert(setUpdatedAt),
dbTester.rules().insert(setUpdatedAt),
dbTester.rules().insert(setUpdatedAt)
};
this.ruleParams = Arrays.stream(ruleDtos)
.map(rule -> dbTester.rules().insertRuleParam(rule))
.toArray(RuleParamDto[]::new);
underTest = new CachingRuleFinder(dbClient, ruleDescriptionFormatter);
// delete all data from DB to ensure tests rely on cache exclusively
dbTester.executeUpdateSql("delete from rules");
dbTester.executeUpdateSql("delete from rules_parameters");
assertThat(dbTester.countRowsOfTable("rules")).isZero();
assertThat(dbTester.countRowsOfTable("rules_parameters")).isZero();
}
@Test
public void constructor_reads_rules_from_DB() {
DbClient dbClient = mock(DbClient.class);
DbSession dbSession = mock(DbSession.class);
RuleDao ruleDao = mock(RuleDao.class);
when(dbClient.openSession(anyBoolean())).thenReturn(dbSession);
when(dbClient.ruleDao()).thenReturn(ruleDao);
new CachingRuleFinder(dbClient, ruleDescriptionFormatter);
verify(dbClient).openSession(anyBoolean());
verify(ruleDao).selectAll(dbSession);
verify(ruleDao).selectAllRuleParams(dbSession);
verifyNoMoreInteractions(ruleDao);
}
@Test
public void constructor_reads_parameters_from_DB() {
DbClient dbClient = mock(DbClient.class);
DbSession dbSession = mock(DbSession.class);
RuleDao ruleDao = mock(RuleDao.class);
when(dbClient.openSession(anyBoolean())).thenReturn(dbSession);
when(dbClient.ruleDao()).thenReturn(ruleDao);
List<RuleKey> ruleKeys = Arrays.asList(RuleKey.of("A", "B"), RuleKey.of("C", "D"), RuleKey.of("E", "F"));
when(ruleDao.selectAll(dbSession)).thenReturn(ruleKeys.stream().map(RuleTesting::newRule).collect(toList()));
new CachingRuleFinder(dbClient, ruleDescriptionFormatter);
verify(ruleDao).selectAllRuleParams(dbSession);
}
@Test
public void findByKey_returns_all_loaded_rules() {
for (int i = 0; i < ruleDtos.length; i++) {
RuleDto ruleDto = ruleDtos[i];
RuleParamDto ruleParam = ruleParams[i];
org.sonar.api.rules.Rule rule = underTest.findByKey(ruleDto.getKey());
verifyRule(rule, ruleDto, ruleParam);
assertThat(underTest.findByKey(ruleDto.getRepositoryKey(), ruleDto.getRuleKey()))
.isSameAs(rule);
}
}
@Test
public void findByKey_returns_null_when_RuleKey_is_null() {
assertThat(underTest.findByKey(null)).isNull();
}
@Test
public void findByKey_returns_null_when_repository_key_is_null() {
assertThat(underTest.findByKey(null, randomAlphabetic(2))).isNull();
}
@Test
public void findByKey_returns_null_when_key_is_null() {
assertThat(underTest.findByKey(randomAlphabetic(2), null)).isNull();
}
@Test
public void findByKey_returns_null_when_both_repository_key_and_key_are_null() {
assertThat(underTest.findByKey(null, null)).isNull();
}
@Test
public void find_returns_null_when_RuleQuery_is_empty() {
assertThat(underTest.find(null)).isNull();
}
@Test
public void find_returns_most_recent_rule_when_RuleQuery_has_no_non_null_field() {
Rule rule = underTest.find(RuleQuery.create());
assertThat(toRuleKey(rule)).isEqualTo(ruleDtos[5].getKey());
}
@Test
public void find_searches_by_exact_match_of_repository_key_and_returns_most_recent_rule() {
String repoKey = "ABCD";
RuleDto[] sameRepoKey = {
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setUpdatedAt(system2.now()))
};
RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient, ruleDescriptionFormatter);
assertThat(toRuleKey(underTest.find(RuleQuery.create().withRepositoryKey(repoKey))))
.isEqualTo(sameRepoKey[1].getKey());
assertThat(toRuleKey(underTest.find(RuleQuery.create().withRepositoryKey(otherRule.getRepositoryKey()))))
.isEqualTo(otherRule.getKey());
assertThat(underTest.find(RuleQuery.create().withRepositoryKey(repoKey.toLowerCase())))
.isNull();
assertThat(underTest.find(RuleQuery.create().withRepositoryKey(randomAlphabetic(3))))
.isNull();
}
@Test
public void find_searches_by_exact_match_of_ruleKey_and_returns_most_recent_rule() {
String ruleKey = "ABCD";
RuleDto[] sameRuleKey = {
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setUpdatedAt(system2.now()))
};
RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient, ruleDescriptionFormatter);
assertThat(toRuleKey(underTest.find(RuleQuery.create().withKey(ruleKey))))
.isEqualTo(sameRuleKey[1].getKey());
assertThat(toRuleKey(underTest.find(RuleQuery.create().withKey(otherRule.getRuleKey()))))
.isEqualTo(otherRule.getKey());
assertThat(underTest.find(RuleQuery.create().withKey(ruleKey.toLowerCase())))
.isNull();
assertThat(underTest.find(RuleQuery.create().withKey(randomAlphabetic(3))))
.isNull();
}
@Test
public void find_searches_by_exact_match_of_configKey_and_returns_most_recent_rule() {
String configKey = "ABCD";
RuleDto[] sameConfigKey = {
dbTester.rules().insert(rule -> rule.setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setConfigKey(configKey).setUpdatedAt(system2.now()))
};
RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient, ruleDescriptionFormatter);
assertThat(toRuleKey(underTest.find(RuleQuery.create().withConfigKey(configKey))))
.isEqualTo(sameConfigKey[1].getKey());
assertThat(toRuleKey(underTest.find(RuleQuery.create().withConfigKey(otherRule.getConfigKey()))))
.isEqualTo(otherRule.getKey());
assertThat(underTest.find(RuleQuery.create().withConfigKey(configKey.toLowerCase())))
.isNull();
assertThat(underTest.find(RuleQuery.create().withConfigKey(randomAlphabetic(3))))
.isNull();
}
@Test
public void find_searches_by_exact_match_and_match_on_all_criterias_and_returns_most_recent_match() {
String repoKey = "ABCD";
String ruleKey = "EFGH";
String configKey = "IJKL";
RuleDto[] rules = {
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setRuleKey(ruleKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()))
};
RuleQuery allQuery = RuleQuery.create().withRepositoryKey(repoKey).withKey(ruleKey).withConfigKey(configKey);
RuleQuery ruleAndConfigKeyQuery = RuleQuery.create().withKey(ruleKey).withConfigKey(configKey);
RuleQuery repoAndConfigKeyQuery = RuleQuery.create().withRepositoryKey(repoKey).withConfigKey(configKey);
RuleQuery repoAndKeyQuery = RuleQuery.create().withRepositoryKey(repoKey).withKey(ruleKey);
RuleQuery configKeyQuery = RuleQuery.create().withConfigKey(configKey);
RuleQuery ruleKeyQuery = RuleQuery.create().withKey(ruleKey);
RuleQuery repoKeyQuery = RuleQuery.create().withRepositoryKey(repoKey);
CachingRuleFinder underTest = new CachingRuleFinder(dbClient, ruleDescriptionFormatter);
assertThat(toRuleKey(underTest.find(allQuery))).isEqualTo(rules[0].getKey());
assertThat(toRuleKey(underTest.find(ruleAndConfigKeyQuery))).isEqualTo(rules[1].getKey());
assertThat(toRuleKey(underTest.find(repoAndConfigKeyQuery))).isEqualTo(rules[2].getKey());
assertThat(toRuleKey(underTest.find(repoAndKeyQuery))).isEqualTo(rules[0].getKey());
assertThat(toRuleKey(underTest.find(repoKeyQuery))).isEqualTo(rules[2].getKey());
assertThat(toRuleKey(underTest.find(ruleKeyQuery))).isEqualTo(rules[1].getKey());
assertThat(toRuleKey(underTest.find(configKeyQuery))).isEqualTo(rules[2].getKey());
}
@Test
public void findAll_returns_empty_when_RuleQuery_is_empty() {
assertThat(underTest.findAll(null)).isEmpty();
}
@Test
public void findAll_returns_all_rules_when_RuleQuery_has_no_non_null_field() {
assertThat(underTest.findAll(RuleQuery.create()))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsOnly(Arrays.stream(ruleDtos).map(RuleDto::getKey).toArray(RuleKey[]::new));
}
@Test
public void findAll_returns_all_rules_with_exact_same_repository_key_and_order_them_most_recent_first() {
String repoKey = "ABCD";
long currentTimeMillis = System.currentTimeMillis();
RuleDto[] sameRepoKey = {
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setUpdatedAt(currentTimeMillis + system2.now())),
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setUpdatedAt(currentTimeMillis + system2.now()))
};
RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(currentTimeMillis + system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient, ruleDescriptionFormatter);
assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey(repoKey)))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(sameRepoKey[1].getKey(), sameRepoKey[0].getKey());
assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey(otherRule.getRepositoryKey())))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(otherRule.getKey());
assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey(repoKey.toLowerCase())))
.isEmpty();
assertThat(underTest.findAll(RuleQuery.create().withRepositoryKey(randomAlphabetic(3))))
.isEmpty();
}
@Test
public void findAll_returns_all_rules_with_exact_same_rulekey_and_order_them_most_recent_first() {
String ruleKey = "ABCD";
RuleDto[] sameRuleKey = {
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setUpdatedAt(system2.now()))
};
RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient, ruleDescriptionFormatter);
assertThat(underTest.findAll(RuleQuery.create().withKey(ruleKey)))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(sameRuleKey[1].getKey(), sameRuleKey[0].getKey());
assertThat(underTest.findAll(RuleQuery.create().withKey(otherRule.getRuleKey())))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(otherRule.getKey());
assertThat(underTest.findAll(RuleQuery.create().withKey(ruleKey.toLowerCase())))
.isEmpty();
assertThat(underTest.findAll(RuleQuery.create().withKey(randomAlphabetic(3))))
.isEmpty();
}
@Test
public void findAll_returns_all_rules_with_exact_same_configkey_and_order_them_most_recent_first() {
String configKey = "ABCD";
RuleDto[] sameConfigKey = {
dbTester.rules().insert(rule -> rule.setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setConfigKey(configKey).setUpdatedAt(system2.now()))
};
RuleDto otherRule = dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()));
CachingRuleFinder underTest = new CachingRuleFinder(dbClient, ruleDescriptionFormatter);
assertThat(underTest.findAll(RuleQuery.create().withConfigKey(configKey)))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(sameConfigKey[1].getKey(), sameConfigKey[0].getKey());
assertThat(underTest.findAll(RuleQuery.create().withConfigKey(otherRule.getConfigKey())))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(otherRule.getKey());
assertThat(underTest.findAll(RuleQuery.create().withConfigKey(configKey.toLowerCase())))
.isEmpty();
assertThat(underTest.findAll(RuleQuery.create().withConfigKey(randomAlphabetic(3))))
.isEmpty();
}
@Test
public void findAll_returns_all_rules_which_match_exactly_all_criteria_and_order_then_by_most_recent_first() {
String repoKey = "ABCD";
String ruleKey = "EFGH";
String configKey = "IJKL";
RuleDto[] rules = {
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setRuleKey(ruleKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRuleKey(ruleKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setRepositoryKey(repoKey).setConfigKey(configKey).setUpdatedAt(system2.now())),
dbTester.rules().insert(rule -> rule.setUpdatedAt(system2.now()))
};
RuleQuery allQuery = RuleQuery.create().withRepositoryKey(repoKey).withKey(ruleKey).withConfigKey(configKey);
RuleQuery ruleAndConfigKeyQuery = RuleQuery.create().withKey(ruleKey).withConfigKey(configKey);
RuleQuery repoAndConfigKeyQuery = RuleQuery.create().withRepositoryKey(repoKey).withConfigKey(configKey);
RuleQuery repoAndKeyQuery = RuleQuery.create().withRepositoryKey(repoKey).withKey(ruleKey);
RuleQuery configKeyQuery = RuleQuery.create().withConfigKey(configKey);
RuleQuery ruleKeyQuery = RuleQuery.create().withKey(ruleKey);
RuleQuery repoKeyQuery = RuleQuery.create().withRepositoryKey(repoKey);
CachingRuleFinder underTest = new CachingRuleFinder(dbClient, ruleDescriptionFormatter);
assertThat(underTest.findAll(allQuery))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(rules[0].getKey());
assertThat(underTest.findAll(ruleAndConfigKeyQuery))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(rules[1].getKey(), rules[0].getKey());
assertThat(underTest.findAll(repoAndConfigKeyQuery))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(rules[2].getKey(), rules[0].getKey());
assertThat(underTest.findAll(repoAndKeyQuery))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(rules[0].getKey());
assertThat(underTest.findAll(repoKeyQuery))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(rules[2].getKey(), rules[0].getKey());
assertThat(underTest.findAll(ruleKeyQuery))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(rules[1].getKey(), rules[0].getKey());
assertThat(underTest.findAll(configKeyQuery))
.extracting(CachingRuleFinderIT::toRuleKey)
.containsExactly(rules[2].getKey(), rules[1].getKey(), rules[0].getKey());
}
@Test
public void findDtoByKey_finds_rules() {
for(RuleDto dto : ruleDtos) {
assertThat(underTest.findDtoByKey(dto.getKey())).contains(dto);
}
}
@Test
public void findDtoByUuid_finds_rules() {
for(RuleDto dto : ruleDtos) {
assertThat(underTest.findDtoByUuid(dto.getUuid())).contains(dto);
}
}
@Test
public void findDtoByKey_returns_empty_if_rule_not_found() {
assertThat(underTest.findDtoByKey(RuleKey.of("unknown", "unknown"))).isEmpty();
}
@Test
public void findDtoByUuid_returns_empty_if_rule_not_found() {
assertThat(underTest.findDtoByUuid("unknown")).isEmpty();
}
@Test
public void findAll_returns_all_rules() {
assertThat(underTest.findAll()).containsOnly(ruleDtos);
}
private static RuleKey toRuleKey(Rule rule) {
return RuleKey.of(rule.getRepositoryKey(), rule.getKey());
}
private void verifyRule(@Nullable Rule rule, RuleDto ruleDto, RuleParamDto ruleParam) {
assertThat(rule).isNotNull();
assertThat(rule.getName()).isEqualTo(ruleDto.getName());
assertThat(rule.getLanguage()).isEqualTo(ruleDto.getLanguage());
assertThat(rule.getKey()).isEqualTo(ruleDto.getRuleKey());
assertThat(rule.getConfigKey()).isEqualTo(ruleDto.getConfigKey());
assertThat(rule.isTemplate()).isEqualTo(ruleDto.isTemplate());
assertThat(rule.getCreatedAt().getTime()).isEqualTo(ruleDto.getCreatedAt());
assertThat(rule.getUpdatedAt().getTime()).isEqualTo(ruleDto.getUpdatedAt());
assertThat(rule.getRepositoryKey()).isEqualTo(ruleDto.getRepositoryKey());
assertThat(rule.getSeverity().name()).isEqualTo(ruleDto.getSeverityString());
assertThat(rule.getSystemTags()).isEqualTo(ruleDto.getSystemTags().toArray(new String[0]));
assertThat(rule.getTags()).isEmpty();
assertThat(rule.getDescription()).isEqualTo(ruleDto.getDefaultRuleDescriptionSection().getContent());
assertThat(rule.getParams()).hasSize(1);
org.sonar.api.rules.RuleParam param = rule.getParams().iterator().next();
assertThat(param.getRule()).isSameAs(rule);
assertThat(param.getKey()).isEqualTo(ruleParam.getName());
assertThat(param.getDescription()).isEqualTo(ruleParam.getDescription());
assertThat(param.getType()).isEqualTo(ruleParam.getType());
assertThat(param.getDefaultValue()).isEqualTo(ruleParam.getDefaultValue());
}
}
| 19,975 | 44.607306 | 142 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/app/ProcessCommandWrapper.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.app;
public interface ProcessCommandWrapper {
/**
* Requests to the main process that SQ be restarted.
*/
void requestSQRestart();
/**
* Requests to the main process that the WebServer is stopped.
*/
void requestHardStop();
/**
* Notifies any listening process that the WebServer is operational.
*/
void notifyOperational();
/**
* Checks whether the Compute Engine is operational.
*/
boolean isCeOperational();
}
| 1,326 | 29.159091 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/app/ProcessCommandWrapperImpl.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.app;
import java.io.File;
import org.sonar.api.config.Configuration;
import org.sonar.process.ProcessId;
import org.sonar.process.sharedmemoryfile.DefaultProcessCommands;
import org.sonar.process.sharedmemoryfile.ProcessCommands;
import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_INDEX;
import static org.sonar.process.ProcessEntryPoint.PROPERTY_SHARED_PATH;
public class ProcessCommandWrapperImpl implements ProcessCommandWrapper {
private static final ProcessMethod<Void> SET_OPERATIONAL = processCommands -> {
processCommands.setOperational();
return null;
};
private static final ProcessMethod<Void> ASK_FOR_RESTART = processCommands -> {
processCommands.askForRestart();
return null;
};
private static final ProcessMethod<Void> ASK_FOR_HARD_STOP = processCommands -> {
processCommands.askForHardStop();
return null;
};
private static final ProcessMethod<Boolean> IS_OPERATIONAL = ProcessCommands::isOperational;
private final Configuration config;
public ProcessCommandWrapperImpl(Configuration config) {
this.config = config;
}
@Override
public void requestSQRestart() {
call(ASK_FOR_RESTART, selfProcessNumber());
}
@Override
public void requestHardStop() {
call(ASK_FOR_HARD_STOP, selfProcessNumber());
}
@Override
public void notifyOperational() {
call(SET_OPERATIONAL, selfProcessNumber());
}
@Override
public boolean isCeOperational() {
return call(IS_OPERATIONAL, ProcessId.COMPUTE_ENGINE.getIpcIndex());
}
private int selfProcessNumber() {
return nonNullAsInt(PROPERTY_PROCESS_INDEX);
}
private <T> T call(ProcessMethod<T> command, int processNumber) {
File shareDir = nonNullValueAsFile(PROPERTY_SHARED_PATH);
try (DefaultProcessCommands commands = DefaultProcessCommands.secondary(shareDir, processNumber)) {
return command.callOn(commands);
}
}
private interface ProcessMethod<T> {
T callOn(ProcessCommands processCommands);
}
private int nonNullAsInt(String key) {
return config.getInt(key).orElseThrow(() -> new IllegalArgumentException(String.format("Property %s is not set", key)));
}
private File nonNullValueAsFile(String key) {
return new File(config.get(key).orElseThrow(() -> new IllegalArgumentException(String.format("Property %s is not set", key))));
}
}
| 3,225 | 32.604167 | 131 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/app/RestartFlagHolder.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.app;
/**
* Holds a boolean flag representing the restarting status of the WebServer.
* This boolean is {@code false} by default and can safely be changed concurrently using methods {@link #set()} and
* {@link #unset()}.
*/
public interface RestartFlagHolder {
/**
* @return whether restarting flag has been set or not.
*/
boolean isRestarting();
/**
* Sets the restarting flag to {@code true}, no matter it already is or not.
*/
void set();
/**
* Sets the restarting flag to {@code false}, no matter it already is or not.
*/
void unset();
}
| 1,446 | 32.651163 | 115 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/app/RestartFlagHolderImpl.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.app;
import java.util.concurrent.atomic.AtomicBoolean;
public class RestartFlagHolderImpl implements RestartFlagHolder {
private final AtomicBoolean restarting = new AtomicBoolean(false);
@Override
public boolean isRestarting() {
return restarting.get();
}
@Override
public void set() {
restarting.set(true);
}
@Override
public void unset() {
restarting.set(false);
}
}
| 1,275 | 29.380952 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/app/package-info.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.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.app;
import javax.annotation.ParametersAreNonnullByDefault;
| 961 | 37.48 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/branch/BranchFeature.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.branch;
interface BranchFeature {
boolean isEnabled();
}
| 930 | 33.481481 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/branch/BranchFeatureExtension.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.branch;
import org.sonar.api.server.ServerSide;
import org.sonar.server.feature.SonarQubeFeature;
/**
* The branch plugin needs to implement this in order to know that the branch feature is supported
*/
@ServerSide
public interface BranchFeatureExtension extends SonarQubeFeature {
}
| 1,157 | 35.1875 | 98 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/branch/BranchFeatureProxy.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.branch;
/**
* The goal of this class is to handle the 2 different use case :
* - The branch plugin exists, the proxy will redirect method calls to the plugin
* - No branch plugin, feature is disabled
*/
public interface BranchFeatureProxy extends BranchFeature {
}
| 1,139 | 37 | 81 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/branch/BranchFeatureProxyImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.branch;
import javax.annotation.Nullable;
public class BranchFeatureProxyImpl implements BranchFeatureProxy {
private final BranchFeatureExtension branchFeatureExtension;
public BranchFeatureProxyImpl(@Nullable BranchFeatureExtension branchFeatureExtension) {
this.branchFeatureExtension = branchFeatureExtension;
}
@Override
public boolean isEnabled() {
return branchFeatureExtension != null && branchFeatureExtension.isAvailable();
}
}
| 1,331 | 35 | 90 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/branch/package-info.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.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.branch;
import javax.annotation.ParametersAreNonnullByDefault;
| 963 | 39.166667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/ce/http/CeHttpClient.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.ce.http;
import java.util.Optional;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo;
public interface CeHttpClient {
Optional<ProtobufSystemInfo.SystemInfo> retrieveSystemInfo();
void changeLogLevel(LoggerLevel level);
}
| 1,156 | 36.322581 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/ce/http/package-info.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.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.ce.http;
import javax.annotation.ParametersAreNonnullByDefault;
| 964 | 39.208333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/exceptions/BadConfigurationException.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.exceptions;
import com.google.common.base.MoreObjects;
import java.util.List;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.util.Collections.singletonList;
/**
* Provided request is not valid within given scope and can not be processed.
*/
public class BadConfigurationException extends ServerException {
private final String scope;
private final transient List<String> errors;
public BadConfigurationException(String scope, String errorMessage) {
super(HTTP_BAD_REQUEST, errorMessage);
this.scope = scope;
this.errors = singletonList(errorMessage);
}
public String scope() {
return scope;
}
public List<String> errors() {
return this.errors;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("scope", this.scope)
.add("errors", this.errors())
.toString();
}
}
| 1,769 | 29.517241 | 77 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/exceptions/BadRequestException.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.exceptions;
import com.google.common.base.MoreObjects;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.util.Arrays.asList;
/**
* Request is not valid and can not be processed.
*/
public class BadRequestException extends ServerException {
private final transient List<String> errors;
BadRequestException(List<String> errors) {
super(HTTP_BAD_REQUEST, errors.get(0));
this.errors = errors;
}
public static void checkRequest(boolean expression, String message, Object... messageArguments) {
if (!expression) {
throw create(format(message, messageArguments));
}
}
public static void checkRequest(boolean expression, List<String> messages) {
if (!expression) {
throw create(messages);
}
}
public static void throwBadRequestException(String message, Object... messageArguments) {
throw create(format(message, messageArguments));
}
public static BadRequestException create(String... errorMessages) {
return create(asList(errorMessages));
}
public static BadRequestException create(List<String> errorMessages) {
checkArgument(!errorMessages.isEmpty(), "At least one error message is required");
checkArgument(errorMessages.stream().noneMatch(message -> message == null || message.isEmpty()), "Message cannot be empty");
return new BadRequestException(errorMessages);
}
public List<String> errors() {
return errors;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("errors", errors)
.toString();
}
}
| 2,579 | 31.25 | 128 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/exceptions/ForbiddenException.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.exceptions;
import com.google.common.base.Preconditions;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
/**
* Permission denied. User does not have the required permissions.
*/
public class ForbiddenException extends ServerException {
public ForbiddenException(String message) {
super(HTTP_FORBIDDEN, Preconditions.checkNotNull(message));
}
}
| 1,235 | 34.314286 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/exceptions/Message.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.exceptions;
import com.google.common.base.Preconditions;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
public class Message {
private final String msg;
private Message(String format, Object... params) {
Preconditions.checkArgument(!isNullOrEmpty(format), "Message cannot be empty");
this.msg = format(format, params);
}
public String getMessage() {
return msg;
}
public static Message of(String msg, Object... arguments) {
return new Message(msg, arguments);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Message other = (Message) o;
return this.msg.equals(other.msg);
}
@Override
public int hashCode() {
return msg.hashCode();
}
@Override
public String toString() {
return msg;
}
}
| 1,802 | 25.910448 | 83 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/exceptions/NotFoundException.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.exceptions;
import javax.annotation.Nullable;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
public class NotFoundException extends ServerException {
public NotFoundException(String message) {
super(HTTP_NOT_FOUND, message);
}
/**
* @throws NotFoundException if the value if null
* @return the value
*/
public static <T> T checkFound(@Nullable T value, String message, Object... messageArguments) {
if (value == null) {
throw new NotFoundException(format(message, messageArguments));
}
return value;
}
/**
* @throws NotFoundException if the value is not present
* @return the value
*/
public static <T> T checkFoundWithOptional(java.util.Optional<T> value, String message, Object... messageArguments) {
if (!value.isPresent()) {
throw new NotFoundException(format(message, messageArguments));
}
return value.get();
}
}
| 1,818 | 30.912281 | 119 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/exceptions/ServerException.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.exceptions;
import static java.util.Objects.requireNonNull;
public class ServerException extends RuntimeException {
private final int httpCode;
public ServerException(int httpCode, String message) {
super(requireNonNull(message, "Error message cannot be null"));
this.httpCode = httpCode;
}
public int httpCode() {
return httpCode;
}
}
| 1,230 | 33.194444 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/exceptions/TemplateMatchingKeyException.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.exceptions;
import com.google.common.base.MoreObjects;
import java.util.List;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.util.Collections.singletonList;
/**
* Provided request is not valid due to Permission template matching key collision.
*/
public class TemplateMatchingKeyException extends ServerException {
private final transient List<String> errors;
public TemplateMatchingKeyException(String errorMessage) {
super(HTTP_BAD_REQUEST, errorMessage);
this.errors = singletonList(errorMessage);
}
public List<String> errors() {
return this.errors;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("errors", this.errors())
.toString();
}
}
| 1,641 | 30.576923 | 83 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/exceptions/UnauthorizedException.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.exceptions;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
/**
* User needs to be authenticated. HTTP request is generally redirected to login form.
*/
public class UnauthorizedException extends ServerException {
public UnauthorizedException(String message) {
super(HTTP_UNAUTHORIZED, message);
}
}
| 1,193 | 35.181818 | 86 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/exceptions/package-info.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.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.exceptions;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 37.76 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/health/ClusterHealth.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.health;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.sonar.process.cluster.health.NodeHealth;
import static com.google.common.collect.ImmutableSet.copyOf;
import static java.util.Objects.requireNonNull;
public class ClusterHealth {
private final Health health;
private final Set<NodeHealth> nodes;
public ClusterHealth(Health health, Set<NodeHealth> nodes) {
this.health = requireNonNull(health, "health can't be null");
this.nodes = copyOf(requireNonNull(nodes, "nodes can't be null"));
}
public Health getHealth() {
return health;
}
public Set<NodeHealth> getNodes() {
return nodes;
}
public Optional<NodeHealth> getNodeHealth(String nodeName) {
return nodes.stream()
.filter(node -> nodeName.equals(node.getDetails().getName()))
.findFirst();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClusterHealth that = (ClusterHealth) o;
return Objects.equals(health, that.health) &&
Objects.equals(nodes, that.nodes);
}
@Override
public int hashCode() {
return Objects.hash(health, nodes);
}
@Override
public String toString() {
return "ClusterHealth{" +
"health=" + health +
", nodes=" + nodes +
'}';
}
}
| 2,253 | 27.531646 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/health/Health.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.health;
import com.google.common.collect.ImmutableSet;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
public class Health {
/**
* The GREEN status without any cause as a constant, for convenience and optimisation.
*/
public static final Health GREEN = builder()
.setStatus(Status.GREEN)
.build();
private final Status status;
private final Set<String> causes;
public Health(Builder builder) {
this.status = builder.status;
this.causes = ImmutableSet.copyOf(builder.causes);
}
public Status getStatus() {
return status;
}
public Set<String> getCauses() {
return causes;
}
public static Builder builder() {
return new Builder();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Health health = (Health) o;
return status == health.status &&
Objects.equals(causes, health.causes);
}
@Override
public int hashCode() {
return Objects.hash(status, causes);
}
@Override
public String toString() {
return "Health{" + status +
", causes=" + causes +
'}';
}
/**
* Builder of {@link Health} which supports being reused for optimization.
*/
public static class Builder {
private Status status;
private Set<String> causes = new HashSet<>(0);
private Builder() {
// use static factory method
}
public Builder setStatus(Status status) {
this.status = checkStatus(status);
return this;
}
public Builder addCause(String cause) {
requireNonNull(cause, "cause can't be null");
checkArgument(!cause.trim().isEmpty(), "cause can't be empty");
causes.add(cause);
return this;
}
public Health build() {
checkStatus(this.status);
return new Health(this);
}
private static Status checkStatus(Status status) {
return requireNonNull(status, "status can't be null");
}
}
public enum Status {
/**
* Fully working
*/
GREEN,
/**
* Yellow: Working but something must be fixed to make SQ fully operational
*/
YELLOW,
/**
* Red: Not working
*/
RED
}
}
| 3,252 | 23.832061 | 88 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.