Skip to content

Commit

Permalink
Adapt tests
Browse files Browse the repository at this point in the history
  • Loading branch information
nquinquenel committed Dec 10, 2024
1 parent 60455ce commit 5c0766a
Show file tree
Hide file tree
Showing 39 changed files with 167 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
*/
package org.sonarsource.sonarlint.core.analysis.container.analysis.filesystem;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
import org.junit.jupiter.api.Test;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;

class MapSettingsTests {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
*/
package org.sonarsource.sonarlint.core.commons;

import java.nio.file.FileSystemNotFoundException;
import java.nio.file.Path;
import org.eclipse.jgit.ignore.IgnoreNode;
import org.sonarsource.sonarlint.core.commons.log.SonarLintLogger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@
package org.sonarsource.sonarlint.core.commons.progress;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutorService;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
Expand All @@ -46,4 +43,4 @@ void should_cancel_all_monitors() {
assertThat(monitors).allMatch(SonarLintCancelMonitor::isCanceled);
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public class MockWebServerExtension implements BeforeEachCallback, AfterEachCall
@Override
public void beforeEach(ExtensionContext context) {
start();
// Most test cases have a call to this endpoint when initializing the data, to decide whether to use Bearer or Basic scheme
addStringResponse("/api/system/status", "{\"id\": \"20160308094653\",\"version\": \"99.9\",\"status\": \"UP\"}");
}

public void start() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@ public ServerApiProvider(ConnectionConfigurationRepository connectionRepository,
this.sonarCloudUri = sonarCloudActiveEnvironment.getUri();
}

public Optional<ServerApi> getServerApiWithoutCredentials(String connectionId) {
var params = connectionRepository.getEndpointParams(connectionId);
if (params.isEmpty()) {
LOG.debug("Connection '{}' is gone", connectionId);
return Optional.empty();
}
return Optional.of(new ServerApi(params.get(), awareHttpClientProvider.getHttpClient()));
}

public Optional<ServerApi> getServerApi(String connectionId) {
var params = connectionRepository.getEndpointParams(connectionId);
if (params.isEmpty()) {
Expand All @@ -74,6 +83,9 @@ public Optional<ServerApi> getServerApi(String connectionId) {
}

private boolean checkIfBearerIsSupported(EndpointParams params) {
if (params.isSonarCloud()) {
return true;
}
var httpClient = awareHttpClientProvider.getHttpClient();
var cancelMonitor = new SonarLintCancelMonitor();
var serverApi = new ServerApi(params, httpClient);
Expand All @@ -84,7 +96,8 @@ private boolean checkIfBearerIsSupported(EndpointParams params) {

public ServerApi getServerApi(String baseUrl, @Nullable String organization, String token) {
var params = new EndpointParams(baseUrl, removeEnd(sonarCloudUri.toString(), "/").equals(removeEnd(baseUrl, "/")), organization);
return new ServerApi(params, httpClientProvider.getHttpClientWithPreemptiveAuth(token, true));
var isBearerSupported = checkIfBearerIsSupported(params);
return new ServerApi(params, httpClientProvider.getHttpClientWithPreemptiveAuth(token, isBearerSupported));
}

public ServerApi getServerApiOrThrow(String connectionId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -99,7 +98,6 @@ private void checkIfSoonUnsupportedOncePerConnection(Set<String> configScopeIds)
}
});
oneConfigScopeIdPerConnection.forEach(this::queueCheckIfSoonUnsupported);

}

private void queueCheckIfSoonUnsupported(String connectionId, String configScopeId) {
Expand All @@ -109,7 +107,7 @@ private void queueCheckIfSoonUnsupported(String connectionId, String configScope
try {
var connection = connectionRepository.getConnectionById(connectionId);
if (connection != null && connection.getKind() == ConnectionKind.SONARQUBE) {
var serverApi = serverApiProvider.getServerApi(connectionId);
var serverApi = serverApiProvider.getServerApiWithoutCredentials(connectionId);
if (serverApi.isPresent()) {
var version = synchronizationService.getServerConnection(connectionId, serverApi.get()).readOrSynchronizeServerVersion(serverApi.get(), cancelMonitor);
var isCached = cacheConnectionIdPerVersion.containsKey(connectionId) && cacheConnectionIdPerVersion.get(connectionId).compareTo(version) == 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,8 @@
package org.sonarsource.sonarlint.core.http;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutionException;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.inject.Named;
import javax.inject.Singleton;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
import javax.annotation.Nullable;
import javax.inject.Named;
import javax.inject.Singleton;
import org.sonarsource.sonarlint.core.ServerApiProvider;
import org.sonarsource.sonarlint.core.commons.Version;
import org.sonarsource.sonarlint.core.repository.connection.ConnectionConfigurationRepository;
import org.sonarsource.sonarlint.core.serverconnection.StoredServerInfo;
import org.sonarsource.sonarlint.core.storage.StorageService;

Expand All @@ -34,18 +34,18 @@ public class SeverityModeService {
private static final String MIN_MQR_MODE_SUPPORT_VERSION = "10.2";

private final StorageService storageService;
private final ServerApiProvider serverApiProvider;
private final ConnectionConfigurationRepository connectionConfigurationRepository;

public SeverityModeService(StorageService storageService, ServerApiProvider serverApiProvider) {
public SeverityModeService(StorageService storageService, ConnectionConfigurationRepository connectionConfigurationRepository) {
this.storageService = storageService;
this.serverApiProvider = serverApiProvider;
this.connectionConfigurationRepository = connectionConfigurationRepository;
}

public boolean isMQRModeForConnection(@Nullable String connectionId) {
if (connectionId == null) {
return true;
}
var isSonarCloud = serverApiProvider.getServerApiOrThrow(connectionId).isSonarCloud();
var isSonarCloud = connectionConfigurationRepository.getEndpointParams(connectionId).orElseThrow().isSonarCloud();
if (isSonarCloud) {
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import org.sonarsource.sonarlint.core.mode.SeverityModeService;
import org.sonarsource.sonarlint.core.reporting.FindingReportingService;
import org.sonarsource.sonarlint.core.repository.config.ConfigurationRepository;
import org.sonarsource.sonarlint.core.repository.connection.ConnectionConfigurationRepository;
import org.sonarsource.sonarlint.core.repository.rules.RulesRepository;
import org.sonarsource.sonarlint.core.rpc.protocol.SonarLintRpcErrorCode;
import org.sonarsource.sonarlint.core.rpc.protocol.backend.initialize.InitializeParams;
Expand Down Expand Up @@ -93,18 +94,20 @@ public class RulesService {
private final Map<String, StandaloneRuleConfigDto> standaloneRuleConfig = new ConcurrentHashMap<>();
private FindingReportingService findingReportingService;
private final SeverityModeService severityModeService;
private final ConnectionConfigurationRepository connectionConfigurationRepository;

@Inject
public RulesService(ServerApiProvider serverApiProvider, ConfigurationRepository configurationRepository, RulesRepository rulesRepository,
StorageService storageService, InitializeParams params,
ApplicationEventPublisher eventPublisher, SeverityModeService severityModeService) {
StorageService storageService, InitializeParams params, ApplicationEventPublisher eventPublisher,
SeverityModeService severityModeService, ConnectionConfigurationRepository connectionConfigurationRepository) {
this(serverApiProvider, configurationRepository, rulesRepository, storageService, eventPublisher,
params.getStandaloneRuleConfigByKey(), severityModeService);
params.getStandaloneRuleConfigByKey(), severityModeService, connectionConfigurationRepository);
}

RulesService(ServerApiProvider serverApiProvider, ConfigurationRepository configurationRepository, RulesRepository rulesRepository,
StorageService storageService, ApplicationEventPublisher eventPublisher,
@Nullable Map<String, StandaloneRuleConfigDto> standaloneRuleConfigByKey, SeverityModeService severityModeService) {
@Nullable Map<String, StandaloneRuleConfigDto> standaloneRuleConfigByKey, SeverityModeService severityModeService,
ConnectionConfigurationRepository connectionConfigurationRepository) {
this.serverApiProvider = serverApiProvider;
this.configurationRepository = configurationRepository;
this.rulesRepository = rulesRepository;
Expand All @@ -114,6 +117,7 @@ public RulesService(ServerApiProvider serverApiProvider, ConfigurationRepository
if (standaloneRuleConfigByKey != null) {
this.standaloneRuleConfig.putAll(standaloneRuleConfigByKey);
}
this.connectionConfigurationRepository = connectionConfigurationRepository;
}

public EffectiveRuleDetailsDto getEffectiveRuleDetails(String configurationScopeId, String ruleKey, @Nullable String contextKey,
Expand All @@ -139,8 +143,9 @@ public RuleDetails getRuleDetails(String configurationScopeId, String ruleKey, S

public RuleDetails getActiveRuleForBinding(String ruleKey, Binding binding, SonarLintCancelMonitor cancelMonitor) {
var connectionId = binding.getConnectionId();
var serverApi = serverApiProvider.getServerApi(connectionId);
if (serverApi.isEmpty()) {

var endpointParams = connectionConfigurationRepository.getEndpointParams(connectionId);
if (endpointParams.isEmpty()) {
throw unknownConnection(connectionId);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import java.net.URI;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.sonarsource.sonarlint.core.commons.log.SonarLintLogTester;
Expand All @@ -47,9 +48,15 @@ class ServerApiProviderTests {
@Test
void getServerApi_for_sonarqube() {
var endpointParams = mock(EndpointParams.class);
when(endpointParams.getBaseUrl()).thenReturn("");
when(connectionRepository.getEndpointParams("sq1")).thenReturn(Optional.of(endpointParams));
var httpClient = mock(HttpClient.class);
when(awareHttpClientProvider.getHttpClient("sq1", false)).thenReturn(httpClient);
when(awareHttpClientProvider.getHttpClient()).thenReturn(httpClient);
var httpResponse = mock(HttpClient.Response.class);
when(httpResponse.isSuccessful()).thenReturn(true);
when(httpResponse.bodyAsString()).thenReturn("{\"id\": \"20160308094653\",\"version\": \"9.9\",\"status\": \"UP\"}");
when(httpClient.getAsync("/api/system/status")).thenReturn(CompletableFuture.completedFuture(httpResponse));

var serverApi = underTest.getServerApi("sq1");

Expand All @@ -60,6 +67,11 @@ void getServerApi_for_sonarqube() {
void getServerApi_for_sonarqube_notConnected() {
var httpClient = mock(HttpClient.class);
when(httpClientProvider.getHttpClientWithPreemptiveAuth("token", false)).thenReturn(httpClient);
when(awareHttpClientProvider.getHttpClient()).thenReturn(httpClient);
var httpResponse = mock(HttpClient.Response.class);
when(httpResponse.isSuccessful()).thenReturn(true);
when(httpResponse.bodyAsString()).thenReturn("{\"id\": \"20160308094653\",\"version\": \"10.0\",\"status\": \"UP\"}");
when(httpClient.getAsync("sq_notConnected/api/system/status")).thenReturn(CompletableFuture.completedFuture(httpResponse));

var serverApi = underTest.getServerApi("sq_notConnected", null, "token");
assertThat(serverApi.isSonarCloud()).isFalse();
Expand All @@ -68,9 +80,15 @@ void getServerApi_for_sonarqube_notConnected() {
@Test
void getServerApi_for_sonarcloud() {
var endpointParams = mock(EndpointParams.class);
when(endpointParams.getBaseUrl()).thenReturn("");
when(connectionRepository.getEndpointParams("sc1")).thenReturn(Optional.of(endpointParams));
var httpClient = mock(HttpClient.class);
when(awareHttpClientProvider.getHttpClient("sc1", true)).thenReturn(httpClient);
when(awareHttpClientProvider.getHttpClient()).thenReturn(httpClient);
var httpResponse = mock(HttpClient.Response.class);
when(httpResponse.isSuccessful()).thenReturn(true);
when(httpResponse.bodyAsString()).thenReturn("{\"id\": \"20160308094653\",\"version\": \"9.9\",\"status\": \"UP\"}");
when(httpClient.getAsync("/api/system/status")).thenReturn(CompletableFuture.completedFuture(httpResponse));

var serverApi = underTest.getServerApi("sc1");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import org.sonarsource.sonarlint.core.commons.ImpactSeverity;
import org.sonarsource.sonarlint.core.commons.SoftwareQuality;
import org.sonarsource.sonarlint.core.repository.config.ConfigurationRepository;
import org.sonarsource.sonarlint.core.repository.connection.ConnectionConfigurationRepository;
import org.sonarsource.sonarlint.core.repository.rules.RulesRepository;
import org.sonarsource.sonarlint.core.rpc.protocol.backend.rules.RuleDefinitionDto;
import org.sonarsource.sonarlint.core.serverapi.push.parsing.common.ImpactPayload;
Expand All @@ -41,18 +42,20 @@ class RulesServiceTests {
private RulesRepository rulesRepository;
private RulesExtractionHelper extractionHelper;
private ConfigurationRepository configurationRepository;
private ConnectionConfigurationRepository connectionConfigurationRepository;

@BeforeEach
void prepare() {
extractionHelper = mock(RulesExtractionHelper.class);
configurationRepository = mock(ConfigurationRepository.class);
connectionConfigurationRepository = mock(ConnectionConfigurationRepository.class);
rulesRepository = new RulesRepository(extractionHelper, configurationRepository);
}

@Test
void it_should_return_all_embedded_rules_from_the_repository() {
when(extractionHelper.extractEmbeddedRules()).thenReturn(List.of(aRule()));
var rulesService = new RulesService(null, null, rulesRepository, null, null, Map.of(), null);
var rulesService = new RulesService(null, null, rulesRepository, null, null, Map.of(), null, connectionConfigurationRepository);

var embeddedRules = rulesService.listAllStandaloneRulesDefinitions().values();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.Mockito.mock;

class PluginInstancesLoaderTests {
@RegisterExtension
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@
import org.sonarsource.sonarlint.core.commons.log.SonarLintLogger;
import org.sonarsource.sonarlint.core.commons.progress.ExecutorServiceShutdownWatchable;
import org.sonarsource.sonarlint.core.embedded.server.EmbeddedServer;
import org.sonarsource.sonarlint.core.http.ConnectionAwareHttpClientProvider;
import org.sonarsource.sonarlint.core.http.HttpClient;
import org.sonarsource.sonarlint.core.local.only.LocalOnlyIssueStorageService;
import org.sonarsource.sonarlint.core.rpc.protocol.SingleThreadedMessageConsumer;
import org.sonarsource.sonarlint.core.rpc.protocol.SonarLintLauncherBuilder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,6 @@ class OrganizationApiTests {
void testListUserOrganizationWithMoreThan20Pages() {
var underTest = new OrganizationApi(new ServerApiHelper(mockServer.endpointParams("myOrg"), HttpClientProvider.forTesting().getHttpClient()));

mockServer.addStringResponse("/api/system/status", "{\"id\": \"20160308094653\",\"version\": \"9.9\",\"status\": \"UP\"}");

for (var i = 0; i < 21; i++) {
mockOrganizationsPage(i + 1, 10500);
}
Expand All @@ -60,10 +58,6 @@ void testListUserOrganizationWithMoreThan20Pages() {

@Test
void should_get_organization_details() {
mockServer.addStringResponse("/api/system/status", "{" +
"\"status\": \"UP\"," +
"\"version\": \"20.0.0\"" +
"}");
mockServer.addProtobufResponse("/api/organizations/search.protobuf?organizations=org%3Akey&ps=500&p=1", SearchWsResponse.newBuilder()
.addOrganizations(Organization.newBuilder()
.setKey("orgKey")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,9 @@
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.sonarsource.sonarlint.core.commons.CleanCodeAttribute;
import org.sonarsource.sonarlint.core.commons.ImpactSeverity;
import org.sonarsource.sonarlint.core.commons.IssueSeverity;
import org.sonarsource.sonarlint.core.commons.RuleKey;
import org.sonarsource.sonarlint.core.commons.RuleType;
import org.sonarsource.sonarlint.core.commons.SoftwareQuality;
import org.sonarsource.sonarlint.core.commons.api.SonarLanguage;
import org.sonarsource.sonarlint.core.commons.api.TextRangeWithHash;
import org.sonarsource.sonarlint.core.commons.log.SonarLintLogger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,16 @@
import java.nio.file.Path;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.sonarsource.sonarlint.core.serverapi.hotspot.ServerHotspot;
import org.sonarsource.sonarlint.core.serverconnection.issues.ServerIssue;
import org.sonarsource.sonarlint.core.serverconnection.storage.ProjectServerIssueStore;
import testutils.InMemoryIssueStore;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonarsource.sonarlint.core.serverconnection.storage.ServerHotspotFixtures.aServerHotspot;
import static org.sonarsource.sonarlint.core.serverconnection.storage.ServerIssueFixtures.aServerIssue;

class IssueStoreReaderTests {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
Expand Down Expand Up @@ -76,6 +77,13 @@ class BindingSuggestionsMediumTests {

private SonarLintRpcServer backend;

@BeforeEach
void init() {
sonarqubeMock.stubFor(get("/api/system/status")
.willReturn(aResponse().withStatus(200).withBody("{\"id\": \"20160308094653\",\"version\": \"10.8\",\"status\": " +
"\"UP\"}")));
}

@AfterEach
void stop() throws ExecutionException, InterruptedException, TimeoutException {
backend.shutdown().get(5, TimeUnit.SECONDS);
Expand Down
Loading

0 comments on commit 5c0766a

Please sign in to comment.