From 076a7616dda6fb07d9c779a55506494c20bfe9d4 Mon Sep 17 00:00:00 2001 From: Dejan Milisavljevic <130993898+dejan-milisavljevic-sonarsource@users.noreply.github.com> Date: Wed, 21 Feb 2024 11:20:59 +0100 Subject: [PATCH] SONAR-21643 Convert some parameterized tests to Junit 5 (#10666) --- sonar-scanner-engine/build.gradle | 11 ++ .../org/sonar/scanner/ProjectInfoTest.java | 53 ++++---- .../qualitygate/QualityGateCheckTest.java | 109 +++++++++------- .../scan/ProjectReactorValidatorTest.java | 120 ++++++++---------- .../scanner/scm/ScmConfigurationTest.java | 75 +++++------ .../scm/git/CompositeBlameCommandIT.java | 37 +++--- 6 files changed, 200 insertions(+), 205 deletions(-) diff --git a/sonar-scanner-engine/build.gradle b/sonar-scanner-engine/build.gradle index 1e29e7f0400..14d071603ef 100644 --- a/sonar-scanner-engine/build.gradle +++ b/sonar-scanner-engine/build.gradle @@ -53,12 +53,18 @@ dependencies { testImplementation 'com.tngtech.java:junit-dataprovider' testImplementation 'commons-io:commons-io' testImplementation 'junit:junit' + testImplementation 'org.junit.jupiter:junit-jupiter-api' + testImplementation 'org.junit.jupiter:junit-jupiter-params' testImplementation 'org.assertj:assertj-core' testImplementation 'com.fasterxml.staxmate:staxmate' testImplementation 'org.hamcrest:hamcrest-core' testImplementation 'org.mockito:mockito-core' + testImplementation 'org.mockito:mockito-junit-jupiter' api 'org.sonarsource.api.plugin:sonar-plugin-api-test-fixtures' testImplementation project(':plugins:sonar-xoo-plugin') + + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' + testRuntimeOnly 'org.junit.vintage:junit-vintage-engine' } license { @@ -79,3 +85,8 @@ publishing { } } } + +test { + // Enabling the JUnit Platform (see https://github.com/junit-team/junit5-samples/tree/master/junit5-migration-gradle) + useJUnitPlatform() +} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java index a5451ee0ec1..db839190139 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/ProjectInfoTest.java @@ -19,9 +19,6 @@ */ package org.sonar.scanner; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.time.Clock; import java.time.LocalDate; import java.time.OffsetDateTime; @@ -30,8 +27,11 @@ import java.time.ZoneOffset; import java.util.Date; import javax.annotation.Nullable; import org.apache.commons.lang.RandomStringUtils; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EmptySource; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.NullSource; import org.sonar.api.CoreProperties; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.MessageException; @@ -41,15 +41,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; -@RunWith(DataProviderRunner.class) -public class ProjectInfoTest { +class ProjectInfoTest { - private MapSettings settings = new MapSettings(); - private Clock clock = mock(Clock.class); - private ProjectInfo underTest = new ProjectInfo(settings.asConfig(), clock); + private final MapSettings settings = new MapSettings(); + private final Clock clock = mock(Clock.class); + private final ProjectInfo underTest = new ProjectInfo(settings.asConfig(), clock); @Test - public void testSimpleDateTime() { + void testSimpleDateTime() { OffsetDateTime date = OffsetDateTime.of(2017, 1, 1, 12, 13, 14, 0, ZoneOffset.ofHours(2)); settings.appendProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01T12:13:14+0200"); settings.appendProperty(CoreProperties.PROJECT_VERSION_PROPERTY, "version"); @@ -61,7 +60,7 @@ public class ProjectInfoTest { } @Test - public void testSimpleDate() { + void testSimpleDate() { LocalDate date = LocalDate.of(2017, 1, 1); settings.appendProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); @@ -72,7 +71,7 @@ public class ProjectInfoTest { } @Test - public void emptyDate() { + void emptyDate() { settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, ""); settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, "version"); @@ -81,7 +80,7 @@ public class ProjectInfoTest { } @Test - public void fail_with_too_long_version() { + void fail_with_too_long_version() { String version = randomAlphabetic(101); settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, version); @@ -93,7 +92,7 @@ public class ProjectInfoTest { } @Test - public void fail_with_too_long_buildString() { + void fail_with_too_long_buildString() { String buildString = randomAlphabetic(101); settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.BUILD_STRING_PROPERTY, buildString); @@ -104,9 +103,9 @@ public class ProjectInfoTest { "The maximum length is 100 characters."); } - @Test - @UseDataProvider("emptyOrNullString") - public void getProjectVersion_is_empty_if_property_is_empty_or_null(@Nullable String projectVersion) { + @ParameterizedTest + @NullAndEmptySource + void getProjectVersion_is_empty_if_property_is_empty_or_null(@Nullable String projectVersion) { settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, projectVersion); @@ -116,7 +115,7 @@ public class ProjectInfoTest { } @Test - public void getProjectVersion_contains_value_of_property() { + void getProjectVersion_contains_value_of_property() { String value = RandomStringUtils.randomAlphabetic(10); settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.PROJECT_VERSION_PROPERTY, value); @@ -126,9 +125,9 @@ public class ProjectInfoTest { assertThat(underTest.getProjectVersion()).contains(value); } - @Test - @UseDataProvider("emptyOrNullString") - public void getBuildString_is_empty_if_property_is_empty_or_null(@Nullable String buildString) { + @ParameterizedTest + @NullAndEmptySource + void getBuildString_is_empty_if_property_is_empty_or_null(@Nullable String buildString) { settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.BUILD_STRING_PROPERTY, buildString); @@ -138,7 +137,7 @@ public class ProjectInfoTest { } @Test - public void getBuildString_contains_value_of_property() { + void getBuildString_contains_value_of_property() { String value = RandomStringUtils.randomAlphabetic(10); settings.setProperty(CoreProperties.PROJECT_DATE_PROPERTY, "2017-01-01"); settings.setProperty(CoreProperties.BUILD_STRING_PROPERTY, value); @@ -147,12 +146,4 @@ public class ProjectInfoTest { assertThat(underTest.getBuildString()).contains(value); } - - @DataProvider - public static Object[][] emptyOrNullString() { - return new Object[][] { - {""}, - {null}, - }; - } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/qualitygate/QualityGateCheckTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/qualitygate/QualityGateCheckTest.java index 2c8b7985c9c..89013ebcbc9 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/qualitygate/QualityGateCheckTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/qualitygate/QualityGateCheckTest.java @@ -19,17 +19,19 @@ */ package org.sonar.scanner.qualitygate; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.Answers; import org.mockito.ArgumentMatcher; -import org.mockito.Mockito; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.event.Level; -import org.sonar.api.testfixtures.log.LogTester; +import org.sonar.api.testfixtures.log.LogTesterJUnit5; import org.sonar.api.utils.MessageException; import org.sonar.scanner.bootstrap.DefaultScannerWsClient; import org.sonar.scanner.bootstrap.GlobalAnalysisMode; @@ -48,30 +50,34 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(DataProviderRunner.class) -public class QualityGateCheckTest { - private DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class, Mockito.RETURNS_DEEP_STUBS); - private GlobalAnalysisMode analysisMode = mock(GlobalAnalysisMode.class); - private CeTaskReportDataHolder reportMetadataHolder = mock(CeTaskReportDataHolder.class); - private ScanProperties properties = mock(ScanProperties.class); - - @Rule - public LogTester logTester = new LogTester(); - - QualityGateCheck underTest = new QualityGateCheck(wsClient, analysisMode, reportMetadataHolder, properties); - - @Before - public void before() { +@ExtendWith(MockitoExtension.class) +class QualityGateCheckTest { + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private DefaultScannerWsClient wsClient; + @Mock + private GlobalAnalysisMode analysisMode; + @Mock + private CeTaskReportDataHolder reportMetadataHolder; + @Mock + private ScanProperties properties; + + @RegisterExtension + private final LogTesterJUnit5 logTester = new LogTesterJUnit5(); + + private QualityGateCheck underTest; + + @BeforeEach + void before() { + underTest = new QualityGateCheck(wsClient, analysisMode, reportMetadataHolder, properties); logTester.setLevel(Level.DEBUG); - when(reportMetadataHolder.getCeTaskId()).thenReturn("task-1234"); - when(reportMetadataHolder.getDashboardUrl()).thenReturn("http://dashboard-url.com"); } @Test - public void should_pass_if_quality_gate_ok() { + void should_pass_if_quality_gate_ok() { + when(reportMetadataHolder.getCeTaskId()).thenReturn("task-1234"); + when(reportMetadataHolder.getDashboardUrl()).thenReturn("http://dashboard-url.com"); when(properties.shouldWaitForQualityGate()).thenReturn(true); when(properties.qualityGateWaitTimeout()).thenReturn(5); @@ -94,7 +100,9 @@ public class QualityGateCheckTest { } @Test - public void should_wait_and_then_pass_if_quality_gate_ok() { + void should_wait_and_then_pass_if_quality_gate_ok() { + when(reportMetadataHolder.getCeTaskId()).thenReturn("task-1234"); + when(reportMetadataHolder.getDashboardUrl()).thenReturn("http://dashboard-url.com"); when(properties.shouldWaitForQualityGate()).thenReturn(true); when(properties.qualityGateWaitTimeout()).thenReturn(10); @@ -114,7 +122,9 @@ public class QualityGateCheckTest { } @Test - public void should_fail_if_quality_gate_none() { + void should_fail_if_quality_gate_none() { + when(reportMetadataHolder.getCeTaskId()).thenReturn("task-1234"); + when(reportMetadataHolder.getDashboardUrl()).thenReturn("http://dashboard-url.com"); when(properties.shouldWaitForQualityGate()).thenReturn(true); when(properties.qualityGateWaitTimeout()).thenReturn(5); @@ -132,7 +142,9 @@ public class QualityGateCheckTest { } @Test - public void should_fail_if_quality_gate_error() { + void should_fail_if_quality_gate_error() { + when(reportMetadataHolder.getCeTaskId()).thenReturn("task-1234"); + when(reportMetadataHolder.getDashboardUrl()).thenReturn("http://dashboard-url.com"); when(properties.shouldWaitForQualityGate()).thenReturn(true); when(properties.qualityGateWaitTimeout()).thenReturn(5); @@ -150,7 +162,9 @@ public class QualityGateCheckTest { } @Test - public void should_wait_and_then_fail_if_quality_gate_error() { + void should_wait_and_then_fail_if_quality_gate_error() { + when(reportMetadataHolder.getCeTaskId()).thenReturn("task-1234"); + when(reportMetadataHolder.getDashboardUrl()).thenReturn("http://dashboard-url.com"); when(properties.shouldWaitForQualityGate()).thenReturn(true); when(properties.qualityGateWaitTimeout()).thenReturn(10); @@ -169,7 +183,9 @@ public class QualityGateCheckTest { } @Test - public void should_fail_if_quality_gate_timeout_exceeded() { + void should_fail_if_quality_gate_timeout_exceeded() { + when(reportMetadataHolder.getCeTaskId()).thenReturn("task-1234"); + when(reportMetadataHolder.getDashboardUrl()).thenReturn("http://dashboard-url.com"); when(properties.shouldWaitForQualityGate()).thenReturn(true); when(properties.qualityGateWaitTimeout()).thenReturn(1); @@ -184,7 +200,7 @@ public class QualityGateCheckTest { } @Test - public void should_fail_if_cant_call_ws_for_quality_gate() { + void should_fail_if_cant_call_ws_for_quality_gate() { when(properties.shouldWaitForQualityGate()).thenReturn(true); when(properties.qualityGateWaitTimeout()).thenReturn(5); @@ -201,7 +217,7 @@ public class QualityGateCheckTest { } @Test - public void should_fail_if_invalid_response_from_quality_gate_ws() { + void should_fail_if_invalid_response_from_quality_gate_ws() { when(properties.shouldWaitForQualityGate()).thenReturn(true); when(properties.qualityGateWaitTimeout()).thenReturn(5); @@ -221,7 +237,7 @@ public class QualityGateCheckTest { } @Test - public void should_fail_if_cant_call_ws_for_task() { + void should_fail_if_cant_call_ws_for_task() { when(properties.shouldWaitForQualityGate()).thenReturn(true); when(properties.qualityGateWaitTimeout()).thenReturn(5); @@ -235,7 +251,7 @@ public class QualityGateCheckTest { } @Test - public void should_fail_if_invalid_response_from_ws_task() { + void should_fail_if_invalid_response_from_ws_task() { when(properties.shouldWaitForQualityGate()).thenReturn(true); when(properties.qualityGateWaitTimeout()).thenReturn(5); @@ -252,9 +268,9 @@ public class QualityGateCheckTest { .hasMessage("Failed to parse response from ce-task-url"); } - @Test - @UseDataProvider("ceTaskNotSucceededStatuses") - public void should_fail_if_task_not_succeeded(TaskStatus taskStatus) { + @ParameterizedTest + @MethodSource("ceTaskNotSucceededStatuses") + void should_fail_if_task_not_succeeded(TaskStatus taskStatus) { when(properties.shouldWaitForQualityGate()).thenReturn(true); when(properties.qualityGateWaitTimeout()).thenReturn(5); @@ -282,7 +298,7 @@ public class QualityGateCheckTest { } @Test - public void should_skip_wait_if_disabled() { + void should_skip_wait_if_disabled() { when(properties.shouldWaitForQualityGate()).thenReturn(false); underTest.start(); @@ -294,7 +310,7 @@ public class QualityGateCheckTest { } @Test - public void should_fail_if_enabled_with_medium_test() { + void should_fail_if_enabled_with_medium_test() { when(properties.shouldWaitForQualityGate()).thenReturn(true); when(analysisMode.isMediumTest()).thenReturn(true); @@ -319,12 +335,11 @@ public class QualityGateCheckTest { return qualityGateWsResponse; } - @DataProvider - public static Object[][] ceTaskNotSucceededStatuses() { - return new Object[][] { - {TaskStatus.CANCELED}, - {TaskStatus.FAILED}, - }; + private static Stream ceTaskNotSucceededStatuses() { + return Stream.of( + TaskStatus.CANCELED, + TaskStatus.FAILED + ); } private static class WsRequestPathMatcher implements ArgumentMatcher { diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectReactorValidatorTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectReactorValidatorTest.java index 3b212377692..e24235de671 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectReactorValidatorTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectReactorValidatorTest.java @@ -19,22 +19,19 @@ */ package org.sonar.scanner.scan; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import java.util.Optional; import java.util.function.Consumer; +import java.util.stream.Stream; import javax.annotation.Nullable; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.sonar.api.CoreProperties; import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.bootstrap.ProjectReactor; import org.sonar.api.utils.MessageException; -import org.sonar.api.testfixtures.log.LogTester; import org.sonar.core.config.ScannerProperties; import org.sonar.core.documentation.DefaultDocumentationLinkGenerator; import org.sonar.scanner.ProjectInfo; @@ -48,11 +45,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.core.config.ScannerProperties.BRANCHES_DOC_LINK_SUFFIX; -@RunWith(DataProviderRunner.class) -public class ProjectReactorValidatorTest { - - @Rule - public LogTester logTester = new LogTester(); +class ProjectReactorValidatorTest { private final GlobalConfiguration settings = mock(GlobalConfiguration.class); private final ProjectInfo projectInfo = mock(ProjectInfo.class); @@ -60,41 +53,40 @@ public class ProjectReactorValidatorTest { private final ProjectReactorValidator underTest = new ProjectReactorValidator(settings, defaultDocumentationLinkGenerator); private static final String LINK_TO_DOC = "link_to_documentation"; - @Before - public void prepare() { + @BeforeEach + void prepare() { when(settings.get(anyString())).thenReturn(Optional.empty()); when(defaultDocumentationLinkGenerator.getDocumentationLink(BRANCHES_DOC_LINK_SUFFIX)).thenReturn(LINK_TO_DOC); } - @Test - @UseDataProvider("validKeys") - public void not_fail_with_valid_key(String validKey) { + @ParameterizedTest + @MethodSource("validKeys") + void not_fail_with_valid_key(String validKey) { ProjectReactor projectReactor = createProjectReactor(validKey); underTest.validate(projectReactor); } - @DataProvider - public static Object[][] validKeys() { - return new Object[][] { - {"foo"}, - {"123foo"}, - {"foo123"}, - {"1Z3"}, - {"a123"}, - {"123a"}, - {"1:2"}, - {"3-3"}, - {"-:"}, - {"Foobar2"}, - {"foo.bar"}, - {"foo-bar"}, - {"foo:bar"}, - {"foo_bar"} - }; + private static Stream validKeys() { + return Stream.of( + "foo", + "123foo", + "foo123", + "1Z3", + "a123", + "123a", + "1:2", + "3-3", + "-:", + "Foobar2", + "foo.bar", + "foo-bar", + "foo:bar", + "foo_bar" + ); } @Test - public void fail_when_invalid_key() { + void fail_when_invalid_key() { ProjectReactor reactor = createProjectReactor("foo$bar"); assertThatThrownBy(() -> underTest.validate(reactor)) @@ -104,7 +96,7 @@ public class ProjectReactorValidatorTest { } @Test - public void fail_when_only_digits() { + void fail_when_only_digits() { ProjectReactor reactor = createProjectReactor("12345"); assertThatThrownBy(() -> underTest.validate(reactor)) @@ -114,7 +106,7 @@ public class ProjectReactorValidatorTest { } @Test - public void fail_when_backslash_in_key() { + void fail_when_backslash_in_key() { ProjectReactor reactor = createProjectReactor("foo\\bar"); assertThatThrownBy(() -> underTest.validate(reactor)) @@ -124,7 +116,7 @@ public class ProjectReactorValidatorTest { } @Test - public void fail_when_branch_name_is_specified_but_branch_plugin_not_present() { + void fail_when_branch_name_is_specified_but_branch_plugin_not_present() { ProjectDefinition def = ProjectDefinition.create().setProperty(CoreProperties.PROJECT_KEY_PROPERTY, "foo"); ProjectReactor reactor = new ProjectReactor(def); @@ -137,7 +129,7 @@ public class ProjectReactorValidatorTest { } @Test - public void fail_when_pull_request_id_specified_but_branch_plugin_not_present() { + void fail_when_pull_request_id_specified_but_branch_plugin_not_present() { ProjectDefinition def = ProjectDefinition.create().setProperty(CoreProperties.PROJECT_KEY_PROPERTY, "foo"); ProjectReactor reactor = new ProjectReactor(def); @@ -150,7 +142,7 @@ public class ProjectReactorValidatorTest { } @Test - public void fail_when_pull_request_branch_is_specified_but_branch_plugin_not_present() { + void fail_when_pull_request_branch_is_specified_but_branch_plugin_not_present() { ProjectDefinition def = ProjectDefinition.create().setProperty(CoreProperties.PROJECT_KEY_PROPERTY, "foo"); ProjectReactor reactor = new ProjectReactor(def); @@ -163,7 +155,7 @@ public class ProjectReactorValidatorTest { } @Test - public void fail_when_pull_request_base_specified_but_branch_plugin_not_present() { + void fail_when_pull_request_base_specified_but_branch_plugin_not_present() { ProjectDefinition def = ProjectDefinition.create().setProperty(CoreProperties.PROJECT_KEY_PROPERTY, "foo"); ProjectReactor reactor = new ProjectReactor(def); @@ -175,42 +167,40 @@ public class ProjectReactorValidatorTest { LINK_TO_DOC)); } - @Test - @UseDataProvider("validVersions") - public void not_fail_with_valid_version(@Nullable String validVersion) { + @ParameterizedTest + @MethodSource("validVersions") + void not_fail_with_valid_version(@Nullable String validVersion) { when(projectInfo.getProjectVersion()).thenReturn(Optional.ofNullable(validVersion)); ProjectReactor projectReactor = createProjectReactor("foo"); underTest.validate(projectReactor); } - @DataProvider - public static Object[][] validVersions() { - return new Object[][] { - {null}, - {"1.0"}, - {"2017-10-16"}, - {randomAscii(100)} - }; + private static Stream validVersions() { + return Stream.of( + null, + "1.0", + "2017-10-16", + randomAscii(100) + ); } - @Test - @UseDataProvider("validBuildStrings") - public void not_fail_with_valid_buildString(@Nullable String validBuildString) { + @ParameterizedTest + @MethodSource("validBuildStrings") + void not_fail_with_valid_buildString(@Nullable String validBuildString) { when(projectInfo.getBuildString()).thenReturn(Optional.ofNullable(validBuildString)); ProjectReactor projectReactor = createProjectReactor("foo"); underTest.validate(projectReactor); } - @DataProvider - public static Object[][] validBuildStrings() { - return new Object[][] { - {null}, - {"1.0"}, - {"2017-10-16"}, - {randomAscii(100)} - }; + private static Stream validBuildStrings() { + return Stream.of( + null, + "1.0", + "2017-10-16", + randomAscii(100) + ); } private ProjectReactor createProjectReactor(String projectKey, Consumer... consumers) { diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scm/ScmConfigurationTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scm/ScmConfigurationTest.java index e0efa66f9f2..a0c6608606b 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scm/ScmConfigurationTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scm/ScmConfigurationTest.java @@ -19,26 +19,28 @@ */ package org.sonar.scanner.scm; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Optional; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; 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.testfixtures.log.LogTesterJUnit5; import org.sonar.api.utils.MessageException; -import org.sonar.api.testfixtures.log.LogTester; import org.sonar.core.config.ScannerProperties; import org.sonar.scanner.fs.InputModuleHierarchy; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.params.provider.Arguments.arguments; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.mock; @@ -49,8 +51,7 @@ import static org.mockito.Mockito.withSettings; import static org.sonar.scanner.scm.ScmConfiguration.MESSAGE_SCM_EXCLUSIONS_IS_DISABLED_BY_CONFIGURATION; import static org.sonar.scanner.scm.ScmConfiguration.MESSAGE_SCM_STEP_IS_DISABLED_BY_CONFIGURATION; -@RunWith(DataProviderRunner.class) -public class ScmConfigurationTest { +class ScmConfigurationTest { private final InputModuleHierarchy inputModuleHierarchy = mock(InputModuleHierarchy.class, withSettings().defaultAnswer(Answers.RETURNS_MOCKS)); private final AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); @@ -61,8 +62,8 @@ public class ScmConfigurationTest { private final ScmConfiguration underTest; - @Rule - public LogTester logTester = new LogTester(); + @RegisterExtension + private final LogTesterJUnit5 logTester = new LogTesterJUnit5(); public ScmConfigurationTest() { when(scmProvider.key()).thenReturn(scmProviderKey); @@ -71,7 +72,7 @@ public class ScmConfigurationTest { } @Test - public void do_not_register_warning_when_success_to_autodetect_scm_provider() { + void do_not_register_warning_when_success_to_autodetect_scm_provider() { when(scmProvider.supports(any())).thenReturn(true); underTest.start(); @@ -81,14 +82,14 @@ public class ScmConfigurationTest { } @Test - public void no_provider_if_no_provider_is_available() { + void no_provider_if_no_provider_is_available() { ScmConfiguration underTest = new ScmConfiguration(inputModuleHierarchy, settings, analysisWarnings); assertThat(underTest.provider()).isNull(); verifyNoInteractions(analysisWarnings); } @Test - public void register_warning_when_fail_to_detect_scm_provider() { + void register_warning_when_fail_to_detect_scm_provider() { underTest.start(); assertThat(underTest.provider()).isNull(); @@ -96,7 +97,7 @@ public class ScmConfigurationTest { } @Test - public void log_when_disabled() { + void log_when_disabled() { logTester.setLevel(Level.DEBUG); when(settings.getBoolean(CoreProperties.SCM_DISABLED_KEY)).thenReturn(Optional.of(true)); @@ -106,7 +107,7 @@ public class ScmConfigurationTest { } @Test - public void log_when_exclusion_is_disabled() { + void log_when_exclusion_is_disabled() { when(settings.getBoolean(CoreProperties.SCM_EXCLUSIONS_DISABLED_KEY)).thenReturn(Optional.of(true)); underTest.start(); @@ -114,9 +115,9 @@ public class ScmConfigurationTest { assertThat(logTester.logs()).contains(MESSAGE_SCM_EXCLUSIONS_IS_DISABLED_BY_CONFIGURATION); } - @Test - @UseDataProvider("scmDisabledProperty") - public void exclusion_is_disabled_by_property(boolean scmDisabled, boolean scmExclusionsDisabled, boolean isScmExclusionDisabled) { + @ParameterizedTest + @MethodSource("scmDisabledProperty") + void exclusion_is_disabled_by_property(boolean scmDisabled, boolean scmExclusionsDisabled, boolean isScmExclusionDisabled) { when(settings.getBoolean(CoreProperties.SCM_DISABLED_KEY)).thenReturn(Optional.of(scmDisabled)); when(settings.getBoolean(CoreProperties.SCM_EXCLUSIONS_DISABLED_KEY)).thenReturn(Optional.of(scmExclusionsDisabled)); @@ -125,18 +126,17 @@ public class ScmConfigurationTest { assertThat(underTest.isExclusionDisabled()).isEqualTo(isScmExclusionDisabled); } - @DataProvider - public static Object[][] scmDisabledProperty() { - return new Object[][] { - {true, true, true}, - {true, false, true}, - {false, true, true}, - {false, false, false} - }; + private static Stream scmDisabledProperty() { + return Stream.of( + arguments(true, true, true), + arguments(true, false, true), + arguments(false, true, true), + arguments(false, false, false) + ); } @Test - public void fail_when_multiple_scm_providers_claim_support() { + void fail_when_multiple_scm_providers_claim_support() { when(scmProvider.supports(any())).thenReturn(true); when(scmProvider.key()).thenReturn("key1", "key2"); @@ -151,7 +151,7 @@ public class ScmConfigurationTest { } @Test - public void fail_when_considerOldScmUrl_finds_invalid_provider_in_link() { + void fail_when_considerOldScmUrl_finds_invalid_provider_in_link() { when(settings.get(ScannerProperties.LINKS_SOURCES_DEV)).thenReturn(Optional.of("scm:invalid")); assertThatThrownBy(() -> underTest.start()) @@ -160,7 +160,7 @@ public class ScmConfigurationTest { } @Test - public void set_provider_from_valid_link() { + void set_provider_from_valid_link() { when(settings.get(ScannerProperties.LINKS_SOURCES_DEV)).thenReturn(Optional.of("scm:" + scmProviderKey)); underTest.start(); @@ -168,22 +168,13 @@ public class ScmConfigurationTest { assertThat(underTest.provider()).isSameAs(scmProvider); } - @Test - @UseDataProvider("malformedScmLinks") - public void dont_set_provider_from_links_if_malformed(String link) { + @ParameterizedTest + @ValueSource(strings = {"invalid prefix", "scm", "scm:"}) + void dont_set_provider_from_links_if_malformed(String link) { when(settings.get(ScannerProperties.LINKS_SOURCES_DEV)).thenReturn(Optional.of(link)); underTest.start(); assertThat(underTest.provider()).isNull(); } - - @DataProvider - public static Object[][] malformedScmLinks() { - return new Object[][] { - {"invalid prefix"}, - {"scm"}, - {"scm:"} - }; - } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scm/git/CompositeBlameCommandIT.java b/sonar-scanner-engine/src/test/java/org/sonar/scm/git/CompositeBlameCommandIT.java index 90856025796..c14c2f6b78e 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scm/git/CompositeBlameCommandIT.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scm/git/CompositeBlameCommandIT.java @@ -19,9 +19,6 @@ */ package org.sonar.scm.git; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -37,10 +34,10 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; @@ -52,11 +49,11 @@ import org.sonar.api.utils.System2; import org.sonar.scm.git.strategy.DefaultBlameStrategy.BlameAlgorithmEnum; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.arguments; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(DataProviderRunner.class) -public class CompositeBlameCommandIT { +class CompositeBlameCommandIT { private final AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); @@ -66,12 +63,12 @@ public class CompositeBlameCommandIT { private final ProcessWrapperFactory processWrapperFactory = new ProcessWrapperFactory(); private final NativeGitBlameCommand nativeGitBlameCommand = new NativeGitBlameCommand(System2.INSTANCE, processWrapperFactory); - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + private File temp; - @Test - @UseDataProvider("namesOfTheTestRepositoriesWithBlameAlgorithm") - public void testThatBlameAlgorithmOutputsTheSameDataAsGitNativeBlame(String folder, BlameAlgorithmEnum blameAlgorithm) throws Exception { + @ParameterizedTest + @MethodSource("namesOfTheTestRepositoriesWithBlameAlgorithm") + void testThatBlameAlgorithmOutputsTheSameDataAsGitNativeBlame(String folder, BlameAlgorithmEnum blameAlgorithm) throws Exception { CompositeBlameCommand underTest = new CompositeBlameCommand(analysisWarnings, new PathResolver(), jGitBlameCommand, nativeGitBlameCommand, (p, f) -> blameAlgorithm); TestBlameOutput output = new TestBlameOutput(); @@ -84,9 +81,9 @@ public class CompositeBlameCommandIT { assertBlameMatchesExpectedBlame(output.blame, gitFolder); } - @DataProvider - public static Object[][] namesOfTheTestRepositoriesWithBlameAlgorithm() { - List testCases = List.of("one-file-one-commit", + private static Stream namesOfTheTestRepositoriesWithBlameAlgorithm() { + List testCases = List.of( + "one-file-one-commit", "one-file-two-commits", "two-files-one-commit", "merge-commits", @@ -102,8 +99,8 @@ public class CompositeBlameCommandIT { List blameStrategies = Arrays.stream(BlameAlgorithmEnum.values()).toList(); return testCases.stream() - .flatMap(t -> blameStrategies.stream().map(b -> new Object[]{t, b})) - .toArray(Object[][]::new); + .flatMap(t -> blameStrategies.stream().map(b -> arguments(t, b))) + .toList().stream(); } @@ -155,7 +152,7 @@ public class CompositeBlameCommandIT { } private File unzipGitRepository(String repositoryName) throws IOException { - File gitFolderForEachTest = temp.newFolder().toPath().toRealPath(LinkOption.NOFOLLOW_LINKS).toFile(); + File gitFolderForEachTest = temp.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS).toFile(); Utils.javaUnzip(repositoryName + ".zip", gitFolderForEachTest); return gitFolderForEachTest.toPath().resolve(repositoryName).toFile(); } -- 2.39.5