dependency 'org.sonarsource.slang:sonar-ruby-plugin:1.12.0.4259'
dependency 'org.sonarsource.slang:sonar-scala-plugin:1.12.0.4259'
dependency "org.sonarsource.api.plugin:sonar-plugin-api:$pluginApiVersion"
+ dependency "org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures:$pluginApiVersion"
dependency 'org.sonarsource.xml:sonar-xml-plugin:2.7.0.3820'
dependency 'org.sonarsource.iac:sonar-iac-plugin:1.15.0.3752'
dependency 'org.sonarsource.text:sonar-text-plugin:2.0.2.1090'
group=org.sonarsource.sonarqube
version=10.1
-pluginApiVersion=9.14.0.375
+pluginApiVersion=9.15.0.435
description=Open source platform for continuous inspection of code quality
projectTitle=SonarQube
org.gradle.jvmargs=-Xmx2048m
testImplementation 'junit:junit'
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation project(':sonar-plugin-api-impl')
}
import org.junit.Test;
import org.sonar.api.batch.postjob.PostJobContext;
import org.sonar.api.batch.postjob.internal.DefaultPostJobDescriptor;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.assertj:assertj-guava'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation 'com.squareup.okhttp3:mockwebserver'
}
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.alm.client.ConstantTimeoutConfiguration;
import org.sonar.alm.client.TimeoutConfiguration;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Before
public void prepare() throws IOException {
+ logTester.setLevel(Level.DEBUG);
server.start();
TimeoutConfiguration timeoutConfiguration = new ConstantTimeoutConfiguration(10_000);
assertThat(request.getMethod()).isEqualTo("GET");
assertThat(logTester.logs()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.DEBUG))
+ assertThat(logTester.logs(Level.DEBUG))
.contains("check pat : [" + server.url("").toString() + "_apis/projects?api-version=3.0]");
}
assertThat(azureDevOpsUrlCall).isEqualTo(server.url("") + "_apis/projects?api-version=3.0");
assertThat(request.getMethod()).isEqualTo("GET");
- assertThat(logTester.logs(LoggerLevel.DEBUG)).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.DEBUG))
+ assertThat(logTester.logs(Level.DEBUG)).hasSize(1);
+ assertThat(logTester.logs(Level.DEBUG))
.contains("get projects : [" + server.url("") + "_apis/projects?api-version=3.0]");
assertThat(projects.getValues()).hasSize(2);
assertThat(projects.getValues())
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(UNABLE_TO_CONTACT_AZURE);
- assertThat(logTester.logs(LoggerLevel.ERROR)).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.ERROR).iterator().next())
+ assertThat(logTester.logs(Level.ERROR)).hasSize(1);
+ assertThat(logTester.logs(Level.ERROR).iterator().next())
.contains("Response from Azure for request [" + server.url("") + "_apis/projects?api-version=3.0] could not be parsed:");
}
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid personal access token");
- assertThat(logTester.logs(LoggerLevel.ERROR)).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.ERROR).iterator().next())
+ assertThat(logTester.logs(Level.ERROR)).hasSize(1);
+ assertThat(logTester.logs(Level.ERROR).iterator().next())
.contains("Unable to contact Azure DevOps server for request [" + server.url("") + "_apis/projects?api-version=3.0]: Invalid personal access token");
}
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid Azure URL");
- assertThat(logTester.logs(LoggerLevel.ERROR)).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.ERROR).iterator().next())
+ assertThat(logTester.logs(Level.ERROR)).hasSize(1);
+ assertThat(logTester.logs(Level.ERROR).iterator().next())
.contains("Unable to contact Azure DevOps server for request [" + server.url("") + "_apis/projects?api-version=3.0]: URL Not Found");
}
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unable to contact Azure DevOps server");
- assertThat(logTester.logs(LoggerLevel.ERROR)).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.ERROR).iterator().next())
+ assertThat(logTester.logs(Level.ERROR)).hasSize(1);
+ assertThat(logTester.logs(Level.ERROR).iterator().next())
.contains("Azure API call to [" + server.url("") + "_apis/projects?api-version=3.0] failed with 500 http code. Azure response content :");
}
assertThat(azureDevOpsUrlCall).isEqualTo(server.url("") + "projectName/_apis/git/repositories?api-version=3.0");
assertThat(request.getMethod()).isEqualTo("GET");
- assertThat(logTester.logs(LoggerLevel.DEBUG)).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.DEBUG))
+ assertThat(logTester.logs(Level.DEBUG)).hasSize(1);
+ assertThat(logTester.logs(Level.DEBUG))
.contains("get repos : [" + server.url("").toString() + "projectName/_apis/git/repositories?api-version=3.0]");
assertThat(repos.getValues()).hasSize(1);
assertThat(repos.getValues())
assertThat(azureDevOpsUrlCall).isEqualTo(server.url("") + "Project-Name/_apis/git/repositories/Repo-Name-1?api-version=3.0");
assertThat(request.getMethod()).isEqualTo("GET");
- assertThat(logTester.logs(LoggerLevel.DEBUG)).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.DEBUG))
+ assertThat(logTester.logs(Level.DEBUG)).hasSize(1);
+ assertThat(logTester.logs(Level.DEBUG))
.contains("get repo : [" + server.url("").toString() + "Project-Name/_apis/git/repositories/Repo-Name-1?api-version=3.0]");
assertThat(repo.getId()).isEqualTo("Repo-Id-1");
assertThat(repo.getName()).isEqualTo("Repo-Name-1");
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonarqube.ws.client.OkHttpClientBuilder;
import static org.assertj.core.api.Assertions.assertThat;
assertThatIllegalArgumentException()
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS);
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "401", "Unauthorized"));
+ assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "401", "Unauthorized"));
}
@Test
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(ERROR_BBC_SERVERS + ": " + MISSING_PULL_REQUEST_READ_PERMISSION);
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly(MISSING_PULL_REQUEST_READ_PERMISSION + String.format(SCOPE, ""));
+ assertThat(logTester.logs(Level.INFO)).containsExactly(MISSING_PULL_REQUEST_READ_PERMISSION + String.format(SCOPE, ""));
}
@Test
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage("Error returned by Bitbucket Cloud: No workspace with identifier 'workspace'.");
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL + "2.0/repositories/workspace", "404", response));
+ assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL + "2.0/repositories/workspace", "404", response));
}
@Test
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS + ": " + OAUTH_CONSUMER_NOT_PRIVATE);
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "400", "invalid_grant"));
+ assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "400", "invalid_grant"));
}
@Test
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS + ": " + UNAUTHORIZED_CLIENT);
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "400", "unauthorized_client"));
+ assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "400", "unauthorized_client"));
}
@Test
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage("Error returned by Bitbucket Cloud: Your credentials lack one or more required privilege scopes.");
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL + "2.0/repositories/workspace", "400", error));
+ assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL + "2.0/repositories/workspace", "400", error));
}
@Test
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> underTest.validateAppPassword("wrong:wrong", "workspace"))
.withMessage("Error returned by Bitbucket Cloud: Invalid credentials.");
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL + "2.0/repositories/workspace", "401", response));
+ assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL + "2.0/repositories/workspace", "401", response));
}
@Test
assertThatIllegalArgumentException()
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS);
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, url, "500", message));
+ assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, url, "500", message));
}
@Test
assertThatIllegalArgumentException()
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS);
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "500", body));
+ assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "500", body));
}
@Test
assertThatIllegalArgumentException()
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS);
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "500", body));
+ assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_RESPONSE, serverURL, "500", body));
}
@Test
assertThatIllegalArgumentException()
.isThrownBy(() -> underTest.validate("clientId", "clientSecret", "workspace"))
.withMessage(UNABLE_TO_CONTACT_BBC_SERVERS);
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly(String.format(BBC_FAIL_WITH_ERROR, serverURL, "SSL verification failed"));
+ assertThat(logTester.logs(Level.INFO)).containsExactly(String.format(BBC_FAIL_WITH_ERROR, serverURL, "SSL verification failed"));
}
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.alm.client.ConstantTimeoutConfiguration;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.sonar.alm.client.github.security.AppToken;
import org.sonar.alm.client.github.security.GithubAppSecurity;
import org.sonar.alm.client.github.security.UserAccessToken;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.slf4j.event.Level;
import org.sonar.alm.client.ConstantTimeoutConfiguration;
import org.sonar.alm.client.github.GithubApplicationHttpClient.GetResponse;
import org.sonar.alm.client.github.GithubApplicationHttpClient.Response;
import org.sonar.alm.client.github.security.AccessToken;
import org.sonar.alm.client.github.security.UserAccessToken;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import static java.lang.String.format;
GetResponse response = underTest.get(appUrl, accessToken, randomEndPoint);
- assertThat(logTester.logs(LoggerLevel.WARN)).isNotEmpty();
+ assertThat(logTester.logs(Level.WARN)).isNotEmpty();
assertThat(response.getContent()).isEmpty();
}
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.alm.client.ConstantTimeoutConfiguration;
import org.sonar.alm.client.TimeoutConfiguration;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
assertThatThrownBy(() -> underTest.checkReadPermission(gitlabUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not validate GitLab read permission. Got an unexpected answer.");
- assertThat(logTester.logs(LoggerLevel.INFO).get(0))
+ assertThat(logTester.logs(Level.INFO).get(0))
.contains("Gitlab API call to [" + server.url("/projects") + "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
}
assertThatThrownBy(() -> underTest.checkToken(gitlabUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not validate GitLab token. Got an unexpected answer.");
- assertThat(logTester.logs(LoggerLevel.INFO).get(0))
+ assertThat(logTester.logs(Level.INFO).get(0))
.contains("Gitlab API call to [" + server.url("user") + "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
}
assertThatThrownBy(() -> underTest.checkWritePermission(gitlabUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not validate GitLab write permission. Got an unexpected answer.");
- assertThat(logTester.logs(LoggerLevel.INFO).get(0))
+ assertThat(logTester.logs(Level.INFO).get(0))
.contains("Gitlab API call to [" + server.url("/markdown") + "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
}
assertThatThrownBy(() -> underTest.getProject(gitlabUrl, "token", 0L))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Failed to connect to");
- assertThat(logTester.logs(LoggerLevel.INFO).get(0))
+ assertThat(logTester.logs(Level.INFO).get(0))
.contains("Gitlab API call to [" + server.url("/projects/0") + "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
}
assertThatThrownBy(() -> underTest.getBranches(gitlabUrl, "token", 0L))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Failed to connect to " + server.getHostName());
- assertThat(logTester.logs(LoggerLevel.INFO).get(0))
+ assertThat(logTester.logs(Level.INFO).get(0))
.contains("Gitlab API call to [" + server.url("/projects/0/repository/branches") + "] " +
"failed with error message : [Failed to connect to " + server.getHostName());
}
assertThatThrownBy(() -> underTest.searchProjects(gitlabUrl, "token", null, 1, 1))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Failed to connect to");
- assertThat(logTester.logs(LoggerLevel.INFO).get(0))
+ assertThat(logTester.logs(Level.INFO).get(0))
.contains(
"Gitlab API call to [" + server.url("/projects?archived=false&simple=true&membership=true&order_by=name&sort=asc&search=&page=1&per_page=1")
+ "] " +
testImplementation 'junit:junit'
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation testFixtures(project(':server:sonar-db-dao'))
}
import org.sonar.api.server.authentication.UnauthorizedException;
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogAndArguments;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogAndArguments;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbTester;
import static org.assertj.core.api.Assertions.assertThat;
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.assertj:assertj-guava'
testImplementation 'org.reflections:reflections'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation project(':sonar-testing-harness')
testImplementation testFixtures(project(':server:sonar-server-common'))
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectanalysis.analysis.Analysis;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import static org.mockito.Mockito.when;
import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder;
import static org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStep.MIN_REQUIRED_SCORE;
-import static org.sonar.db.component.BranchType.*;
+import static org.sonar.db.component.BranchType.BRANCH;
+import static org.sonar.db.component.BranchType.PULL_REQUEST;
public class FileMoveDetectionStepIT {
@Before
public void setUp() throws Exception {
+ logTester.setLevel(Level.DEBUG);
project = dbTester.components().insertPrivateProject();
treeRootHolder.setRoot(builder(Component.Type.PROJECT, ROOT_REF).setUuid(project.uuid()).build());
}
assertThat(scoreMatrixDumper.scoreMatrix.getMaxScore()).isZero();
assertThat(addedFileRepository.getComponents()).contains(file2);
verifyStatistics(context, 1, 1, 1, 0);
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("max score in matrix is less than min required score (85). Do nothing.");
+ assertThat(logTester.logs(Level.DEBUG)).contains("max score in matrix is less than min required score (85). Do nothing.");
}
@Test
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.projectanalysis.analysis.Analysis;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
ScmAccountToUserLoader underTest = new ScmAccountToUserLoader(db.getDbClient());
assertThat(underTest.load("charlie")).isNull();
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Multiple users share the SCM account 'charlie': another.charlie, charlie");
+ assertThat(logTester.logs(Level.WARN)).contains("Multiple users share the SCM account 'charlie': another.charlie, charlie");
}
@Test
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.projectanalysis.analysis.Analysis;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.sonar.api.utils.log.LoggerLevel.TRACE;
+import static org.slf4j.event.Level.TRACE;
import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder;
public class ScmInfoDbLoaderIT {
@Before
public void before() {
+ logTester.setLevel(TRACE);
periodHolder.setPeriod(new Period(NewCodePeriodType.PREVIOUS_VERSION.name(), null, null));
}
assertThat(scmInfo.getAllChangesets()).hasSize(1);
assertThat(scmInfo.fileHash()).isEqualTo(hash);
- assertThat(logTester.logs(TRACE)).containsOnly("Reading SCM info from DB for file 'FILE_UUID'");
+ assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'FILE_UUID'");
}
@Test
DbScmInfo scmInfo = underTest.getScmInfo(FILE).get();
assertThat(scmInfo.getAllChangesets()).hasSize(1);
assertThat(scmInfo.fileHash()).isEqualTo(hash);
- assertThat(logTester.logs(TRACE)).containsOnly("Reading SCM info from DB for file 'referenceFileUuid'");
+ assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'referenceFileUuid'");
}
@Test
DbScmInfo scmInfo = underTest.getScmInfo(FILE).get();
assertThat(scmInfo.getAllChangesets()).hasSize(1);
assertThat(scmInfo.fileHash()).isEqualTo(hash);
- assertThat(logTester.logs(TRACE)).containsOnly("Reading SCM info from DB for file 'targetBranchFileUuid'");
+ assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'targetBranchFileUuid'");
}
@Test
DbScmInfo scmInfo = underTest.getScmInfo(FILE).get();
assertThat(scmInfo.getAllChangesets()).hasSize(1);
assertThat(scmInfo.fileHash()).isEqualTo(hash);
- assertThat(logTester.logs(TRACE)).containsOnly("Reading SCM info from DB for file 'targetBranchFileUuid'");
+ assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'targetBranchFileUuid'");
}
@Test
DbScmInfo scmInfo = underTest.getScmInfo(FILE).get();
assertThat(scmInfo.getAllChangesets()).hasSize(1);
assertThat(scmInfo.fileHash()).isEqualTo(hash);
- assertThat(logTester.logs(TRACE)).containsOnly("Reading SCM info from DB for file 'FILE_UUID'");
+ assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'FILE_UUID'");
}
@Test
Optional<DbScmInfo> scmInfo = underTest.getScmInfo(FILE);
- assertThat(logTester.logs(TRACE)).containsOnly("Reading SCM info from DB for file 'FILE_UUID'");
+ assertThat(logTester.logs(TRACE)).contains("Reading SCM info from DB for file 'FILE_UUID'");
assertThat(scmInfo).isEmpty();
}
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.impl.utils.JUnitTempFolder;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.ZipUtils;
-import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.projectanalysis.batch.BatchReportDirectoryHolderImpl;
assertThat(unzippedDir.listFiles()).hasSize(1);
assertThat(new File(unzippedDir, "metadata.pb")).hasContent("{metadata}");
- assertThat(logTester.logs(LoggerLevel.DEBUG)).anyMatch(log -> log.matches("Analysis report is \\d+ bytes uncompressed"));
+ assertThat(logTester.logs(Level.DEBUG)).anyMatch(log -> log.matches("Analysis report is \\d+ bytes uncompressed"));
}
@Test
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.slf4j.event.Level;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogAndArguments;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogAndArguments;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.log.CeTaskMessages;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
@Before
public void setUp() {
+ logTester.setLevel(Level.TRACE);
project = dbTester.components().insertPublicProject();
when(analysisMetadataHolder.isBranch()).thenReturn(true);
}
private void verifyDebugLogs(String log, String... otherLogs) {
- assertThat(logTester.getLogs()).hasSize(1 + otherLogs.length);
- assertThat(logTester.getLogs(LoggerLevel.DEBUG))
- .extracting(LogAndArguments::getFormattedMsg)
- .containsOnly(Stream.concat(Stream.of(log), Arrays.stream(otherLogs)).toArray(String[]::new));
+ assertThat(logTester.logs(Level.DEBUG))
+ .contains(Stream.concat(Stream.of(log), Arrays.stream(otherLogs)).toArray(String[]::new));
}
private void setupRoot(ComponentDto branchComponent) {
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
@Before
public void setUp() {
+ logTester.setLevel(Level.DEBUG);
ComponentDto projectDto = dbTester.components().insertPublicProject(PROJECT);
componentRepository.register(1, projectDto.uuid(), false);
dbTester.getDbClient().componentDao().insert(dbTester.getSession(), Set.of(DIR, FILE), true);
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("3 analyses exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("3 analyses exported");
List<ProjectDump.Analysis> analyses = dumpWriter.getWrittenMessagesOf(DumpElement.ANALYSES);
assertThat(analyses).hasSize(3);
assertAnalysis(analyses.get(0), PROJECT, firstAnalysis);
List<ProjectDump.Analysis> analyses = dumpWriter.getWrittenMessagesOf(DumpElement.ANALYSES);
assertThat(analyses).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("0 analyses exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("0 analyses exported");
}
@Test
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
@Before
public void setUp() {
+ logTester.setLevel(Level.DEBUG);
Date createdAt = new Date();
ComponentDto projectDto = dbTester.components().insertPublicProject(PROJECT).setCreatedAt(createdAt);
for (BranchDto branch : branches) {
public void export_branches() {
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("3 branches exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("3 branches exported");
Map<String, ProjectDump.Branch> branches = dumpWriter.getWrittenMessagesOf(DumpElement.BRANCHES)
.stream()
.collect(toMap(ProjectDump.Branch::getUuid, Function.identity()));
import java.util.Date;
import java.util.List;
import org.junit.After;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
private final MutableComponentRepository componentRepository = new ComponentRepositoryImpl();
private final ExportComponentsStep underTest = new ExportComponentsStep(dbTester.getDbClient(), projectHolder, componentRepository, dumpWriter);
+ @Before
+ public void before() {
+ logTester.setLevel(Level.DEBUG);
+ }
+
@After
public void tearDown() {
dbTester.getSession().close();
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("2 components exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("2 components exported");
List<ProjectDump.Component> components = dumpWriter.getWrittenMessagesOf(DumpElement.COMPONENTS);
assertThat(components).extracting(ProjectDump.Component::getQualifier, ProjectDump.Component::getUuid, ProjectDump.Component::getUuidPath)
.containsExactlyInAnyOrder(
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import java.util.List;
import org.junit.After;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.projectexport.component.MutableComponentRepository;
import org.sonar.ce.task.projectexport.steps.DumpElement;
private ExportLineHashesStep underTest = new ExportLineHashesStep(dbClient, dumpWriter, componentRepository);
+ @Before
+ public void before() {
+ logTester.setLevel(Level.DEBUG);
+ }
+
@After
public void tearDown() {
dbSession.close();
.extracting(ProjectDump.LineHashes::getHashes)
.containsExactly("A", "C", "D", "E");
- assertThat(logTester.logs(LoggerLevel.DEBUG)).containsExactly("Lines hashes of 4 files exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("Lines hashes of 4 files exported");
}
private FileSourceDto insertFileSource(String fileUuid, String hashes) {
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
@Before
public void setUp() {
+ logTester.setLevel(Level.DEBUG);
ComponentDto projectDto = dbTester.components().insertPublicProject(p -> p.setUuid(PROJECT_UUID));
when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDto(projectDto));
when(projectHolder.branches()).thenReturn(newArrayList(
@Test
public void execute_logs_number_total_exported_issue_changes_count_when_successful() {
+ logTester.setLevel(Level.DEBUG);
insertIssueChange(ISSUE_OPEN_UUID);
insertIssueChange(ISSUE_CONFIRMED_UUID);
insertIssueChange(ISSUE_REOPENED_UUID);
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).containsExactly("3 issue changes exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("3 issue changes exported");
}
@Test
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.slf4j.event.Level;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rules.RuleType;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.projectexport.component.MutableComponentRepository;
import org.sonar.ce.task.projectexport.rule.RuleRepository;
@Before
public void setUp() {
+ logTester.setLevel(Level.DEBUG);
ProjectDto project = createProject();
when(projectHolder.projectDto()).thenReturn(project);
when(projectHolder.branches()).thenReturn(newArrayList(
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).containsExactly("3 issues exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("3 issues exported");
}
@Test
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
@Before
public void setup() {
+ logTester.setLevel(Level.DEBUG);
ProjectDto project = createProject();
when(projectHolder.projectDto()).thenReturn(project);
}
List<ProjectDump.AdHocRule> exportedRules = dumpWriter.getWrittenMessagesOf(DumpElement.AD_HOC_RULES);
assertThat(exportedRules).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("0 ad-hoc rules exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("0 ad-hoc rules exported");
}
@Test
List<ProjectDump.AdHocRule> exportedRules = dumpWriter.getWrittenMessagesOf(DumpElement.AD_HOC_RULES);
assertThat(exportedRules).hasSize(1);
assertProtobufAdHocRuleIsCorrectlyBuilt(exportedRules.iterator().next(), rule2);
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("1 ad-hoc rules exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("1 ad-hoc rules exported");
}
@Test
List<ProjectDump.AdHocRule> exportedRules = dumpWriter.getWrittenMessagesOf(DumpElement.AD_HOC_RULES);
assertThat(exportedRules).hasSize(1);
assertProtobufAdHocRuleIsCorrectlyBuilt(exportedRules.iterator().next(), rule3);
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("1 ad-hoc rules exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("1 ad-hoc rules exported");
}
@Test
List<ProjectDump.AdHocRule> exportedRules = dumpWriter.getWrittenMessagesOf(DumpElement.AD_HOC_RULES);
assertThat(exportedRules).hasSize(1);
assertProtobufAdHocRuleIsCorrectlyBuilt(exportedRules.iterator().next(), rule2);
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("1 ad-hoc rules exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("1 ad-hoc rules exported");
}
@Test
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
@Before
public void setUp() {
+ logTester.setLevel(Level.DEBUG);
ComponentDto projectDto = dbTester.components().insertPublicProject(PROJECT);
componentRepository.register(1, projectDto.uuid(), false);
projectHolder.setProjectDto(dbTester.components().getProjectDto(projectDto));
public void export_zero_events() {
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("0 events exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("0 events exported");
List<ProjectDump.Event> events = dumpWriter.getWrittenMessagesOf(DumpElement.EVENTS);
assertThat(events).isEmpty();
}
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("2 events exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("2 events exported");
List<ProjectDump.Event> events = dumpWriter.getWrittenMessagesOf(DumpElement.EVENTS);
assertThat(events).hasSize(2);
assertThat(events).extracting(ProjectDump.Event::getUuid).containsOnly("E1", "E2");
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.component.ComponentRepository;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
@Before
public void setUp() {
+ logTester.setLevel(Level.DEBUG);
ComponentDto project = db.components().insertPublicProject(PROJECT);
when(projectHolder.projectDto()).thenReturn(db.components().getProjectDto(project));
when(componentRepository.getRef(PROJECT_UUID)).thenReturn(1L);
public void export_zero_links() {
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("0 links exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("0 links exported");
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.LINKS)).isEmpty();
}
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("2 links exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("2 links exported");
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.LINKS))
.extracting(Link::getUuid, Link::getName, Link::getType, Link::getHref)
.containsExactlyInAnyOrder(
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import java.util.List;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
private FakeDumpWriter dumpWriter = new FakeDumpWriter();
private ExportLiveMeasuresStep underTest = new ExportLiveMeasuresStep(dbTester.getDbClient(), projectHolder, componentRepository, metricRepository, dumpWriter);
+ @Before
+ public void before() {
+ logTester.setLevel(Level.DEBUG);
+ }
+
@Test
public void export_zero_measures() {
when(projectHolder.branches()).thenReturn(newArrayList());
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.LIVE_MEASURES)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("0 live measures exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("0 live measures exported");
assertThat(metricRepository.getRefByUuid()).isEmpty();
}
assertThat(exportedMeasures)
.extracting(ProjectDump.LiveMeasure::getMetricRef, m -> m.getDoubleValue().getValue(), ProjectDump.LiveMeasure::hasVariation)
.containsOnly(tuple(0, 4711.0d, false));
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("1 live measures exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("1 live measures exported");
assertThat(metricRepository.getRefByUuid()).containsOnlyKeys(metric.getUuid());
}
0.0d,
"test",
7.0d));
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("1 live measures exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("1 live measures exported");
assertThat(metricRepository.getRefByUuid()).containsOnlyKeys(metric.getUuid());
}
false,
"",
false));
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("1 live measures exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("1 live measures exported");
assertThat(metricRepository.getRefByUuid()).containsOnlyKeys(metric.getUuid());
}
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
@Before
public void setUp() {
+ logTester.setLevel(Level.DEBUG);
String projectUuid = dbTester.components().insertPublicProject(PROJECT).uuid();
componentRepository.register(1, projectUuid, false);
dbTester.getDbClient().componentDao().insert(dbTester.getSession(), List.of(FILE, ANOTHER_PROJECT), true);
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.MEASURES)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("0 measures exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("0 measures exported");
assertThat(metricRepository.getRefByUuid()).isEmpty();
}
assertThat(exportedMeasures).hasSize(2);
assertThat(exportedMeasures).extracting(ProjectDump.Measure::getAnalysisUuid).containsOnly(firstAnalysis.getUuid(), secondAnalysis.getUuid());
assertThat(exportedMeasures).extracting(ProjectDump.Measure::getMetricRef).containsOnly(0);
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("2 measures exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("2 measures exported");
assertThat(metricRepository.getRefByUuid()).containsOnlyKeys(NCLOC.getUuid());
}
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.metric.MetricDto;
@Before
public void setUp() {
+ logTester.setLevel(Level.DEBUG);
dbTester.getDbClient().metricDao().insert(dbTester.getSession(), NCLOC, COVERAGE);
dbTester.commit();
}
public void export_zero_metrics() {
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("0 metrics exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("0 metrics exported");
}
@Test
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("2 metrics exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("2 metrics exported");
List<ProjectDump.Metric> exportedMetrics = dumpWriter.getWrittenMessagesOf(DumpElement.METRICS);
ProjectDump.Metric ncloc = exportedMetrics.stream().filter(input -> input.getRef() == 0).findAny().orElseThrow();
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
@Before
public void setUp() {
+ logTester.setLevel(Level.DEBUG);
Date createdAt = new Date();
ComponentDto projectDto = dbTester.components().insertPublicProject(PROJECT);
PROJECT_BRANCHES.forEach(branch -> dbTester.components().insertProjectBranch(projectDto, branch).setCreatedAt(createdAt));
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.NEW_CODE_PERIODS)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("0 new code periods exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("0 new code periods exported");
}
@Test
List<ProjectDump.NewCodePeriod> exportedProps = dumpWriter.getWrittenMessagesOf(DumpElement.NEW_CODE_PERIODS);
assertThat(exportedProps).hasSize(2);
assertThat(exportedProps).extracting(ProjectDump.NewCodePeriod::getUuid).containsOnly("uuid1", "uuid2");
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("2 new code periods exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("2 new code periods exported");
}
@Test
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.projectexport.component.MutableComponentRepository;
import org.sonar.ce.task.step.TestComputationStepContext;
@Before
public void setUp() {
+ logTester.setLevel(Level.DEBUG);
dbTester.components().insertPublicProject(PROJECT);
dbTester.components().insertPublicProject(ANOTHER_PROJECT);
dbTester.commit();
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.SETTINGS)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("0 settings exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("0 settings exported");
}
@Test
List<ProjectDump.Setting> exportedProps = dumpWriter.getWrittenMessagesOf(DumpElement.SETTINGS);
assertThat(exportedProps).hasSize(2);
assertThat(exportedProps).extracting(ProjectDump.Setting::getKey).containsOnly("p1", "p2");
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("2 settings exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("2 settings exported");
}
@Test
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.SETTINGS)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("0 settings exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("0 settings exported");
}
@Test
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
+import org.slf4j.event.Level;
import org.sonar.api.ce.posttask.PostProjectAnalysisTask;
import org.sonar.api.ce.posttask.Project;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
assertThat(allValues.get(0)).isSameAs(allValues.get(1));
assertThat(logTester.logs()).hasSize(2);
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
assertThat(logs.get(0)).matches("^PT1 \\| status=SUCCESS \\| time=\\d+ms$");
assertThat(logs.get(1)).matches("^PT2 \\| status=SUCCESS \\| time=\\d+ms$");
verify(logStatisticsTask).finished(taskContextCaptor.capture());
assertThat(logTester.logs()).hasSize(1);
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(1);
StringBuilder expectedLog = new StringBuilder("^PT1 ");
stats.forEach((k, v) -> expectedLog.append("\\| " + k + "=" + v + " "));
inOrder.verifyNoMoreInteractions();
assertThat(logTester.logs()).hasSize(4);
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(3);
assertThat(logs.get(0)).matches("^PT1 \\| status=SUCCESS \\| time=\\d+ms$");
assertThat(logs.get(1)).matches("^PT2 \\| status=FAILED \\| time=\\d+ms$");
*/
package org.sonar.ce.task.projectanalysis.duplication;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
private CrossProjectDuplicationStatusHolderImpl underTest = new CrossProjectDuplicationStatusHolderImpl(analysisMetadataHolder);
+ @Before
+ public void before() {
+ logTester.setLevel(Level.DEBUG);
+ }
+
@Test
public void cross_project_duplication_is_enabled_when_enabled_in_report_and_no_branch() {
analysisMetadataHolder
underTest.start();
assertThat(underTest.isEnabled()).isTrue();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).containsOnly("Cross project duplication is enabled");
+ assertThat(logTester.logs(Level.DEBUG)).containsOnly("Cross project duplication is enabled");
}
@Test
underTest.start();
assertThat(underTest.isEnabled()).isFalse();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).containsOnly("Cross project duplication is disabled because it's disabled in the analysis report");
+ assertThat(logTester.logs(Level.DEBUG)).containsOnly("Cross project duplication is disabled because it's disabled in the analysis report");
}
@Test
underTest.start();
assertThat(underTest.isEnabled()).isFalse();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).containsOnly("Cross project duplication is disabled because of a branch is used");
+ assertThat(logTester.logs(Level.DEBUG)).containsOnly("Cross project duplication is disabled because of a branch is used");
}
@Test
underTest.start();
assertThat(underTest.isEnabled()).isFalse();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).containsOnly("Cross project duplication is disabled because it's disabled in the analysis report");
+ assertThat(logTester.logs(Level.DEBUG)).containsOnly("Cross project duplication is disabled because it's disabled in the analysis report");
}
@Test
import java.util.Collections;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.TestSystem2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.log.CeTaskMessages;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.FileAttributes;
underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks);
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly(
+ assertThat(logTester.logs(Level.WARN)).containsOnly(
"Too many duplication references on file " + ORIGIN_FILE_KEY + " for block at line 30. Keeping only the first 100 references.");
Iterable<Duplication> duplications = duplicationRepository.getDuplications(ORIGIN_FILE);
assertThat(duplications).hasSize(1);
underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks);
assertThat(duplicationRepository.getDuplications(ORIGIN_FILE)).hasSize(100);
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly("Too many duplication groups on file " + ORIGIN_FILE_KEY + ". Keeping only the first 100 groups.");
+ assertThat(logTester.logs(Level.WARN)).containsOnly("Too many duplication groups on file " + ORIGIN_FILE_KEY + ". Keeping only the first 100 groups.");
}
@Test
import java.util.Arrays;
import javax.annotation.Nullable;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.scm.Changeset;
private DefaultAssignee defaultAssignee = mock(DefaultAssignee.class);
private IssueAssigner underTest = new IssueAssigner(analysisMetadataHolder, scmInfoRepository, scmAccountToUser, defaultAssignee, new IssueFieldsSetter());
+ @Before
+ public void before() {
+ logTester.setLevel(Level.DEBUG);
+ }
+
@Test
public void do_not_set_author_if_no_changeset() {
DefaultIssue issue = newIssueOnLines(1);
assertThat(issue.authorLogin()).isNull();
assertThat(issue.assignee()).isEqualTo("John C");
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("SCM account '" + scmAuthor + "' is too long to be stored as issue author");
+ assertThat(logTester.logs(Level.DEBUG)).contains("SCM account '" + scmAuthor + "' is too long to be stored as issue author");
}
@Test
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.core.metric.ScannerMetrics;
ScannerMetrics scannerMetrics = mock(ScannerMetrics.class);
+ @Before
+ public void before() {
+ logTester.setLevel(Level.DEBUG);
+ }
+
@Test
public void validate_metric() {
when(scannerMetrics.getMetrics()).thenReturn(ImmutableSet.of(new Builder(METRIC_KEY, "name", ValueType.INT).create()));
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
-import static org.sonar.api.utils.log.LoggerLevel.TRACE;
+import static org.slf4j.event.Level.TRACE;
import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder;
@RunWith(DataProviderRunner.class)
@Before
public void setUp() {
+ logTester.setLevel(TRACE);
analysisMetadata.setAnalysisDate(analysisDate);
}
import java.util.List;
import java.util.Map;
import java.util.Random;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter.RangeOffsetConverterException;
import org.sonar.db.protobuf.DbFileSources;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.sonar.api.utils.log.LoggerLevel.DEBUG;
+import static org.slf4j.event.Level.DEBUG;
import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder;
import static org.sonar.ce.task.projectanalysis.source.linereader.LineReader.Data.HIGHLIGHTING;
import static org.sonar.db.protobuf.DbFileSources.Data.newBuilder;
private DbFileSources.Line.Builder line3 = sourceData.addLinesBuilder().setSource("line3").setLine(3);
private DbFileSources.Line.Builder line4 = sourceData.addLinesBuilder().setSource("line4").setLine(4);
+ @Before
+ public void before() {
+ logTester.setLevel(Level.TRACE);
+ }
+
@Test
public void nothing_to_read() {
HighlightingLineReader highlightingLineReader = newReader(Collections.emptyMap());
import java.util.Arrays;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.scanner.protocol.output.ScannerReport;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.sonar.api.utils.log.LoggerLevel.WARN;
+import static org.slf4j.event.Level.WARN;
import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder;
import static org.sonar.ce.task.projectanalysis.source.linereader.LineReader.Data.SYMBOLS;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.ChangeLogLevel;
import org.sonar.ce.task.projectanalysis.component.Component;
@Before
public void setUp() throws Exception {
+ logTester.setLevel(Level.DEBUG);
treeRootHolder.setRoot(
builder(PROJECT, ROOT_REF).setKey("project")
.addChildren(
underTest.execute(new TestComputationStepContext());
- List<String> logs = logTester.logs(LoggerLevel.DEBUG);
+ List<String> logs = logTester.logs(Level.DEBUG);
assertThat(logs).hasSize(4);
assertThat(logs.get(0)).isEqualTo(" Execution time for each component visitor:");
assertThat(logs.get(1)).startsWith(" - VisitorA | time=");
import java.util.Collection;
import java.util.List;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.rule.RuleKey;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
import org.sonar.ce.task.step.TestComputationStepContext;
@Test
public void execute_logs_number_total_exported_rules_count_when_successful() {
+ logTester.setLevel(Level.DEBUG);
ruleRepository.add("A").add("B").add("C").add("D");
underTest.execute(new TestComputationStepContext());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).containsExactly("4 rules exported");
+ assertThat(logTester.logs(Level.DEBUG)).containsExactly("4 rules exported");
}
@Test
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.TempFolder;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor;
import org.sonar.ce.task.projectexport.util.ProjectExportDumpFS;
assertThat(rootDir).doesNotExist();
assertThat(targetZipFile).isFile().exists();
- assertThat(logTester.logs(LoggerLevel.INFO).get(0))
+ assertThat(logTester.logs(Level.INFO).get(0))
.contains("Dump file published", "size=", "path=" + targetZipFile.getAbsolutePath());
}
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
private FakeDumpWriter dumpWriter = new FakeDumpWriter();
ExportPluginsStep underTest = new ExportPluginsStep(pluginRepository, dumpWriter);
+ @Before
+ public void before() {
+ logTester.setLevel(Level.DEBUG);
+ }
+
@Test
public void export_plugins() {
when(pluginRepository.getPluginInfos()).thenReturn(Arrays.asList(
List<ProjectDump.Plugin> exportedPlugins = dumpWriter.getWrittenMessagesOf(DumpElement.PLUGINS);
assertThat(exportedPlugins).hasSize(2);
assertThat(exportedPlugins).extracting(ProjectDump.Plugin::getKey).containsExactlyInAnyOrder("java", "cs");
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("2 plugins exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("2 plugins exported");
}
@Test
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.PLUGINS)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("0 plugins exported");
+ assertThat(logTester.logs(Level.DEBUG)).contains("0 plugins exported");
}
@Test
testImplementation 'org.assertj:assertj-guava'
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.reflections:reflections'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation testFixtures(project(':server:sonar-db-dao'))
testFixturesApi 'org.assertj:assertj-core'
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InOrder;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.CeTaskInterrupter;
import org.sonar.ce.task.ChangeLogLevel;
ChangeLogLevel logLevel3 = new ChangeLogLevel(step3.getClass(), LoggerLevel.INFO)) {
new ComputationStepExecutor(mockComputationSteps(step1, step2, step3), taskInterrupter).execute();
- List<String> infoLogs = logTester.logs(LoggerLevel.INFO);
+ List<String> infoLogs = logTester.logs(Level.INFO);
assertThat(infoLogs).hasSize(3);
assertThat(infoLogs.get(0)).contains("Step One | foo=100 | bar=20 | status=SUCCESS | time=");
assertThat(infoLogs.get(1)).contains("Step Two | foo=50 | baz=10 | status=SUCCESS | time=");
new ComputationStepExecutor(mockComputationSteps(step1, step2, step3), taskInterrupter).execute();
fail("a RuntimeException should have been thrown");
} catch (RuntimeException e) {
- List<String> infoLogs = logTester.logs(LoggerLevel.INFO);
+ List<String> infoLogs = logTester.logs(Level.INFO);
assertThat(infoLogs).hasSize(3);
assertThat(infoLogs.get(0)).contains("Step One | foo=100 | bar=20 | status=SUCCESS | time=");
assertThat(infoLogs.get(1)).contains("Step Two | foo=50 | baz=10 | status=SUCCESS | time=");
testImplementation 'org.awaitility:awaitility'
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.slf4j:slf4j-api'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation testFixtures(project(':server:sonar-db-dao'))
import org.sonar.api.config.Configuration;
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.config.ComputeEngineProperties;
import org.sonar.db.DbTester;
import org.sonar.db.ce.CeQueueDto;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.stubbing.Answer;
+import org.slf4j.event.Level;
import org.sonar.api.impl.utils.TestSystem2;
+import org.sonar.api.testfixtures.log.LogAndArguments;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogAndArguments;
-import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.queue.InternalCeQueue;
import org.sonar.ce.task.CeTask;
underTest.call();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
for (int i = 0; i < 2; i++) {
assertThat(logs.get(i)).contains("pullRequest=123");
underTest.call();
verifyWorkerUuid();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
for (int i = 0; i < 2; i++) {
assertThat(logs.get(i)).doesNotContain("submitter=");
underTest.call();
verifyWorkerUuid();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
assertThat(logs.get(0)).doesNotContain("submitter=");
assertThat(logs.get(1)).doesNotContain("submitter=");
- logs = logTester.logs(LoggerLevel.ERROR);
+ logs = logTester.logs(Level.ERROR);
assertThat(logs).hasSize(1);
assertThat(logs.iterator().next()).doesNotContain("submitter=");
- assertThat(logTester.logs(LoggerLevel.DEBUG)).isEmpty();
+ assertThat(logTester.logs(Level.DEBUG)).isEmpty();
}
@Test
underTest.call();
verifyWorkerUuid();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
assertThat(logs.get(0)).contains(String.format("submitter=%s", userDto.getLogin()));
assertThat(logs.get(1)).contains(String.format("submitter=%s | status=SUCCESS | time=", userDto.getLogin()));
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.DEBUG)).isEmpty();
}
@Test
underTest.call();
verifyWorkerUuid();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
assertThat(logs.get(0)).contains("submitter=UUID_USER");
assertThat(logs.get(1)).contains("submitter=UUID_USER | status=SUCCESS | time=");
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.DEBUG)).isEmpty();
}
@Test
underTest.call();
verifyWorkerUuid();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
assertThat(logs.get(0)).contains(String.format("submitter=%s", userDto.getLogin()));
assertThat(logs.get(1)).contains(String.format("submitter=%s | status=FAILED | time=", userDto.getLogin()));
- logs = logTester.logs(LoggerLevel.ERROR);
+ logs = logTester.logs(Level.ERROR);
assertThat(logs).hasSize(1);
assertThat(logs.get(0)).isEqualTo("Failed to execute task " + ceTask.getUuid());
}
underTest.call();
verifyWorkerUuid();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
assertThat(logs.get(0)).contains(" | submitter=" + submitter.login());
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=SUCCESS | time=", submitter.login()));
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.DEBUG)).isEmpty();
}
@Test
underTest.call();
verifyWorkerUuid();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
assertThat(logs.get(0)).contains(" | submitter=" + submitter.login());
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login()));
- logs = logTester.logs(LoggerLevel.ERROR);
+ logs = logTester.logs(Level.ERROR);
assertThat(logs).hasSize(1);
assertThat(logs.iterator().next()).isEqualTo("Failed to execute task " + ceTask.getUuid());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).isEmpty();
+ assertThat(logTester.logs(Level.DEBUG)).isEmpty();
}
@Test
underTest.call();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
assertThat(logs.get(0)).contains(" | submitter=" + submitter.login());
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login()));
- logs = logTester.logs(LoggerLevel.ERROR);
+ logs = logTester.logs(Level.ERROR);
assertThat(logs).hasSize(1);
assertThat(logs.iterator().next()).isEqualTo("Failed to execute task " + ceTask.getUuid());
}
underTest.call();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
assertThat(logs.get(1)).contains(" | submitter=" + submitter.login());
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login()));
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
}
@Test
underTest.call();
- assertThat(logTester.logs(LoggerLevel.ERROR)).containsOnly("Failed to finalize task with uuid '" + ceTask.getUuid() + "' and persist its state to db");
+ assertThat(logTester.logs(Level.ERROR)).containsOnly("Failed to finalize task with uuid '" + ceTask.getUuid() + "' and persist its state to db");
}
@Test
underTest.call();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
assertThat(logs.get(0)).contains(" | submitter=" + submitter.login());
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login()));
- List<LogAndArguments> logAndArguments = logTester.getLogs(LoggerLevel.ERROR);
+ List<LogAndArguments> logAndArguments = logTester.getLogs(Level.ERROR);
assertThat(logAndArguments).hasSize(2);
LogAndArguments executionErrorLog = logAndArguments.get(0);
assertThat(executionErrorLog.getFormattedMsg()).isEqualTo("Failed to execute task " + ceTask.getUuid());
- assertThat(executionErrorLog.getArgs().get()).containsOnly(ceTask.getUuid(), ex);
LogAndArguments finalizingErrorLog = logAndArguments.get(1);
assertThat(finalizingErrorLog.getFormattedMsg()).isEqualTo("Failed to finalize task with uuid '" + ceTask.getUuid() + "' and persist its state to db");
- Object arg1 = finalizingErrorLog.getArgs().get()[0];
- assertThat(arg1).isSameAs(runtimeException);
- assertThat(((Exception) arg1).getSuppressed()).containsOnly(ex);
}
@Test
underTest.call();
- List<String> logs = logTester.logs(LoggerLevel.INFO);
+ List<String> logs = logTester.logs(Level.INFO);
assertThat(logs).hasSize(2);
assertThat(logs.get(0)).contains(" | submitter=" + submitter.login());
assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login()));
- List<LogAndArguments> logAndArguments = logTester.getLogs(LoggerLevel.ERROR);
+ List<LogAndArguments> logAndArguments = logTester.getLogs(Level.ERROR);
assertThat(logAndArguments).hasSize(1);
assertThat(logAndArguments.get(0).getFormattedMsg()).isEqualTo("Failed to finalize task with uuid '" + ceTask.getUuid() + "' and persist its state to db");
- Object arg1 = logAndArguments.get(0).getArgs().get()[0];
- assertThat(arg1).isSameAs(runtimeException);
- assertThat(((Exception) arg1).getSuppressed()).containsOnly(ex);
}
@Test
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
private void verifyWarnMessage() {
assertThat(logTester.logs()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly("Property sonar.ce.workerCount is not supported anymore and will be ignored." +
+ assertThat(logTester.logs(Level.WARN)).containsOnly("Property sonar.ce.workerCount is not supported anymore and will be ignored." +
" Remove it from sonar.properties to remove this warning.");
}
}
import java.util.Random;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.configuration.CeConfigurationRule;
import static org.assertj.core.api.Assertions.assertThat;
private void verifyInfoLog(int workerCount) {
assertThat(logTester.logs()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.containsOnly("Compute Engine will use " + workerCount + " concurrent workers to process tasks");
}
}
import java.util.Random;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskCanceledException;
import org.sonar.ce.task.CeTaskTimeoutException;
new TimeoutCeTaskInterrupter(timeout, ceWorkerController, system2);
assertThat(logTester.logs()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.containsExactly("Compute Engine Task timeout enabled: " + timeout + " ms");
}
testImplementation 'com.tngtech.java:junit-dataprovider'
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.postgresql:postgresql'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation project(':sonar-testing-harness')
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.Loggers;
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.dialect.Oracle;
getDriver(connection);
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Fail to determine database driver.");
+ assertThat(logTester.logs(Level.WARN)).contains("Fail to determine database driver.");
}
@Test
log(Loggers.get(getClass()), root);
- assertThat(logTester.logs(LoggerLevel.ERROR)).contains("SQL error: 456. Message: this is next");
+ assertThat(logTester.logs(Level.ERROR)).contains("SQL error: 456. Message: this is next");
}
@Test
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.config.internal.MapSettings;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.process.logging.LogbackHelper;
import java.sql.DatabaseMetaData;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public void init_logs_warning() {
underTest.init(mock(DatabaseMetaData.class));
- assertThat(logs.logs(LoggerLevel.WARN)).contains("H2 database should be used for evaluation purpose only.");
+ assertThat(logs.logs(Level.WARN)).contains("H2 database should be used for evaluation purpose only.");
}
@Test
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
underTest.init(metadata);
assertThat(underTest.supportsUpsert()).isFalse();
- assertThat(logs.logs(LoggerLevel.WARN)).contains("Upgrading PostgreSQL to 9.5 or greater is recommended for better performances");
+ assertThat(logs.logs(Level.WARN)).contains("Upgrading PostgreSQL to 9.5 or greater is recommended for better performances");
}
@Test
underTest.init(metadata);
assertThat(underTest.supportsUpsert()).isTrue();
- assertThat(logs.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logs.logs(Level.WARN)).isEmpty();
}
@Test
import java.util.concurrent.ThreadFactory;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import static java.nio.charset.StandardCharsets.UTF_8;
assertThat(statementProxy.getConnection()).isNull();
assertThat(statementProxy.execute(sql)).isTrue();
- assertThat(logTester.logs(LoggerLevel.TRACE)).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.TRACE).get(0))
+ assertThat(logTester.logs(Level.TRACE)).hasSize(1);
+ assertThat(logTester.logs(Level.TRACE).get(0))
.contains("sql=select from dual");
}
assertThat(preparedStatementProxy.getConnection()).isNull();
assertThat(preparedStatementProxy.execute()).isTrue();
- assertThat(logTester.logs(LoggerLevel.TRACE)).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.TRACE).get(0))
+ assertThat(logTester.logs(Level.TRACE)).hasSize(1);
+ assertThat(logTester.logs(Level.TRACE).get(0))
.contains("sql=insert into polop (col1, col2, col3, col4) values (?, ?, ?, ?, ?)")
.contains("params=42, plouf");
}
assertThat(preparedStatementProxy.getConnection()).isNull();
assertThat(preparedStatementProxy.execute()).isTrue();
- assertThat(logTester.logs(LoggerLevel.TRACE)).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.TRACE).get(0))
+ assertThat(logTester.logs(Level.TRACE)).hasSize(1);
+ assertThat(logTester.logs(Level.TRACE).get(0))
.contains("sql=select from dual")
.doesNotContain("params=");
}
testImplementation 'org.assertj:assertj-guava'
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.sonarsource.orchestrator:sonar-orchestrator'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation project(':sonar-testing-harness')
testImplementation project(':sonar-plugin-api-impl')
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.util.stream.MoreCollectors;
import static java.lang.Math.abs;
underTest.disableCaching();
- List<String> errorLogs = logTester.logs(LoggerLevel.ERROR);
+ List<String> errorLogs = logTester.logs(Level.ERROR);
assertThat(errorLogs)
.hasSize(1)
.containsOnly("Failed to close " + (batchOrRegular ? "batch" : "regular") + " connection in " + Thread.currentThread());
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.xmlunit:xmlunit-core'
testImplementation 'org.xmlunit:xmlunit-matchers'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation project(':sonar-scanner-protocol')
testImplementation project(':sonar-testing-harness')
testImplementation testFixtures(project(':server:sonar-db-core'))
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.server.platform.db.migration.engine.MigrationContainer;
import org.sonar.server.platform.db.migration.engine.SimpleMigrationContainer;
underTest.execute(Collections.emptyList());
assertThat(logTester.logs()).hasSize(2);
- assertLogLevel(LoggerLevel.INFO, "Executing DB migrations...", "Executed DB migrations: success | time=");
+ assertLogLevel(Level.INFO, "Executing DB migrations...", "Executed DB migrations: success | time=");
}
@Test
assertThat(e).hasMessage("Unable to load component " + MigrationStep1.class);
} finally {
assertThat(logTester.logs()).hasSize(2);
- assertLogLevel(LoggerLevel.INFO, "Executing DB migrations...");
- assertLogLevel(LoggerLevel.ERROR, "Executed DB migrations: failure | time=");
+ assertLogLevel(Level.INFO, "Executing DB migrations...");
+ assertLogLevel(Level.ERROR, "Executed DB migrations: failure | time=");
}
}
- private void assertLogLevel(LoggerLevel level, String... expected) {
+ private void assertLogLevel(Level level, String... expected) {
List<String> logs = logTester.logs(level);
assertThat(logs).hasSize(expected.length);
Iterator<String> iterator = logs.iterator();
assertThat(SingleCallCheckerMigrationStep.calledSteps)
.containsExactly(MigrationStep2.class, MigrationStep1.class, MigrationStep3.class);
assertThat(logTester.logs()).hasSize(8);
- assertLogLevel(LoggerLevel.INFO,
+ assertLogLevel(Level.INFO,
"Executing DB migrations...",
"#1 '1-MigrationStep2'...",
"#1 '1-MigrationStep2': success | time=",
assertThat(e).hasCause(SqlExceptionFailingMigrationStep.THROWN_EXCEPTION);
} finally {
assertThat(logTester.logs()).hasSize(6);
- assertLogLevel(LoggerLevel.INFO,
+ assertLogLevel(Level.INFO,
"Executing DB migrations...",
"#1 '1-MigrationStep2'...",
"#1 '1-MigrationStep2': success | time=",
"#2 '2-SqlExceptionFailingMigrationStep'...");
- assertLogLevel(LoggerLevel.ERROR,
+ assertLogLevel(Level.ERROR,
"#2 '2-SqlExceptionFailingMigrationStep': failure | time=",
"Executed DB migrations: failure | time=");
}
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.step.DataChange;
underTest.execute();
- assertThat(logger.logs(LoggerLevel.WARN))
+ assertThat(logger.logs(Level.WARN))
.hasSize(1)
.containsExactly("'" + SONAR_SCIM_ENABLED + "' property is defined but not read anymore. Please read the upgrade notes" +
" for the instruction to upgrade. User provisioning is deactivated until reactivated from the SonarQube" +
underTest.execute();
- assertThat(logger.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logger.logs(Level.WARN)).isEmpty();
}
@Test
underTest.execute();
underTest.execute();
- assertThat(logger.logs(LoggerLevel.WARN)).hasSize(2);
+ assertThat(logger.logs(Level.WARN)).hasSize(2);
}
}
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.hamcrest:hamcrest-core'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation testFixtures(project(':server:sonar-db-dao'))
testImplementation project(':sonar-plugin-api-impl')
testImplementation project(':sonar-testing-harness')
testFixturesCompileOnly 'com.google.code.findbugs:jsr305'
testFixturesImplementation 'org.elasticsearch.plugin:transport-netty4-client'
-
testFixturesImplementation 'org.codelibs.elasticsearch.module:analysis-common'
testFixturesImplementation 'org.codelibs.elasticsearch.module:reindex'
testFixturesImplementation 'org.elasticsearch:mocksocket'
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.impl.utils.TestSystem2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.DbTester;
import org.sonar.server.es.BulkIndexer.Size;
indexer.add(newIndexRequestWithDocId("bar"));
indexer.stop();
- assertThat(logTester.logs(LoggerLevel.TRACE)
+ assertThat(logTester.logs(Level.TRACE)
.stream()
.filter(log -> log.contains("Bulk[2 index requests on fakes/_doc, 1 delete requests on fakes/_doc]"))
.count()).isNotZero();
import org.elasticsearch.search.SearchHit;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
recover();
- assertThat(logTester.logs(LoggerLevel.ERROR))
+ assertThat(logTester.logs(Level.ERROR))
.filteredOn(l -> l.contains("Unsupported es_queue.doc_id_type for issues. Manual fix is required: "))
.hasSize(1);
assertThatEsQueueTableHasSize(1);
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.slf4j.event.Level;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
@Test
@UseDataProvider("twoDifferentCategoriesButOTHERS")
public void log_debug_if_hotspot_rule_maps_to_multiple_SQCategories(SQCategory sqCategory1, SQCategory sqCategory2) {
+ logTester.setLevel(Level.DEBUG);
Set<String> standards = Stream.of(sqCategory1, sqCategory2)
.flatMap(t -> CWES_BY_SQ_CATEGORY.get(t).stream().map(e -> "cwe:" + e))
.collect(toSet());
.setSecurityStandards(standards));
underTest.commitAndIndex(dbTester.getSession(), rule.getUuid());
- assertThat(logTester.getLogs()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.DEBUG).get(0))
- .isEqualTo(format(
+ assertThat(logTester.logs(Level.DEBUG))
+ .contains(format(
"Rule %s with CWEs '%s' maps to multiple SQ Security Categories: %s",
rule.getKey(),
String.join(", ", securityStandards.getCwe()),
import java.io.IOException;
import java.util.List;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.ce.posttask.PostProjectAnalysisTask;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDbTester;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.sonar.api.utils.log.LoggerLevel.DEBUG;
+import static org.slf4j.event.Level.DEBUG;
import static org.sonar.db.DbTester.create;
import static org.sonar.db.webhook.WebhookTesting.newGlobalWebhook;
import static org.sonar.db.webhook.WebhookTesting.newWebhook;
private final PostProjectAnalysisTask.LogStatistics taskStatistics = mock(PostProjectAnalysisTask.LogStatistics.class);
private final WebHooksImpl underTest = new WebHooksImpl(caller, deliveryStorage, synchronousAsyncExecution, dbClient);
+ @Before
+ public void before() {
+ logTester.setLevel(Level.DEBUG);
+ }
+
@Test
public void isEnabled_returns_false_if_no_webhooks() {
ProjectDto projectDto = componentDbTester.insertPrivateProjectDto();
underTest.sendProjectAnalysisUpdate(new WebHooks.Analysis(componentDto.uuid(), "1", "#1"), () -> mock);
assertThat(caller.countSent()).isZero();
- assertThat(logTester.logs(DEBUG)).isEmpty();
+ assertNoWebhookLogs();
verifyNoInteractions(deliveryStorage);
}
underTest.sendProjectAnalysisUpdate(new WebHooks.Analysis(componentDto.uuid(), "1", "#1"), () -> mock, taskStatistics);
assertThat(caller.countSent()).isZero();
- assertThat(logTester.logs(DEBUG)).isEmpty();
+ assertNoWebhookLogs();
verifyNoInteractions(deliveryStorage);
verifyLogStatistics(0, 0);
}
verifyLogStatistics(2, 0);
}
+ private void assertNoWebhookLogs() {
+ assertThat(logTester.logs(DEBUG))
+ .noneMatch(s -> s.contains("Sent webhook"))
+ .noneMatch(s -> s.contains("Failed to send webhook"));
+ }
+
@Test
public void send_project_webhooks() {
ProjectDto projectDto = componentDbTester.insertPrivateProjectDto();
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
});
assertThat(logTester.logs()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.ERROR)).containsOnly("Asynchronous task failed");
+ assertThat(logTester.logs(Level.ERROR)).containsOnly("Asynchronous task failed");
}
@Test
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
assertThat(node.getHost().getAddress().getHostName()).isEqualTo(localhostHostname);
assertThat(node.getHost().getPort()).isEqualTo(9000);
- assertThat(logTester.logs(LoggerLevel.INFO)).has(new Condition<>(s -> s.contains("Connected to local Elasticsearch: [http://" + localhostHostname + ":9000]"), ""));
+ assertThat(logTester.logs(Level.INFO)).has(new Condition<>(s -> s.contains("Connected to local Elasticsearch: [http://" + localhostHostname + ":9000]"), ""));
}
@Test
assertThat(node.getHost().getAddress().getHostName()).isEqualTo(localhostHostname);
assertThat(node.getHost().getPort()).isEqualTo(8081);
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.has(new Condition<>(s -> s.contains("Connected to remote Elasticsearch: [http://" + localhostHostname + ":8080, http://" + localhostHostname + ":8081]"), ""));
}
assertThat(node.getHost().getAddress().getHostName()).isEqualTo(localhostHostname);
assertThat(node.getHost().getPort()).isEqualTo(8081);
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.has(new Condition<>(s -> s.contains("Connected to remote Elasticsearch: [http://" + localhostHostname + ":9001, http://" + localhostHostname + ":8081]"), ""));
}
}
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.sonar.api.config.internal.MapSettings;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.Database;
import org.sonar.process.logging.LogLevelConfig;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.config.Configuration;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+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;
assertThat(underTest.isCompatible(pluginWithoutBase)).isFalse();
assertThat(underTest.isCompatible(pluginWithBase)).isTrue();
- assertThat(logTester.logs(LoggerLevel.WARN))
+ 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");
}
assertThat(underTest.isCompatible(pluginWithoutRequired)).isFalse();
assertThat(underTest.isCompatible(pluginWithRequired)).isTrue();
- assertThat(logTester.logs(LoggerLevel.WARN))
+ 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");
}
assertThat(underTest.isCompatible(pluginWithoutRequired)).isFalse();
assertThat(underTest.isCompatible(pluginWithRequired)).isTrue();
- assertThat(logTester.logs(LoggerLevel.WARN))
+ 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");
}
testImplementation 'com.tngtech.java:junit-dataprovider'
testImplementation 'javax.servlet:javax.servlet-api'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation testFixtures(project(':server:sonar-server-common'))
testImplementation project(':sonar-testing-harness')
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.core.extension.PluginRiskConsent;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
underTest.start();
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Plugin(s) detected. Plugins are not provided by SonarSource"
+ assertThat(logTester.logs(Level.WARN)).contains("Plugin(s) detected. Plugins are not provided by SonarSource"
+ " and are therefore installed at your own risk. A SonarQube administrator needs to acknowledge this risk once logged in.");
assertThat(dbClient.propertiesDao().selectGlobalProperty(PLUGINS_RISK_CONSENT))
.extracting(PropertyDto::getValue)
import org.junit.rules.TemporaryFolder;
import org.sonar.api.SonarRuntime;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.platform.PluginInfo;
import org.sonar.server.platform.ServerFileSystem;
import org.sonar.updatecenter.common.PluginManifest;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.Plugin;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.plugin.PluginType;
import org.sonar.server.platform.ServerFileSystem;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
-import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.Plugin;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.platform.ExplodedPlugin;
import org.sonar.core.platform.PluginClassLoader;
import org.sonar.core.platform.PluginJarExploder;
import java.util.stream.Stream;
import org.apache.commons.lang.RandomStringUtils;
import org.assertj.core.groups.Tuple;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
+import org.slf4j.event.Level;
import org.sonar.api.issue.Issue;
import org.sonar.api.rules.RuleType;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.component.BranchDto;
import org.sonar.server.qualitygate.changeevent.QGChangeEventListener.ChangedIssue;
private final QGChangeEventListenersImpl underTest = new QGChangeEventListenersImpl(new LinkedHashSet<>(List.of(listener1, listener2, listener3)));
+ @Before
+ public void before() {
+ logTester.setLevel(Level.TRACE);
+ }
+
@Test
public void broadcastOnIssueChange_has_no_effect_when_issues_are_empty() {
underTest.broadcastOnIssueChange(emptyList(), singletonList(component1QGChangeEvent), false);
inOrder.verify(listener3).onIssueChanges(same(component1QGChangeEvent), same(changedIssues));
inOrder.verifyNoMoreInteractions();
assertThat(logTester.logs()).hasSize(4);
- assertThat(logTester.logs(LoggerLevel.WARN)).hasSize(1);
+ assertThat(logTester.logs(Level.WARN)).hasSize(1);
}
@Test
inOrder.verify(listener2).onIssueChanges(same(component1QGChangeEvent), same(changedIssues));
inOrder.verifyNoMoreInteractions();
assertThat(logTester.logs()).hasSize(3);
- assertThat(logTester.logs(LoggerLevel.WARN)).hasSize(1);
+ assertThat(logTester.logs(Level.WARN)).hasSize(1);
}
@Test
underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false);
assertThat(logTester.logs()).hasSize(3);
- List<String> traceLogs = logTester.logs(LoggerLevel.TRACE);
+ List<String> traceLogs = logTester.logs(Level.TRACE);
assertThat(traceLogs).hasSize(3)
.containsOnly(
"calling onChange() on listener " + listener1.getClass().getName() + " for events " + component1QGChangeEvent + "...",
testImplementation 'org.apache.logging.log4j:log4j-core'
testImplementation 'org.assertj:assertj-guava'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation testFixtures(project(':server:sonar-server-common'))
testImplementation project(':sonar-testing-harness')
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.notifications.Notification;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbTester;
import org.sonar.db.user.UserDto;
import org.sonar.server.notification.NotificationManager;
underTest.runAtStart();
assertThat(db.users().selectUserByLogin(admin.getLogin()).get().isResetPassword()).isTrue();
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Default Administrator credentials are still being used. Make sure to change the password or deactivate the account.");
+ assertThat(logTester.logs(Level.WARN)).contains("Default Administrator credentials are still being used. Make sure to change the password or deactivate the account.");
assertThat(db.getDbClient().internalPropertiesDao().selectByKey(db.getSession(), DEFAULT_ADMIN_CREDENTIAL_USAGE_EMAIL)).contains("true");
verify(notificationManager).scheduleForSending(any(Notification.class));
}
import org.mockito.Mockito;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.internal.Settings;
-import org.sonar.api.utils.log.LogAndArguments;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogAndArguments;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.DbTester;
import org.sonar.db.alm.setting.AlmSettingDto;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
+import org.slf4j.event.Level;
import org.sonar.api.server.authentication.BaseIdentityProvider;
import org.sonar.api.server.authentication.Display;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.api.server.authentication.UnauthorizedException;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
underTest.doFilter(request, response, chain);
verify(response).sendRedirect("/sessions/unauthorized");
- assertThat(logTester.logs(LoggerLevel.WARN)).containsExactlyInAnyOrder("Fail to initialize authentication with provider 'failing'");
+ assertThat(logTester.logs(Level.WARN)).containsExactlyInAnyOrder("Fail to initialize authentication with provider 'failing'");
verifyDeleteAuthCookie();
}
}
private void assertOAuth2InitCalled() {
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
assertThat(oAuth2IdentityProvider.isInitCalled()).isTrue();
}
private void assertBasicInitCalled() {
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
assertThat(baseIdentityProvider.isInitCalled()).isTrue();
}
private void assertError(String expectedError) throws Exception {
- assertThat(logTester.logs(LoggerLevel.WARN)).contains(expectedError);
+ assertThat(logTester.logs(Level.WARN)).contains(expectedError);
verify(response).sendRedirect("/sessions/unauthorized");
assertThat(oAuth2IdentityProvider.isInitCalled()).isFalse();
}
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.platform.Server;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
underTest.start();
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly("For security reasons, OAuth authentication should use HTTPS. You should set the property 'Administration > Configuration > Server base URL' to a HTTPS URL.");
+ assertThat(logTester.logs(Level.WARN)).containsOnly("For security reasons, OAuth authentication should use HTTPS. You should set the property 'Administration > Configuration > Server base URL' to a HTTPS URL.");
underTest.stop();
}
underTest.start();
- assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logTester.logs(Level.WARN)).isEmpty();
underTest.stop();
}
underTest.start();
- assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logTester.logs(Level.WARN)).isEmpty();
underTest.stop();
}
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
+import org.slf4j.event.Level;
import org.sonar.api.server.authentication.OAuth2IdentityProvider;
import org.sonar.api.server.authentication.UnauthorizedException;
import org.sonar.api.server.authentication.UserIdentity;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.server.authentication.event.AuthenticationEvent;
import org.sonar.server.authentication.event.AuthenticationException;
import org.sonar.server.user.ThreadLocalUserSession;
underTest.doFilter(request, response, chain);
verify(response).sendRedirect("/sessions/unauthorized");
- assertThat(logTester.logs(LoggerLevel.WARN)).containsExactlyInAnyOrder("Fail to callback authentication with 'failing'");
+ assertThat(logTester.logs(Level.WARN)).containsExactlyInAnyOrder("Fail to callback authentication with 'failing'");
verify(oAuthRedirection).delete(request, response);
}
}
private void assertCallbackCalled(FakeOAuth2IdentityProvider oAuth2IdentityProvider) {
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
assertThat(oAuth2IdentityProvider.isCallbackCalled()).isTrue();
}
private void assertError(String expectedError) throws Exception {
- assertThat(logTester.logs(LoggerLevel.WARN)).contains(expectedError);
+ assertThat(logTester.logs(Level.WARN)).contains(expectedError);
verify(response).sendRedirect("/sessions/unauthorized");
assertThat(oAuth2IdentityProvider.isInitCalled()).isFalse();
}
import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
import org.sonar.api.server.authentication.IdentityProvider;
import org.sonar.api.server.authentication.UserIdentity;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbTester;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.user.GroupDto;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import static java.util.Arrays.asList;
private void verifyLog(String expected) {
assertThat(logTester.logs()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.DEBUG))
+ assertThat(logTester.logs(Level.DEBUG))
.containsOnly(expected);
}
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
-import org.sonar.api.utils.log.LogAndArguments;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogAndArguments;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.DbTester;
import org.sonar.db.user.SamlMessageIdDto;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.ws.SimpleGetRequest;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
configurePasscode("foo");
underTest.start();
- assertThat(logTester.logs(LoggerLevel.INFO)).contains("System authentication by passcode is enabled");
+ assertThat(logTester.logs(Level.INFO)).contains("System authentication by passcode is enabled");
}
@Test
public void startup_logs_show_that_feature_is_disabled() {
underTest.start();
- assertThat(logTester.logs(LoggerLevel.INFO)).contains("System authentication by passcode is disabled");
+ assertThat(logTester.logs(Level.INFO)).contains("System authentication by passcode is disabled");
}
@Test
configurePasscode("");
underTest.start();
- assertThat(logTester.logs(LoggerLevel.INFO)).contains("System authentication by passcode is disabled");
+ assertThat(logTester.logs(Level.INFO)).contains("System authentication by passcode is disabled");
}
@DataProvider
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogAndArguments;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogAndArguments;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.server.util.GlobalLockManager;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
-import org.sonar.api.utils.log.LogAndArguments;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogAndArguments;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.DbClient;
import org.sonar.db.user.UserDao;
@Test
public void no_notification_when_email_setting_is_not_set() {
+ logTester.setLevel(Level.DEBUG);
when(emailComposer.areEmailSettingsSet()).thenReturn(false);
underTest.sendNotifications();
- assertThat(logTester.getLogs(LoggerLevel.DEBUG))
+ assertThat(logTester.getLogs(Level.DEBUG))
.extracting(LogAndArguments::getFormattedMsg)
.containsExactly("Emails for token expiration notification have not been sent because email settings are not configured.");
}
testImplementation 'org.eclipse.jetty:jetty-servlet'
testImplementation 'org.hamcrest:hamcrest-all'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation 'org.subethamail:subethasmtp'
testImplementation testFixtures(project(':server:sonar-server-common'))
testImplementation testFixtures(project(':server:sonar-webserver-auth'))
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.queue.CeQueue;
import org.sonar.ce.queue.CeTaskSubmit;
import org.sonar.core.util.SequenceUuidFactory;
assertThat(branch.get().isNeedIssueSync()).isTrue();
verify(ceQueue, times(1)).prepareSubmit();
verify(ceQueue, times(1)).massSubmit(anyCollection());
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.contains("1 branch found in need of issue sync.");
}
assertThat(branch.get().isNeedIssueSync()).isTrue();
verify(ceQueue, times(2)).prepareSubmit();
verify(ceQueue, times(1)).massSubmit(anyCollection());
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.contains("2 branch(es) found in need of issue sync for project.");
}
public void triggerOnIndexCreation_no_branch() {
underTest.triggerOnIndexCreation();
- assertThat(logTester.logs(LoggerLevel.INFO)).contains("0 branch found in need of issue sync.");
+ assertThat(logTester.logs(Level.INFO)).contains("0 branch found in need of issue sync.");
}
@Test
public void triggerForProject_no_branch() {
underTest.triggerForProject("some-random-uuid");
- assertThat(logTester.logs(LoggerLevel.INFO)).contains("0 branch(es) found in need of issue sync for project.");
+ assertThat(logTester.logs(Level.INFO)).contains("0 branch(es) found in need of issue sync for project.");
}
@Test
assertThat(dbClient.ceActivityDao().selectByTaskType(dbTester.getSession(), REPORT)).hasSize(1);
assertThat(dbClient.ceTaskCharacteristicsDao().selectByTaskUuids(dbTester.getSession(), new HashSet<>(List.of("uuid_2")))).isEmpty();
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.contains(
"1 pending indexation task found to be deleted...",
"1 completed indexation task found to be deleted...",
.extracting(CeActivityDto::getMainComponentUuid)
.containsExactly(anotherProjectDto.getUuid());
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.contains(
"2 pending indexation task found to be deleted...",
"2 completed indexation task found to be deleted...",
.extracting(p -> p.getComponent().get().getUuid())
.containsExactly("branch_uuid2", "branch_uuid1");
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.contains("2 projects found in need of issue sync.");
}
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.config.internal.MapSettings;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.server.platform.db.migration.version.DatabaseVersion;
import static org.assertj.core.api.Assertions.assertThat;
new DatabaseServerCompatibility(version).start();
assertThat(logTester.logs()).hasSize(4);
- assertThat(logTester.logs(LoggerLevel.WARN)).contains(
+ assertThat(logTester.logs(Level.WARN)).contains(
"The database must be manually upgraded. Please backup the database and browse /setup. "
+ "For more information: https://docs.sonarqube.org/latest/setup/upgrading",
"################################################################################",
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
}
private void assertProjectLevelAnyonePermissionWarningNotInLogs() {
- boolean noneMatch = logTester.logs(LoggerLevel.WARN).stream()
+ boolean noneMatch = logTester.logs(Level.WARN).stream()
.noneMatch(s -> s.startsWith("Authentication is not enforced, and project permissions assigned to the 'Anyone' group expose"));
assertThat(noneMatch).isTrue();
}
String expected = String.format("Authentication is not enforced, and project permissions assigned to the 'Anyone' group expose %d " +
"public project(s) to security risks, including: %s. Unauthenticated visitors have permissions on these project(s).",
expectedProjectCount, String.join(", ", expectedListedProjects));
- assertThat(logTester.logs(LoggerLevel.WARN)).contains(expected);
+ assertThat(logTester.logs(Level.WARN)).contains(expected);
}
private void assertGlobalLevelAnyonePermissionWarningNotInLogs() {
- boolean noneMatch = !logTester.logs(LoggerLevel.WARN).contains(
+ boolean noneMatch = !logTester.logs(Level.WARN).contains(
"Authentication is not enforced, and permissions assigned to the 'Anyone' group globally expose the " +
"instance to security risks. Unauthenticated visitors may unintentionally have permissions on projects.");
assertThat(noneMatch).isTrue();
private void assertGlobalLevelAnyonePermissionWarningInLogs() {
String expected = "Authentication is not enforced, and permissions assigned to the 'Anyone' group globally " +
"expose the instance to security risks. Unauthenticated visitors may unintentionally have permissions on projects.";
- assertThat(logTester.logs(LoggerLevel.WARN)).contains(expected);
+ assertThat(logTester.logs(Level.WARN)).contains(expected);
}
}
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.measures.CoreMetrics;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.DbTester;
settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "1" + "." + CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_SIZE_METRIC_KEY, CoreMetrics.COMPLEXITY_KEY);
underTest.start();
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.contains("The development cost used for calculating the technical debt is currently configured with 2 language specific parameters [Key: languageSpecificParameters]. " +
"Please be aware that this functionality is deprecated, and will be removed in a future version.");
}
@Test
public void log_does_not_show_when_language_specific_params_used() {
underTest.start();
- boolean noneMatch = logTester.logs(LoggerLevel.WARN).stream()
+ boolean noneMatch = logTester.logs(Level.WARN).stream()
.noneMatch(s -> s.startsWith("The development cost used for calculating the technical debt is currently configured with"));
assertThat(noneMatch).isTrue();
}
import org.junit.rules.Timeout;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.process.NetworkUtilsImpl;
import static junit.framework.Assert.fail;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbClient;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
underTest.start();
verifyNoInteractions(migrationEngine);
- assertThat(logTester.logs(LoggerLevel.INFO)).isEmpty();
+ assertThat(logTester.logs(Level.INFO)).isEmpty();
}
@Test
underTest.start();
verify(migrationEngine).execute();
- assertThat(logTester.logs(LoggerLevel.INFO)).contains("Automatically perform DB migration, as automatic database upgrade is enabled");
+ assertThat(logTester.logs(Level.INFO)).contains("Automatically perform DB migration, as automatic database upgrade is enabled");
}
@Test
underTest.start();
verifyNoInteractions(migrationEngine);
- assertThat(logTester.logs(LoggerLevel.INFO)).isEmpty();
+ assertThat(logTester.logs(Level.INFO)).isEmpty();
}
@Test
private void verifyInfoLog() {
assertThat(logTester.logs()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.INFO)).containsExactly("Automatically perform DB migration on fresh install");
+ assertThat(logTester.logs(Level.INFO)).containsExactly("Automatically perform DB migration on fresh install");
}
}
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import static java.util.stream.Collectors.joining;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void throwable_in_doFilter_is_logged_in_debug_if_response_is_already_committed() throws Exception {
+ logTester.setLevel(Level.DEBUG);
doThrow(new RuntimeException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
HttpServletResponse response = mockHttpResponse(true);
underTest.doFilter(request("POST", "/context/service/call", "param=value"), response, chain);
- List<String> debugLogs = logTester.logs(LoggerLevel.DEBUG);
+ List<String> debugLogs = logTester.logs(Level.DEBUG);
assertThat(debugLogs.size()).isOne();
assertThat(debugLogs.get(0)).contains("Processing of request", "failed");
}
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
underTest.notifyStart();
assertProjectsInWarningValue(2L);
- assertThat(logger.logs(LoggerLevel.INFO)).contains("Counting number of projects in warning is enabled.");
+ assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled.");
}
@Test
insertProjectInWarning(qualityGateStatus);
assertProjectsInWarningValue(3L);
- assertThat(logger.logs(LoggerLevel.INFO)).contains("Counting number of projects in warning is enabled.");
+ assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled.");
}
@Test
projectMeasuresIndexer.indexOnAnalysis(project.uuid());
assertProjectsInWarningValue(0L);
- assertThat(logger.logs(LoggerLevel.INFO))
+ assertThat(logger.logs(Level.INFO))
.contains(
"Counting number of projects in warning is enabled.",
"Counting number of projects in warning will be disabled as there are no more projects in warning.");
underTest.notifyStart();
assertProjectsInWarningValue(2L);
- assertThat(logger.logs(LoggerLevel.INFO)).contains("Counting number of projects in warning is enabled.");
+ assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled.");
}
@Test
underTest.notifyStart();
assertProjectsInWarningValue(0L);
- assertThat(logger.logs(LoggerLevel.INFO)).contains("Counting number of projects in warning is enabled.");
+ assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is enabled.");
}
@Test
underTest.notifyStart();
assertProjectsInWarningValue(0L);
- assertThat(logger.logs(LoggerLevel.INFO)).contains("Counting number of projects in warning is not started as there are no projects in this situation.");
+ assertThat(logger.logs(Level.INFO)).contains("Counting number of projects in warning is not started as there are no projects in this situation.");
}
@Test
import org.sonar.api.server.rule.RuleDescriptionSection;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.api.utils.DateUtils;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbClient;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.platform.Server;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
LogServerId underTest = new LogServerId(server);
underTest.start();
- assertThat(logTester.logs(LoggerLevel.INFO)).contains("Server ID: foo");
+ assertThat(logTester.logs(Level.INFO)).contains("Server ID: foo");
// do not fail
underTest.stop();
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.security.DefaultGroups;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbTester;
verifyDefaultTemplateForProject(defaultTemplate.getUuid());
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
}
@Test
verifyDefaultTemplateForProject(defaultTemplate.getUuid());
- assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Cannot setup default permission for group: sonar-administrators");
+ assertThat(logTester.logs(Level.ERROR)).contains("Cannot setup default permission for group: sonar-administrators");
}
@Test
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.impl.utils.TestSystem2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.server.property.InternalProperties;
verify(client, after(2_000).never()).upload(anyString());
verify(client, timeout(2_000).times(1)).optOut(anyString());
- assertThat(logger.logs(LoggerLevel.INFO)).contains("Sharing of SonarQube statistics is disabled.");
+ assertThat(logger.logs(Level.INFO)).contains("Sharing of SonarQube statistics is disabled.");
}
@Test
testImplementation 'com.google.code.findbugs:jsr305'
testImplementation 'com.tngtech.java:junit-dataprovider'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation testFixtures(project(':server:sonar-webserver-auth'))
testImplementation project(':sonar-testing-harness')
import org.elasticsearch.common.settings.Settings;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.config.internal.MapSettings;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.server.es.IndexType.IndexMainType;
import org.sonar.server.es.metadata.MetadataIndex;
import org.sonar.server.es.metadata.MetadataIndexDefinition;
run(new FakeIndexDefinition());
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.doesNotContain(LOG_DB_VENDOR_CHANGED)
.doesNotContain(LOG_DB_SCHEMA_CHANGED)
.contains("Create mapping fakes")
private void testDeleteOnDbChange(String expectedLog, Consumer<TestEsDbCompatibility> afterFirstStart) {
run(new FakeIndexDefinition());
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.doesNotContain(expectedLog)
.contains("Create mapping fakes")
.contains("Create mapping metadatas");
logTester.clear();
run(new FakeIndexDefinition());
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.contains(expectedLog)
.contains("Create mapping fakes")
// keep existing metadata
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import org.junit.After;
+import org.junit.Before;
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.slf4j.event.Level;
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.MessageException;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
-import static org.sonar.api.utils.log.LoggerLevel.ERROR;
-import static org.sonar.api.utils.log.LoggerLevel.INFO;
-import static org.sonar.api.utils.log.LoggerLevel.TRACE;
+import static org.slf4j.event.Level.ERROR;
+import static org.slf4j.event.Level.INFO;
+import static org.slf4j.event.Level.TRACE;
public class RecoveryIndexerTest {
private RecoveryIndexer underTest;
+ @Before
+ public void before() {
+ logTester.setLevel(TRACE);
+ }
+
@After
public void tearDown() {
if (underTest != null) {
underTest.start();
underTest.stop();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains(
+ assertThat(logTester.logs(Level.DEBUG)).contains(
"Elasticsearch recovery - sonar.search.recovery.delayInMs=300000",
"Elasticsearch recovery - sonar.search.recovery.minAgeInMs=300000");
}
system2.setNow(system2.now() + 100_000_000L);
}
- private void assertThatLogsContain(LoggerLevel loggerLevel, String message) {
+ private void assertThatLogsContain(Level loggerLevel, String message) {
assertThat(logTester.logs(loggerLevel)).filteredOn(m -> m.contains(message)).isNotEmpty();
}
- private void assertThatLogsDoNotContain(LoggerLevel loggerLevel, String message) {
+ private void assertThatLogsDoNotContain(Level loggerLevel, String message) {
assertThat(logTester.logs(loggerLevel)).filteredOn(m -> m.contains(message)).isEmpty();
}
- private void assertThatNoLogsFromRecovery(LoggerLevel loggerLevel) {
+ private void assertThatNoLogsFromRecovery(Level loggerLevel) {
assertThat(logTester.logs(loggerLevel)).filteredOn(m -> m.contains("Elasticsearch recovery - ")).isEmpty();
}
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.rule.RuleKey;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
testImplementation 'junit:junit'
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
}
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
+import org.slf4j.event.Level;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.internal.apachecommons.io.IOUtils;
import org.sonar.api.internal.apachecommons.lang.StringUtils;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.response.NodeStatsResponse;
// elasticsearch health status is not mocked in this test, so this part raise an exception
assertThat(logTester.logs()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.ERROR)).containsOnly("Failed to query ES status");
+ assertThat(logTester.logs(Level.ERROR)).containsOnly("Failed to query ES status");
}
@Test
verifyNoMoreInteractions(serverMonitoringMetrics);
assertThat(logTester.logs()).hasSize(2);
- assertThat(logTester.logs(LoggerLevel.ERROR)).containsOnly("Failed to query ES status");
+ assertThat(logTester.logs(Level.ERROR)).containsOnly("Failed to query ES status");
}
@Test
testImplementation 'com.squareup.okhttp3:mockwebserver'
testImplementation 'javax.servlet:javax.servlet-api'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation 'org.springframework:spring-test:5.3.23'
testImplementation testFixtures(project(':server:sonar-server-common'))
testImplementation testFixtures(project(':server:sonar-webserver-auth'))
import org.junit.runner.RunWith;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
-import org.sonar.api.utils.log.LogAndArguments;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogAndArguments;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.api.web.UserRole;
import org.sonar.core.config.CorePropertyDefinitions;
import java.util.Random;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
verifyCorrectBuiltInQualityGate();
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate [Sonar way] has been created")).isTrue();
+ logTester.logs(Level.INFO)).contains("Built-in quality gate [Sonar way] has been created");
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate's conditions of [Sonar way] has been updated")).isTrue();
+ logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated");
}
@Test
assertThat(db.countRowsOfTable("quality_gates")).isOne();
verifyCorrectBuiltInQualityGate();
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate's conditions of [Sonar way] has been updated")).isTrue();
+ logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated");
}
@Test
assertThat(db.countRowsOfTable("quality_gates")).isOne();
verifyCorrectBuiltInQualityGate();
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate's conditions of [Sonar way] has been updated")).isTrue();
+ logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated");
}
@Test
assertThat(db.countRowsOfTable("quality_gates")).isOne();
verifyCorrectBuiltInQualityGate();
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate's conditions of [Sonar way] has been updated")).isTrue();
+ logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated");
}
@Test
assertThat(db.countRowsOfTable("quality_gates")).isOne();
verifyCorrectBuiltInQualityGate();
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Quality gate [Sonar way] has been set as built-in")).isTrue();
+ logTester.logs(Level.INFO)).contains("Quality gate [Sonar way] has been set as built-in");
}
@Test
verifyCorrectBuiltInQualityGate();
// Log must not be present
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Quality gate [Sonar way] has been set as built-in")).isFalse();
+ logTester.logs(Level.INFO)).doesNotContain("Quality gate [Sonar way] has been set as built-in");
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate [Sonar way] has been created")).isFalse();
+ logTester.logs(Level.INFO)).doesNotContain("Built-in quality gate [Sonar way] has been created");
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate's conditions of [Sonar way] has been updated")).isFalse();
+ logTester.logs(Level.INFO)).doesNotContain("Built-in quality gate's conditions of [Sonar way] has been updated");
}
@Test
.extracting(column -> column.get("name"))
.containsExactly(BUILT_IN_NAME);
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate [Sonar way] has been created")).isTrue();
+ logTester.logs(Level.INFO)).contains("Built-in quality gate [Sonar way] has been created");
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate's conditions of [Sonar way] has been updated")).isTrue();
+ logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated");
}
@Test
// No exception thrown
verifyCorrectBuiltInQualityGate();
assertThat(
- logTester.logs(LoggerLevel.INFO).contains("Built-in quality gate's conditions of [Sonar way] has been updated")).isTrue();
+ logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated");
}
private void insertMetrics() {
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.resources.Language;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
assertThat(insert.callLogs).containsExactly(builtInQProfile);
assertThat(update.callLogs).isEmpty();
- assertThat(logTester.logs(LoggerLevel.INFO)).contains("Register profile foo/Sonar way");
+ assertThat(logTester.logs(Level.INFO)).contains("Register profile foo/Sonar way");
}
@Test
underTest.start();
assertThat(selectPersistedName(outdatedProfile)).isEqualTo("Sonar way (outdated copy)");
- assertThat(logTester.logs(LoggerLevel.INFO)).contains("Rename Quality profiles [foo/Sonar way] to [Sonar way (outdated copy)]");
+ assertThat(logTester.logs(Level.INFO)).contains("Rename Quality profiles [foo/Sonar way] to [Sonar way (outdated copy)]");
}
@Test
assertThat(insert.callLogs).isEmpty();
assertThat(update.callLogs).containsExactly(builtIn);
- assertThat(logTester.logs(LoggerLevel.INFO)).contains("Update profile foo/Sonar way");
+ assertThat(logTester.logs(Level.INFO)).contains("Update profile foo/Sonar way");
}
@Test
underTest.start();
- assertThat(logTester.logs(LoggerLevel.INFO)).containsAnyOf(
+ assertThat(logTester.logs(Level.INFO)).containsAnyOf(
format("Default built-in quality profile for language [foo] has been updated from [%s] to [%s] since previous default does not have active rules.",
qProfileWithoutRule.getName(), qProfileWithOneRule.getName()));
var expectedSuffix = " (outdated copy since " + formatter.format(Instant.ofEpochMilli(system2.now())) + ")";
- assertThat(logTester.logs(LoggerLevel.INFO)).contains(
+ assertThat(logTester.logs(Level.INFO)).contains(
format("Quality profile [%s] for language [%s] is no longer built-in and has been renamed to [%s] "
+ "since it does not have any active rules.",
qProfileWithoutRule.getName(), qProfileWithoutRule.getLanguage(), qProfileWithoutRule.getName() + expectedSuffix),
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.BuiltInActiveRule;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.NewBuiltInQualityProfile;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.server.app.ProcessCommandWrapper;
import org.sonar.server.app.RestartFlagHolder;
import org.sonar.server.exceptions.ForbiddenException;
actionTester.newRequest().execute();
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.contains("SonarQube restart requested by " + login);
}
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.web.page.Page;
import org.sonar.api.web.page.Page.Qualifier;
import org.sonar.api.web.page.PageDefinition;
testImplementation 'javax.servlet:javax.servlet-api'
testImplementation 'org.apache.tomcat.embed:tomcat-embed-core'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testFixturesApi project(':sonar-testing-harness')
import java.util.function.Consumer;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.connector.ClientAbortException;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
+import org.slf4j.event.Level;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.RequestHandler;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.server.exceptions.BadConfigurationException;
import org.sonar.server.exceptions.BadRequestException;
import org.sonarqube.ws.MediaTypes;
@Rule
public LogTester logTester = new LogTester();
+ @Before
+ public void setup() {
+ logTester.setLevel(Level.DEBUG);
+ }
+
@Test
public void load_ws_definitions_at_startup() {
WebServiceEngine underTest = new WebServiceEngine(new WebService[]{
assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[{\"msg\":\"An error has occurred. Please contact your administrator\"}]}");
assertThat(response.status()).isEqualTo(500);
assertThat(response.mediaType()).isEqualTo(MediaTypes.JSON);
- assertThat(logTester.logs(LoggerLevel.ERROR)).filteredOn(l -> l.contains("Fail to process request api/foo")).isNotEmpty();
+ assertThat(logTester.logs(Level.ERROR)).filteredOn(l -> l.contains("Fail to process request api/foo")).isNotEmpty();
}
@Test
"{\"errors\":[{\"msg\":\"Bad request !\"}]}");
assertThat(response.status()).isEqualTo(400);
assertThat(response.mediaType()).isEqualTo(MediaTypes.JSON);
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
}
@Test
+ "]}");
assertThat(response.status()).isEqualTo(400);
assertThat(response.mediaType()).isEqualTo(MediaTypes.JSON);
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
}
@Test
"{\"scope\":\"PROJECT\",\"errors\":[{\"msg\":\"Bad request !\"}]}");
assertThat(response.status()).isEqualTo(400);
assertThat(response.mediaType()).isEqualTo(MediaTypes.JSON);
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
}
@Test
// response is committed (status is already sent), so status can't be changed
verify(response.stream(), never()).setStatus(anyInt());
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("Request api/foo has been aborted by client");
+ assertThat(logTester.logs(Level.DEBUG)).contains("Request api/foo has been aborted by client");
}
@Test
run(request, response, newClientAbortWs());
verify(response.stream()).setStatus(299);
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("Request api/foo has been aborted by client");
+ assertThat(logTester.logs(Level.DEBUG)).contains("Request api/foo has been aborted by client");
}
@Test
// response is committed (status is already sent), so status can't be changed
verify(response.stream(), never()).setStatus(anyInt());
- assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Fail to process request api/foo");
+ assertThat(logTester.logs(Level.ERROR)).contains("Fail to process request api/foo");
}
@Test
run(request, response, newFailWs());
verify(response.stream()).setStatus(500);
- assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Fail to process request api/foo");
+ assertThat(logTester.logs(Level.ERROR)).contains("Fail to process request api/foo");
}
@Test
underTest.execute(request, response);
- assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Fail to process request /api/ping");
+ assertThat(logTester.logs(Level.ERROR)).contains("Fail to process request /api/ping");
}
private static WebService newWs(String path, Consumer<WebService.NewAction> consumer) {
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.server.exceptions.BadRequestException;
import org.sonarqube.ws.Issues;
import org.sonarqube.ws.MediaTypes;
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.eclipse.jetty:jetty-server'
testImplementation 'org.eclipse.jetty:jetty-servlet'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation testFixtures(project(':server:sonar-server-common'))
testImplementation testFixtures(project(':server:sonar-webserver-auth'))
testImplementation testFixtures(project(':server:sonar-webserver-es'))
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.web.ServletFilter;
import org.sonar.api.web.ServletFilter.UrlPattern;
master.init(config, singletonList(filter));
- assertThat(logTester.logs(LoggerLevel.INFO)).containsOnly("Initializing servlet filter PatternFilter [pattern=UrlPattern{inclusions=[/api/issues], exclusions=[/batch/projects]}]");
+ assertThat(logTester.logs(Level.INFO)).containsOnly("Initializing servlet filter PatternFilter [pattern=UrlPattern{inclusions=[/api/issues], exclusions=[/batch/projects]}]");
}
private static ServletFilter createMockFilter() {
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogAndArguments;
+import org.sonar.api.testfixtures.log.LogTester;
+import org.sonar.core.extension.CoreExtensionRepository;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
-import org.sonar.core.extension.CoreExtensionRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@Before
public void setUp() throws Exception {
+ logTester.setLevel(Level.TRACE);
jetty = new Server(0);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
}
}
- private Response call(String path) throws Exception {
+ private Response callAndStop(String path) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(jetty.getURI().resolve(path).toString())
.build();
- return client.newCall(request).execute();
+ Response response = client.newCall(request).execute();
+ jetty.stop();
+ return response;
}
@Test
system.pluginStream = IOUtils.toInputStream("bar");
when(pluginRepository.hasPlugin("myplugin")).thenReturn(true);
- Response response = call("/static/myplugin/foo.txt");
+ Response response = callAndStop("/static/myplugin/foo.txt");
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body().string()).isEqualTo("bar");
system.pluginStream = IOUtils.toInputStream("bar");
when(pluginRepository.hasPlugin("myplugin")).thenReturn(true);
- Response response = call("/static/myplugin/foo/bar.txt");
+ Response response = callAndStop("/static/myplugin/foo/bar.txt");
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body().string()).isEqualTo("bar");
system.coreExtensionStream = IOUtils.toInputStream("bar");
when(coreExtensionRepository.isInstalled("coreext")).thenReturn(true);
- Response response = call("/static/coreext/foo/bar.txt");
+ Response response = callAndStop("/static/coreext/foo/bar.txt");
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body().string()).isEqualTo("bar");
system.coreExtensionStream = IOUtils.toInputStream("bar of core extension");
when(coreExtensionRepository.isInstalled("samekey")).thenReturn(true);
- Response response = call("/static/samekey/foo/bar.txt");
+ Response response = callAndStop("/static/samekey/foo/bar.txt");
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body().string()).isEqualTo("bar of core extension");
system.pluginStream = IOUtils.toInputStream("bar");
when(pluginRepository.hasPlugin("myplugin")).thenReturn(true);
- Response response = call("/static/myplugin/foo.css");
+ Response response = callAndStop("/static/myplugin/foo.css");
assertThat(response.header("Content-Type")).isEqualTo("text/css");
assertThat(response.body().string()).isEqualTo("bar");
system.pluginStream = null;
when(pluginRepository.hasPlugin("myplugin")).thenReturn(true);
- Response response = call("/static/myplugin/foo.css");
+ Response response = callAndStop("/static/myplugin/foo.css");
assertThat(response.code()).isEqualTo(404);
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.WARN)).isEmpty();
}
@Test
system.pluginStream = null;
when(pluginRepository.hasPlugin("myplugin")).thenReturn(false);
- Response response = call("/static/myplugin/foo.css");
+ Response response = callAndStop("/static/myplugin/foo.css");
assertThat(response.code()).isEqualTo(404);
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.WARN)).isEmpty();
}
@Test
when(pluginRepository.hasPlugin("myplugin")).thenReturn(true);
when(pluginRepository.getPluginInfo("myplugin")).thenReturn(new PluginInfo("myplugin"));
- Response response = call("/static/myplugin/foo.css");
+ Response response = callAndStop("/static/myplugin/foo.css");
assertThat(response.isSuccessful()).isTrue();
assertThat(response.body().string()).isEqualTo("bar");
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.WARN)).isEmpty();
}
@Test
system.isCommitted = true;
when(pluginRepository.hasPlugin("myplugin")).thenReturn(false);
- Response response = call("/static/myplugin/foo.css");
+ Response response = callAndStop("/static/myplugin/foo.css");
assertThat(response.code()).isEqualTo(200);
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.TRACE)).contains("Response is committed. Cannot send error response code 404");
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.TRACE)).contains("Response is committed. Cannot send error response code 404");
}
@Test
system.sendErrorException = new IOException("Simulating sendError throwing IOException");
when(pluginRepository.hasPlugin("myplugin")).thenReturn(false);
- Response response = call("/static/myplugin/foo.css");
+ Response response = callAndStop("/static/myplugin/foo.css");
assertThat(response.code()).isEqualTo(200);
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.TRACE)).contains("Failed to send error code 404: java.io.IOException: Simulating sendError throwing IOException");
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.TRACE)).contains("Failed to send error code 404: {}");
}
@Test
system.pluginStream = null;
when(pluginRepository.hasPlugin("myplugin")).thenReturn(true);
- Response response = call("/static/myplugin/foo.css");
+ Response response = callAndStop("/static/myplugin/foo.css");
assertThat(response.code()).isEqualTo(200);
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.TRACE)).contains("Response is committed. Cannot send error response code 404");
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.TRACE)).contains("Response is committed. Cannot send error response code 404");
}
@Test
system.pluginStreamException = new ClientAbortException("Simulating ClientAbortException");
when(pluginRepository.hasPlugin("myplugin")).thenReturn(true);
- Response response = call("/static/myplugin/foo.css");
+ Response response = callAndStop("/static/myplugin/foo.css");
assertThat(response.code()).isEqualTo(200);
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
- assertThat(logTester.logs(LoggerLevel.TRACE)).contains(
- "Client canceled loading resource [static/foo.css] from plugin [myplugin]: org.apache.catalina.connector.ClientAbortException: Simulating ClientAbortException");
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
+ assertThat(logTester.getLogs(Level.TRACE)).extracting(LogAndArguments::getFormattedMsg).contains(
+ "Client canceled loading resource [static/foo.css] from plugin [myplugin]: {}");
}
@Test
system.pluginStreamException = new RuntimeException("Simulating a error");
when(pluginRepository.hasPlugin("myplugin")).thenReturn(true);
- Response response = call("/static/myplugin/foo.css");
+ Response response = callAndStop("/static/myplugin/foo.css");
assertThat(response.code()).isEqualTo(200);
- assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Unable to load resource [static/foo.css] from plugin [myplugin]");
+ assertThat(logTester.logs(Level.ERROR)).contains("Unable to load resource [static/foo.css] from plugin [myplugin]");
}
private static class TestSystem extends StaticResourcesServlet.System {
testImplementation 'org.hamcrest:hamcrest-core'
testImplementation 'org.mockito:mockito-core'
testImplementation 'org.simpleframework:simple'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation project(':sonar-testing-harness')
testCompileOnly 'com.google.code.findbugs:jsr305'
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.updatecenter.common.Version;
import static org.assertj.core.api.Assertions.assertThat;
ImmutableMap.of("foo", createExplodedPlugin(info)));
assertThat(defs).extracting(PluginClassLoaderDef::getBasePluginKey).containsExactly("foo");
- List<String> warnings = logTester.logs(LoggerLevel.WARN);
+ List<String> warnings = logTester.logs(Level.WARN);
assertThat(warnings).contains("Plugin foo [foo] uses a child first classloader which is deprecated");
}
ImmutableMap.of("foo", createExplodedPlugin(info)));
assertThat(defs).extracting(PluginClassLoaderDef::getBasePluginKey).containsExactly("foo");
- List<String> warnings = logTester.logs(LoggerLevel.WARN);
+ List<String> warnings = logTester.logs(Level.WARN);
assertThat(warnings).contains("API compatibility mode is no longer supported. In case of error, plugin foo [foo] should package its dependencies.");
}
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.Loggers;
import static org.assertj.core.api.Assertions.assertThat;
ProgressLogger progress = new ProgressLogger("ProgressLoggerTest", counter, Loggers.get(getClass()));
progress.setPeriodMs(1L);
progress.start();
- while (logTester.logs(LoggerLevel.INFO).size()<2) {
+ while (logTester.logs(Level.INFO).size()<2) {
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MILLISECONDS);
}
progress.stop();
}
private boolean hasInfoLog(String expectedLog) {
- return logTester.logs(LoggerLevel.INFO).stream().anyMatch(s -> s.startsWith(expectedLog));
+ return logTester.logs(Level.INFO).stream().anyMatch(s -> s.startsWith(expectedLog));
}
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.api.utils.log.Loggers;
addSomeContext(underTest);
underTest.startInfo("Foo");
- assertThat(tester.logs(LoggerLevel.INFO)).containsOnly("Foo | a_string=bar | an_int=42 | after_start=true");
+ assertThat(tester.logs(Level.INFO)).containsOnly("Foo | a_string=bar | an_int=42 | after_start=true");
}
@Test
addSomeContext(underTest);
underTest.startDebug("Foo");
- assertThat(tester.logs(LoggerLevel.DEBUG)).containsOnly("Foo | a_string=bar | an_int=42 | after_start=true");
+ assertThat(tester.logs(Level.DEBUG)).containsOnly("Foo | a_string=bar | an_int=42 | after_start=true");
}
@Test
addSomeContext(underTest);
underTest.startTrace("Foo");
- assertThat(tester.logs(LoggerLevel.TRACE)).containsOnly("Foo | a_string=bar | an_int=42 | after_start=true");
+ assertThat(tester.logs(Level.TRACE)).containsOnly("Foo | a_string=bar | an_int=42 | after_start=true");
}
@Test
underTest.start().stopError("Rules registered");
assertThat(tester.logs()).hasSize(1);
- assertThat(tester.logs(LoggerLevel.ERROR).get(0))
+ assertThat(tester.logs(Level.ERROR).get(0))
.startsWith("Rules registered | time=")
.endsWith("ms | a_string=bar | an_int=42 | after_start=true");
}
underTest.start().stopInfo("Rules registered");
assertThat(tester.logs()).hasSize(1);
- assertThat(tester.logs(LoggerLevel.INFO).get(0))
+ assertThat(tester.logs(Level.INFO).get(0))
.startsWith("Rules registered | time=")
.endsWith("ms | a_string=bar | an_int=42 | after_start=true");
}
underTest.start().stopTrace("Rules registered");
assertThat(tester.logs()).hasSize(1);
- assertThat(tester.logs(LoggerLevel.TRACE).get(0))
+ assertThat(tester.logs(Level.TRACE).get(0))
.startsWith("Rules registered | time=")
.endsWith("ms | a_string=bar | an_int=42 | after_start=true");
}
underTest.start().stopError("Rules registered");
assertThat(tester.logs()).hasSize(1);
- assertThat(tester.logs(LoggerLevel.ERROR).get(0))
+ assertThat(tester.logs(Level.ERROR).get(0))
.startsWith("Rules registered | a_string=bar | an_int=42 | after_start=true | time=")
.endsWith("ms");
}
underTest.start().stopInfo("Rules registered");
assertThat(tester.logs()).hasSize(1);
- assertThat(tester.logs(LoggerLevel.INFO).get(0))
+ assertThat(tester.logs(Level.INFO).get(0))
.startsWith("Rules registered | a_string=bar | an_int=42 | after_start=true | time=")
.endsWith("ms");
}
underTest.start().stopTrace("Rules registered");
assertThat(tester.logs()).hasSize(1);
- assertThat(tester.logs(LoggerLevel.TRACE).get(0))
+ assertThat(tester.logs(Level.TRACE).get(0))
.startsWith("Rules registered | a_string=bar | an_int=42 | after_start=true | time=")
.endsWith("ms");
}
underTest.start().stopInfo("Bar");
assertThat(tester.logs()).hasSize(2);
- List<String> logs = tester.logs(LoggerLevel.INFO);
+ List<String> logs = tester.logs(Level.INFO);
assertThat(logs.get(0))
.startsWith("Foo | a_string=bar | an_int=42 | after_start=true | time=")
.endsWith("ms");
underTest.start().stopDebug("Bar");
assertThat(tester.logs()).hasSize(2);
- List<String> logs = tester.logs(LoggerLevel.DEBUG);
+ List<String> logs = tester.logs(Level.DEBUG);
assertThat(logs.get(0))
.startsWith("Foo | a_string=bar | an_int=42 | after_start=true | time=")
.endsWith("ms");
underTest.start().stopTrace("Bar");
assertThat(tester.logs()).hasSize(2);
- List<String> logs = tester.logs(LoggerLevel.TRACE);
+ List<String> logs = tester.logs(Level.TRACE);
assertThat(logs.get(0))
.startsWith("Foo | a_string=bar | an_int=42 | after_start=true | time=")
.endsWith("ms");
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.api.utils.log.Loggers;
testImplementation 'junit:junit'
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.mockito:mockito-core'
+ testImplementation 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
}
import org.apache.tools.ant.filters.ReplaceTokens
/**
* Digest hash of the file.
*/
- public String hash() {
+ @Override
+ public String md5Hash() {
checkMetadata();
return metadata.hash();
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.FileMetadata;
import org.sonar.api.batch.fs.internal.Metadata;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.notifications.AnalysisWarnings;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
import static org.assertj.core.api.Assertions.assertThat;
assertThat(metadata.nonBlankLines()).isEqualTo(133);
assertThat(metadata.hash()).isNotEmpty();
- assertThat(logTester.logs(LoggerLevel.WARN).get(0)).contains("Invalid character encountered in file");
+ assertThat(logTester.logs(Level.WARN).get(0)).contains("Invalid character encountered in file");
verify(analysisWarnings).addUnique("There are problems with file encoding in the source code. Please check the scanner logs for more details.");
- assertThat(logTester.logs(LoggerLevel.WARN).get(0)).contains(
+ assertThat(logTester.logs(Level.WARN).get(0)).contains(
"glyphicons-halflings-regular.woff at line 1 for encoding UTF-8. Please fix file content or configure the encoding to be used using property 'sonar.sourceEncoding'.");
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
// second call does not fail, nor log ERROR logs
underTest.clean();
- assertThat(logTester.logs(LoggerLevel.ERROR)).isEmpty();
+ assertThat(logTester.logs(Level.ERROR)).isEmpty();
}
}
testImplementation 'com.fasterxml.staxmate:staxmate'
testImplementation 'org.hamcrest:hamcrest-core'
testImplementation 'org.mockito:mockito-core'
+ api 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures'
testImplementation project(':plugins:sonar-xoo-plugin')
}
props.putAll(tester.globalProperties);
props.putAll(taskProperties);
- Batch.builder()
+ Batch.Builder builder = Batch.builder()
.setGlobalProperties(props)
.setEnableLoggingConfiguration(true)
.addComponents(new EnvironmentInformation("mediumTest", "1.0"),
tester.analysisCacheLoader,
tester.sonarRuntime,
tester.reportMetadataHolder,
- result)
- .setLogOutput(tester.logOutput)
- .build().execute();
+ result);
+ if (tester.logOutput != null) {
+ builder.setLogOutput(tester.logOutput);
+ } else {
+ builder.setEnableLoggingConfiguration(false);
+ }
+ builder.build().execute();
return result;
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.FileMetadata;
import org.sonar.api.notifications.AnalysisWarnings;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport;
@Before
public void prepare() throws IOException {
+ logTester.setLevel(Level.DEBUG);
baseDir = temp.newFolder();
Path filepath = baseDir.toPath().resolve(FILE_PATH);
Files.write(filepath, FILE_CONTENT.getBytes());
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.batch.fs.InputFile;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport;
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way");
+ @Before
+ public void prepare() throws IOException {
+ logTester.setLevel(Level.DEBUG);
+ }
+
@Test
public void singleReport() throws IOException {
InputFile fileB = result.inputFile("moduleB/src/sampleB.xoo");
assertThat(result.coverageFor(fileB, 2)).isNotNull();
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Specifying module-relative paths at project level in the property 'sonar.coverage.exclusions' is deprecated. " +
+ assertThat(logTester.logs(Level.WARN)).contains("Specifying module-relative paths at project level in the property 'sonar.coverage.exclusions' is deprecated. " +
"To continue matching files like 'moduleA/src/sampleA.xoo', update this property so that patterns refer to project-relative paths.");
}
InputFile fileB = result.inputFile("moduleB/src/sample.xoo");
assertThat(result.coverageFor(fileB, 2)).isNull();
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Specifying module-relative paths at project level in the property 'sonar.coverage.exclusions' is deprecated. " +
+ assertThat(logTester.logs(Level.WARN)).contains("Specifying module-relative paths at project level in the property 'sonar.coverage.exclusions' is deprecated. " +
"To continue matching files like 'moduleA/src/sample.xoo', update this property so that patterns refer to project-relative paths.");
}
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.assertThat;
public class GenericCoverageMediumIT {
- private final List<String> logs = new ArrayList<>();
-
+ @Rule
+ public LogTester logTester = new LogTester();
+
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-coverage");
AnalysisResult result = tester
- .setLogOutput((msg, level) -> logs.add(msg))
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.coverageReportPaths", "coverage.xml")
.execute();
assertThat(result.coverageFor(withConditions, 3).getConditions()).isEqualTo(2);
assertThat(result.coverageFor(withConditions, 3).getCoveredConditions()).isOne();
- assertThat(logs).noneMatch(l -> l.contains("Please use 'sonar.coverageReportPaths'"));
+ assertThat(logTester.logs()).noneMatch(l -> l.contains("Please use 'sonar.coverageReportPaths'"));
}
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-coverage");
AnalysisResult result = tester
- .setLogOutput((msg, level) -> logs.add(msg))
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.coverageReportPaths", "coverage.xml,coverage2.xml")
.execute();
assertThat(result.coverageFor(withConditions, 3).getConditions()).isEqualTo(2);
assertThat(result.coverageFor(withConditions, 3).getCoveredConditions()).isEqualTo(2);
- assertThat(logs).noneMatch(l -> l.contains("Please use 'sonar.coverageReportPaths'"));
+ assertThat(logTester.logs()).noneMatch(l -> l.contains("Please use 'sonar.coverageReportPaths'"));
}
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.batch.fs.InputFile;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport;
@Before
public void prepare() {
+ logTester.setLevel(Level.DEBUG);
baseDir = temp.getRoot();
builder = ImmutableMap.<String, String>builder()
List<ScannerReport.Duplication> duplicationGroupsFile2 = result.duplicationsFor(inputFile2);
assertThat(duplicationGroupsFile2).isEmpty();
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Specifying module-relative paths at project level in the property 'sonar.cpd.exclusions' is deprecated. " +
+ assertThat(logTester.logs(Level.WARN)).contains("Specifying module-relative paths at project level in the property 'sonar.cpd.exclusions' is deprecated. " +
"To continue matching files like 'moduleA/src/sampleA.xoo', update this property so that patterns refer to project-relative paths.");
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.CoreProperties;
import org.sonar.api.SonarEdition;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.PathUtils;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
@Before
public void prepare() throws IOException {
+ logTester.setLevel(Level.DEBUG);
baseDir = temp.newFolder().getCanonicalFile();
builder = ImmutableMap.<String, String>builder()
InputFile fileB = result.inputFile("moduleB/src/sample.xoo");
assertThat(fileB).isNull();
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.contains("Specifying module-relative paths at project level in the property 'sonar.exclusions' is deprecated. " +
"To continue matching files like 'moduleA/src/sample.xoo', update this property so that patterns refer to project-relative paths.");
}
InputFile fileB = result.inputFile("moduleB/src/sample.xoo");
assertThat(fileB).isNull();
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.contains("Specifying module-relative paths at project level in the property 'sonar.exclusions' is deprecated. " +
"To continue matching files like 'moduleA/src/sample.xoo', update this property so that patterns refer to project-relative paths.");
}
.execute();
assertThat(result.inputFiles()).hasSize(4);
- assertThat(logTester.logs(LoggerLevel.INFO)).contains(
+ assertThat(logTester.logs(Level.INFO)).contains(
"Deprecated Global Sensor: module_a/module_a1/src/main/xoo/com/sonar/it/samples/modules/a1/HelloA1.xoo",
"Deprecated Global Sensor: module_a/module_a2/src/main/xoo/com/sonar/it/samples/modules/a2/HelloA2.xoo",
"Deprecated Global Sensor: module_b/module_b1/src/main/xoo/com/sonar/it/samples/modules/b1/HelloB1.xoo",
.execute();
assertThat(result.inputFiles()).hasSize(4);
- assertThat(logTester.logs(LoggerLevel.INFO)).contains(
+ assertThat(logTester.logs(Level.INFO)).contains(
"Global Sensor: module_a/module_a1/src/main/xoo/com/sonar/it/samples/modules/a1/HelloA1.xoo",
"Global Sensor: module_a/module_a2/src/main/xoo/com/sonar/it/samples/modules/a2/HelloA2.xoo",
"Global Sensor: module_b/module_b1/src/main/xoo/com/sonar/it/samples/modules/b1/HelloB1.xoo",
.build())
.execute();
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.containsSequence("Project configuration:",
" Included sources: **/global.inclusions",
" Excluded sources: **/global.exclusions, **/global.test.inclusions",
" Excluded sources for duplication: **/cpd.exclusions",
"Indexing files of module 'moduleA'",
" Base dir: " + baseDirModuleA.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS),
- " Source paths: src",
" Included sources: **/global.inclusions",
" Excluded sources: **/global.exclusions, **/global.test.inclusions",
" Included tests: **/global.test.inclusions",
" Excluded sources for duplication: **/cpd.exclusions",
"Indexing files of module 'moduleB'",
" Base dir: " + baseDirModuleB.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS),
- " Source paths: src",
" Included sources: **/global.inclusions",
" Excluded sources: **/global.exclusions, **/global.test.inclusions",
" Included tests: **/global.test.inclusions",
.execute();
assertThat(result.inputFiles()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("File '" + xooFile2.getAbsolutePath() + "' is ignored. It is not located in project basedir '" + baseDir + "'.");
+ assertThat(logTester.logs(Level.WARN)).contains("File '" + xooFile2.getAbsolutePath() + "' is ignored. It is not located in project basedir '" + baseDir + "'.");
}
@Test
.execute();
assertThat(result.inputFiles()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.WARN)).doesNotContain("File '" + xooFile2.getAbsolutePath() + "' is ignored. It is not located in project basedir '" + baseDir + "'.");
+ assertThat(logTester.logs(Level.WARN)).doesNotContain("File '" + xooFile2.getAbsolutePath() + "' is ignored. It is not located in project basedir '" + baseDir + "'.");
}
@Test
.execute();
assertThat(result.inputFiles()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.contains("File '" + xooFile2.getAbsolutePath() + "' is ignored. It is not located in module basedir '" + new File(baseDir, "moduleA") + "'.");
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.Constants.Severity;
@Test
public void testLoadIssuesFromJsonReport() throws URISyntaxException, IOException {
+ logs.setLevel(Level.DEBUG);
File projectDir = new File("test-resources/mediumtest/xoo/sample");
File tmpDir = temp.newFolder();
FileUtils.copyDirectory(projectDir, tmpDir);
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.FileUtils;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.batch.rule.LoadedActiveRule;
import org.sonar.api.rule.RuleKey;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport.ExternalIssue;
.addRules(new XooRulesDefinition())
.addActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", "OneIssuePerLine.internal", "xoo");
+ @Before
+ public void setUp() throws Exception {
+ logTester.setLevel(Level.DEBUG);
+ }
+
@Test
public void testOneIssuePerLine() throws Exception {
File projectDir = new File("test-resources/mediumtest/xoo/sample");
.build())
.execute();
- assertThat(logTester.logs(LoggerLevel.WARN)).contains(
+ assertThat(logTester.logs(Level.WARN)).contains(
"Specifying module-relative paths at project level in property 'sonar.issue.ignore.multicriteria' is deprecated. To continue matching files like 'moduleA/src/sampleA.xoo', update this property so that patterns refer to project-relative paths.");
List<Issue> issues = result.issuesFor(result.inputFile("moduleA/src/sampleA.xoo"));
.build())
.execute();
- assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logTester.logs(Level.WARN)).isEmpty();
result = tester.newAnalysis()
.properties(ImmutableMap.<String, String>builder()
.build())
.execute();
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly(
+ assertThat(logTester.logs(Level.WARN)).containsOnly(
"Specifying issue exclusions at module level is not supported anymore. Configure the property 'sonar.issue.ignore.multicriteria' and any other issue exclusions at project level.");
List<Issue> issues = result.issuesFor(result.inputFile("moduleA/src/sampleA.xoo"));
.build())
.execute();
- assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logTester.logs(Level.WARN)).isEmpty();
}
@Test
.build())
.execute();
- assertThat(logTester.logs(LoggerLevel.WARN)).contains(
+ assertThat(logTester.logs(Level.WARN)).contains(
"Specifying module-relative paths at project level in property 'sonar.issue.enforce.multicriteria' is deprecated. To continue matching files like 'moduleA/src/sampleA.xoo', update this property so that patterns refer to project-relative paths.");
List<Issue> issues = result.issuesFor(result.inputFile("moduleA/src/sampleA.xoo"));
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
+import org.sonar.batch.bootstrapper.LogOutput;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.protocol.output.ScannerReport.Measure;
import static org.junit.Assert.fail;
public class MeasuresMediumIT {
-
@Rule
public LogTester logTester = new LogTester();
-
@Rule
public TemporaryFolder temp = new TemporaryFolder();
.execute();
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Storing measures on folders or modules is deprecated. Provided value of metric 'tests' is ignored.");
+ assertThat(logTester.logs(Level.WARN)).contains("Storing measures on folders or modules is deprecated. Provided value of metric 'tests' is ignored.");
}
@Test
.execute();
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Storing measures on folders or modules is deprecated. Provided value of metric 'tests' is ignored.");
+ assertThat(logTester.logs(Level.WARN)).contains("Storing measures on folders or modules is deprecated. Provided value of metric 'tests' is ignored.");
}
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.SonarEdition;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester.AnalysisBuilder;
import org.sonar.scanner.protocol.output.FileStructure;
@Test
public void log_files_with_missing_blame() throws IOException, URISyntaxException {
-
+ logTester.setLevel(Level.DEBUG);
File baseDir = prepareProject();
File xooFileWithoutBlame = new File(baseDir, "src/sample_no_blame.xoo");
FileUtils.write(xooFileWithoutBlame, "Sample xoo\ncontent\n3\n4\n5", StandardCharsets.UTF_8);
// SONAR-6397
@Test
public void optimize_blame() throws IOException, URISyntaxException {
-
+ logTester.setLevel(Level.DEBUG);
File baseDir = prepareProject();
File changedContentScmOnServer = new File(baseDir, CHANGED_CONTENT_SCM_ON_SERVER_XOO);
FileUtils.write(changedContentScmOnServer, SAMPLE_XOO_CONTENT + "\nchanged", StandardCharsets.UTF_8);
import org.junit.Test;
import org.sonar.api.Plugin;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.measures.CoreMetrics;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.mediumtest.AnalysisResult;
import org.sonar.scanner.mediumtest.ScannerMediumTester;
import org.sonar.xoo.XooPlugin;
import static org.assertj.core.api.Assertions.tuple;
public class GenericTestExecutionMediumIT {
- private final List<String> logs = new ArrayList<>();
-
+ @Rule
+ public LogTester logTester = new LogTester();
@Rule
public ScannerMediumTester tester = new ScannerMediumTester()
.registerPlugin("xoo", new XooPlugin())
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-test-exec");
AnalysisResult result = tester
- .setLogOutput((msg, level) -> logs.add(msg))
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.testExecutionReportPaths", "unittest.xml")
.execute();
tuple(CoreMetrics.TEST_EXECUTION_TIME_KEY, 0, 1105L),
tuple(CoreMetrics.TEST_FAILURES_KEY, 1, 0L));
- assertThat(logs).noneMatch(l -> l.contains("Please use 'sonar.testExecutionReportPaths'"));
+ assertThat(logTester.logs()).noneMatch(l -> l.contains("Please use 'sonar.testExecutionReportPaths'"));
}
@Test
File projectDir = new File("test-resources/mediumtest/xoo/sample-generic-test-exec");
AnalysisResult result = tester
- .setLogOutput((msg, level) -> logs.add(msg))
.newAnalysis(new File(projectDir, "sonar-project.properties"))
.property("sonar.testExecutionReportPaths", "unittest.xml,unittest2.xml")
.execute();
tuple(CoreMetrics.TEST_EXECUTION_TIME_KEY, 0, 1610L),
tuple(CoreMetrics.TEST_FAILURES_KEY, 1, 0L));
- assertThat(logs).noneMatch(l -> l.contains("Please use 'sonar.testExecutionReportPaths'"));
+ assertThat(logTester.logs()).noneMatch(l -> l.contains("Please use 'sonar.testExecutionReportPaths'"));
}
}
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.mockito.ArgumentCaptor;
+import org.slf4j.event.Level;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.scm.BlameCommand.BlameInput;
import org.sonar.api.batch.scm.BlameCommand.BlameOutput;
import org.sonar.api.batch.scm.BlameLine;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.tmatesoft.svn.core.SVNAuthenticationException;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNURL;
assertThrows(IllegalStateException.class, () -> {
svnBlameCommand.blame(clientManager, inputFile, output);
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Authentication to SVN server is required but no " +
+ assertThat(logTester.logs(Level.WARN)).contains("Authentication to SVN server is required but no " +
"authentication data was passed to the scanner");
});
any(SVNRevision.class), any(SVNRevision.class), anyBoolean(), anyBoolean(), any(AnnotationHandler.class),
eq(null));
- assertThrows(IllegalStateException.class, () -> {
- svnBlameCommand.blame(clientManager, inputFile, output);
- assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty();
- });
-
+ assertThrows(IllegalStateException.class, () -> svnBlameCommand.blame(clientManager, inputFile, output));
+ assertThat(logTester.logs(Level.WARN)).contains("Authentication to SVN server is required but no authentication data was passed to the scanner");
}
private static void javaUnzip(File zip, File toDir) {
}
private RuntimeException handleException(RuntimeException t) {
- if (loggingConfig.isVerbose()) {
+ if (loggingConfig != null && loggingConfig.isVerbose()) {
return t;
}
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
+import org.slf4j.event.Level;
import org.sonar.api.notifications.AnalysisWarnings;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.HttpException;
assertThat(result).isSameAs(response);
// check logs
- List<String> debugLogs = logTester.logs(LoggerLevel.DEBUG);
+ List<String> debugLogs = logTester.logs(Level.DEBUG);
assertThat(debugLogs).hasSize(1);
assertThat(debugLogs.get(0)).contains("GET 200 https://local/api/issues/search | time=");
}
underTest.call(request);
// check logs
- List<String> warningLogs = logTester.logs(LoggerLevel.WARN);
+ List<String> warningLogs = logTester.logs(Level.WARN);
assertThat(warningLogs).hasSize(2);
assertThat(warningLogs.get(0)).contains("The token used for this analysis will expire on: " + fiveDaysLatter.format(DateTimeFormatter.ofPattern("MMMM dd, yyyy")));
assertThat(warningLogs.get(1)).contains("Analysis executed with this token will fail after the expiration date.");
import org.junit.Test;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import org.mockito.ArgumentCaptor;
import org.sonar.api.scanner.fs.InputProject;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.protocol.internal.ScannerInternal.SensorCacheEntry;
import org.sonar.scanner.protocol.internal.SensorCacheData;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiVendor;
CiConfiguration configuration = underTest.loadConfiguration();
assertThat(configuration.getScmRevision()).isEmpty();
- assertThat(logs.logs(LoggerLevel.WARN)).contains("Missing environment variable CIRRUS_CHANGE_IN_REPO");
+ assertThat(logs.logs(Level.WARN)).contains("Missing environment variable CIRRUS_CHANGE_IN_REPO");
}
private void setEnvVariable(String key, @Nullable String value) {
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiVendor;
setEnvVariable("FCI_BUILD_ID", "1");
CiConfiguration ciConfiguration = underTest.loadConfiguration();
- List<String> logs = logTester.logs(LoggerLevel.WARN);
+ List<String> logs = logTester.logs(Level.WARN);
assertThat(ciConfiguration.getScmRevision()).isEmpty();
assertThat(logs).hasSize(1);
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.scanner.ci.CiVendor;
import static org.assertj.core.api.Assertions.assertThat;
setEnvVariable("GITHUB_ACTION", "build");
assertThat(underTest.loadConfiguration().getScmRevision()).isEmpty();
- assertThat(logs.logs(LoggerLevel.WARN)).contains("Missing environment variable GITHUB_SHA");
+ assertThat(logs.logs(Level.WARN)).contains("Missing environment variable GITHUB_SHA");
}
private void setEnvVariable(String key, @Nullable String value) {
import java.util.Arrays;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.PropertyFieldDefinition;
import org.sonar.api.config.internal.Encryption;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
};
assertThat(config.get("multiA")).hasValue("a,b");
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.contains(
"Access to the multi-values/property set property 'multiA' should be made using 'getStringArray' method. The SonarQube plugin using this property should be updated.");
logTester.clear();
assertThat(config.getStringArray("single")).containsExactly("foo");
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.contains(
"Property 'single' is not declared as multi-values/property set but was read using 'getStringArray' method. The SonarQube plugin declaring this property should be updated.");
assertThat(config.get("notDeclared")).hasValue("c,d");
assertThat(config.getStringArray("notDeclared")).containsExactly("c", "d");
- assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logTester.logs(Level.WARN)).isEmpty();
}
@Test
};
assertThat(config.get("props")).hasValue("1,2");
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.contains(
"Access to the multi-values/property set property 'props' should be made using 'getStringArray' method. The SonarQube plugin using this property should be updated.");
logTester.clear();
assertThat(config.getStringArray("props")).containsExactly("1", "2");
- assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logTester.logs(Level.WARN)).isEmpty();
}
@Test
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.ArgumentMatchers;
+import org.slf4j.event.Level;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.util.CloseableIterator;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.block.ByteArray;
Duplication[] dups = readDuplications(1);
assertThat(dups[0].getDuplicateList()).hasSize(CpdExecutor.MAX_CLONE_PART_PER_GROUP);
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.contains("Too many duplication references on file " + batchComponent1 + " for block at line 0. Keep only the first "
+ CpdExecutor.MAX_CLONE_PART_PER_GROUP + " references.");
}
assertThat(reader.readComponentDuplications(batchComponent1.scannerId())).toIterable().hasSize(CpdExecutor.MAX_CLONE_GROUP_PER_FILE);
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.contains("Too many duplication groups on file " + batchComponent1 + ". Keep only the first " + CpdExecutor.MAX_CLONE_GROUP_PER_FILE + " groups.");
}
verify(executorService).shutdown();
verifyNoMoreInteractions(executorService);
readDuplications(batchComponent1, 0);
- assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Resource not found in component store: unknown. Skipping CPD computation for it");
+ assertThat(logTester.logs(Level.ERROR)).contains("Resource not found in component store: unknown. Skipping CPD computation for it");
}
@Test
executor.execute(1);
readDuplications(0);
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.usingElementComparator((l, r) -> l.matches(r) ? 0 : 1)
.containsOnly(
"Timeout during detection of duplications for .*Foo.php");
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.batch.fs.TextRange;
-import org.sonar.api.batch.rule.Severity;
-import org.sonar.api.batch.sensor.issue.ExternalIssue;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
+import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
+import org.sonar.api.batch.sensor.issue.ExternalIssue;
+import org.sonar.api.testfixtures.log.LogTester;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.commons.lang.ObjectUtils.defaultIfNull;
assertThat(context.allExternalIssues()).isEmpty();
assertThat(context.allIssues()).isEmpty();
- assertThat(logs.logs(LoggerLevel.INFO)).contains("Imported 0 issues in 0 files");
+ assertThat(logs.logs(Level.INFO)).contains("Imported 0 issues in 0 files");
}
@Test
assertThat(output.ruleId()).isEqualTo(input.ruleId);
assertThat(output.severity()).isEqualTo(Severity.valueOf(input.severity));
assertThat(output.remediationEffort()).isNull();
- assertThat(logs.logs(LoggerLevel.INFO)).contains("Imported 1 issue in 1 file");
+ assertThat(logs.logs(Level.INFO)).contains("Imported 1 issue in 1 file");
}
@Test
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.event.Level;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.sarif.Run;
import org.sonar.core.sarif.Sarif210;
assertThat(sarifImportResults.getSuccessFullyImportedIssues()).isOne();
assertThat(sarifImportResults.getSuccessFullyImportedRuns()).isOne();
assertThat(sarifImportResults.getFailedRuns()).isOne();
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly("Failed to import a sarif run, error: " + testException.getMessage());
+ assertThat(logTester.logs(Level.WARN)).containsOnly("Failed to import a sarif run, error: " + testException.getMessage());
verify(issue1run2).save();
}
import org.assertj.core.api.Assertions;
import org.assertj.core.groups.Tuple;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.batch.rule.Severity;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.core.sarif.DefaultConfiguration;
import org.sonar.core.sarif.Driver;
private void assertWarningLog(String driverName, Severity defaultSeverity) {
assertThat(logTester.logs()).hasSize(1);
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.containsOnly(format(UNSUPPORTED_RULE_SEVERITIES_WARNING, driverName, defaultSeverity));
}
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.event.Level;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.sarif.Result;
import org.sonar.core.sarif.Run;
assertThat(newExternalIssues)
.containsExactly(externalIssue2);
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly("Failed to import an issue raised by tool Test driver, error: test");
+ assertThat(logTester.logs(Level.WARN)).containsOnly("Failed to import an issue raised by tool Test driver, error: test");
}
}
import com.google.common.collect.MoreCollectors;
import java.nio.file.Path;
import java.util.Optional;
-import java.util.stream.Collectors;
import org.apache.commons.lang.math.RandomUtils;
-import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.event.Level;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.config.internal.MapSettings;
-import org.sonar.api.utils.log.LogAndArguments;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogAndArguments;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.core.sarif.Sarif210;
import org.sonar.core.sarif.SarifSerializer;
verify(sarifImporter).importSarif(reportAndResults.getSarifReport());
- assertThat(logTester.logs(LoggerLevel.INFO)).hasSize(1);
+ assertThat(logTester.logs(Level.INFO)).hasSize(1);
assertSummaryIsCorrectlyDisplayed(FILE_1, reportAndResults.getSarifImportResults());
}
sensor.execute(sensorContext);
verify(sarifImporter).importSarif(reportAndResults2.getSarifReport());
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Failed to process SARIF report from file 'path/to/sarif/file.sarif', error: 'import failed'");
+ assertThat(logTester.logs(Level.WARN)).contains("Failed to process SARIF report from file 'path/to/sarif/file.sarif', error: 'import failed'");
assertSummaryIsCorrectlyDisplayed(FILE_2, reportAndResults2.getSarifImportResults());
}
sensor.execute(sensorContext);
verify(sarifImporter).importSarif(reportAndResults2.getSarifReport());
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Failed to process SARIF report from file 'path/to/sarif/file.sarif', error: 'deserialization failed'");
+ assertThat(logTester.logs(Level.WARN)).contains("Failed to process SARIF report from file 'path/to/sarif/file.sarif', error: 'deserialization failed'");
assertSummaryIsCorrectlyDisplayed(FILE_2, reportAndResults2.getSarifImportResults());
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
@Before
public void before() {
+ logs.setLevel(Level.DEBUG);
context = SensorContextTester.create(new File(""));
fileWithBranches = setupFile("src/main/java/com/example/ClassWithBranches.java");
fileWithoutBranch = setupFile("src/main/java/com/example/ClassWithoutBranch.java");
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.config.DefaultConfiguration;
import org.sonar.scanner.scan.ProjectConfiguration;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.deprecated.test.DefaultTestCase;
import org.sonar.scanner.deprecated.test.DefaultTestPlan;
import org.sonar.scanner.deprecated.test.TestPlanBuilder;
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logs = new LogTester();
+
private TestPlanBuilder testPlanBuilder;
private DefaultInputFile fileWithBranches;
private DefaultInputFile emptyFile;
@Before
public void before() {
+ logs.setLevel(Level.DEBUG);
context = SensorContextTester.create(new File(""));
fileWithBranches = setupFile("src/main/java/com/example/ClassWithBranches.java");
emptyFile = setupFile("src/main/java/com/example/EmptyClass.java");
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.config.DefaultConfiguration;
import org.sonar.scanner.deprecated.test.TestPlanBuilder;
import org.sonar.scanner.scan.ProjectConfiguration;
DefaultConfiguration config = new ProjectConfiguration(defs, new Encryption(null), settings);
new GenericTestExecutionSensor(mock(TestPlanBuilder.class), config).execute(context);
- assertThat(logTester.logs(LoggerLevel.WARN)).contains(
+ assertThat(logTester.logs(Level.WARN)).contains(
"Using 'unitTest' as root element of the report is deprecated. Please change to 'testExecutions'.",
"Property 'sonar.genericcoverage.unitTestReportPaths' is deprecated. Please use 'sonar.testExecutionReportPaths' instead.");
- assertThat(logTester.logs(LoggerLevel.INFO)).contains(
+ assertThat(logTester.logs(Level.INFO)).contains(
"Imported test execution data for 0 files",
"Test execution data ignored for 1 unknown files, including:\nA.java");
}
import org.sonar.api.rule.RuleKey;
import org.sonar.api.scan.issue.filter.IssueFilterChain;
import org.sonar.api.utils.WildcardPattern;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.issue.DefaultFilterableIssue;
import static java.util.Collections.singleton;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.bootstrap.ScannerPluginRepository;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
+import org.slf4j.event.Level;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.report.CeTaskReportDataHolder;
@Before
public void before() {
+ logTester.setLevel(Level.DEBUG);
when(reportMetadataHolder.getCeTaskId()).thenReturn("task-1234");
when(reportMetadataHolder.getDashboardUrl()).thenReturn("http://dashboard-url.com");
}
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.core.platform.PluginInfo;
import org.sonar.scanner.bootstrap.GlobalServerSettings;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.scm.ScmProvider;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.StandardCharsets;
-import java.nio.file.Path;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
+import org.slf4j.event.Level;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.impl.utils.JUnitTempFolder;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.platform.Server;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.TempFolder;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.fs.InputModuleHierarchy;
@Before
public void setUp() {
+ logTester.setLevel(Level.DEBUG);
root = new DefaultInputModule(
ProjectDefinition.create().setKey("org.sonarsource.sonarqube:sonarqube").setBaseDir(reportTempFolder.newDir()).setWorkDir(reportTempFolder.getRoot()));
when(moduleHierarchy.root()).thenReturn(root);
underTest.start();
underTest.execute();
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.contains("ANALYSIS SUCCESSFUL")
.doesNotContain("dashboard/index");
underTest.execute();
assertThat(properties.metadataFilePath()).exists();
- assertThat(logTester.logs(LoggerLevel.DEBUG))
+ assertThat(logTester.logs(Level.DEBUG))
.contains("Report metadata written to " + properties.metadataFilePath());
- assertThat(logTester.logs(LoggerLevel.INFO))
+ assertThat(logTester.logs(Level.INFO))
.contains("ANALYSIS SUCCESSFUL, you can find the results at: https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube")
.contains("More about the report processing at https://publicserver/sonarqube/api/ce/task?id=TASK-123");
}
underTest.prepareAndDumpMetadata("TASK-123");
assertThat(properties.metadataFilePath()).exists();
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("Report metadata written to " + properties.metadataFilePath());
+ assertThat(logTester.logs(Level.DEBUG)).contains("Report metadata written to " + properties.metadataFilePath());
}
@Test
underTest.start();
underTest.execute();
- assertThat(logTester.logs(LoggerLevel.WARN)).isEmpty();
+ assertThat(logTester.logs(Level.WARN)).isEmpty();
verifyNoInteractions(analysisWarnings);
}
underTest.start();
underTest.execute();
- assertThat(logTester.logs(LoggerLevel.WARN)).containsOnly(SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE);
+ assertThat(logTester.logs(Level.WARN)).containsOnly(SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE);
verify(analysisWarnings).addUnique(SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE);
}
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.rule.QualityProfiles;
import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
+import org.slf4j.event.Level;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.notifications.AnalysisWarnings;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.batch.bootstrapper.EnvironmentInformation;
import static org.mockito.Mockito.times;
underTest.execute();
verify(analysisWarnings, times(1)).addUnique(LOGIN_WARN_MESSAGE);
- Assertions.assertThat(logger.logs(LoggerLevel.WARN)).contains(LOGIN_WARN_MESSAGE);
+ Assertions.assertThat(logger.logs(Level.WARN)).contains(LOGIN_WARN_MESSAGE);
}
@Test
underTest.execute();
verify(analysisWarnings, times(1)).addUnique(PASSWORD_WARN_MESSAGE);
- Assertions.assertThat(logger.logs(LoggerLevel.WARN)).contains(PASSWORD_WARN_MESSAGE);
+ Assertions.assertThat(logger.logs(Level.WARN)).contains(PASSWORD_WARN_MESSAGE);
}
@Test
underTest.execute();
verify(analysisWarnings, times(1)).addUnique(LOGIN_WARN_MESSAGE + SCANNER_DOTNET_WARN_MESSAGE);
- Assertions.assertThat(logger.logs(LoggerLevel.WARN)).contains(LOGIN_WARN_MESSAGE + SCANNER_DOTNET_WARN_MESSAGE);
+ Assertions.assertThat(logger.logs(Level.WARN)).contains(LOGIN_WARN_MESSAGE + SCANNER_DOTNET_WARN_MESSAGE);
}
@Test
underTest.execute();
verify(analysisWarnings, times(1)).addUnique(PASSWORD_WARN_MESSAGE + SCANNER_DOTNET_WARN_MESSAGE);
- Assertions.assertThat(logger.logs(LoggerLevel.WARN)).contains(PASSWORD_WARN_MESSAGE + SCANNER_DOTNET_WARN_MESSAGE);
+ Assertions.assertThat(logger.logs(Level.WARN)).contains(PASSWORD_WARN_MESSAGE + SCANNER_DOTNET_WARN_MESSAGE);
}
@Test
underTest.execute();
verifyNoInteractions(analysisWarnings);
- Assertions.assertThat(logger.logs(LoggerLevel.WARN)).isEmpty();
+ Assertions.assertThat(logger.logs(Level.WARN)).isEmpty();
}
}
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.bootstrap.ScannerProperties;
import static java.util.Collections.emptyMap;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.config.ScannerProperties;
import org.sonar.scanner.ProjectInfo;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import org.slf4j.event.Level;
import org.sonar.api.batch.fs.IndexedFile;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultIndexedFile;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.notifications.AnalysisWarnings;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
String expectedWarn = "Use of sonar.tests.inclusions detected. " +
"While being taken into account, the only supported property is sonar.test.inclusions. Consider updating your configuration.";
- assertThat( logTester.logs(LoggerLevel.WARN) ).hasSize(1)
- .contains(expectedWarn);
+ assertThat(logTester.logs(Level.WARN)).hasSize(1)
+ .contains(expectedWarn);
verify(analysisWarnings).addUnique(expectedWarn);
}
String expectedWarn = "Use of sonar.tests.exclusions detected. " +
"While being taken into account, the only supported property is sonar.test.exclusions. Consider updating your configuration.";
- assertThat( logTester.logs(LoggerLevel.WARN) ).hasSize(1)
+ assertThat(logTester.logs(Level.WARN)).hasSize(1)
.contains(expectedWarn);
verify(analysisWarnings).addUnique(expectedWarn);
}
@Test
- public void should_keepLegacyValue_when_legacyAndAliasPropertiesAreUsedForTestInclusions(){
+ public void should_keepLegacyValue_when_legacyAndAliasPropertiesAreUsedForTestInclusions() {
settings.setProperty(PROJECT_TESTS_INCLUSIONS_PROPERTY, "**/*Dao.java");
- settings.setProperty(PROJECT_TEST_INCLUSIONS_PROPERTY,"**/*Dto.java");
+ settings.setProperty(PROJECT_TEST_INCLUSIONS_PROPERTY, "**/*Dto.java");
AbstractExclusionFilters filter = new AbstractExclusionFilters(analysisWarnings, settings.asConfig()::getStringArray) {
};
assertThat(filter.isIncluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isTrue();
String expectedWarn = "Use of sonar.test.inclusions and sonar.tests.inclusions at the same time. sonar.test.inclusions is taken into account. Consider updating your configuration";
- assertThat( logTester.logs(LoggerLevel.WARN) ).hasSize(1)
+ assertThat(logTester.logs(Level.WARN)).hasSize(1)
.contains(expectedWarn);
verify(analysisWarnings).addUnique(expectedWarn);
}
@Test
- public void should_keepLegacyValue_when_legacyAndAliasPropertiesAreUsedForTestExclusions(){
+ public void should_keepLegacyValue_when_legacyAndAliasPropertiesAreUsedForTestExclusions() {
settings.setProperty(PROJECT_TESTS_EXCLUSIONS_PROPERTY, "**/*Dao.java");
- settings.setProperty(PROJECT_TEST_EXCLUSIONS_PROPERTY,"**/*Dto.java");
+ settings.setProperty(PROJECT_TEST_EXCLUSIONS_PROPERTY, "**/*Dto.java");
AbstractExclusionFilters filter = new AbstractExclusionFilters(analysisWarnings, settings.asConfig()::getStringArray) {
};
assertThat(filter.isExcluded(indexedFile.path(), Paths.get(indexedFile.relativePath()), InputFile.Type.TEST)).isTrue();
String expectedWarn = "Use of sonar.test.exclusions and sonar.tests.exclusions at the same time. sonar.test.exclusions is taken into account. Consider updating your configuration";
- assertThat( logTester.logs(LoggerLevel.WARN) ).hasSize(1)
+ assertThat(logTester.logs(Level.WARN)).hasSize(1)
.contains(expectedWarn);
verify(analysisWarnings).addUnique(expectedWarn);
}
DefaultInputFile inputFile = createInputFileWithMetadata(tempFile);
assertThat(inputFile.lines()).isEqualTo(3);
assertThat(inputFile.nonBlankLines()).isEqualTo(3);
- assertThat(inputFile.hash()).isEqualTo(md5Hex("foo\nbar\nbaz"));
+ assertThat(inputFile.md5Hash()).isEqualTo(md5Hex("foo\nbar\nbaz"));
assertThat(inputFile.originalLineStartOffsets()).containsOnly(0, 4, 9);
assertThat(inputFile.originalLineEndOffsets()).containsOnly(3, 7, 12);
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
+import org.slf4j.event.Level;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.api.config.Configuration;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.MessageException;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.config.ScannerProperties;
import org.sonar.scanner.fs.InputModuleHierarchy;
@Test
public void log_when_disabled() {
+ logTester.setLevel(Level.DEBUG);
when(settings.getBoolean(CoreProperties.SCM_DISABLED_KEY)).thenReturn(Optional.of(true));
underTest.start();
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.branch.DefaultBranchConfiguration;
@Test
public void not_active_if_its_pr() {
+ logTester.setLevel(Level.DEBUG);
BranchConfiguration prConfig = branchConfiguration(null, null, true);
UnchangedFilesHandler handler = new UnchangedFilesHandler(enabledConfig, prConfig, executingSensorContext);
assertThat(logTester.logs()).contains("Optimization for unchanged files not enabled because it's not an analysis of a branch with a previous analysis");
@Test
public void not_active_if_using_different_reference() {
+ logTester.setLevel(Level.DEBUG);
BranchConfiguration differentRefConfig = branchConfiguration("a", "b", false);
UnchangedFilesHandler handler = new UnchangedFilesHandler(enabledConfig, differentRefConfig, executingSensorContext);
assertThat(logTester.logs()).contains("Optimization for unchanged files not enabled because it's not an analysis of a branch with a previous analysis");
import org.junit.rules.DisableOnDebug;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
}
@Test
- public void do_log() {
+ public void do_log() throws InterruptedException {
+ logTester.setLevel(Level.DEBUG);
underTest.start("start");
underTest.message("Some message");
boolean logged = false;
+ Thread.sleep(1000);
while (!logged) {
logged = logTester.logs().contains("Some message");
}
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
+import org.slf4j.event.Level;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.scm.BlameLine;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.scan.filesystem.PathResolver;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.scm.git.strategy.BlameStrategy;
import org.sonar.scm.git.strategy.DefaultBlameStrategy.BlameAlgorithmEnum;
@Test
public void use_jgit_if_native_git_disabled() throws IOException {
+ logTester.setLevel(Level.DEBUG);
NativeGitBlameCommand gitCmd = new NativeGitBlameCommand("invalidcommandnotfound", System2.INSTANCE, processWrapperFactory);
BlameCommand blameCmd = new CompositeBlameCommand(analysisWarnings, pathResolver, jGitBlameCommand, gitCmd, (p, f) -> GIT_NATIVE_BLAME);
File projectDir = createNewTempFolder();
TestBlameOutput output = new TestBlameOutput();
blameCmd.blame(input, output);
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("Using GIT_NATIVE_BLAME strategy to blame files");
+ assertThat(logTester.logs(Level.DEBUG)).contains("Using GIT_NATIVE_BLAME strategy to blame files");
assertThat(output.blame).hasSize(1);
assertThat(output.blame.get(input.filesToBlame().iterator().next())).hasSize(29);
}
@Test
public void fallback_to_jgit_if_native_git_fails() throws Exception {
+ logTester.setLevel(Level.DEBUG);
NativeGitBlameCommand gitCmd = mock(NativeGitBlameCommand.class);
BlameCommand blameCmd = new CompositeBlameCommand(analysisWarnings, pathResolver, jGitBlameCommand, gitCmd, (p, f) -> GIT_NATIVE_BLAME);
File projectDir = createNewTempFolder();
TestBlameOutput output = new TestBlameOutput();
blameCmd.blame(input, output);
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("Using GIT_NATIVE_BLAME strategy to blame files");
+ assertThat(logTester.logs(Level.DEBUG)).contains("Using GIT_NATIVE_BLAME strategy to blame files");
assertThat(output.blame).hasSize(1);
assertThat(output.blame.get(input.filesToBlame().iterator().next())).hasSize(29);
assertThat(output.blame).isEmpty();
verifyNoInteractions(jgit);
- assertThat(logTester.logs(LoggerLevel.WARN))
+ assertThat(logTester.logs(Level.WARN))
.contains("Could not find HEAD commit");
}
blameCommand.blame(input, output);
assertThat(logTester.logs())
- .haveAtLeastOne(new Condition<>(s-> s.startsWith("This git repository references another local repository which is not well supported"),
+ .haveAtLeastOne(new Condition<>(s -> s.startsWith("This git repository references another local repository which is not well supported"),
"log for reference detected"));
// contains commits referenced from the old clone and commits in the new clone
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import static java.nio.charset.StandardCharsets.UTF_8;
.isFalse();
int expectedIncludedFiles = (int) Math.pow(child_folders_per_folder, folder_depth) + 1; // The .gitignore file is indexed
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains(expectedIncludedFiles + " non excluded files in this Git repository");
+ assertThat(logTester.logs(Level.DEBUG)).contains(expectedIncludedFiles + " non excluded files in this Git repository");
}
@Test
assertThat(underTest.isIgnored(projectDir.resolve("module1/folder_0_0/Foo.php"))).isFalse();
int expectedIncludedFiles = 6;
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains(expectedIncludedFiles + " non excluded files in this Git repository");
+ assertThat(logTester.logs(Level.DEBUG)).contains(expectedIncludedFiles + " non excluded files in this Git repository");
}
@Test
assertThat(underTest.isIgnored(projectDir.resolve("folder_0_0/Foo.php"))).isFalse();
// ignoring not cloned submodules
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("Git submodule [module1] found, but has not been cloned, skipping.");
+ assertThat(logTester.logs(Level.DEBUG)).contains("Git submodule [module1] found, but has not been cloned, skipping.");
int expectedIncludedFiles = 3;
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains(expectedIncludedFiles + " non excluded files in this Git repository");
+ assertThat(logTester.logs(Level.DEBUG)).contains(expectedIncludedFiles + " non excluded files in this Git repository");
}
@Test
.isTrue();
int expectedIncludedFiles = (int) Math.pow(child_folders_per_folder, folder_depth - 1);
- assertThat(logTester.logs(LoggerLevel.DEBUG)).contains(expectedIncludedFiles + " non excluded files in this Git repository");
+ assertThat(logTester.logs(Level.DEBUG)).contains(expectedIncludedFiles + " non excluded files in this Git repository");
}
private Path createGitRepoWithIgnore() throws IOException, GitAPIException {
import org.sonar.api.scan.filesystem.PathResolver;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogAndArguments;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogAndArguments;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.core.documentation.DocumentationLinkGenerator;
import org.sonar.scm.git.strategy.DefaultBlameStrategy;
import org.sonar.api.batch.scm.BlameLine;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
+import org.slf4j.event.Level;
import org.sonar.api.batch.scm.BlameLine;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
-import org.sonar.api.utils.log.LogTester;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.scm.git.ProcessWrapperFactory.ProcessWrapper;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void execution_on_windows_should_fallback_to_full_path() {
+ logTester.setLevel(Level.DEBUG);
System2 system2 = mock(System2.class);
when(system2.isOsWindows()).thenReturn(true);
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import org.sonar.api.utils.log.LogTester;
+import org.slf4j.event.Level;
+import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import static org.assertj.core.api.Assertions.assertThat;
@Test
public void should_log_error_output_in_debug_mode() throws IOException {
+ logTester.setLevel(Level.DEBUG);
var root = temp.newFolder().toPath();
var processWrapper = underTest.create(root, v -> {}, "git", "blame");
assertThatThrownBy(() -> processWrapper.execute())
.isInstanceOf(IllegalStateException.class);
- assertThat(logTester.logs(LoggerLevel.DEBUG).get(0)).contains("fatal: not a git repository");
+ assertThat(logTester.logs(Level.DEBUG).get(0)).contains("fatal: not a git repository");
}
}
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
+import org.slf4j.event.Level;
import org.sonar.api.config.Configuration;
-import org.sonar.api.utils.log.LogTester;
-import org.sonar.api.utils.log.LoggerLevel;
+import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
assertThat(underTest.getBlameAlgorithm(1, 10)).isEqualTo(GIT_NATIVE_BLAME);
assertThat(underTest.getBlameAlgorithm(1, 11)).isEqualTo(GIT_FILES_BLAME);
-
assertThat(underTest.getBlameAlgorithm(0, 10)).isEqualTo(GIT_NATIVE_BLAME);
- assertThat(logTester.logs(LoggerLevel.WARN)).contains("Available processors are 0. Falling back to native git blame");
+ assertThat(logTester.logs(Level.WARN)).contains("Available processors are 0. Falling back to native git blame");
}
}