diff --git a/pom.xml b/pom.xml index ca691fd14b..b83ef69955 100644 --- a/pom.xml +++ b/pom.xml @@ -45,6 +45,7 @@ false Max Low + false @@ -111,16 +112,6 @@ mailer - - org.jenkins-ci.plugins - junit - test - - - junit - junit - test - org.mockito mockito-core diff --git a/src/test/java/hudson/plugins/git/AbstractGitProject.java b/src/test/java/hudson/plugins/git/AbstractGitProject.java index 4b468ca9fd..8cd043afcd 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitProject.java +++ b/src/test/java/hudson/plugins/git/AbstractGitProject.java @@ -48,31 +48,40 @@ import java.util.List; import jenkins.MasterToSlaveFileCallable; + +import static org.junit.jupiter.api.Assertions.assertTrue; import org.eclipse.jgit.lib.Repository; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.JGitTool; -import static org.junit.Assert.assertTrue; - -import org.junit.Rule; - +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.jvnet.hudson.test.CaptureEnvironmentBuilder; -import org.jvnet.hudson.test.FlagRule; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Abstract class that provides convenience methods to configure projects. * @author Mark Waite */ -public class AbstractGitProject extends AbstractGitRepository { +@WithJenkins +class AbstractGitProject extends AbstractGitRepository { + + protected JenkinsRule r; - @Rule - public JenkinsRule r = new JenkinsRule(); + private String notifyCommitAccessControl; - @Rule - public FlagRule notifyCommitAccessControl = - new FlagRule<>(() -> GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL, x -> GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL = x); + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + notifyCommitAccessControl = GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL; + } + + @AfterEach + void afterEach() throws Exception { + GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL = notifyCommitAccessControl; + } protected FreeStyleProject setupProject(List branches, boolean authorOrCommitter) throws Exception { FreeStyleProject project = r.createFreeStyleProject(); @@ -208,7 +217,7 @@ protected FreeStyleProject setupProject(List repos, List() { + return build.getWorkspace().act(new MasterToSlaveFileCallable<>() { @Override public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { try (@SuppressWarnings("deprecation") // Local repository reference diff --git a/src/test/java/hudson/plugins/git/AbstractGitRepository.java b/src/test/java/hudson/plugins/git/AbstractGitRepository.java index 630693a25f..a24051205a 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitRepository.java +++ b/src/test/java/hudson/plugins/git/AbstractGitRepository.java @@ -8,11 +8,9 @@ import java.util.List; import hudson.plugins.git.util.GitUtilsTest; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.eclipse.jgit.util.SystemReader; -import org.junit.Before; -import org.junit.Rule; - -import hudson.EnvVars; +import org.junit.jupiter.api.BeforeEach; import hudson.model.TaskListener; import hudson.util.StreamTaskListener; @@ -30,16 +28,17 @@ * * @author Mark Waite */ +@WithGitSampleRepo public abstract class AbstractGitRepository { protected File testGitDir; protected GitClient testGitClient; - @Rule - public GitSampleRepoRule repo = new GitSampleRepoRule(); + protected GitSampleRepoRule repo; - @Before - public void createGitRepository() throws Exception { + @BeforeEach + protected void beforeEach(GitSampleRepoRule repo) throws Exception { + this.repo = repo; SystemReader.getInstance().getUserConfig().clear(); TaskListener listener = StreamTaskListener.fromStderr(); repo.init(); @@ -78,9 +77,4 @@ protected List remoteConfigs() throws IOException { list.add(new UserRemoteConfig(testGitDir.getAbsolutePath(), "origin", "", null)); return list; } - - /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ - private boolean isWindows() { - return File.pathSeparatorChar==';'; - } } diff --git a/src/test/java/hudson/plugins/git/AbstractGitTestCase.java b/src/test/java/hudson/plugins/git/AbstractGitTestCase.java index 5b3cd44207..cb41ee44fb 100644 --- a/src/test/java/hudson/plugins/git/AbstractGitTestCase.java +++ b/src/test/java/hudson/plugins/git/AbstractGitTestCase.java @@ -38,20 +38,22 @@ import java.util.List; import jenkins.MasterToSlaveFileCallable; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.util.SystemReader; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.JGitTool; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; import jenkins.plugins.git.GitSampleRepoRule; import org.jvnet.hudson.test.CaptureEnvironmentBuilder; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.stapler.DataBoundConstructor; /** @@ -60,12 +62,13 @@ * @author Kohsuke Kawaguchi * @author ishaaq */ +@WithJenkins +@WithGitSampleRepo public abstract class AbstractGitTestCase { - @Rule - public JenkinsRule r = new JenkinsRule(); - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + protected JenkinsRule r; + + protected GitSampleRepoRule sampleRepo; protected TaskListener listener; @@ -78,8 +81,11 @@ public abstract class AbstractGitTestCase { protected FilePath workspace; // aliases "gitDirPath" protected GitClient git; - @Before - public void setUp() throws Exception { + @BeforeEach + protected void beforeEach(JenkinsRule rule, GitSampleRepoRule repo) throws Exception { + r = rule; + sampleRepo = repo; + SystemReader.getInstance().getUserConfig().clear(); listener = StreamTaskListener.fromStderr(); @@ -246,7 +252,7 @@ protected FreeStyleProject setupSimpleProject(String branchString) throws Except protected FreeStyleBuild build(final FreeStyleProject project, final Result expectedResult, final String...expectedNewlyCommittedFiles) throws Exception { final FreeStyleBuild build = project.scheduleBuild2(0).get(); for(final String expectedNewlyCommittedFile : expectedNewlyCommittedFiles) { - assertTrue(expectedNewlyCommittedFile + " file not found in workspace", build.getWorkspace().child(expectedNewlyCommittedFile).exists()); + assertTrue(build.getWorkspace().child(expectedNewlyCommittedFile).exists(), expectedNewlyCommittedFile + " file not found in workspace"); } if(expectedResult != null) { r.assertBuildStatus(expectedResult, build); @@ -268,7 +274,7 @@ protected FreeStyleBuild build(final FreeStyleProject project, final String pare protected MatrixBuild build(final MatrixProject project, final Result expectedResult, final String...expectedNewlyCommittedFiles) throws Exception { final MatrixBuild build = project.scheduleBuild2(0).get(); for(final String expectedNewlyCommittedFile : expectedNewlyCommittedFiles) { - assertTrue(expectedNewlyCommittedFile + " file not found in workspace", build.getWorkspace().child(expectedNewlyCommittedFile).exists()); + assertTrue(build.getWorkspace().child(expectedNewlyCommittedFile).exists(), expectedNewlyCommittedFile + " file not found in workspace"); } if(expectedResult != null) { r.assertBuildStatus(expectedResult, build); @@ -294,19 +300,19 @@ protected void setVariables(Node node, EnvironmentVariablesNodeProperty.Entry... } protected String getHeadRevision(AbstractBuild build, final String branch) throws IOException, InterruptedException { - return build.getWorkspace().act(new MasterToSlaveFileCallable() { - public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { - try { - @SuppressWarnings("deprecation") // Local repository reference - org.eclipse.jgit.lib.Repository repo = Git.with(null, null).in(f).getClient().getRepository(); - ObjectId oid = repo.resolve("refs/heads/" + branch); - return oid.name(); - } catch (GitException e) { - throw new RuntimeException(e); - } + return build.getWorkspace().act(new MasterToSlaveFileCallable<>() { + public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { + try { + @SuppressWarnings("deprecation") // Local repository reference + org.eclipse.jgit.lib.Repository repo = Git.with(null, null).in(f).getClient().getRepository(); + ObjectId oid = repo.resolve("refs/heads/" + branch); + return oid.name(); + } catch (GitException e) { + throw new RuntimeException(e); } + } - }); + }); } public static class HasCredentialBuilder extends Builder { diff --git a/src/test/java/hudson/plugins/git/BranchSpecTest.java b/src/test/java/hudson/plugins/git/BranchSpecTest.java index 58d42e83e4..835cf16a5b 100644 --- a/src/test/java/hudson/plugins/git/BranchSpecTest.java +++ b/src/test/java/hudson/plugins/git/BranchSpecTest.java @@ -1,16 +1,18 @@ package hudson.plugins.git; import hudson.EnvVars; +import org.junit.jupiter.api.Test; + import java.util.HashMap; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; + import org.jvnet.hudson.test.Issue; -public class BranchSpecTest { - @Test - public void testMatch() { +class BranchSpecTest { + @Test + void testMatch() { BranchSpec l = new BranchSpec("master"); assertTrue(l.matches("origin/master")); assertFalse(l.matches("origin/something/master")); @@ -54,9 +56,9 @@ public void testMatch() { assertTrue(p.matches("origin/x")); assertFalse(p.matches("origin/my-branch/b1")); } - + @Test - public void testMatchEnv() { + void testMatchEnv() { HashMap envMap = new HashMap<>(); envMap.put("master", "master"); envMap.put("origin", "origin"); @@ -116,26 +118,28 @@ public void testMatchEnv() { } @Test - public void testEmptyName() { + void testEmptyName() { BranchSpec branchSpec = new BranchSpec(""); assertEquals("**",branchSpec.getName()); } - @Test(expected = IllegalArgumentException.class) - public void testNullName() { - BranchSpec branchSpec = new BranchSpec(null); + @Test + void testNullName() { + assertThrows(IllegalArgumentException.class, () -> { + BranchSpec branchSpec = new BranchSpec(null); + }); } - + @Test - public void testNameTrimming() { + void testNameTrimming() { BranchSpec branchSpec = new BranchSpec(" master "); assertEquals("master",branchSpec.getName()); branchSpec.setName(" other "); assertEquals("other",branchSpec.getName()); } - + @Test - public void testUsesRefsHeads() { + void testUsesRefsHeads() { BranchSpec m = new BranchSpec("refs/heads/j*n*"); assertTrue(m.matches("refs/heads/jenkins")); assertTrue(m.matches("refs/heads/jane")); @@ -144,9 +148,9 @@ public void testUsesRefsHeads() { assertFalse(m.matches("origin/jenkins")); assertFalse(m.matches("remote/origin/jane")); } - + @Test - public void testUsesJavaPatternDirectlyIfPrefixedWithColon() { + void testUsesJavaPatternDirectlyIfPrefixedWithColon() { BranchSpec m = new BranchSpec(":^(?!(origin/prefix)).*"); assertTrue(m.matches("origin")); assertTrue(m.matches("origin/master")); @@ -159,7 +163,7 @@ public void testUsesJavaPatternDirectlyIfPrefixedWithColon() { @Test @Issue("JENKINS-26842") - public void testUsesJavaPatternWithRepetition() { + void testUsesJavaPatternWithRepetition() { // match pattern from JENKINS-26842 BranchSpec m = new BranchSpec(":origin/release-\\d{8}"); assertTrue(m.matches("origin/release-20150101")); @@ -169,7 +173,7 @@ public void testUsesJavaPatternWithRepetition() { } @Test - public void testUsesJavaPatternToExcludeMultipleBranches() { + void testUsesJavaPatternToExcludeMultipleBranches() { BranchSpec m = new BranchSpec(":^(?!origin/master$|origin/develop$).*"); assertTrue(m.matches("origin/branch1")); assertTrue(m.matches("origin/branch-2")); @@ -193,7 +197,7 @@ private EnvVars createEnvMap(String key, String value) { */ @Test @Issue("JENKINS-6856") - public void testUsesEnvValueWithBraces() { + void testUsesEnvValueWithBraces() { EnvVars env = createEnvMap("GIT_BRANCH", "origin/master"); BranchSpec withBraces = new BranchSpec("${GIT_BRANCH}"); @@ -204,7 +208,7 @@ public void testUsesEnvValueWithBraces() { @Test @Issue("JENKINS-6856") - public void testUsesEnvValueWithoutBraces() { + void testUsesEnvValueWithoutBraces() { EnvVars env = createEnvMap("GIT_BRANCH", "origin/master"); BranchSpec withoutBraces = new BranchSpec("$GIT_BRANCH"); @@ -215,7 +219,7 @@ public void testUsesEnvValueWithoutBraces() { @Test @Issue("JENKINS-6856") - public void testUsesEnvValueWithToken() { + void testUsesEnvValueWithToken() { EnvVars env = createEnvMap("GIT_BRANCH", "origin/master"); BranchSpec withToken = new BranchSpec("${GIT_BRANCH,fullName=True}"); @@ -226,7 +230,7 @@ public void testUsesEnvValueWithToken() { @Test @Issue("JENKINS-6856") - public void testUsesEnvValueWithTokenFalse() { + void testUsesEnvValueWithTokenFalse() { EnvVars env = createEnvMap("GIT_BRANCH", "origin/master"); BranchSpec withTokenFalse = new BranchSpec("${GIT_BRANCH,fullName=false}"); diff --git a/src/test/java/hudson/plugins/git/ChangelogToBranchOptionsTest.java b/src/test/java/hudson/plugins/git/ChangelogToBranchOptionsTest.java index 4ebe2d6d8e..ff5b9950c3 100644 --- a/src/test/java/hudson/plugins/git/ChangelogToBranchOptionsTest.java +++ b/src/test/java/hudson/plugins/git/ChangelogToBranchOptionsTest.java @@ -23,39 +23,34 @@ */ package hudson.plugins.git; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -public class ChangelogToBranchOptionsTest { - - private final ChangelogToBranchOptions options; - private final String compareRemote; - private final String compareTarget; +class ChangelogToBranchOptionsTest { - public ChangelogToBranchOptionsTest() { - compareRemote = "origin"; - compareTarget = "feature/new-thing"; - options = new ChangelogToBranchOptions(compareRemote, compareTarget); - } + private final String compareRemote = "origin"; + private final String compareTarget = "feature/new-thing"; + private final ChangelogToBranchOptions options = new ChangelogToBranchOptions(compareRemote, compareTarget); @Test - public void testGetCompareRemote() { + void testGetCompareRemote() { assertThat(options.getCompareRemote(), is(compareRemote)); } @Test - public void testGetCompareTarget() { + void testGetCompareTarget() { assertThat(options.getCompareTarget(), is(compareTarget)); } @Test - public void testGetRef() { + void testGetRef() { assertThat(options.getRef(), is(compareRemote + "/" + compareTarget)); } @Test - public void testAlternateConstructor() { + void testAlternateConstructor() { ChangelogToBranchOptions newOptions = new ChangelogToBranchOptions(options); assertThat(newOptions.getCompareRemote(), is(options.getCompareRemote())); assertThat(newOptions.getCompareTarget(), is(options.getCompareTarget())); diff --git a/src/test/java/hudson/plugins/git/CheckoutStepSnippetizerTest.java b/src/test/java/hudson/plugins/git/CheckoutStepSnippetizerTest.java index 2ba8e0154b..f8bd678b3a 100644 --- a/src/test/java/hudson/plugins/git/CheckoutStepSnippetizerTest.java +++ b/src/test/java/hudson/plugins/git/CheckoutStepSnippetizerTest.java @@ -33,9 +33,10 @@ import java.util.Random; import org.jenkinsci.plugins.workflow.cps.SnippetizerTester; import org.jenkinsci.plugins.workflow.steps.scm.GenericSCMStep; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Test workflow snippet generation for the checkout step. Workflow @@ -44,10 +45,10 @@ * * @author Mark Waite */ -public class CheckoutStepSnippetizerTest { +@WithJenkins +class CheckoutStepSnippetizerTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; private final Random random = new Random(); private final SnippetizerTester tester = new SnippetizerTester(r); @@ -75,10 +76,13 @@ public class CheckoutStepSnippetizerTest { /* Tested values common to many tests */ private final String remoteConfig = "userRemoteConfigs: [[url: '" + url + "']]"; - public CheckoutStepSnippetizerTest() throws Exception {} + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; + } @Test - public void checkoutSimplest() throws Exception { + void checkoutSimplest() throws Exception { tester.assertRoundTrip(checkoutStep, "checkout scmGit(" + junkBranches + junkExtensions @@ -91,7 +95,7 @@ public void checkoutSimplest() throws Exception { } @Test - public void checkoutNoPoll() throws Exception { + void checkoutNoPoll() throws Exception { checkoutStep.setPoll(false); tester.assertRoundTrip(checkoutStep, "checkout poll: false, scm: scmGit(" + junkBranches @@ -105,7 +109,7 @@ public void checkoutNoPoll() throws Exception { } @Test - public void checkoutNoChangelog() throws Exception { + void checkoutNoChangelog() throws Exception { checkoutStep.setChangelog(false); tester.assertRoundTrip(checkoutStep, "checkout changelog: false, scm: scmGit(" + junkBranches @@ -119,7 +123,7 @@ public void checkoutNoChangelog() throws Exception { } @Test - public void checkoutCredentials() throws Exception { + void checkoutCredentials() throws Exception { String myCredential = "my-credential"; UserRemoteConfig config = new UserRemoteConfig(url, remoteName, remoteRefspec, myCredential); List configList = new ArrayList(List.of(config)); @@ -137,7 +141,7 @@ public void checkoutCredentials() throws Exception { } @Test - public void checkoutBranch() throws Exception { + void checkoutBranch() throws Exception { String branch = "4.10.x"; List branchList = new ArrayList(List.of(new BranchSpec(branch))); GitSCM gitSCM = new GitSCM(userRemoteConfigList, branchList, browser, gitTool, extensionList); @@ -154,7 +158,7 @@ public void checkoutBranch() throws Exception { } @Test - public void checkoutSubmoduleSimplest() throws Exception { + void checkoutSubmoduleSimplest() throws Exception { GitSCM gitSCM = new GitSCM(url); List extensions = gitSCM.getExtensions(); extensions.add(new SubmoduleOption()); @@ -171,7 +175,7 @@ public void checkoutSubmoduleSimplest() throws Exception { } @Test - public void checkoutSubmoduleOldConstructorMinimalArgs() throws Exception { + void checkoutSubmoduleOldConstructorMinimalArgs() throws Exception { GitSCM gitSCM = new GitSCM(url); List extensions = gitSCM.getExtensions(); boolean disableSubmodules = false; @@ -194,7 +198,7 @@ public void checkoutSubmoduleOldConstructorMinimalArgs() throws Exception { } @Test - public void checkoutSubmoduleOldConstructorReferenceRepo() throws Exception { + void checkoutSubmoduleOldConstructorReferenceRepo() throws Exception { GitSCM gitSCM = new GitSCM(url); List extensions = gitSCM.getExtensions(); boolean disableSubmodules = false; @@ -217,7 +221,7 @@ public void checkoutSubmoduleOldConstructorReferenceRepo() throws Exception { } @Test - public void checkoutSubmoduleOldConstructorDisableSubmodules() throws Exception { + void checkoutSubmoduleOldConstructorDisableSubmodules() throws Exception { GitSCM gitSCM = new GitSCM(url); List extensions = gitSCM.getExtensions(); boolean disableSubmodules = true; // Only change from default values @@ -240,7 +244,7 @@ public void checkoutSubmoduleOldConstructorDisableSubmodules() throws Exception } @Test - public void checkoutTimeoutCheckoutDefault() throws Exception { + void checkoutTimeoutCheckoutDefault() throws Exception { GitSCM gitSCM = new GitSCM(url); List extensions = gitSCM.getExtensions(); Integer timeout = null; @@ -258,7 +262,7 @@ public void checkoutTimeoutCheckoutDefault() throws Exception { } @Test - public void checkoutTimeoutCheckoutNonDefault() throws Exception { + void checkoutTimeoutCheckoutNonDefault() throws Exception { GitSCM gitSCM = new GitSCM(url); List extensions = gitSCM.getExtensions(); Integer timeout = 347; @@ -276,7 +280,7 @@ public void checkoutTimeoutCheckoutNonDefault() throws Exception { } @Test - public void checkoutLargeFileSupport() throws Exception { + void checkoutLargeFileSupport() throws Exception { GitSCM gitSCM = new GitSCM(url); List extensions = gitSCM.getExtensions(); extensions.add(new GitLFSPull()); diff --git a/src/test/java/hudson/plugins/git/CliGitSCMTriggerLocalPollTest.java b/src/test/java/hudson/plugins/git/CliGitSCMTriggerLocalPollTest.java index 38c00e23bf..b6eaf1a9f4 100644 --- a/src/test/java/hudson/plugins/git/CliGitSCMTriggerLocalPollTest.java +++ b/src/test/java/hudson/plugins/git/CliGitSCMTriggerLocalPollTest.java @@ -3,8 +3,7 @@ import hudson.plugins.git.extensions.GitClientType; import hudson.plugins.git.extensions.impl.EnforceGitClient; -public class CliGitSCMTriggerLocalPollTest extends SCMTriggerTest -{ +class CliGitSCMTriggerLocalPollTest extends SCMTriggerTest { @Override protected EnforceGitClient getGitClient() diff --git a/src/test/java/hudson/plugins/git/CliGitSCMTriggerRemotePollTest.java b/src/test/java/hudson/plugins/git/CliGitSCMTriggerRemotePollTest.java index 43b2db913f..00e547bc61 100644 --- a/src/test/java/hudson/plugins/git/CliGitSCMTriggerRemotePollTest.java +++ b/src/test/java/hudson/plugins/git/CliGitSCMTriggerRemotePollTest.java @@ -9,7 +9,7 @@ * The isChangeExpected() method adjusts the tests to the difference between * local and remote polling. */ -public class CliGitSCMTriggerRemotePollTest extends SCMTriggerTest { +class CliGitSCMTriggerRemotePollTest extends SCMTriggerTest { @Override protected EnforceGitClient getGitClient() diff --git a/src/test/java/hudson/plugins/git/CredentialsUserRemoteConfigTest.java b/src/test/java/hudson/plugins/git/CredentialsUserRemoteConfigTest.java index 60763c11cc..1027e2f773 100644 --- a/src/test/java/hudson/plugins/git/CredentialsUserRemoteConfigTest.java +++ b/src/test/java/hudson/plugins/git/CredentialsUserRemoteConfigTest.java @@ -12,34 +12,38 @@ import java.util.Random; import jenkins.model.Jenkins; import jenkins.plugins.git.GitSampleRepoRule; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; -public class CredentialsUserRemoteConfigTest { +@WithJenkins +@WithGitSampleRepo +class CredentialsUserRemoteConfigTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + private GitSampleRepoRule sampleRepo; private CredentialsStore store = null; private boolean useSymbolForGitSCM = true; private Random random = new Random(); private String credential = "undefined-credential"; - @Before - public void enableSystemCredentialsProvider() { + @BeforeEach + void beforeEach(JenkinsRule rule, GitSampleRepoRule repo) throws Exception { + r = rule; + sampleRepo = repo; + SystemCredentialsProvider.getInstance().setDomainCredentialsMap( Collections.singletonMap(Domain.global(), Collections.emptyList())); for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.get())) { @@ -49,23 +53,14 @@ public void enableSystemCredentialsProvider() { } } assertThat("The system credentials provider is enabled", store, notNullValue()); - } - @Before - public void chooseSymbolForGitSCM() { /* Use the 'scmGit' symbol instead of '$class: GitSCM */ useSymbolForGitSCM = random.nextBoolean(); - } - @Before - public void generateCredentialID() { credential = "credential-id-" + (100 + random.nextInt(900)); - } - @Before - public void initSampleRepo() throws Exception { sampleRepo.init(); - assertTrue("Failed to create src dir in sample repo", sampleRepo.mkdirs("src")); + assertTrue(sampleRepo.mkdirs("src"), "Failed to create src dir in sample repo"); sampleRepo.write("src/sample.txt", "Contents of src/sample.txt"); sampleRepo.git("add", "src/sample.txt"); sampleRepo.git("commit", "-m", "Add src/sample.txt to sample repo"); @@ -269,7 +264,7 @@ private String randomPipelineCheckoutExtras() throws Exception { @Issue("JENKINS-30515") @Test - public void checkoutWithValidCredentials() throws Exception { + void checkoutWithValidCredentials() throws Exception { store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, credential)); store.save(); @@ -280,7 +275,7 @@ public void checkoutWithValidCredentials() throws Exception { @Issue("JENKINS-30515") @Test - public void checkoutWithDifferentCredentials() throws Exception { + void checkoutWithDifferentCredentials() throws Exception { store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "other")); store.save(); @@ -300,7 +295,7 @@ public void checkoutWithDifferentCredentials() throws Exception { @Issue("JENKINS-30515") @Test - public void checkoutWithInvalidCredentials() throws Exception { + void checkoutWithInvalidCredentials() throws Exception { String systemCredential = "system-credential-" + (100 + random.nextInt(900)); store.addCredentials(Domain.global(), createCredential(CredentialsScope.SYSTEM, systemCredential)); store.save(); @@ -320,7 +315,7 @@ public void checkoutWithInvalidCredentials() throws Exception { @Issue("JENKINS-30515") @Test - public void checkoutWithNoCredentialsStoredButUsed() throws Exception { + void checkoutWithNoCredentialsStoredButUsed() throws Exception { WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "node {\n" @@ -336,7 +331,7 @@ public void checkoutWithNoCredentialsStoredButUsed() throws Exception { @Issue("JENKINS-30515") @Test - public void checkoutWithNoCredentialsSpecified() throws Exception { + void checkoutWithNoCredentialsSpecified() throws Exception { WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "node {\n" diff --git a/src/test/java/hudson/plugins/git/FIPSModeUrlCheckTest.java b/src/test/java/hudson/plugins/git/FIPSModeUrlCheckTest.java index fbb5724e94..d43d682883 100644 --- a/src/test/java/hudson/plugins/git/FIPSModeUrlCheckTest.java +++ b/src/test/java/hudson/plugins/git/FIPSModeUrlCheckTest.java @@ -3,6 +3,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey; import com.cloudbees.plugins.credentials.CredentialsScope; @@ -17,6 +18,7 @@ import hudson.model.Result; import hudson.util.FormValidation; import java.io.File; +import java.io.IOException; import java.nio.file.Files; import java.util.List; import jenkins.branch.MultiBranchProject; @@ -29,26 +31,25 @@ import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject; import org.jetbrains.annotations.NotNull; -import org.junit.Assume; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.jvnet.hudson.test.RealJenkinsRule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.jvnet.hudson.test.junit.jupiter.RealJenkinsExtension; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.BindMode; -public class FIPSModeUrlCheckTest { +class FIPSModeUrlCheckTest { - @Rule public RealJenkinsRule rule = new RealJenkinsRule().omitPlugins("eddsa-api", "trilead-api", "git-tag-message") + @RegisterExtension + private final RealJenkinsExtension extension = new RealJenkinsExtension().omitPlugins("eddsa-api", "trilead-api", "git-tag-message") .javaOptions("-Djenkins.security.FIPS140.COMPLIANCE=true"); - @Rule - public TemporaryFolder directory = new TemporaryFolder(); - + @TempDir + private File directory; @Test - public void testFIPSLtsMethod() throws Throwable { - rule.then( r -> { + void testFIPSLtsMethod() throws Throwable { + extension.then(r -> { assertThat(GitSCMSource.isFIPSCompliantTLS(null, "http://github.com/cheese/wine"), is(true)); assertThat(GitSCMSource.isFIPSCompliantTLS("beer", "http://github.com/cheese/wine"), is(false)); assertThat(GitSCMSource.isFIPSCompliantTLS(null, "https://github.com/cheese/wine"), is(true)); @@ -61,8 +62,8 @@ public void testFIPSLtsMethod() throws Throwable { } @Test - public void testGitSCMSourceCheck() throws Throwable { - rule.then( r -> { + void testGitSCMSourceCheck() throws Throwable { + extension.then(r -> { SystemCredentialsProvider.getInstance() .getCredentials() .add(new UsernamePasswordCredentialsImpl( @@ -99,8 +100,8 @@ public void testGitSCMSourceCheck() throws Throwable { } @Test - public void testUserRemoteConfigCheck() throws Throwable { - Assume.assumeTrue(DockerClientFactory.instance().isDockerAvailable()); + void testUserRemoteConfigCheck() throws Throwable { + assumeTrue(DockerClientFactory.instance().isDockerAvailable()); // ssh with credentials all good try (GitServerContainer containerUnderTest = new GitServerContainer(GitServerVersions.V2_45.getDockerImageName()).withGitRepo("someRepo")) { @@ -127,7 +128,7 @@ public void testUserRemoteConfigCheck() throws Throwable { // we don't want the user part of the uri or jgit will use this user // and we want to be sure to test our implementation with dynamic user final String repoUrl = StringUtils.remove(containerUnderTest.getGitRepoURIAsSSH().toString(), "git@"); - rule.then( r -> { + extension.then(r -> { BasicSSHUserPrivateKey sshUserPrivateKey = getBasicSSHUserPrivateKey(privateKey, passphrase); SystemCredentialsProvider.getInstance().getCredentials().add(sshUserPrivateKey); SystemCredentialsProvider.getInstance() @@ -152,7 +153,7 @@ public void testUserRemoteConfigCheck() throws Throwable { assertThat(validation.kind, is(FormValidation.Kind.OK)); } - Assume.assumeTrue(DockerClientFactory.instance().isDockerAvailable()); + assumeTrue(DockerClientFactory.instance().isDockerAvailable()); { FormValidation validation = descriptor.doCheckUrl(p, sshUserPrivateKey.getId(), repoUrl); @@ -166,7 +167,7 @@ public void testUserRemoteConfigCheck() throws Throwable { new GitHttpServerContainer(GitServerVersions.V2_45.getDockerImageName())) { containerUnderTest.start(); String repoUri = containerUnderTest.getGitRepoURIAsHttp().toString(); - rule.then( r -> { + extension.then(r -> { FreeStyleProject p = r.createProject(FreeStyleProject.class, "mbp2"); UserRemoteConfig.DescriptorImpl descriptor = ExtensionList.lookupSingleton(UserRemoteConfig.DescriptorImpl.class); @@ -197,13 +198,13 @@ public List getPrivateKeys() { } @Test - public void gitStepTLSCheck() throws Throwable { - Assume.assumeTrue(DockerClientFactory.instance().isDockerAvailable()); + void gitStepTLSCheck() throws Throwable { + assumeTrue(DockerClientFactory.instance().isDockerAvailable()); try (GitHttpServerContainer containerUnderTest = new GitHttpServerContainer(GitServerVersions.V2_45.getDockerImageName())) { containerUnderTest.start(); // need to have at least on revision to avoid build failure - File tmp = directory.newFolder(); + File tmp = newFolder(directory, "junit"); Git git = Git.cloneRepository() .setURI(containerUnderTest.getGitRepoURIAsHttp().toString()) .setDirectory(tmp) @@ -217,7 +218,7 @@ public void gitStepTLSCheck() throws Throwable { git.commit().setMessage("add foo").call(); git.push().call(); String repoUri = containerUnderTest.getGitRepoURIAsHttp().toString(); - rule.then(r -> { + extension.then(r -> { WorkflowJob p = r.createProject(WorkflowJob.class, "some project"); { // http with creds rejected @@ -248,13 +249,13 @@ public void gitStepTLSCheck() throws Throwable { } @Test - public void checkoutStepTLSCheck() throws Throwable { - Assume.assumeTrue(DockerClientFactory.instance().isDockerAvailable()); + void checkoutStepTLSCheck() throws Throwable { + assumeTrue(DockerClientFactory.instance().isDockerAvailable()); try (GitHttpServerContainer containerUnderTest = new GitHttpServerContainer(GitServerVersions.V2_45.getDockerImageName())) { containerUnderTest.start(); // need to have at least on revision to avoid build failure - File tmp = directory.newFolder(); + File tmp = newFolder(directory, "junit"); Git git = Git.cloneRepository() .setURI(containerUnderTest.getGitRepoURIAsHttp().toString()) .setDirectory(tmp) @@ -268,7 +269,7 @@ public void checkoutStepTLSCheck() throws Throwable { git.commit().setMessage("add foo").call(); git.push().call(); String repoUri = containerUnderTest.getGitRepoURIAsHttp().toString(); - rule.then(r -> { + extension.then(r -> { WorkflowJob p = r.createProject(WorkflowJob.class, "some project"); { // http with creds rejected @@ -303,4 +304,13 @@ checkout scmGit(branches: [[name: 'master']], }); } } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/git/GitBranchSpecifierColumnTest.java b/src/test/java/hudson/plugins/git/GitBranchSpecifierColumnTest.java index 1113899fd4..caea90252b 100644 --- a/src/test/java/hudson/plugins/git/GitBranchSpecifierColumnTest.java +++ b/src/test/java/hudson/plugins/git/GitBranchSpecifierColumnTest.java @@ -24,24 +24,22 @@ package hudson.plugins.git; import hudson.model.Item; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.List; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Mark Waite */ -public class GitBranchSpecifierColumnTest { - - public GitBranchSpecifierColumnTest() { - } +class GitBranchSpecifierColumnTest { @Test - public void testGetBranchSpecifierNull() { + void testGetBranchSpecifierNull() { Item item = null; GitBranchSpecifierColumn branchSpecifierColumn = new GitBranchSpecifierColumn(); List result = branchSpecifierColumn.getBranchSpecifier(item); @@ -49,7 +47,7 @@ public void testGetBranchSpecifierNull() { } @Test - public void testBreakOutString() { + void testBreakOutString() { List branches = new ArrayList<>(); final String MASTER_BRANCH = "master"; branches.add(MASTER_BRANCH); @@ -61,7 +59,7 @@ public void testBreakOutString() { } @Test - public void testBreakOutStringEmpty() { + void testBreakOutStringEmpty() { List branches = new ArrayList<>(); GitBranchSpecifierColumn branchSpecifier = new GitBranchSpecifierColumn(); String result = branchSpecifier.breakOutString(branches); @@ -69,7 +67,7 @@ public void testBreakOutStringEmpty() { } @Test - public void testBreakOutStringNull() { + void testBreakOutStringNull() { List branches = null; GitBranchSpecifierColumn branchSpecifier = new GitBranchSpecifierColumn(); String result = branchSpecifier.breakOutString(branches); diff --git a/src/test/java/hudson/plugins/git/GitChangeLogParserTest.java b/src/test/java/hudson/plugins/git/GitChangeLogParserTest.java index 7686f02bd7..25c3c41317 100644 --- a/src/test/java/hudson/plugins/git/GitChangeLogParserTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeLogParserTest.java @@ -11,27 +11,25 @@ import java.io.FileWriter; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * Unit tests of {@link GitChangeLogParser} */ -public class GitChangeLogParserTest { +class GitChangeLogParserTest { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); + @TempDir + private File tmpFolder; private final String firstMessageTruncated = "123456789 123456789 123456789 123456789 123456789 123456789 123456789 1"; private final String firstMessage = firstMessageTruncated + " 345 789"; /* Test duplicate changes filtered from parsed CLI git change set list. */ @Test - public void testDuplicatesFilteredCliGit() throws Exception { + void testDuplicatesFilteredCliGit() throws Exception { GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).using("Default").in(new File(".")).getClient(); assertThat(gitClient, instanceOf(CliGitAPIImpl.class)); /* JENKINS-29977 notes that CLI git impl truncates summary message - confirm default behavior retained */ @@ -40,7 +38,7 @@ public void testDuplicatesFilteredCliGit() throws Exception { /* Test duplicate changes filtered from parsed JGit change set list. */ @Test - public void testDuplicatesFilteredJGit() throws Exception { + void testDuplicatesFilteredJGit() throws Exception { GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).using("jgit").in(new File(".")).getClient(); assertThat(gitClient, instanceOf(JGitAPIImpl.class)); /* JENKINS-29977 notes that JGit impl retains full summary message - confirm default behavior retained */ @@ -49,7 +47,7 @@ public void testDuplicatesFilteredJGit() throws Exception { private void generateDuplicateChanges(GitClient gitClient, String expectedMessage) throws Exception { GitChangeLogParser parser = new GitChangeLogParser(gitClient, true); - File log = tmpFolder.newFile(); + File log = File.createTempFile("junit", null, tmpFolder); try (FileWriter writer = new FileWriter(log)) { writer.write("commit 123abc456def\n"); writer.write(" " + firstMessage + "\n"); @@ -64,6 +62,6 @@ private void generateDuplicateChanges(GitClient gitClient, String expectedMessag assertNotNull(first); assertEquals("123abc456def", first.getId()); assertThat(first.getMsg(), is(expectedMessage)); - assertTrue("Temp file delete failed for " + log, log.delete()); + assertTrue(log.delete(), "Temp file delete failed for " + log); } } diff --git a/src/test/java/hudson/plugins/git/GitChangeSetBadArgsTest.java b/src/test/java/hudson/plugins/git/GitChangeSetBadArgsTest.java index 408310628a..dc886aef39 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetBadArgsTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetBadArgsTest.java @@ -4,16 +4,22 @@ import hudson.model.User; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Rule; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class GitChangeSetBadArgsTest { +@WithJenkins +class GitChangeSetBadArgsTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } private GitChangeSet createChangeSet(boolean authorOrCommitter, String name, String email) { String dataSource = authorOrCommitter ? "Author" : "Committer"; @@ -49,7 +55,7 @@ private GitChangeSet createCommitterChangeSet(String committerName, String commi private static final String DEGENERATE_EMAIL_ADDRESS = "@"; @Test - public void testFindOrCreateUserAuthorBadEmail() { + void testFindOrCreateUserAuthorBadEmail() { String authorName = "Bad Author Test 1"; GitChangeSet changeSet = createAuthorChangeSet(authorName, DEGENERATE_EMAIL_ADDRESS); assertEquals(User.getUnknown(), changeSet.findOrCreateUser(authorName, DEGENERATE_EMAIL_ADDRESS, false, false)); @@ -58,7 +64,7 @@ public void testFindOrCreateUserAuthorBadEmail() { } @Test - public void testFindOrCreateUserCommitterBadEmail() { + void testFindOrCreateUserCommitterBadEmail() { String committerName = "Bad Committer Test 2"; GitChangeSet changeSet = createCommitterChangeSet(committerName, DEGENERATE_EMAIL_ADDRESS); assertEquals(User.getUnknown(), changeSet.findOrCreateUser(committerName, DEGENERATE_EMAIL_ADDRESS, false, false)); @@ -67,7 +73,7 @@ public void testFindOrCreateUserCommitterBadEmail() { } @Test - public void testFindOrCreateUserEmptyAuthor() { + void testFindOrCreateUserEmptyAuthor() { String emptyAuthorName = ""; String incompleteAuthorEmail = "@test3.example.com"; GitChangeSet changeSet = createAuthorChangeSet(emptyAuthorName, incompleteAuthorEmail); @@ -77,7 +83,7 @@ public void testFindOrCreateUserEmptyAuthor() { } @Test - public void testFindOrCreateEmptyCommitter() { + void testFindOrCreateEmptyCommitter() { String emptyCommitterName = ""; String incompleteCommitterEmail = "@test4.example.com"; GitChangeSet changeSet = createCommitterChangeSet(emptyCommitterName, incompleteCommitterEmail); @@ -87,7 +93,7 @@ public void testFindOrCreateEmptyCommitter() { } @Test - public void testFindOrCreateUserEmptyAuthorEmail() { + void testFindOrCreateUserEmptyAuthorEmail() { String authorName = "Author Test 5"; String emptyAuthorEmail = ""; GitChangeSet changeSet = createAuthorChangeSet(authorName, emptyAuthorEmail); @@ -96,7 +102,7 @@ public void testFindOrCreateUserEmptyAuthorEmail() { } @Test - public void testFindOrCreateUserNullAuthorEmail() { + void testFindOrCreateUserNullAuthorEmail() { String authorName = "Author Test 6"; String emptyAuthorEmail = ""; GitChangeSet changeSet = createAuthorChangeSet(authorName, emptyAuthorEmail); @@ -105,7 +111,7 @@ public void testFindOrCreateUserNullAuthorEmail() { } @Test - public void testFindOrCreateUserEmptyCommitterEmail() { + void testFindOrCreateUserEmptyCommitterEmail() { String committerName = "Committer Test 7"; String emptyCommitterEmail = ""; GitChangeSet changeSet = createCommitterChangeSet(committerName, emptyCommitterEmail); @@ -114,7 +120,7 @@ public void testFindOrCreateUserEmptyCommitterEmail() { } @Test - public void testFindOrCreateUserNullCommitterEmail() { + void testFindOrCreateUserNullCommitterEmail() { String committerName = "Committer Test 8"; String emptyCommitterEmail = ""; GitChangeSet changeSet = createCommitterChangeSet(committerName, emptyCommitterEmail); diff --git a/src/test/java/hudson/plugins/git/GitChangeSetBasicTest.java b/src/test/java/hudson/plugins/git/GitChangeSetBasicTest.java index 898d0f9736..5f72bdb3b8 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetBasicTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetBasicTest.java @@ -1,16 +1,17 @@ package hudson.plugins.git; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.Collections; import static hudson.plugins.git.GitChangeSet.TRUNCATE_LIMIT; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertEquals; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -public class GitChangeSetBasicTest { +class GitChangeSetBasicTest { private GitChangeSet genChangeSet(boolean authorOrCommitter, boolean useLegacyFormat) { return GitChangeSetUtil.genChangeSet(authorOrCommitter, useLegacyFormat, true); @@ -21,47 +22,47 @@ private GitChangeSet genChangeSet(boolean authorOrCommitter, boolean useLegacyFo } @Test - public void testLegacyChangeSet() { + void testLegacyChangeSet() { GitChangeSet gitChangeSet = GitChangeSetUtil.genChangeSet(false, true, false, GitChangeSetUtil.COMMIT_TITLE ,false); GitChangeSetUtil.assertChangeSet( gitChangeSet ); } @Test - public void testChangeSet() { + void testChangeSet() { GitChangeSetUtil.assertChangeSet(genChangeSet(false, false)); } @Test - public void testChangeSetNoParent() { + void testChangeSetNoParent() { GitChangeSet changeSet = genChangeSet(false, false, false); GitChangeSetUtil.assertChangeSet(changeSet); assertNull(changeSet.getParentCommit()); } @Test - public void testCommitter() { + void testCommitter() { assertEquals(GitChangeSetUtil.COMMITTER_NAME, genChangeSet(false, false).getAuthorName()); assertEquals(GitChangeSetUtil.COMMITTER_EMAIL, genChangeSet(false, false).getAuthorEmail()); } @Test - public void testAuthor() { + void testAuthor() { assertEquals(GitChangeSetUtil.AUTHOR_NAME, genChangeSet(true, false).getAuthorName()); assertEquals(GitChangeSetUtil.AUTHOR_EMAIL, genChangeSet(true, false).getAuthorEmail()); } @Test - public void testGetDate() { + void testGetDate() { assertEquals("1970-01-15T06:56:08-0600", genChangeSet(true, false).getDate()); } @Test - public void testGetTimestamp() { + void testGetTimestamp() { assertEquals(1256168000L, genChangeSet(true, false).getTimestamp()); } @Test - public void testInvalidDate() { + void testInvalidDate() { final String badDateString = "2015-03-03x09:22:42 -0700"; GitChangeSet c = new GitChangeSet(Collections.singletonList("author John Doe " + badDateString), true); assertEquals(badDateString, c.getDate()); @@ -69,7 +70,7 @@ public void testInvalidDate() { } @Test - public void testIsoDate() { + void testIsoDate() { GitChangeSet c = new GitChangeSet(Collections.singletonList("author John Doe 2015-03-03T09:22:42-0700"), true); assertEquals("2015-03-03T09:22:42-0700", c.getDate()); @@ -118,27 +119,27 @@ private GitChangeSet genChangeSetForSwedCase(boolean authorOrCommitter) { } @Test - public void testSwedishCommitterName() { + void testSwedishCommitterName() { assertEquals("Mister Ã…hlander", genChangeSetForSwedCase(false).getAuthorName()); } @Test - public void testSwedishAuthorName() { + void testSwedishAuthorName() { assertEquals("misterÃ…", genChangeSetForSwedCase(true).getAuthorName()); } @Test - public void testSwedishDate() { + void testSwedishDate() { assertEquals("2013-03-21T15:16:44+0100", genChangeSetForSwedCase(true).getDate()); } @Test - public void testSwedishTimestamp() { + void testSwedishTimestamp() { assertEquals(1363875404000L, genChangeSetForSwedCase(true).getTimestamp()); } @Test - public void testChangeLogTruncationWithShortMessage(){ + void testChangeLogTruncationWithShortMessage(){ GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, "Lorem ipsum dolor sit amet.", false); @@ -148,7 +149,7 @@ public void testChangeLogTruncationWithShortMessage(){ } @Test - public void testChangeLogTruncationWithNewLine(){ + void testChangeLogTruncationWithNewLine(){ GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, "Lorem ipsum dolor sit amet, "+System.lineSeparator()+"consectetur adipiscing elit.", false); @@ -158,7 +159,7 @@ public void testChangeLogTruncationWithNewLine(){ } @Test - public void testChangeLogRetainSummaryWithoutNewLine(){ + void testChangeLogRetainSummaryWithoutNewLine(){ String originalCommitMessage = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit"; GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, originalCommitMessage, @@ -167,7 +168,7 @@ public void testChangeLogRetainSummaryWithoutNewLine(){ } @Test - public void testChangeLogDoNotRetainSummaryWithoutNewLine(){ + void testChangeLogDoNotRetainSummaryWithoutNewLine(){ String msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit"; GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, msg, @@ -176,7 +177,7 @@ public void testChangeLogDoNotRetainSummaryWithoutNewLine(){ } @Test - public void testChangeLogNoTruncationWithNewLine(){ + void testChangeLogNoTruncationWithNewLine(){ GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, "Lorem ipsum dolor sit amet, consectetur "+System.lineSeparator()+" adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit", true); @@ -185,7 +186,7 @@ public void testChangeLogNoTruncationWithNewLine(){ } @Test - public void testChangeLogEdgeCaseNotTruncating(){ + void testChangeLogEdgeCaseNotTruncating(){ GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, "[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0 2 4 5", false); @@ -195,7 +196,7 @@ public void testChangeLogEdgeCaseNotTruncating(){ } @Test - public void testChangeLogEdgeCaseTruncating(){ + void testChangeLogEdgeCaseTruncating(){ GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, "[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0 2 4 5", true); @@ -204,7 +205,7 @@ public void testChangeLogEdgeCaseTruncating(){ } @Test - public void testChangeLogEdgeCaseTruncatingAndNewLine(){ + void testChangeLogEdgeCaseTruncatingAndNewLine(){ GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, "[JENKINS-012345] 8901 34567 " + System.lineSeparator() + "90 23456 8901 34567 9012 4567890 2345678 0 2 4 5", true); @@ -213,7 +214,7 @@ public void testChangeLogEdgeCaseTruncatingAndNewLine(){ } @Test - public void testLongString(){ + void testLongString(){ GitChangeSet changeSet = GitChangeSetUtil.genChangeSet(true, false, true, "12345678901234567890123456789012345678901234567890123456789012345678901234567890", false); @@ -222,7 +223,7 @@ public void testLongString(){ } @Test - public void stringSplitter(){ + void stringSplitter(){ String msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pellentesque ipsum non aliquam interdum. Integer metus orci, vulputate id turpis in, pharetra pretium magna. Fusce sollicitudin vehicula lectus. Nam ut eros purus. Mauris aliquam mi et nunc porta, non consectetur mauris pretium. Fusce a venenatis dolor. Sed commodo, dui ac posuere dignissim, dolor tortor semper eros, varius consequat nulla purus a lacus. Vestibulum egestas, orci vitae pellentesque laoreet, dolor lorem molestie tellus, nec luctus lorem ex quis orci. Phasellus interdum elementum luctus. Nam commodo, turpis in sollicitudin auctor, ipsum lectus finibus erat, in iaculis sapien neque ultrices sapien. In congue diam semper tortor laoreet aliquet. Mauris lacinia quis nunc vel accumsan. Nullam sed nisl eget orci porttitor venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit"; assertThat(GitChangeSet.splitString(msg, 15), is("Lorem ipsum")); assertThat(GitChangeSet.splitString(msg, 16), is("Lorem ipsum")); @@ -239,17 +240,17 @@ public void stringSplitter(){ } @Test - public void splitingWithBrackets(){ + void splitingWithBrackets(){ assertThat(GitChangeSet.splitString("[task] Lorem ipsum dolor sit amet, consectetur adipiscing elit.", 25), is("[task] Lorem ipsum dolor")); } @Test - public void splitingEmptyString(){ + void splitingEmptyString(){ assertThat(GitChangeSet.splitString("", 25), is("")); } @Test - public void splitingNullString(){ + void splitingNullString(){ assertThat(GitChangeSet.splitString(null, 25), is("")); } } diff --git a/src/test/java/hudson/plugins/git/GitChangeSetEmptyTest.java b/src/test/java/hudson/plugins/git/GitChangeSetEmptyTest.java index b813156066..d34de47ce1 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetEmptyTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetEmptyTest.java @@ -1,100 +1,99 @@ package hudson.plugins.git; import java.util.ArrayList; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; -public class GitChangeSetEmptyTest { +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; - private GitChangeSet changeSet = null; +import static org.junit.jupiter.api.Assertions.*; - public GitChangeSetEmptyTest() { - } +class GitChangeSetEmptyTest { + + private GitChangeSet changeSet = null; - @Before - public void createEmptyChangeSet() { + @BeforeEach + void beforeEach() { changeSet = new GitChangeSet(new ArrayList<>(), false); } @Test - public void testGetDate() { + void testGetDate() { assertNull(changeSet.getDate()); } @Test - public void testGetTimestamp() { + void testGetTimestamp() { assertEquals(-1L, changeSet.getTimestamp()); } @Test - public void testGetCommitId() { + void testGetCommitId() { assertNull(changeSet.getCommitId()); } @Test - public void testSetParent() { + void testSetParent() { changeSet.setParent(null); assertNull(changeSet.getParent()); } @Test - public void testGetParentCommit() { + void testGetParentCommit() { assertNull(changeSet.getParentCommit()); } @Test - public void testGetAffectedPaths() { + void testGetAffectedPaths() { assertTrue(changeSet.getAffectedPaths().isEmpty()); } @Test - public void testGetPaths() { + void testGetPaths() { assertTrue(changeSet.getPaths().isEmpty()); } @Test - public void testGetAffectedFiles() { + void testGetAffectedFiles() { assertTrue(changeSet.getAffectedFiles().isEmpty()); } @Test - public void testGetAuthorName() { + void testGetAuthorName() { assertNull(changeSet.getAuthorName()); } @Test - public void testGetMsg() { + void testGetMsg() { assertNull(changeSet.getMsg()); } @Test - public void testGetId() { + void testGetId() { assertNull(changeSet.getId()); } @Test - public void testGetRevision() { + void testGetRevision() { assertNull(changeSet.getRevision()); } @Test - public void testGetComment() { + void testGetComment() { assertNull(changeSet.getComment()); } @Test - public void testGetBranch() { + void testGetBranch() { assertNull(changeSet.getBranch()); } @Test - public void testHashCode() { + void testHashCode() { assertTrue(changeSet.hashCode() != 0); } @Test - public void testEquals() { + void testEquals() { assertEquals(changeSet, changeSet); assertNotEquals(changeSet, GitChangeSetUtil.genChangeSet(true, true)); } diff --git a/src/test/java/hudson/plugins/git/GitChangeSetEuroTest.java b/src/test/java/hudson/plugins/git/GitChangeSetEuroTest.java index 77e78c5477..37755470a9 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetEuroTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetEuroTest.java @@ -3,14 +3,18 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -@RunWith(Parameterized.class) -public class GitChangeSetEuroTest { +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; + +@ParameterizedClass(name = "{0}") +@MethodSource("permuteAuthorNameAndLegacyLayout") +class GitChangeSetEuroTest { private final String id = "1567861636cd854f4dd6fa40bf94c0c657681dd5"; private final String parent = "e74a24e995305bd67a180f0ebc57927e2b8783ce"; @@ -23,23 +27,22 @@ public class GitChangeSetEuroTest { private GitChangeSet changeSet = null; private final boolean useAuthorName; - public GitChangeSetEuroTest(String useAuthorName) { - this.useAuthorName = Boolean.valueOf(useAuthorName); + public GitChangeSetEuroTest(boolean useAuthorName) { + this.useAuthorName = useAuthorName; } - @Parameterized.Parameters(name = "{0}") - public static Collection permuteAuthorNameAndLegacyLayout() { + static Collection permuteAuthorNameAndLegacyLayout() { List values = new ArrayList<>(); - String[] allowed = {"true", "false"}; - for (String authorName : allowed) { + boolean[] allowed = {true, false}; + for (boolean authorName : allowed) { Object[] combination = {authorName}; values.add(combination); } return values; } - @Before - public void createEuroChangeSet() { + @BeforeEach + void beforeEach() { ArrayList gitChangeLog = new ArrayList<>(); gitChangeLog.add("commit " + id); gitChangeLog.add("tree 66236cf9a1ac0c589172b450ed01f019a5697c49"); @@ -64,83 +67,83 @@ public void createEuroChangeSet() { } @Test - public void testGetCommitId() { + void testGetCommitId() { assertEquals(id, changeSet.getCommitId()); } @Test - public void testSetParent() { + void testSetParent() { changeSet.setParent(null); assertNull(changeSet.getParent()); } @Test - public void testGetParentCommit() { + void testGetParentCommit() { assertEquals(parent, changeSet.getParentCommit()); } @Test - public void testGetAffectedPaths() { + void testGetAffectedPaths() { assertTrue(changeSet.getAffectedPaths().isEmpty()); } @Test - public void testGetPaths() { + void testGetPaths() { assertTrue(changeSet.getPaths().isEmpty()); } @Test - public void testGetAffectedFiles() { + void testGetAffectedFiles() { assertTrue(changeSet.getAffectedFiles().isEmpty()); } @Test - public void testGetAuthorName() { + void testGetAuthorName() { assertEquals(useAuthorName ? authorName : committerName, changeSet.getAuthorName()); } @Test - public void testGetMsg() { + void testGetMsg() { assertEquals(msg, changeSet.getMsg()); } @Test - public void testGetId() { + void testGetId() { assertEquals(id, changeSet.getId()); } @Test - public void testGetRevision() { + void testGetRevision() { assertEquals(id, changeSet.getRevision()); } @Test - public void testGetComment() { + void testGetComment() { assertTrue(changeSet.getComment().startsWith(commentStartText)); } @Test - public void testGetBranch() { + void testGetBranch() { assertNull(changeSet.getBranch()); } @Test - public void testGetDate() { + void testGetDate() { assertEquals(useAuthorName ? "2013-03-21T15:16:44+0100" : "2013-03-25T08:18:59-0400", changeSet.getDate()); } @Test - public void testGetTimestamp() { + void testGetTimestamp() { assertEquals(useAuthorName ? 1363875404000L : 1364213939000L, changeSet.getTimestamp()); } @Test - public void testHashCode() { + void testHashCode() { assertTrue(changeSet.hashCode() != 0); } @Test - public void testEquals() { + void testEquals() { assertEquals(changeSet, changeSet); assertEquals(GitChangeSetUtil.genChangeSet(false, false), GitChangeSetUtil.genChangeSet(false, false)); diff --git a/src/test/java/hudson/plugins/git/GitChangeSetListTest.java b/src/test/java/hudson/plugins/git/GitChangeSetListTest.java index b2fb32f864..5c65897b66 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetListTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetListTest.java @@ -25,31 +25,27 @@ import hudson.model.Run; import hudson.scm.RepositoryBrowser; +import org.junit.jupiter.api.BeforeEach; + import java.util.Iterator; import java.util.List; import java.util.ArrayList; -import org.junit.Test; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Before; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; -public class GitChangeSetListTest { +class GitChangeSetListTest { - private final GitChangeSetList emptyChangeSetList; + private final GitChangeSetList emptyChangeSetList = new GitChangeSetList(null, null, new ArrayList<>()); private GitChangeSetList changeSetList; private GitChangeSet changeSet; - public GitChangeSetListTest() { - RepositoryBrowser browser = null; - Run build = null; - emptyChangeSetList = new GitChangeSetList(build, browser, new ArrayList<>()); - } - - @Before - public void createGitChangeSetList() { + @BeforeEach + void beforeEach() { RepositoryBrowser browser = null; Run build = null; List logs = new ArrayList<>(); @@ -62,17 +58,17 @@ public void createGitChangeSetList() { } @Test - public void testIsEmptySet() { + void testIsEmptySet() { assertFalse(changeSetList.isEmptySet()); } @Test - public void testIsEmptySetReallyEmpty() { + void testIsEmptySetReallyEmpty() { assertTrue(emptyChangeSetList.isEmptySet()); } @Test - public void testIterator() { + void testIterator() { Iterator iterator = changeSetList.iterator(); GitChangeSet firstChangeSet = iterator.next(); assertThat(firstChangeSet, is(changeSet)); @@ -80,25 +76,25 @@ public void testIterator() { } @Test - public void testIteratorReallyE() { + void testIteratorReallyE() { Iterator iterator = emptyChangeSetList.iterator(); assertFalse(iterator.hasNext()); } @Test - public void testGetLogs() { + void testGetLogs() { List result = changeSetList.getLogs(); assertThat(result, contains(changeSet)); } @Test - public void testGetLogsReallyEmpty() { + void testGetLogsReallyEmpty() { List result = emptyChangeSetList.getLogs(); assertThat(result, is(empty())); } @Test - public void testGetKind() { + void testGetKind() { assertThat(changeSetList.getKind(), is("git")); } } diff --git a/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java b/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java index 0b9c142442..6e355e23c2 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetPluginHistoryTest.java @@ -1,5 +1,6 @@ package hudson.plugins.git; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -25,15 +26,18 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import jenkins.plugins.git.GitSampleRepoRule; -@RunWith(Parameterized.class) -public class GitChangeSetPluginHistoryTest { +@ParameterizedClass(name = "{2}-{1}") +@MethodSource("generateData") +@WithGitSampleRepo +class GitChangeSetPluginHistoryTest { private static final long FIRST_COMMIT_TIMESTAMP = 1198029565000L; private static final long NOW = System.currentTimeMillis(); @@ -42,8 +46,7 @@ public class GitChangeSetPluginHistoryTest { private final GitChangeSet changeSet; - @ClassRule - public static GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + private static GitSampleRepoRule sampleRepo; public GitChangeSetPluginHistoryTest(GitClient git, boolean authorOrCommitter, String sha1String) throws Exception { this.sha1 = ObjectId.fromString(sha1String); @@ -53,6 +56,11 @@ public GitChangeSetPluginHistoryTest(GitClient git, boolean authorOrCommitter, S changeSet = new GitChangeSet(changeLogStrings, authorOrCommitter); } + @BeforeAll + static void beforeAll(GitSampleRepoRule repo) { + sampleRepo = repo; + } + /** * Merge changes won't compute their date in GitChangeSet, apparently as an * intentional design choice. Return all changes for this repository which @@ -74,8 +82,7 @@ private static List getNonMergeChanges() throws IOException { return nonMergeChanges; } - @Parameterized.Parameters(name = "{2}-{1}") - public static Collection generateData() throws Exception { + static Collection generateData() throws Exception { List args = new ArrayList<>(); String[] implementations = new String[]{"git", "jgit"}; boolean[] choices = {true, false}; @@ -99,7 +106,7 @@ public static Collection generateData() throws Exception { } @Test - public void timestampInRange() { + void timestampInRange() { long timestamp = changeSet.getTimestamp(); assertThat(timestamp, is(greaterThanOrEqualTo(FIRST_COMMIT_TIMESTAMP))); assertThat(timestamp, is(lessThan(NOW))); diff --git a/src/test/java/hudson/plugins/git/GitChangeSetSimpleTest.java b/src/test/java/hudson/plugins/git/GitChangeSetSimpleTest.java index e0b67e4785..0b67a6c79d 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetSimpleTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetSimpleTest.java @@ -1,41 +1,39 @@ package hudson.plugins.git; import hudson.scm.EditType; +import org.junit.jupiter.api.BeforeEach; + import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) -public class GitChangeSetSimpleTest { +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; + +@ParameterizedClass(name = "{0},{1}") +@MethodSource("permuteAuthorNameAndLegacyLayout") +class GitChangeSetSimpleTest { private GitChangeSet changeSet = null; private final boolean useAuthorName; private final boolean useLegacyFormat; - public GitChangeSetSimpleTest(String useAuthorName, String useLegacyFormat) { - this.useAuthorName = Boolean.valueOf(useAuthorName); - this.useLegacyFormat = Boolean.valueOf(useLegacyFormat); + public GitChangeSetSimpleTest(boolean useAuthorName, boolean useLegacyFormat) { + this.useAuthorName = useAuthorName; + this.useLegacyFormat = useLegacyFormat; } - @Parameterized.Parameters(name = "{0},{1}") - public static Collection permuteAuthorNameAndLegacyLayout() { + static Collection permuteAuthorNameAndLegacyLayout() { List values = new ArrayList<>(); - String[] allowed = {"true", "false"}; - for (String authorName : allowed) { - for (String legacyFormat : allowed) { + boolean[] allowed = {true, false}; + for (boolean authorName : allowed) { + for (boolean legacyFormat : allowed) { Object[] combination = {authorName, legacyFormat}; values.add(combination); } @@ -43,13 +41,13 @@ public static Collection permuteAuthorNameAndLegacyLayout() { return values; } - @Before - public void createSimpleChangeSet() { + @BeforeEach + void beforeEach() { changeSet = GitChangeSetUtil.genChangeSet(useAuthorName, useLegacyFormat); } @Test - public void testChangeSetDetails() { + void testChangeSetDetails() { assertEquals(GitChangeSetUtil.ID, changeSet.getId()); assertEquals(GitChangeSetUtil.COMMIT_TITLE, changeSet.getMsg()); assertEquals("Commit title.\nCommit extended description.\n", changeSet.getComment()); @@ -104,75 +102,75 @@ public void testChangeSetDetails() { } @Test - public void testGetCommitId() { + void testGetCommitId() { assertEquals(GitChangeSetUtil.ID, changeSet.getCommitId()); } @Test - public void testSetParent() { + void testSetParent() { changeSet.setParent(null); assertNull(changeSet.getParent()); } @Test - public void testGetParentCommit() { + void testGetParentCommit() { assertEquals(GitChangeSetUtil.PARENT, changeSet.getParentCommit()); } @Test - public void testGetAffectedFiles() { + void testGetAffectedFiles() { assertEquals(6, changeSet.getAffectedFiles().size()); } @Test - public void testGetAuthorName() { + void testGetAuthorName() { assertEquals(useAuthorName ? GitChangeSetUtil.AUTHOR_NAME : GitChangeSetUtil.COMMITTER_NAME, changeSet.getAuthorName()); } @Test - public void testGetDate() { + void testGetDate() { assertEquals(useAuthorName ? GitChangeSetUtil.AUTHOR_DATE_FORMATTED : GitChangeSetUtil.COMMITTER_DATE_FORMATTED, changeSet.getDate()); } @Test - public void testGetMsg() { + void testGetMsg() { assertEquals(GitChangeSetUtil.COMMIT_TITLE, changeSet.getMsg()); } @Test - public void testGetId() { + void testGetId() { assertEquals(GitChangeSetUtil.ID, changeSet.getId()); } @Test - public void testGetRevision() { + void testGetRevision() { assertEquals(GitChangeSetUtil.ID, changeSet.getRevision()); } @Test - public void testGetComment() { + void testGetComment() { String changeComment = changeSet.getComment(); - assertTrue("Comment '" + changeComment + "' does not start with '" + GitChangeSetUtil.COMMENT + "'", changeComment.startsWith(GitChangeSetUtil.COMMENT)); + assertTrue(changeComment.startsWith(GitChangeSetUtil.COMMENT), "Comment '" + changeComment + "' does not start with '" + GitChangeSetUtil.COMMENT + "'"); } @Test - public void testGetBranch() { + void testGetBranch() { assertNull(changeSet.getBranch()); } @Test - public void testHashCode() { + void testHashCode() { assertTrue(changeSet.hashCode() != 0); } @Test - public void testEquals() { + void testEquals() { assertEquals(changeSet, changeSet); - assertNotEquals(changeSet, new GitChangeSet(new ArrayList<>(), false)); + assertNotEquals(new GitChangeSet(new ArrayList<>(), false), changeSet); } @Test - public void testChangeSetExceptionMessage() { + void testChangeSetExceptionMessage() { final String expectedLineContent = "commit "; ArrayList lines = new ArrayList<>(); lines.add(expectedLineContent); diff --git a/src/test/java/hudson/plugins/git/GitChangeSetTest.java b/src/test/java/hudson/plugins/git/GitChangeSetTest.java index af3a8614a2..776e275f88 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetTest.java @@ -3,9 +3,10 @@ import hudson.model.User; import hudson.tasks.Mailer; import hudson.tasks.Mailer.UserProperty; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.MockedStatic; import org.springframework.security.authentication.DisabledException; @@ -15,21 +16,24 @@ import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; -public class GitChangeSetTest { +@WithJenkins +class GitChangeSetTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; private final Random random = new Random(); + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } + @Test - public void testFindOrCreateUser() { + void testFindOrCreateUser() { final GitChangeSet committerCS = GitChangeSetUtil.genChangeSet(false, false); final String email = "jauthor@nospam.com"; final boolean createAccountBasedOnEmail = true; @@ -50,7 +54,7 @@ public void testFindOrCreateUser() { } @Test - public void testFindOrCreateUserNullAuthorEmail() { + void testFindOrCreateUserNullAuthorEmail() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); final boolean createAccountBasedOnEmail = true; final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); @@ -61,7 +65,7 @@ public void testFindOrCreateUserNullAuthorEmail() { } @Test - public void testFindOrCreateUserEmptyAuthorEmail() { + void testFindOrCreateUserEmptyAuthorEmail() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); final boolean createAccountBasedOnEmail = true; final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); @@ -72,7 +76,7 @@ public void testFindOrCreateUserEmptyAuthorEmail() { } @Test - public void testFindOrCreateUserEmptyAuthorEmailDoNotCreateAccountBasedOnEmail() { + void testFindOrCreateUserEmptyAuthorEmailDoNotCreateAccountBasedOnEmail() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); final boolean createAccountBasedOnEmail = false; final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); @@ -83,7 +87,7 @@ public void testFindOrCreateUserEmptyAuthorEmailDoNotCreateAccountBasedOnEmail() } @Test - public void testFindOrCreateUserEmptyAuthorDoNotCreateAccountBasedOnEmail() { + void testFindOrCreateUserEmptyAuthorDoNotCreateAccountBasedOnEmail() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); final boolean createAccountBasedOnEmail = false; final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); @@ -94,7 +98,7 @@ public void testFindOrCreateUserEmptyAuthorDoNotCreateAccountBasedOnEmail() { } @Test - public void testFindOrCreateUserBadAuthorEmailDoNotCreateAccountBasedOnEmail() { + void testFindOrCreateUserBadAuthorEmailDoNotCreateAccountBasedOnEmail() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); final boolean createAccountBasedOnEmail = false; final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); @@ -105,7 +109,7 @@ public void testFindOrCreateUserBadAuthorEmailDoNotCreateAccountBasedOnEmail() { } @Test - public void testFindOrCreateUserOKAuthorEmailDoNotCreateAccountBasedOnEmail() { + void testFindOrCreateUserOKAuthorEmailDoNotCreateAccountBasedOnEmail() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); final boolean createAccountBasedOnEmail = false; final boolean useExistingAccountBasedOnEmail = random.nextBoolean(); @@ -116,7 +120,7 @@ public void testFindOrCreateUserOKAuthorEmailDoNotCreateAccountBasedOnEmail() { } @Test - public void testFindOrCreateUserBlankAuthorEmail() { + void testFindOrCreateUserBlankAuthorEmail() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); final boolean createAccountBasedOnEmail = true; final boolean useExistingAccountBasedOnEmail = false; @@ -127,7 +131,7 @@ public void testFindOrCreateUserBlankAuthorEmail() { } @Test - public void testFindOrCreateUserBlankAuthorEmailUseExistingAccountBasedOnEmail() { + void testFindOrCreateUserBlankAuthorEmailUseExistingAccountBasedOnEmail() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); final boolean createAccountBasedOnEmail = true; final boolean useExistingAccountBasedOnEmail = true; @@ -138,7 +142,7 @@ public void testFindOrCreateUserBlankAuthorEmailUseExistingAccountBasedOnEmail() } @Test - public void testFindOrCreateUserValidAuthorEmailUseExistingAccountBasedOnEmail() { + void testFindOrCreateUserValidAuthorEmailUseExistingAccountBasedOnEmail() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); final boolean createAccountBasedOnEmail = true; final boolean useExistingAccountBasedOnEmail = true; @@ -149,7 +153,7 @@ public void testFindOrCreateUserValidAuthorEmailUseExistingAccountBasedOnEmail() } @Test - public void testFindOrCreateUserUseExistingAuthorEmailUseExistingAccountBasedOnEmail() { + void testFindOrCreateUserUseExistingAuthorEmailUseExistingAccountBasedOnEmail() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); final boolean createAccountBasedOnEmail = true; final boolean useExistingAccountBasedOnEmail = true; @@ -162,8 +166,8 @@ public void testFindOrCreateUserUseExistingAuthorEmailUseExistingAccountBasedOnE assertThat(existing, is(user)); } - @Test - public void testFindOrCreateUserHandlesAuthenticationException() { + @Test + void testFindOrCreateUserHandlesAuthenticationException() { final GitChangeSet changeset = GitChangeSetUtil.genChangeSet(random.nextBoolean(), random.nextBoolean()); // TODO this only test one code path, there are several code paths using User.get() final boolean createAccountBasedOnEmail = false; @@ -189,9 +193,10 @@ public void testFindOrCreateUserHandlesAuthenticationException() { } } + // Test deprecated User.get() @Test - @Deprecated // Test deprecated User.get() - public void testFindOrCreateUserBasedOnExistingUsersEmail() throws IOException { + @Deprecated + void testFindOrCreateUserBasedOnExistingUsersEmail() throws IOException { final GitChangeSet committerCS = GitChangeSetUtil.genChangeSet(true, false); final String existingUserId = "An existing user"; final String existingUserFullName = "Some FullName"; @@ -208,8 +213,8 @@ public void testFindOrCreateUserBasedOnExistingUsersEmail() throws IOException { User user = committerCS.findOrCreateUser(GitChangeSetUtil.COMMITTER_NAME, email, createAccountBasedOnEmail, useExistingAccountBasedOnEmail); assertNotNull(user); - assertEquals(user.getId(), existingUserId); - assertEquals(user.getFullName(), existingUserFullName); + assertEquals(existingUserId, user.getId()); + assertEquals(existingUserFullName, user.getFullName()); UserProperty property = user.getProperty(Mailer.UserProperty.class); assertNotNull(property); @@ -222,9 +227,10 @@ public void testFindOrCreateUserBasedOnExistingUsersEmail() throws IOException { assertEquals(User.getUnknown(), committerCS.findOrCreateUser(null, email, true, useExistingAccountBasedOnEmail)); } + // Testing deprecated User.get @Test - @Deprecated // Testing deprecated User.get - public void findOrCreateByFullName() throws Exception { + @Deprecated + void findOrCreateByFullName() throws Exception { GitChangeSet cs = GitChangeSetUtil.genChangeSet(false, false); User user = User.get("john"); user.setFullName(GitChangeSetUtil.COMMITTER_NAME); diff --git a/src/test/java/hudson/plugins/git/GitChangeSetTimestampTest.java b/src/test/java/hudson/plugins/git/GitChangeSetTimestampTest.java index ec2ca2595b..74fd870cc9 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetTimestampTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetTimestampTest.java @@ -7,9 +7,10 @@ import java.util.Random; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; /** @@ -20,8 +21,9 @@ * * @author Mark Waite */ -@RunWith(Parameterized.class) -public class GitChangeSetTimestampTest { +@ParameterizedClass(name = "{0}") +@MethodSource("createSampleChangeSets") +class GitChangeSetTimestampTest { private final String normalizedTimestamp; private final long millisecondsSinceEpoch; @@ -34,8 +36,7 @@ public GitChangeSetTimestampTest(String timestamp, String normalizedTimestamp, l changeSet = genChangeSet(timestamp); } - @Parameterized.Parameters(name = "{0}") - public static Collection createSampleChangeSets() { + static Collection createSampleChangeSets() { Object[][] samples = { /* git log dates from various time zones, months, & days */ {"2015-10-06 19:29:47 +0300", null, 1444148987000L}, @@ -68,13 +69,13 @@ public static Collection createSampleChangeSets() { } @Test - public void testChangeSetDate() { + void testChangeSetDate() { assertThat(changeSet.getDate(), is(normalizedTimestamp)); } @Test @Issue("JENKINS-30073") - public void testChangeSetTimeStamp() { + void testChangeSetTimeStamp() { assertThat(changeSet.getTimestamp(), is(millisecondsSinceEpoch)); } diff --git a/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java b/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java index eb1bc5a362..7852926c31 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetTruncateTest.java @@ -1,9 +1,6 @@ package hudson.plugins.git; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.PrintWriter; -import java.io.StringWriter; +import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; @@ -14,6 +11,7 @@ import java.util.UUID; import hudson.plugins.git.util.GitUtilsTest; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; @@ -26,22 +24,23 @@ import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; -@RunWith(Parameterized.class) -public class GitChangeSetTruncateTest { +@ParameterizedClass(name = "{0} \"{1}\" --->>> \"{2}\"") +@MethodSource("gitObjects") +@WithGitSampleRepo +class GitChangeSetTruncateTest { - @ClassRule - public static TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private static File tempFolder; - @ClassRule - public static GitSampleRepoRule versionCheckRepo = new GitSampleRepoRule(); + private static GitSampleRepoRule versionCheckRepo; private static File repoRoot = null; @@ -59,8 +58,8 @@ public class GitChangeSetTruncateTest { private static class TestData { - final public String testDataCommitSummary; - final public String testDataTruncatedSummary; + public final String testDataCommitSummary; + public final String testDataTruncatedSummary; TestData(String commitSummary, String truncatedSummary) { this.testDataCommitSummary = commitSummary; @@ -70,10 +69,10 @@ private static class TestData { // 1 2 3 4 5 6 7 // 1234567890123456789012345678901234567890123456789012345678901234567890 - private final static String SEVENTY_CHARS = "[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0"; - private final static String EIGHTY_CHARS = "12345678901234567890123456789012345678901234567890123456789012345678901234567890"; + private static final String SEVENTY_CHARS = "[JENKINS-012345] 8901 34567 90 23456 8901 34567 9012 4567890 2345678 0"; + private static final String EIGHTY_CHARS = "12345678901234567890123456789012345678901234567890123456789012345678901234567890"; - private final static TestData[] TEST_DATA = { + private static final TestData[] TEST_DATA = { new TestData(EIGHTY_CHARS, EIGHTY_CHARS), // surprising that longer than 72 is returned new TestData(EIGHTY_CHARS + " A B C", EIGHTY_CHARS), // surprising that longer than 72 is returned new TestData(SEVENTY_CHARS, SEVENTY_CHARS), @@ -106,8 +105,13 @@ public GitChangeSetTruncateTest(String gitImpl, String commitSummary, String tru changeSetTruncatedSummary = new GitChangeSet(changeLogList, random.nextBoolean(), false); } - @Parameterized.Parameters(name = "{0} \"{1}\" --->>> \"{2}\"") - public static Collection gitObjects() { + + @BeforeAll + static void beforeAll(GitSampleRepoRule repo) { + versionCheckRepo = repo; + } + + static Collection gitObjects() { String[] bothGitImplementations = {"git", "jgit"}; List arguments = new ArrayList<>(); for (String implementation : bothGitImplementations) { @@ -120,10 +124,10 @@ public static Collection gitObjects() { return arguments; } - @BeforeClass - public static void createRepo() throws Exception { + @BeforeAll + static void beforeAll() throws Exception { SystemReader.getInstance().getUserConfig().clear(); - repoRoot = tempFolder.newFolder(); + repoRoot = newFolder(tempFolder, "junit"); String initialImpl = random.nextBoolean() ? "git" : "jgit"; GitClient gitClient = Git.with(TaskListener.NULL, GitUtilsTest.getConfigNoSystemEnvsVars()) @@ -169,9 +173,10 @@ private void createFile(String path, String content) throws Exception { } } + // CLI git truncates first line of commit message in Changes page, JGit doesn't @Test - @Issue("JENKINS-29977") // CLI git truncates first line of commit message in Changes page, JGit doesn't - public void summaryTruncatedAtLastWord72CharactersOrLess() throws Exception { + @Issue("JENKINS-29977") + void summaryTruncatedAtLastWord72CharactersOrLess() throws Exception { /* * Before git plugin 4.0, calls to GitChangeSet(x, y) truncated CLI git, did not truncate JGit. * After git plugin 4.0, calls to GitChangeSet(x, y) truncates CLI git, truncates JGit. @@ -182,13 +187,22 @@ public void summaryTruncatedAtLastWord72CharactersOrLess() throws Exception { @Test @Issue("JENKINS-29977") - public void summaryAlwaysTruncatedAtLastWord72CharactersOrLess() throws Exception { + void summaryAlwaysTruncatedAtLastWord72CharactersOrLess() throws Exception { assertThat(changeSetTruncatedSummary.getMsg(), is(truncatedSummary)); } @Test @Issue("JENKINS-29977") - public void summaryNotTruncatedAtLastWord72CharactersOrLess() throws Exception { + void summaryNotTruncatedAtLastWord72CharactersOrLess() throws Exception { assertThat(changeSetFullSummary.getMsg(), is(commitSummary)); } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/git/GitChangeSetUtil.java b/src/test/java/hudson/plugins/git/GitChangeSetUtil.java index e72c24c4de..6d64f81ad7 100644 --- a/src/test/java/hudson/plugins/git/GitChangeSetUtil.java +++ b/src/test/java/hudson/plugins/git/GitChangeSetUtil.java @@ -16,7 +16,10 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; -import junit.framework.TestCase; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** Utility class to support GitChangeSet testing. */ public class GitChangeSetUtil { @@ -77,10 +80,10 @@ public static GitChangeSet genChangeSet(boolean authorOrCommitter, boolean useLe } static void assertChangeSet(GitChangeSet changeSet) { - TestCase.assertEquals("123abc456def", changeSet.getId()); - TestCase.assertEquals("Commit title.", changeSet.getMsg()); - TestCase.assertEquals("Commit title.\nCommit extended description.\n", changeSet.getComment()); - TestCase.assertEquals("Commit title.\nCommit extended description.\n".replace("\n", "
"), changeSet.getCommentAnnotated()); + assertEquals("123abc456def", changeSet.getId()); + assertEquals("Commit title.", changeSet.getMsg()); + assertEquals("Commit title.\nCommit extended description.\n", changeSet.getComment()); + assertEquals("Commit title.\nCommit extended description.\n".replace("\n", "
"), changeSet.getCommentAnnotated()); HashSet expectedAffectedPaths = new HashSet<>(7); expectedAffectedPaths.add("src/test/add.file"); expectedAffectedPaths.add("src/test/deleted.file"); @@ -88,43 +91,43 @@ static void assertChangeSet(GitChangeSet changeSet) { expectedAffectedPaths.add("src/test/renamedFrom.file"); expectedAffectedPaths.add("src/test/renamedTo.file"); expectedAffectedPaths.add("src/test/copyOf.file"); - TestCase.assertEquals(expectedAffectedPaths, changeSet.getAffectedPaths()); + assertEquals(expectedAffectedPaths, changeSet.getAffectedPaths()); Collection actualPaths = changeSet.getPaths(); - TestCase.assertEquals(6, actualPaths.size()); + assertEquals(6, actualPaths.size()); for (GitChangeSet.Path path : actualPaths) { if (null != path.getPath()) switch (path.getPath()) { case "src/test/add.file": - TestCase.assertEquals(EditType.ADD, path.getEditType()); - TestCase.assertNull(path.getSrc()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); + assertEquals(EditType.ADD, path.getEditType()); + assertNull(path.getSrc()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); break; case "src/test/deleted.file": - TestCase.assertEquals(EditType.DELETE, path.getEditType()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - TestCase.assertNull(path.getDst()); + assertEquals(EditType.DELETE, path.getEditType()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + assertNull(path.getDst()); break; case "src/test/modified.file": - TestCase.assertEquals(EditType.EDIT, path.getEditType()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); + assertEquals(EditType.EDIT, path.getEditType()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); break; case "src/test/renamedFrom.file": - TestCase.assertEquals(EditType.DELETE, path.getEditType()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); + assertEquals(EditType.DELETE, path.getEditType()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); break; case "src/test/renamedTo.file": - TestCase.assertEquals(EditType.ADD, path.getEditType()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); - TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); + assertEquals(EditType.ADD, path.getEditType()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); + assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); break; case "src/test/copyOf.file": - TestCase.assertEquals(EditType.ADD, path.getEditType()); - TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getSrc()); - TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); + assertEquals(EditType.ADD, path.getEditType()); + assertEquals("bc234def567abc890def123abc456def789abc01", path.getSrc()); + assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); break; default: - TestCase.fail("Unrecognized path."); + fail("Unrecognized path."); break; } } diff --git a/src/test/java/hudson/plugins/git/GitHooksTest.java b/src/test/java/hudson/plugins/git/GitHooksTest.java index d2f43a43b1..6d35912e0e 100644 --- a/src/test/java/hudson/plugins/git/GitHooksTest.java +++ b/src/test/java/hudson/plugins/git/GitHooksTest.java @@ -3,7 +3,6 @@ import hudson.FilePath; import hudson.model.Label; import hudson.slaves.DumbSlave; -import hudson.tools.ToolProperty; import jenkins.plugins.git.CliGitCommand; import jenkins.plugins.git.GitHooksConfiguration; import org.eclipse.jgit.util.SystemReader; @@ -11,15 +10,13 @@ import org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.jvnet.hudson.test.BuildWatcher; -import org.jvnet.hudson.test.LoggerRule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.jvnet.hudson.test.LogRecorder; +import org.jvnet.hudson.test.junit.jupiter.BuildWatcherExtension; import java.io.File; import java.io.IOException; @@ -31,36 +28,36 @@ import java.util.concurrent.TimeUnit; import java.util.logging.Level; +import static hudson.Functions.isWindows; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsIterableContaining.hasItem; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.StringStartsWith.startsWith; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; -public class GitHooksTest extends AbstractGitTestCase { +class GitHooksTest extends AbstractGitTestCase { - @Rule - public LoggerRule lr = new LoggerRule(); - @ClassRule - public static BuildWatcher watcher = new BuildWatcher(); + private final LogRecorder lr = new LogRecorder(); + + @SuppressWarnings("unused") + @RegisterExtension + private static final BuildWatcherExtension BUILD_WATCHER = new BuildWatcherExtension(); private static final String JENKINS_URL = System.getenv("JENKINS_URL") != null ? System.getenv("JENKINS_URL") : "http://localhost:8080/"; - @BeforeClass - public static void setGitDefaults() throws Exception { + @BeforeAll + static void beforeAll() throws Exception { SystemReader.getInstance().getUserConfig().clear(); CliGitCommand gitCmd = new CliGitCommand(null); gitCmd.setDefaults(); } - @Before - public void setGitTool() throws IOException { + @BeforeEach + void beforeEach() throws IOException { lr.record(GitHooksConfiguration.class.getName(), Level.ALL).capture(1024); - GitTool tool = new GitTool("my-git", "git", Collections.>emptyList()); + GitTool tool = new GitTool("my-git", "git", Collections.emptyList()); r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); //Jenkins 2.308 changes the default label to "built-in" causing test failures when testing with newer core // e.g. java 17 testing @@ -68,15 +65,15 @@ public void setGitTool() throws IOException { r.jenkins.setNumExecutors(3); //In case this changes in the future as well. } - @After - public void tearDown() { + @AfterEach + void afterEach() { GitHooksConfiguration.get().setAllowedOnController(false); GitHooksConfiguration.get().setAllowedOnAgents(false); assertThat(lr.getMessages(), not(hasItem(startsWith("core.hooksPath explicitly set to ")))); } @Test - public void testPipelineFromScm() throws Exception { + void testPipelineFromScm() throws Exception { if (isWindows() && JENKINS_URL.contains("ci.jenkins.io")) { /* * The test works on Windows, but for unknown reason does not work @@ -84,6 +81,7 @@ public void testPipelineFromScm() throws Exception { */ return; } + GitHooksConfiguration.get().setAllowedOnController(true); GitHooksConfiguration.get().setAllowedOnAgents(true); final DumbSlave agent = r.createOnlineSlave(Label.get("somewhere")); @@ -110,10 +108,9 @@ public void testPipelineFromScm() throws Exception { final FilePath jobWorkspace = agent.getWorkspaceFor(job); assertNotNull(jobWorkspace); - TemporaryFolder tf = new TemporaryFolder(); - tf.create(); - final File postCheckoutOutput1 = new File(tf.newFolder(), "svn-git-fun-post-checkout-1"); - final File postCheckoutOutput2 = new File(tf.newFolder(), "svn-git-fun-post-checkout-2"); + File tf = Files.createTempDirectory("junit").toFile(); + final File postCheckoutOutput1 = new File(tf,"svn-git-fun-post-checkout-1"); + final File postCheckoutOutput2 = new File(tf,"svn-git-fun-post-checkout-2"); //Add hook on agent workspace FilePath hook = jobWorkspace.child(".git/hooks/post-checkout"); @@ -186,15 +183,15 @@ private void createHookScriptAt(final File postCheckoutOutput, final FilePath ho } private void checkFileOutput(final File postCheckoutOutput, final Instant before, final Instant after) throws IOException { - assertTrue("Output file should exist", postCheckoutOutput.exists()); + assertTrue(postCheckoutOutput.exists(), "Output file should exist"); final String s = Files.readString(postCheckoutOutput.toPath(), Charset.defaultCharset()).trim(); final Instant when = Instant.ofEpochSecond(Integer.parseInt(s)); - assertTrue("Sometime else", when.isAfter(before) && when.isBefore(after)); + assertTrue(when.isAfter(before) && when.isBefore(after), "Sometime else"); Files.delete(postCheckoutOutput.toPath()); } @Test - public void testPipelineCheckoutController() throws Exception { + void testPipelineCheckoutController() throws Exception { if (isWindows() && JENKINS_URL.contains("ci.jenkins.io")) { /* * The test works on Windows, but for unknown reason does not work @@ -217,7 +214,7 @@ public void testPipelineCheckoutController() throws Exception { } @Test - public void testPipelineCheckoutAgent() throws Exception { + void testPipelineCheckoutAgent() throws Exception { if (isWindows() && JENKINS_URL.contains("ci.jenkins.io")) { /* * The test works on Windows, but for unknown reason does not work @@ -281,9 +278,4 @@ private WorkflowJob setupAndRunPipelineCheckout(String node) throws Exception { private static String lines(String... lines) { return String.join("\n", lines); } - - /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ - private boolean isWindows() { - return java.io.File.pathSeparatorChar==';'; - } } diff --git a/src/test/java/hudson/plugins/git/GitPublisherTest.java b/src/test/java/hudson/plugins/git/GitPublisherTest.java index 336d1d4a1e..aa7de7dbb8 100644 --- a/src/test/java/hudson/plugins/git/GitPublisherTest.java +++ b/src/test/java/hudson/plugins/git/GitPublisherTest.java @@ -47,10 +47,12 @@ import org.jenkinsci.plugins.gitclient.JGitTool; import org.jenkinsci.plugins.gitclient.MergeCommand; import org.jenkinsci.plugins.gitclient.UnsupportedCommand; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.Issue; import java.io.File; import java.io.IOException; +import java.io.Serial; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -63,32 +65,27 @@ import jenkins.plugins.git.GitToolChooser; import org.eclipse.jgit.lib.PersonIdent; import org.jenkinsci.plugins.gitclient.GitClient; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; + +import static hudson.Functions.isWindows; +import static org.junit.jupiter.api.Assertions.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Tests for {@link GitPublisher} * * @author Kohsuke Kawaguchi */ -public class GitPublisherTest extends AbstractGitProject { +class GitPublisherTest extends AbstractGitProject { - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); + @TempDir + private File tmpFolder; - @BeforeClass - public static void setGitDefaults() throws Exception { + @BeforeAll + static void beforeAll() throws Exception { SystemReader.getInstance().getUserConfig().clear(); CliGitCommand gitCmd = new CliGitCommand(null); gitCmd.setDefaults(); @@ -96,7 +93,7 @@ public static void setGitDefaults() throws Exception { @Issue("JENKINS-5005") @Test - public void testMatrixBuild() throws Exception { + void testMatrixBuild() throws Exception { final AtomicInteger run = new AtomicInteger(); // count the number of times the perform is called commitNewFile("a"); @@ -131,6 +128,7 @@ public BuildStepDescriptor getDescriptor() { return (BuildStepDescriptor)Jenkins.get().getDescriptorOrDie(GitPublisher.class); // fake } + @Serial private Object writeReplace() { return new NullSCM(); } }); @@ -145,7 +143,7 @@ public BuildStepDescriptor getDescriptor() { } @Test - public void GitPublisherFreestylePushBranchWithJGit() throws Exception { + void GitPublisherFreestylePushBranchWithJGit() throws Exception { GitTool tool = new JGitTool(Collections.emptyList()); r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); @@ -192,7 +190,7 @@ public void GitPublisherFreestylePushBranchWithJGit() throws Exception { } @Test - public void GitPublisherFailWithJGit() throws Exception { + void GitPublisherFailWithJGit() throws Exception { final AtomicInteger run = new AtomicInteger(); // count the number of times the perform is called commitNewFile("a"); @@ -235,6 +233,7 @@ public BuildStepDescriptor getDescriptor() { return (BuildStepDescriptor)Jenkins.get().getDescriptorOrDie(GitPublisher.class); // fake } + @Serial private Object writeReplace() { return new NullSCM(); } }); @@ -249,7 +248,7 @@ public BuildStepDescriptor getDescriptor() { } @Test - public void testMergeAndPush() throws Exception { + void testMergeAndPush() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( @@ -285,7 +284,7 @@ public void testMergeAndPush() throws Exception { @Issue("JENKINS-12402") @Test - public void testMergeAndPushFF() throws Exception { + void testMergeAndPushFF() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( @@ -309,7 +308,7 @@ public void testMergeAndPushFF() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, "commitFileBase"); assertTrue(build1.getWorkspace().child("commitFileBase").exists()); String shaIntegration = getHeadRevision(build1, "integration"); - assertEquals("the integration branch should be at HEAD", shaIntegration, testGitClient.revParse(Constants.HEAD).name()); + assertEquals(shaIntegration, testGitClient.revParse(Constants.HEAD).name(), "the integration branch should be at HEAD"); // create a new branch and build, this results in a fast-forward merge testGitClient.checkout("master"); @@ -330,12 +329,12 @@ public void testMergeAndPushFF() throws Exception { assertTrue(build2.getWorkspace().child("commitFile1").exists()); shaIntegration = getHeadRevision(build2, "integration"); String shaHead = testGitClient.revParse(Constants.HEAD).name(); - assertEquals("the integration branch and branch1 should line up",shaIntegration, shaBranch1); - assertEquals("the integration branch should be at HEAD",shaIntegration, shaHead); + assertEquals(shaIntegration,shaBranch1, "the integration branch and branch1 should line up"); + assertEquals(shaIntegration,shaHead, "the integration branch should be at HEAD"); // integration should have master as the parent commit List revList = testGitClient.revList("integration^1"); ObjectId integrationParent = revList.get(0); - assertEquals("Fast-forward merge should have had master as a parent",master,integrationParent); + assertEquals(master,integrationParent,"Fast-forward merge should have had master as a parent"); // create a second branch off of master, so as to force a merge commit and to test // that --ff gracefully falls back to a merge commit @@ -362,14 +361,14 @@ public void testMergeAndPushFF() throws Exception { assertTrue(build1.getWorkspace().child(commitFile2).exists()); // the integration branch should have branch1 and branch2 as parents revList = testGitClient.revList("integration^1"); - assertEquals("Integration should have branch1 as a parent",revList.get(0).name(),shaBranch1); + assertEquals(revList.get(0).name(),shaBranch1,"Integration should have branch1 as a parent"); revList = testGitClient.revList("integration^2"); - assertEquals("Integration should have branch2 as a parent",revList.get(0).name(),shaBranch2); + assertEquals(revList.get(0).name(),shaBranch2,"Integration should have branch2 as a parent"); } @Issue("JENKINS-12402") @Test - public void testMergeAndPushNoFF() throws Exception { + void testMergeAndPushNoFF() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( @@ -393,7 +392,7 @@ public void testMergeAndPushNoFF() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, "commitFileBase"); assertTrue(build1.getWorkspace().child("commitFileBase").exists()); String shaIntegration = getHeadRevision(build1, "integration"); - assertEquals("integration branch should be at HEAD", shaIntegration, testGitClient.revParse(Constants.HEAD).name()); + assertEquals(shaIntegration, testGitClient.revParse(Constants.HEAD).name(), "integration branch should be at HEAD"); // create a new branch and build // This would be a fast-forward merge, but we're calling for --no-ff and that should work @@ -418,9 +417,9 @@ public void testMergeAndPushNoFF() throws Exception { // assertTrue(build2.getWorkspace().child("commitFile1").exists()); List revList = testGitClient.revList("integration^1"); - assertEquals("Integration should have master as a parent",revList.get(0),master); + assertEquals(revList.get(0),master,"Integration should have master as a parent"); revList = testGitClient.revList("integration^2"); - assertEquals("Integration should have branch1 as a parent",revList.get(0).name(),shaBranch1); + assertEquals(revList.get(0).name(),shaBranch1,"Integration should have branch1 as a parent"); // create a second branch off of master, so as to test that --no-ff is published as expected testGitClient.checkout("master"); @@ -446,18 +445,18 @@ public void testMergeAndPushNoFF() throws Exception { // |/ // * a5dda1a (master) Initial Commit // - assertTrue("commitFile1 should exist in the workspace",build1.getWorkspace().child(commitFile1).exists()); - assertTrue("commitFile2 should exist in the workspace",build1.getWorkspace().child(commitFile2).exists()); + assertTrue(build1.getWorkspace().child(commitFile1).exists(),"commitFile1 should exist in the workspace"); + assertTrue(build1.getWorkspace().child(commitFile2).exists(),"commitFile2 should exist in the workspace"); // the integration branch should have branch1 and branch2 as parents revList = testGitClient.revList("integration^1"); - assertEquals("Integration should have the first merge commit as a parent",revList.get(0),mergeCommit); + assertEquals(revList.get(0),mergeCommit,"Integration should have the first merge commit as a parent"); revList = testGitClient.revList("integration^2"); - assertEquals("Integration should have branch2 as a parent",revList.get(0).name(),shaBranch2); + assertEquals(revList.get(0).name(),shaBranch2,"Integration should have branch2 as a parent"); } @Issue("JENKINS-12402") @Test - public void testMergeAndPushFFOnly() throws Exception { + void testMergeAndPushFFOnly() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( @@ -481,7 +480,7 @@ public void testMergeAndPushFFOnly() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, "commitFileBase"); assertTrue(build1.getWorkspace().child("commitFileBase").exists()); String shaIntegration = getHeadRevision(build1, "integration"); - assertEquals("integration should be at HEAD", shaIntegration, testGitClient.revParse(Constants.HEAD).name()); + assertEquals(shaIntegration, testGitClient.revParse(Constants.HEAD).name(), "integration should be at HEAD"); // create a new branch and build // This merge can work with --ff-only @@ -501,15 +500,15 @@ public void testMergeAndPushFFOnly() throws Exception { // * f4d190c (HEAD, integration, branch1) Commit number 1 // * f787536 (master) Initial Commit // - assertTrue("commitFile1 should exist in the workspace",build2.getWorkspace().child("commitFile1").exists()); + assertTrue(build2.getWorkspace().child("commitFile1").exists(),"commitFile1 should exist in the workspace"); shaIntegration = getHeadRevision(build2, "integration"); String shaHead = testGitClient.revParse(Constants.HEAD).name(); - assertEquals("integration and branch1 should line up",shaIntegration, shaBranch1); - assertEquals("integration and head should line up",shaIntegration, shaHead); + assertEquals(shaIntegration,shaBranch1, "integration and branch1 should line up"); + assertEquals(shaIntegration,shaHead, "integration and head should line up"); // integration should have master as the parent commit List revList = testGitClient.revList("integration^1"); ObjectId integrationParent = revList.get(0); - assertEquals("Fast-forward merge should have had master as a parent",master,integrationParent); + assertEquals(master,integrationParent,"Fast-forward merge should have had master as a parent"); // create a second branch off of master, so as to force a merge commit // but the publish will fail as --ff-only cannot work with a parallel branch @@ -528,21 +527,21 @@ public void testMergeAndPushFFOnly() throws Exception { // | * 79c49b2 (integration, branch1) Commit number 1 // |/ // * ebffeb3 (master) Initial Commit - assertFalse("commitFile1 should not exist in the workspace",build2.getWorkspace().child("commitFile1").exists()); - assertTrue("commitFile2 should exist in the workspace",build2.getWorkspace().child("commitFile2").exists()); + assertFalse(build2.getWorkspace().child("commitFile1").exists(),"commitFile1 should not exist in the workspace"); + assertTrue(build2.getWorkspace().child("commitFile2").exists(),"commitFile2 should exist in the workspace"); revList = testGitClient.revList("branch2^1"); - assertEquals("branch2 should have master as a parent",revList.get(0),master); - assertThrows("branch2 should have no other parent than master", NullPointerException.class, () -> testGitClient.revList("branch2^2")); + assertEquals(revList.get(0),master,"branch2 should have master as a parent"); + assertThrows(NullPointerException.class, () -> testGitClient.revList("branch2^2"), "branch2 should have no other parent than master"); } @Issue("JENKINS-24786") @Test - public void testPushEnvVarsInRemoteConfig() throws Exception{ + void testPushEnvVarsInRemoteConfig() throws Exception{ FreeStyleProject project = setupSimpleProject("master"); // create second (bare) test repository as target TaskListener listener = StreamTaskListener.fromStderr(); - TestGitRepo testTargetRepo = new TestGitRepo("target", tmpFolder.newFolder("push_env_vars"), listener); + TestGitRepo testTargetRepo = new TestGitRepo("target", newFolder(tmpFolder, "push_env_vars"), listener); testTargetRepo.git.init_().workspace(testTargetRepo.gitDir.getAbsolutePath()).bare(true).execute(); testTargetRepo.commit("lostTargetFile", new PersonIdent("John Doe", "john@example.com"), "Initial Target Commit"); @@ -586,7 +585,7 @@ public void testPushEnvVarsInRemoteConfig() throws Exception{ @Issue("JENKINS-24082") @Test - public void testForcePush() throws Exception { + void testForcePush() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( @@ -625,10 +624,10 @@ public void testForcePush() throws Exception { // build will merge and push to "otherbranch" in test repo // Without force, this would fail assertEquals(otherCommit, testGitClient.revParse("otherbranch")); // not merged yet - assertTrue("otherCommit not in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit)); + assertTrue(testGitClient.revList("otherbranch").contains(otherCommit), "otherCommit not in otherbranch"); build(project, Result.SUCCESS, "commitFile2"); assertEquals(masterCommit2, testGitClient.revParse("otherbranch")); // merge done - assertFalse("otherCommit in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit)); + assertFalse(testGitClient.revList("otherbranch").contains(otherCommit), "otherCommit in otherbranch"); // Commit to otherbranch in test repo so that next merge will fail testGitClient.checkout("otherbranch"); @@ -653,10 +652,10 @@ public void testForcePush() throws Exception { // build will attempts to merge and push to "otherbranch" in test repo. // Without force, will fail assertEquals(otherCommit2, testGitClient.revParse("otherbranch")); // not merged yet - assertTrue("otherCommit2 not in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit2)); + assertTrue(testGitClient.revList("otherbranch").contains(otherCommit2), "otherCommit2 not in otherbranch"); build(project, Result.FAILURE, "commitFile3"); assertEquals(otherCommit2, testGitClient.revParse("otherbranch")); // still not merged - assertTrue("otherCommit2 not in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit2)); + assertTrue(testGitClient.revList("otherbranch").contains(otherCommit2), "otherCommit2 not in otherbranch"); // Remove unforcedPublisher, add forcedPublisher project.getPublishersList().remove(unforcedPublisher); @@ -669,18 +668,18 @@ public void testForcePush() throws Exception { // build will merge and push to "otherbranch" in test repo. assertEquals(otherCommit2, testGitClient.revParse("otherbranch")); - assertTrue("otherCommit2 not in test repo", testGitClient.isCommitInRepo(otherCommit2)); - assertTrue("otherCommit2 not in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit2)); + assertTrue(testGitClient.isCommitInRepo(otherCommit2), "otherCommit2 not in test repo"); + assertTrue(testGitClient.revList("otherbranch").contains(otherCommit2), "otherCommit2 not in otherbranch"); build(project, Result.SUCCESS, "commitFile4"); assertEquals(masterCommit4, testGitClient.revParse("otherbranch")); assertEquals(masterCommit3, testGitClient.revParse("otherbranch^")); - assertFalse("otherCommit2 in otherbranch", testGitClient.revList("otherbranch").contains(otherCommit2)); + assertFalse(testGitClient.revList("otherbranch").contains(otherCommit2), "otherCommit2 in otherbranch"); } /* Fix push to remote when skipTag is enabled */ @Issue("JENKINS-17769") @Test - public void testMergeAndPushWithSkipTagEnabled() throws Exception { + void testMergeAndPushWithSkipTagEnabled() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( @@ -713,7 +712,7 @@ public void testMergeAndPushWithSkipTagEnabled() throws Exception { } @Test - public void testRebaseBeforePush() throws Exception { + void testRebaseBeforePush() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( @@ -757,7 +756,7 @@ public void testRebaseBeforePush() throws Exception { @Issue("JENKINS-24786") @Test - public void testMergeAndPushWithCharacteristicEnvVar() throws Exception { + void testMergeAndPushWithCharacteristicEnvVar() throws Exception { // jgit doesn't work because of missing PerBuildTag //GitTool tool = new JGitTool(Collections.emptyList()); //r.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool); @@ -772,14 +771,14 @@ public void testMergeAndPushWithCharacteristicEnvVar() throws Exception { */ String envName = "JENKINS_SERVER_COOKIE"; String envValue = project.getCharacteristicEnvVars().get(envName, "NOT-SET"); - assertNotEquals("Env " + envName + " not set", "NOT-SET", envValue); + assertNotEquals("NOT-SET", envValue, "Env " + envName + " not set"); checkEnvVar(project, envName, envValue); } @Issue("JENKINS-24786") @Test - public void testMergeAndPushWithSystemEnvVar() throws Exception { + void testMergeAndPushWithSystemEnvVar() throws Exception { String envName = isWindows() ? "COMPUTERNAME" : "LOGNAME"; String envValue = System.getenv().get(envName); if (envValue == null || envValue.isEmpty()) { @@ -789,8 +788,8 @@ public void testMergeAndPushWithSystemEnvVar() throws Exception { FreeStyleProject project = setupSimpleProject("master"); - assertNotNull("Env " + envName + " not set", envValue); - assertFalse("Env " + envName + " empty", envValue.isEmpty()); + assertNotNull(envValue, "Env " + envName + " not set"); + assertFalse(envValue.isEmpty(), "Env " + envName + " empty"); checkEnvVar(project, envName, envValue); } @@ -832,24 +831,24 @@ private void checkEnvVar(FreeStyleProject project, String envName, String envVal assertTrue(testGitClient.isCommitInRepo(initialCommit)); // Create branch in the test repo (pulled into the project workspace at build) - assertFalse("Test repo has " + envValue + " branch", hasBranch(envValue)); + assertFalse(hasBranch(envValue), "Test repo has " + envValue + " branch"); testGitClient.branch(envValue); - assertTrue("Test repo missing " + envValue + " branch", hasBranch(envValue)); - assertFalse(tagNameValue + " in " + testGitClient, testGitClient.tagExists(tagNameValue)); + assertTrue(hasBranch(envValue), "Test repo missing " + envValue + " branch"); + assertFalse(testGitClient.tagExists(tagNameValue), tagNameValue + " in " + testGitClient); // Build the branch final FreeStyleBuild build0 = build(project, Result.SUCCESS, "commitFileBase"); String build0HeadBranch = getHeadRevision(build0, envValue); assertEquals(build0HeadBranch, initialCommit.getName()); - assertTrue(tagNameValue + " not in " + testGitClient, testGitClient.tagExists(tagNameValue)); - assertTrue(tagNameValue + " not in build", build0.getWorkspace().child(".git/refs/tags/" + tagNameValue).exists()); + assertTrue(testGitClient.tagExists(tagNameValue), tagNameValue + " not in " + testGitClient); + assertTrue(build0.getWorkspace().child(".git/refs/tags/" + tagNameValue).exists(), tagNameValue + " not in build"); // Create a topic branch in the source repository and commit to topic branch String topicBranch = envValue + "-topic1"; - assertFalse("Test repo has " + topicBranch + " branch", hasBranch(topicBranch)); + assertFalse(hasBranch(topicBranch), "Test repo has " + topicBranch + " branch"); testGitClient.checkout(null, topicBranch); - assertTrue("Test repo has no " + topicBranch + " branch", hasBranch(topicBranch)); + assertTrue(hasBranch(topicBranch), "Test repo has no " + topicBranch + " branch"); final String commitFile1 = "commitFile1"; commitNewFile(commitFile1); ObjectId topicCommit = testGitClient.getHeadRev(testGitDir.getAbsolutePath(), topicBranch); @@ -859,11 +858,11 @@ private void checkEnvVar(FreeStyleProject project, String envName, String envVal final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); FilePath myWorkspace = build1.getWorkspace(); assertTrue(myWorkspace.child(commitFile1).exists()); - assertTrue("Tag " + tagNameValue + " not in build", myWorkspace.child(".git/refs/tags/" + tagNameValue).exists()); + assertTrue(myWorkspace.child(".git/refs/tags/" + tagNameValue).exists(), "Tag " + tagNameValue + " not in build"); String build1Head = getHeadRevision(build1, envValue); assertEquals(build1Head, testGitClient.revParse(Constants.HEAD).name()); - assertEquals("Wrong head commit in build1", topicCommit.getName(), build1Head); + assertEquals(topicCommit.getName(), build1Head, "Wrong head commit in build1"); } @@ -925,9 +924,13 @@ private boolean hasBranch(String branchName) throws GitException, InterruptedExc return false; } - /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ - private boolean isWindows() { - return java.io.File.pathSeparatorChar==';'; + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; } } diff --git a/src/test/java/hudson/plugins/git/GitRevisionTokenMacroTest.java b/src/test/java/hudson/plugins/git/GitRevisionTokenMacroTest.java index e3c7fef5ee..62ab4b8af7 100644 --- a/src/test/java/hudson/plugins/git/GitRevisionTokenMacroTest.java +++ b/src/test/java/hudson/plugins/git/GitRevisionTokenMacroTest.java @@ -26,45 +26,43 @@ import hudson.model.AbstractBuild; import hudson.model.TaskListener; import hudson.plugins.git.util.BuildData; +import org.junit.jupiter.api.BeforeEach; + import org.eclipse.jgit.lib.ObjectId; -import org.junit.Test; -import org.junit.Before; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; -public class GitRevisionTokenMacroTest { +class GitRevisionTokenMacroTest { private GitRevisionTokenMacro tokenMacro; - public GitRevisionTokenMacroTest() { - } - - @Before - public void createTokenMacro() { + @BeforeEach + void beforeEach() { tokenMacro = new GitRevisionTokenMacro(); } @Test - public void testAcceptsMacroName() { + void testAcceptsMacroName() { assertTrue(tokenMacro.acceptsMacroName("GIT_REVISION")); } @Test - public void testAcceptsMacroNameFalse() { + void testAcceptsMacroNameFalse() { assertFalse(tokenMacro.acceptsMacroName("NOT_A_GIT_REVISION")); } - @Test(expected = NullPointerException.class) - public void testEvaluate() throws Exception { - // Real test in GitSCMTest#testBasicRemotePoll - tokenMacro.evaluate(null, TaskListener.NULL, "GIT_REVISION"); + @Test + void testEvaluate() throws Exception { + assertThrows(NullPointerException.class, () -> + // Real test in GitSCMTest#testBasicRemotePoll + tokenMacro.evaluate(null, TaskListener.NULL, "GIT_REVISION")); } @Test - public void testEvaluateMockBuildNull() throws Exception { + void testEvaluateMockBuildNull() throws Exception { // Real test in GitSCMTest#testBasicRemotePoll AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getAction(BuildData.class)).thenReturn(null); @@ -72,7 +70,7 @@ public void testEvaluateMockBuildNull() throws Exception { } @Test - public void testEvaluateMockBuildDataNull() throws Exception { + void testEvaluateMockBuildDataNull() throws Exception { // Real test in GitSCMTest#testBasicRemotePoll BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(null); @@ -82,7 +80,7 @@ public void testEvaluateMockBuildDataNull() throws Exception { } @Test - public void testEvaluateMockBuildData() throws Exception { + void testEvaluateMockBuildData() throws Exception { // Real test in GitSCMTest#testBasicRemotePoll Revision revision = new Revision(ObjectId.fromString("42ab63c2d69c012122d9b373450404244cc58e81")); BuildData buildData = Mockito.mock(BuildData.class); @@ -93,7 +91,7 @@ public void testEvaluateMockBuildData() throws Exception { } @Test - public void testEvaluateMockBuildDataLength() throws Exception { + void testEvaluateMockBuildDataLength() throws Exception { // Real test in GitSCMTest#testBasicRemotePoll Revision revision = new Revision(ObjectId.fromString("42ab63c2d69c012122d9b373450404244cc58e81")); BuildData buildData = Mockito.mock(BuildData.class); diff --git a/src/test/java/hudson/plugins/git/GitSCMBrowserTest.java b/src/test/java/hudson/plugins/git/GitSCMBrowserTest.java index 08dd0da57f..5f030daebf 100644 --- a/src/test/java/hudson/plugins/git/GitSCMBrowserTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMBrowserTest.java @@ -27,18 +27,21 @@ import hudson.plugins.git.browser.GitLab; import hudson.plugins.git.browser.GitRepositoryBrowser; import hudson.plugins.git.browser.GithubWeb; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -@RunWith(Parameterized.class) -public class GitSCMBrowserTest { +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; + +@ParameterizedClass(name = "{0}") +@MethodSource("permuteRepositoryURL") +class GitSCMBrowserTest { private final String gitURI; private final Class expectedClass; @@ -81,8 +84,7 @@ private static String expectedURL(String url) { } - @Parameterized.Parameters(name = "{0}") - public static Collection permuteRepositoryURL() { + static Collection permuteRepositoryURL() { /* Systematically formed test URLs */ String[] protocols = {"https", "ssh", "git"}; String[] usernames = {"git:password@", "git@", "bob@", ""}; @@ -126,7 +128,7 @@ public static Collection permuteRepositoryURL() { } @Test - public void guessedBrowser() throws Exception { + void guessedBrowser() throws Exception { GitSCM gitSCM = new GitSCM(gitURI); GitRepositoryBrowser browser = (GitRepositoryBrowser) gitSCM.guessBrowser(); if (expectedClass == null || expectedURI == null) { diff --git a/src/test/java/hudson/plugins/git/GitSCMSlowTest.java b/src/test/java/hudson/plugins/git/GitSCMSlowTest.java index 2e2c9ac384..1ba6c70b36 100644 --- a/src/test/java/hudson/plugins/git/GitSCMSlowTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMSlowTest.java @@ -24,6 +24,8 @@ import hudson.slaves.EnvironmentVariablesNodeProperty; import java.io.File; import java.io.IOException; +import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -31,30 +33,22 @@ import java.util.Set; import jenkins.model.Jenkins; import jenkins.plugins.git.CliGitCommand; -import jenkins.plugins.git.RandomOrder; import jenkins.security.MasterToSlaveCallable; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeTrue; +import static hudson.Functions.isWindows; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.junit.jupiter.api.Assertions.*; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.storage.file.UserConfigFile; import org.eclipse.jgit.util.FS; import org.eclipse.jgit.util.SystemReader; import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Stopwatch; -import org.junit.rules.TestName; -import org.junit.runner.OrderWith; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.jvnet.hudson.test.Issue; /** @@ -62,22 +56,19 @@ * * @author Mark Waite */ -@OrderWith(RandomOrder.class) -public class GitSCMSlowTest extends AbstractGitTestCase { +@TestMethodOrder(MethodOrderer.Random.class) +class GitSCMSlowTest extends AbstractGitTestCase { private final Random random = new Random(); private boolean useChangelogToBranch = random.nextBoolean(); private static boolean gpgsignEnabled = false; // set by gpgsignCheck() - @BeforeClass - public static void setGitDefaults() throws Exception { + @BeforeAll + static void beforeAll() throws Exception { SystemReader.getInstance().getUserConfig().clear(); CliGitCommand gitCmd = new CliGitCommand(null); gitCmd.setDefaults(); - } - @BeforeClass - public static void gpgsignCheck() throws Exception { File userGitConfig = new File(System.getProperty("user.home"), ".gitconfig"); File xdgGitConfig = userGitConfig; String xdgDirName = System.getenv("XDG_CONFIG_HOME"); @@ -90,20 +81,17 @@ public static void gpgsignCheck() throws Exception { userConfig.getBoolean(ConfigConstants.CONFIG_TAG_SECTION, ConfigConstants.CONFIG_KEY_GPGSIGN, false); } - @ClassRule - public static Stopwatch stopwatch = new Stopwatch(); - @Rule - public TestName testName = new TestName(); + private static final Instant START_TIME = Instant.now(); private static final int MAX_SECONDS_FOR_THESE_TESTS = 180; private boolean isTimeAvailable() { String env = System.getenv("CI"); - if (env == null || !Boolean.parseBoolean(env)) { + if (!Boolean.parseBoolean(env)) { // Run all tests when not in CI environment return true; } - return stopwatch.runtime(SECONDS) <= MAX_SECONDS_FOR_THESE_TESTS; + return Duration.between(START_TIME, Instant.now()).toSeconds() <= MAX_SECONDS_FOR_THESE_TESTS; } private void addChangelogToBranchExtension(GitSCM scm) { @@ -120,14 +108,14 @@ private void addChangelogToBranchExtension(GitSCM scm) { */ @Issue("JENKINS-22604") @Test - public void testConfigRoundtripURLPreserved() throws Exception { + void testConfigRoundtripURLPreserved() throws Exception { /* Long running test of low value on Windows * Only run on non-Windows and approximately 50% of test runs * On Windows, it requires 24 seconds before test finishes */ if (isWindows() || random.nextBoolean()) { return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject p = createFreeStyleProject(); final String url = "https://github.com/jenkinsci/jenkins"; GitRepositoryBrowser browser = new GithubWeb(url); @@ -137,7 +125,7 @@ public void testConfigRoundtripURLPreserved() throws Exception { p.setScm(scm); r.configRoundtrip(p); r.assertEqualDataBoundBeans(scm, p.getScm()); - assertEquals("Wrong key", "git " + url, scm.getKey()); + assertEquals("git " + url, scm.getKey(), "Wrong key"); } private List createRepoList(String url) { @@ -151,14 +139,14 @@ private List createRepoList(String url) { */ @Issue("JENKINS-33695") @Test - public void testConfigRoundtripExtensionsPreserved() throws Exception { + void testConfigRoundtripExtensionsPreserved() throws Exception { /* Long running test of low value on Windows * Only run on non-Windows and approximately 50% of test runs * On Windows, it requires 26 seconds before test finishes */ if (isWindows() || random.nextBoolean()) { return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject p = createFreeStyleProject(); final String url = "https://github.com/jenkinsci/git-plugin.git"; GitRepositoryBrowser browser = new GithubWeb(url); @@ -179,14 +167,14 @@ public void testConfigRoundtripExtensionsPreserved() throws Exception { p = r.configRoundtrip(p); List extensions = scm.getExtensions().toList(); assertTrue(extensions.contains(localBranchExtension)); - assertEquals("Wrong extension count before reload", 1, extensions.size()); + assertEquals(1, extensions.size(), "Wrong extension count before reload"); r.assertEqualDataBoundBeans(browser, p.getScm().getBrowser()); /* Reload configuration from disc */ p.doReload(); GitSCM reloadedGit = (GitSCM) p.getScm(); List reloadedExtensions = reloadedGit.getExtensions().toList(); - assertEquals("Wrong extension count after reload", 1, reloadedExtensions.size()); + assertEquals(1, reloadedExtensions.size(), "Wrong extension count after reload"); LocalBranch reloadedLocalBranch = (LocalBranch) reloadedExtensions.get(0); assertEquals(localBranchExtension.getLocalBranch(), reloadedLocalBranch.getLocalBranch()); r.assertEqualDataBoundBeans(browser, reloadedGit.getBrowser()); @@ -196,14 +184,14 @@ public void testConfigRoundtripExtensionsPreserved() throws Exception { * Makes sure that the configuration form works. */ @Test - public void testConfigRoundtrip() throws Exception { + void testConfigRoundtrip() throws Exception { /* Long running test of low value on Windows. * Only run on non-Windows and approximately 50% of test runs * On Windows, it requires 20 seconds before test finishes */ if (isWindows() || random.nextBoolean()) { return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject p = createFreeStyleProject(); GitSCM scm = new GitSCM("https://github.com/jenkinsci/jenkins"); p.setScm(scm); @@ -212,25 +200,19 @@ public void testConfigRoundtrip() throws Exception { } @Test - public void testBuildChooserContext() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBuildChooserContext() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); final FreeStyleProject p = createFreeStyleProject(); final FreeStyleBuild b = r.buildAndAssertSuccess(p); GitSCM.BuildChooserContextImpl c = new GitSCM.BuildChooserContextImpl(p, b, null); - c.actOnBuild(new BuildChooserContext.ContextCallable, Object>() { - @Override - public Object invoke(Run param, VirtualChannel channel) throws IOException, InterruptedException { - assertSame(param, b); - return null; - } + c.actOnBuild((BuildChooserContext.ContextCallable, Object>) (param, channel) -> { + assertSame(param, b); + return null; }); - c.actOnProject(new BuildChooserContext.ContextCallable, Object>() { - @Override - public Object invoke(Job param, VirtualChannel channel) throws IOException, InterruptedException { - assertSame(param, p); - return null; - } + c.actOnProject((BuildChooserContext.ContextCallable, Object>) (param, channel) -> { + assertSame(param, p); + return null; }); DumbSlave agent = r.createOnlineSlave(); assertEquals(p.toString(), agent.getChannel().call(new GitSCMSlowTest.BuildChooserContextTestCallable(c))); @@ -247,10 +229,11 @@ public BuildChooserContextTestCallable(BuildChooserContext c) { @Override public String call() throws IOException { try { + // Can not be a lamda -> SecurityException: Rejected: java.lang.invoke.SerializedLambda; see https://jenkins.io/redirect/class-filter/ return c.actOnProject(new BuildChooserContext.ContextCallable, String>() { @Override public String invoke(Job param, VirtualChannel channel) throws IOException, InterruptedException { - assertTrue(channel instanceof Channel); + assertInstanceOf(Channel.class, channel); assertNotNull(Jenkins.getInstanceOrNull()); return param.toString(); } @@ -262,8 +245,8 @@ public String invoke(Job param, VirtualChannel channel) throws IOException } @Test - public void testMergeFailedWithAgent() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeFailedWithAgent() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(r.createSlave().getSelfLabel()); @@ -287,21 +270,21 @@ public void testMergeFailedWithAgent() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); r.buildAndAssertStatus(Result.FAILURE, project); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } @Test - public void testMergeWithAgent() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeWithAgent() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(r.createSlave().getSelfLabel()); @@ -325,7 +308,7 @@ public void testMergeWithAgent() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); @@ -333,11 +316,11 @@ public void testMergeWithAgent() throws Exception { testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } /** @@ -358,8 +341,8 @@ public GitClient decorate(GitSCM scm, GitClient git) throws IOException, Interru } @Test - public void testMergeWithMatrixBuild() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeWithMatrixBuild() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); /* The testMergeWithMatrixBuild test fails randomly on several * machines when commit.gpgsign and tag.gpgsign are not * enabled if the TestPreBuildMerge implementation is used. It @@ -371,7 +354,7 @@ public void testMergeWithMatrixBuild() throws Exception { * Other tests in this class are able to use TestPreBuildMerge * without issue. */ - assumeFalse("gpgsign enabled", gpgsignEnabled); + assumeFalse(gpgsignEnabled, "gpgsign enabled"); //Create a matrix project and a couple of axes MatrixProject project = r.jenkins.createProject(MatrixProject.class, "xyz"); project.setAxes(new AxisList(new Axis("VAR", "a", "b"))); @@ -396,7 +379,7 @@ public void testMergeWithMatrixBuild() throws Exception { final MatrixBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); @@ -404,16 +387,16 @@ public void testMergeWithMatrixBuild() throws Exception { testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); final MatrixBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } @Test - public void testInitSparseCheckout() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testInitSparseCheckout() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupProject("master", Collections.singletonList(new SparseCheckoutPath("toto"))); // run build first to create workspace @@ -430,8 +413,8 @@ public void testInitSparseCheckout() throws Exception { } @Test - public void testInitSparseCheckoutBis() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testInitSparseCheckoutBis() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupProject("master", Collections.singletonList(new SparseCheckoutPath("titi"))); // run build first to create workspace @@ -448,8 +431,8 @@ public void testInitSparseCheckoutBis() throws Exception { } @Test - public void testInitSparseCheckoutOverAgent() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testInitSparseCheckoutOverAgent() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupProject("master", Collections.singletonList(new SparseCheckoutPath("titi"))); project.setAssignedLabel(r.createSlave().getSelfLabel()); @@ -468,8 +451,8 @@ public void testInitSparseCheckoutOverAgent() throws Exception { @Issue("HUDSON-7411") @Test - public void testNodeEnvVarsAvailable() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testNodeEnvVarsAvailable() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); DumbSlave agent = r.createSlave(); setVariables(agent, new EnvironmentVariablesNodeProperty.Entry("TESTKEY", "agent value")); @@ -482,8 +465,8 @@ public void testNodeEnvVarsAvailable() throws Exception { } @Test - public void testBasicWithAgent() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBasicWithAgent() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(r.createSlave().getSelfLabel()); @@ -492,26 +475,18 @@ public void testBasicWithAgent() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); - assertEquals("The build should have only one culprit", 1, culprits.size()); - assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); + assertEquals(1, culprits.size(), "The build should have only one culprit"); + assertEquals(janeDoe.getName(), culprits.iterator().next().getFullName(), ""); assertTrue(build2.getWorkspace().child(commitFile2).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); - } - - /** - * inline ${@link hudson.Functions#isWindows()} to prevent a transient - * remote classloader issue - */ - private boolean isWindows() { - return java.io.File.pathSeparatorChar == ';'; + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } } diff --git a/src/test/java/hudson/plugins/git/GitSCMTest.java b/src/test/java/hudson/plugins/git/GitSCMTest.java index f9cf6fee2e..98ceda2b2c 100644 --- a/src/test/java/hudson/plugins/git/GitSCMTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMTest.java @@ -8,6 +8,7 @@ import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.htmlunit.html.HtmlPage; import hudson.EnvVars; @@ -65,24 +66,30 @@ import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.LoggerRule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.jvnet.hudson.test.LogRecorder; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.TestExtension; -import static org.jvnet.hudson.test.LoggerRule.recorded; +import static hudson.Functions.isWindows; +import static org.junit.jupiter.api.Assertions.*; +import static org.jvnet.hudson.test.LogRecorder.recorded; import java.io.File; import java.io.IOException; -import java.io.InputStream; import java.io.ObjectStreamException; +import java.io.Serial; import java.io.Serializable; -import java.net.URL; -import java.nio.charset.StandardCharsets; import java.text.MessageFormat; +import java.time.Duration; +import java.time.Instant; import java.util.*; -import static java.util.concurrent.TimeUnit.SECONDS; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; @@ -94,20 +101,7 @@ import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.rules.Stopwatch; -import org.junit.rules.TestName; -import org.junit.runner.OrderWith; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.anyString; @@ -117,47 +111,44 @@ import jenkins.model.Jenkins; import jenkins.plugins.git.CliGitCommand; import jenkins.plugins.git.GitSampleRepoRule; -import jenkins.plugins.git.RandomOrder; /** * Tests for {@link GitSCM}. * @author ishaaq */ -@OrderWith(RandomOrder.class) -public class GitSCMTest extends AbstractGitTestCase { - @Rule - public GitSampleRepoRule secondRepo = new GitSampleRepoRule(); +@TestMethodOrder(MethodOrderer.Random.class) +@WithGitSampleRepo +class GitSCMTest extends AbstractGitTestCase { - @Rule - public LoggerRule logRule = new LoggerRule(); + private GitSampleRepoRule secondRepo; + + private final LogRecorder recorder = new LogRecorder(); private CredentialsStore store = null; - @ClassRule - public static Stopwatch stopwatch = new Stopwatch(); - @Rule - public TestName testName = new TestName(); + private static final Instant START_TIME = Instant.now(); private static final int MAX_SECONDS_FOR_THESE_TESTS = 570; private boolean isTimeAvailable() { String env = System.getenv("CI"); - if (env == null || !Boolean.parseBoolean(env)) { + if (!Boolean.parseBoolean(env)) { // Run all tests when not in CI environment return true; } - return stopwatch.runtime(SECONDS) <= MAX_SECONDS_FOR_THESE_TESTS; + return Duration.between(START_TIME, Instant.now()).toSeconds() <= MAX_SECONDS_FOR_THESE_TESTS; } - @BeforeClass - public static void setGitDefaults() throws Exception { + @BeforeAll + static void beforeAll() throws Exception { SystemReader.getInstance().getUserConfig().clear(); CliGitCommand gitCmd = new CliGitCommand(null); gitCmd.setDefaults(); } - @Before - public void enableSystemCredentialsProvider() throws Exception { + @BeforeEach + void beforeEach(GitSampleRepoRule repo) throws Exception { + secondRepo = repo; SystemCredentialsProvider.getInstance().setDomainCredentialsMap( Collections.singletonMap(Domain.global(), Collections.emptyList())); for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.get())) { @@ -170,8 +161,8 @@ public void enableSystemCredentialsProvider() throws Exception { assertThat("The system credentials provider is enabled", store, notNullValue()); } - @After - public void waitForJenkinsIdle() throws Exception { + @AfterEach + void afterEach() throws Exception { if (cleanupIsUnreliable()) { r.waitUntilNoActivityUpTo(5001); } @@ -186,12 +177,12 @@ private StandardCredentials getInvalidCredential() throws FormException { } @Test - public void testAddGitTagAction() throws Exception { + void testAddGitTagAction() throws Exception { /* Low value test of low value feature, never run on Windows, run 50% on others */ if (isWindows() || random.nextBoolean()) { return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); List remoteConfigs = GitSCM.createRepoList("https://github.com/jenkinsci/git-plugin", "github"); project.setScm(new GitSCM(remoteConfigs, @@ -200,11 +191,11 @@ public void testAddGitTagAction() throws Exception { GitSCM scm = (GitSCM) project.getScm(); final DescriptorImpl descriptor = scm.getDescriptor(); boolean originalValue = scm.isAddGitTagAction(); - assertFalse("Wrong initial value for hide tag action", originalValue); + assertFalse(originalValue, "Wrong initial value for hide tag action"); descriptor.setAddGitTagAction(true); - assertTrue("Hide tag action not set", scm.isAddGitTagAction()); + assertTrue(scm.isAddGitTagAction(), "Hide tag action not set"); descriptor.setAddGitTagAction(false); - assertFalse("Wrong final value for hide tag action", scm.isAddGitTagAction()); + assertFalse(scm.isAddGitTagAction(), "Wrong final value for hide tag action"); descriptor.setAddGitTagAction(originalValue); // restore original value of addGitTagAction /* Exit test early if running on Windows and path will be too long */ @@ -215,27 +206,27 @@ public void testAddGitTagAction() throws Exception { return; } - logRule.record(GitSCM.class, Level.FINE).capture(20); + recorder.record(GitSCM.class, Level.FINE).capture(20); // Build 1 will not add a tag action commit("commitFileWithoutGitTagAction", johnDoe, "Commit 1 without git tag action"); build(project, Result.SUCCESS); - assertThat(logRule, recorded(containsString("Not adding GitTagAction to build 1"))); + assertThat(recorder, recorded(containsString("Not adding GitTagAction to build 1"))); // Build 2 will add a tag action descriptor.setAddGitTagAction(true); build(project, Result.SUCCESS); - assertThat(logRule, recorded(containsString("Adding GitTagAction to build 2"))); + assertThat(recorder, recorded(containsString("Adding GitTagAction to build 2"))); // Build 3 will not add a tag action descriptor.setAddGitTagAction(false); build(project, Result.SUCCESS); - assertThat(logRule, recorded(containsString("Not adding GitTagAction to build 3"))); + assertThat(recorder, recorded(containsString("Not adding GitTagAction to build 3"))); } @Test - public void manageShouldAccessGlobalConfig() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void manageShouldAccessGlobalConfig() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); final String USER = "user"; final String MANAGER = "manager"; r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); @@ -256,13 +247,13 @@ public void manageShouldAccessGlobalConfig() throws Exception { Collection descriptors = Functions.getSortedDescriptorsForGlobalConfigUnclassified(); Optional found = descriptors.stream().filter(descriptor -> descriptor instanceof GitSCM.DescriptorImpl).findFirst(); - assertTrue("Global configuration should be accessible to MANAGE users", found.isPresent()); + assertTrue(found.isPresent(), "Global configuration should be accessible to MANAGE users"); } } @Test - public void trackCredentials() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void trackCredentials() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); StandardCredentials credential = getInvalidCredential(); store.addCredentials(Domain.global(), credential); @@ -304,8 +295,8 @@ public void trackCredentials() throws Exception { * @throws Exception on error */ @Test - public void testBasic() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBasic() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: @@ -313,25 +304,25 @@ public void testBasic() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); - assertEquals("The build should have only one culprit", 1, culprits.size()); - assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); + assertEquals(1, culprits.size(), "The build should have only one culprit"); + assertEquals(janeDoe.getName(), culprits.iterator().next().getFullName(), ""); assertTrue(build2.getWorkspace().child(commitFile2).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } @Test @Issue("JENKINS-56176") - public void testBasicRemotePoll() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBasicRemotePoll() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); // FreeStyleProject project = setupProject("master", true, false); FreeStyleProject project = setupProject("master", false, null, null, null, true, null); // create initial commit and then run the build against it: @@ -339,19 +330,19 @@ public void testBasicRemotePoll() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; String sha1String = commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); - assertEquals("The build should have only one culprit", 1, culprits.size()); - assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); + assertEquals(1, culprits.size(), "The build should have only one culprit"); + assertEquals(janeDoe.getName(), culprits.iterator().next().getFullName(), ""); assertTrue(build2.getWorkspace().child(commitFile2).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); // JENKINS-56176 token macro expansion broke when BuildData was no longer updated assertThat(TokenMacro.expandAll(build2, listener, "${GIT_REVISION,length=7}"), is(sha1String.substring(0, 7))); assertThat(TokenMacro.expandAll(build2, listener, "${GIT_REVISION}"), is(sha1String)); @@ -359,8 +350,8 @@ public void testBasicRemotePoll() throws Exception { } @Test - public void testBranchSpecWithRemotesMaster() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBranchSpecWithRemotesMaster() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject projectMasterBranch = setupProject("remotes/origin/master", false, null, null, null, true, null); // create initial commit and build final String commitFile1 = "commitFile1"; @@ -378,8 +369,8 @@ public void testBranchSpecWithRemotesMaster() throws Exception { */ @Test @Issue("JENKINS-31393") - public void testSpecificRefspecs() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testSpecificRefspecs() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); List repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); @@ -411,8 +402,8 @@ public void testSpecificRefspecs() throws Exception { **/ @Test @Issue("JENKINS-56404") - public void testAvoidRedundantFetch() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testAvoidRedundantFetch() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); List repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/*:refs/remotes/*", null)); @@ -442,8 +433,8 @@ public void testAvoidRedundantFetch() throws Exception { **/ @Test @Issue("JENKINS-56404") - public void testAvoidRedundantFetchWithoutHonorRefSpec() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testAvoidRedundantFetchWithoutHonorRefSpec() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); List repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); @@ -487,8 +478,8 @@ public void testAvoidRedundantFetchWithoutHonorRefSpec() throws Exception { **/ @Test @Issue("JENKINS-56404") - public void testAvoidRedundantFetchWithHonorRefSpec() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testAvoidRedundantFetchWithHonorRefSpec() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); List repos = new ArrayList<>(); String refSpec = "+refs/heads/foo:refs/remotes/foo"; repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", refSpec, null)); @@ -525,8 +516,8 @@ public void testAvoidRedundantFetchWithHonorRefSpec() throws Exception { @Test @Issue("JENKINS-49757") - public void testAvoidRedundantFetchWithNullRefspec() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testAvoidRedundantFetchWithNullRefspec() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String nullRefspec = null; List repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", nullRefspec, null)); @@ -560,8 +551,8 @@ public void testAvoidRedundantFetchWithNullRefspec() throws Exception { */ @Test @Issue("JENKINS-49757") - public void testRetainRedundantFetch() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testRetainRedundantFetch() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String refspec = "+refs/heads/*:refs/remotes/origin/* +refs/pull/553/head:refs/remotes/origin/pull/553"; List repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", refspec, null)); @@ -595,8 +586,8 @@ public void testRetainRedundantFetch() throws Exception { */ @Test @Issue("JENKINS-49757") - public void testRetainRedundantFetchIfSecondFetchIsAllowed() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testRetainRedundantFetchIfSecondFetchIsAllowed() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String refspec = "+refs/heads/*:refs/remotes/*"; List repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", refspec, null)); @@ -670,8 +661,8 @@ private FilePath returnFile(FreeStyleBuild build) throws IOException, Interrupte */ @Test @Issue("JENKINS-36507") - public void testSpecificRefspecsWithoutCloneOption() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testSpecificRefspecsWithoutCloneOption() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); List repos = new ArrayList<>(); repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null)); FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); @@ -697,8 +688,8 @@ public void testSpecificRefspecsWithoutCloneOption() throws Exception { */ @Test @Issue("JENKINS-38608") - public void testAddFirstRepositoryWithNullRepoURL() throws Exception{ - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testAddFirstRepositoryWithNullRepoURL() throws Exception{ + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); List repos = new ArrayList<>(); repos.add(new UserRemoteConfig(null, null, null, null)); FreeStyleProject project = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null); @@ -720,8 +711,8 @@ public void testAddFirstRepositoryWithNullRepoURL() throws Exception{ */ @Test @Issue("JENKINS-38608") - public void testAddSecondRepositoryWithNullRepoURL() throws Exception{ - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testAddSecondRepositoryWithNullRepoURL() throws Exception{ + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String repoURL = "https://example.com/non-empty/repo/url"; List repos = new ArrayList<>(); repos.add(new UserRemoteConfig(repoURL, null, null, null)); @@ -737,8 +728,8 @@ public void testAddSecondRepositoryWithNullRepoURL() throws Exception{ } @Test - public void testBranchSpecWithRemotesHierarchical() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBranchSpecWithRemotesHierarchical() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject projectMasterBranch = setupProject("master", false, null, null, null, true, null); FreeStyleProject projectHierarchicalBranch = setupProject("remotes/origin/rel-1/xy", false, null, null, null, true, null); // create initial commit @@ -753,8 +744,8 @@ public void testBranchSpecWithRemotesHierarchical() throws Exception { } @Test - public void testBranchSpecUsingTagWithSlash() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBranchSpecUsingTagWithSlash() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject projectMasterBranch = setupProject("path/tag", false, null, null, null, true, null); // create initial commit and build final String commitFile1 = "commitFile1"; @@ -764,8 +755,8 @@ public void testBranchSpecUsingTagWithSlash() throws Exception { } @Test - public void testBasicIncludedRegion() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBasicIncludedRegion() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupProject("master", false, null, null, null, ".*3"); // create initial commit and then run the build against it: @@ -773,20 +764,20 @@ public void testBasicIncludedRegion() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling detected commit2 change, which should not have been included"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); - assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit3 change"); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set culprits = build2.getCulprits(); - assertEquals("The build should have two culprit", 2, culprits.size()); + assertEquals(2, culprits.size(), "The build should have two culprit"); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); @@ -794,7 +785,7 @@ public void testBasicIncludedRegion() throws Exception { assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } /** @@ -805,10 +796,10 @@ public void testBasicIncludedRegion() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test - public void testMergeCommitInExcludedRegionIsIgnored() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeCommitInExcludedRegionIsIgnored() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, ".*\\.excluded", null, ".*\\.included"); @@ -830,8 +821,8 @@ public void testMergeCommitInExcludedRegionIsIgnored() throws Exception { mergeCommand.execute(); // Should return false, because our merge commit falls within the excluded region. - assertFalse("Polling should report no changes, because they are in the excluded region.", - project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), + "Polling should report no changes, because they are in the excluded region."); } /** @@ -842,10 +833,10 @@ public void testMergeCommitInExcludedRegionIsIgnored() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test - public void testMergeCommitInExcludedDirectoryIsIgnored() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeCommitInExcludedDirectoryIsIgnored() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, "excluded/.*", null, "included/.*"); @@ -867,8 +858,8 @@ public void testMergeCommitInExcludedDirectoryIsIgnored() throws Exception { mergeCommand.execute(); // Should return false, because our merge commit falls within the excluded directory. - assertFalse("Polling should see no changes, because they are in the excluded directory.", - project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), + "Polling should see no changes, because they are in the excluded directory."); } /** @@ -879,10 +870,10 @@ public void testMergeCommitInExcludedDirectoryIsIgnored() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test - public void testMergeCommitInIncludedRegionIsProcessed() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeCommitInIncludedRegionIsProcessed() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, ".*\\.excluded", null, ".*\\.included"); @@ -905,8 +896,8 @@ public void testMergeCommitInIncludedRegionIsProcessed() throws Exception { mergeCommand.execute(); // Should return true, because our commit falls within the included region. - assertTrue("Polling should report changes, because they fall within the included region.", - project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), + "Polling should report changes, because they fall within the included region."); } /** @@ -917,10 +908,10 @@ public void testMergeCommitInIncludedRegionIsProcessed() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test - public void testMergeCommitInIncludedDirectoryIsProcessed() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeCommitInIncludedDirectoryIsProcessed() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, "excluded/.*", null, "included/.*"); @@ -944,8 +935,8 @@ public void testMergeCommitInIncludedDirectoryIsProcessed() throws Exception { // When this test passes, project.poll(listener).hasChanges()) should return // true, because our commit falls within the included region. - assertTrue("Polling should report changes, because they are in the included directory.", - project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), + "Polling should report changes, because they are in the included directory."); } /** @@ -956,10 +947,10 @@ public void testMergeCommitInIncludedDirectoryIsProcessed() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test - public void testMergeCommitOutsideIncludedRegionIsIgnored() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeCommitOutsideIncludedRegionIsIgnored() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, null, null, ".*\\.included"); @@ -982,8 +973,8 @@ public void testMergeCommitOutsideIncludedRegionIsIgnored() throws Exception { mergeCommand.execute(); // Should return false, because our commit falls outside the included region. - assertFalse("Polling should ignore the change, because it falls outside the included region.", - project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), + "Polling should ignore the change, because it falls outside the included region."); } /** @@ -994,10 +985,10 @@ public void testMergeCommitOutsideIncludedRegionIsIgnored() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test - public void testMergeCommitOutsideIncludedDirectoryIsIgnored() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeCommitOutsideIncludedDirectoryIsIgnored() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, null, null, "included/.*"); @@ -1020,8 +1011,8 @@ public void testMergeCommitOutsideIncludedDirectoryIsIgnored() throws Exception mergeCommand.execute(); // Should return false, because our commit falls outside of the included directory - assertFalse("Polling should ignore the change, because it falls outside the included directory.", - project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), + "Polling should ignore the change, because it falls outside the included directory."); } /** @@ -1033,10 +1024,10 @@ public void testMergeCommitOutsideIncludedDirectoryIsIgnored() throws Exception * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test - public void testMergeCommitOutsideExcludedRegionIsProcessed() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeCommitOutsideExcludedRegionIsProcessed() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, ".*\\.excluded", null, null); @@ -1059,8 +1050,8 @@ public void testMergeCommitOutsideExcludedRegionIsProcessed() throws Exception { mergeCommand.execute(); // Should return true, because our commit falls outside of the excluded region - assertTrue("Polling should process the change, because it falls outside the excluded region.", - project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), + "Polling should process the change, because it falls outside the excluded region."); } /** @@ -1072,10 +1063,10 @@ public void testMergeCommitOutsideExcludedRegionIsProcessed() throws Exception { * * @throws Exception on error */ - @Issue({"JENKINS-20389","JENKINS-23606"}) + @Issue({"JENKINS-20389", "JENKINS-23606"}) @Test - public void testMergeCommitOutsideExcludedDirectoryIsProcessed() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeCommitOutsideExcludedDirectoryIsProcessed() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); final String branchToMerge = "new-branch-we-merge-to-master"; FreeStyleProject project = setupProject("master", false, null, "excluded/.*", null, null); @@ -1099,13 +1090,13 @@ public void testMergeCommitOutsideExcludedDirectoryIsProcessed() throws Exceptio mergeCommand.execute(); // Should return true, because our commit falls outside of the excluded directory - assertTrue("SCM polling should process the change, because it falls outside the excluded directory.", - project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), + "SCM polling should process the change, because it falls outside the excluded directory."); } @Test - public void testIncludedRegionWithDeeperCommits() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testIncludedRegionWithDeeperCommits() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupProject("master", false, null, null, null, ".*3"); // create initial commit and then run the build against it: @@ -1113,11 +1104,11 @@ public void testIncludedRegionWithDeeperCommits() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling detected commit2 change, which should not have been included"); final String commitFile3 = "commitFile3"; @@ -1125,12 +1116,12 @@ public void testIncludedRegionWithDeeperCommits() throws Exception { final String commitFile4 = "commitFile4"; commit(commitFile4, janeDoe, "Commit number 4"); - assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit3 change"); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set culprits = build2.getCulprits(); - assertEquals("The build should have two culprit", 2, culprits.size()); + assertEquals(2, culprits.size(), "The build should have two culprit"); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); @@ -1138,12 +1129,12 @@ public void testIncludedRegionWithDeeperCommits() throws Exception { assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } @Test - public void testBasicExcludedRegion() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBasicExcludedRegion() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupProject("master", false, null, ".*2", null, null); // create initial commit and then run the build against it: @@ -1151,19 +1142,19 @@ public void testBasicExcludedRegion() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling detected commit2 change, which should have been excluded"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); - assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit3 change"); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set culprits = build2.getCulprits(); - assertEquals("The build should have two culprit", 2, culprits.size()); + assertEquals(2, culprits.size(), "The build should have two culprit"); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); @@ -1171,7 +1162,7 @@ public void testBasicExcludedRegion() throws Exception { assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } private int findLogLineStartsWith(List buildLog, String initialString) { @@ -1186,8 +1177,8 @@ private int findLogLineStartsWith(List buildLog, String initialString) { } @Test - public void testCleanBeforeCheckout() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testCleanBeforeCheckout() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null); ((GitSCM)p.getScm()).getExtensions().add(new CleanBeforeCheckout()); @@ -1208,8 +1199,8 @@ public void testCleanBeforeCheckout() throws Exception { } @Test - public void testFirstBuiltChangelog() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testFirstBuiltChangelog() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null); FirstBuildChangelog fbc = new FirstBuildChangelog(); ((GitSCM) p.getScm()).getExtensions().add(fbc); @@ -1228,8 +1219,8 @@ public void testFirstBuiltChangelog() throws Exception { @Issue("JENKINS-8342") @Test - public void testExcludedRegionMultiCommit() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testExcludedRegionMultiCommit() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); // Got 2 projects, each one should only build if changes in its own file FreeStyleProject clientProject = setupProject("master", false, null, ".*serverFile", null, null); FreeStyleProject serverProject = setupProject("master", false, null, ".*clientFile", null, null); @@ -1238,21 +1229,21 @@ public void testExcludedRegionMultiCommit() throws Exception { build(clientProject, Result.SUCCESS, initialCommitFile); build(serverProject, Result.SUCCESS, initialCommitFile); - assertFalse("scm polling should not detect any more changes after initial build", clientProject.poll(listener).hasChanges()); - assertFalse("scm polling should not detect any more changes after initial build", serverProject.poll(listener).hasChanges()); + assertFalse(clientProject.poll(listener).hasChanges(), "scm polling should not detect any more changes after initial build"); + assertFalse(serverProject.poll(listener).hasChanges(), "scm polling should not detect any more changes after initial build"); // Got commits on serverFile, so only server project should build. commit("myserverFile", johnDoe, "commit first server file"); - assertFalse("scm polling should not detect any changes in client project", clientProject.poll(listener).hasChanges()); - assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); + assertFalse(clientProject.poll(listener).hasChanges(), "scm polling should not detect any changes in client project"); + assertTrue(serverProject.poll(listener).hasChanges(), "scm polling did not detect changes in server project"); // Got commits on both client and serverFile, so both projects should build. commit("myNewserverFile", johnDoe, "commit new server file"); commit("myclientFile", johnDoe, "commit first clientfile"); - assertTrue("scm polling did not detect changes in client project", clientProject.poll(listener).hasChanges()); - assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); + assertTrue(clientProject.poll(listener).hasChanges(), "scm polling did not detect changes in client project"); + assertTrue(serverProject.poll(listener).hasChanges(), "scm polling did not detect changes in server project"); } /* @@ -1332,8 +1323,8 @@ public void testMultipleBranchWithExcludedUser() throws Exception { } */ @Test - public void testBasicExcludedUser() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBasicExcludedUser() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupProject("master", false, null, null, "Jane Doe", null); // create initial commit and then run the build against it: @@ -1341,18 +1332,18 @@ public void testBasicExcludedUser() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling detected commit2 change, which should have been excluded"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); - assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit3 change"); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set culprits = build2.getCulprits(); - assertEquals("The build should have two culprit", 2, culprits.size()); + assertEquals(2, culprits.size(), "The build should have two culprit"); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); @@ -1360,13 +1351,13 @@ public void testBasicExcludedUser() throws Exception { assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } @Test - public void testBasicInSubdir() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBasicInSubdir() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); ((GitSCM)project.getScm()).getExtensions().add(new RelativeTargetDirectory("subdir")); @@ -1375,27 +1366,27 @@ public void testBasicInSubdir() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, "subdir", Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); //... and build it... final FreeStyleBuild build2 = build(project, "subdir", Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); - assertEquals("The build should have only one culprit", 1, culprits.size()); - assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); - assertTrue("The workspace should have a 'subdir' subdirectory, but does not.", build2.getWorkspace().child("subdir").exists()); - assertTrue("The 'subdir' subdirectory should contain commitFile2, but does not.", build2.getWorkspace().child("subdir").child(commitFile2).exists()); + assertEquals(1, culprits.size(), "The build should have only one culprit"); + assertEquals(janeDoe.getName(), culprits.iterator().next().getFullName(), ""); + assertTrue(build2.getWorkspace().child("subdir").exists(), "The workspace should have a 'subdir' subdirectory, but does not."); + assertTrue(build2.getWorkspace().child("subdir").child(commitFile2).exists(), "The 'subdir' subdirectory should contain commitFile2, but does not."); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } @Issue("HUDSON-7547") @Test - public void testBasicWithAgentNoExecutorsOnMaster() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBasicWithAgentNoExecutorsOnMaster() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); r.jenkins.setNumExecutors(0); @@ -1407,24 +1398,24 @@ public void testBasicWithAgentNoExecutorsOnMaster() throws Exception { commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); - assertEquals("The build should have only one culprit", 1, culprits.size()); - assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); + assertEquals(1, culprits.size(), "The build should have only one culprit"); + assertEquals(janeDoe.getName(), culprits.iterator().next().getFullName(), ""); assertTrue(build2.getWorkspace().child(commitFile2).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } @Test - public void testAuthorOrCommitterFalse() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testAuthorOrCommitterFalse() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); // Test with authorOrCommitter set to false and make sure we get the committer. FreeStyleProject project = setupSimpleProject("master"); @@ -1433,26 +1424,26 @@ public void testAuthorOrCommitterFalse() throws Exception { commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final Set secondCulprits = secondBuild.getCulprits(); - assertEquals("The build should have only one culprit", 1, secondCulprits.size()); - assertEquals("Did not get the committer as the change author with authorOrCommitter==false", - janeDoe.getName(), secondCulprits.iterator().next().getFullName()); + assertEquals(1, secondCulprits.size(), "The build should have only one culprit"); + assertEquals(janeDoe.getName(), + secondCulprits.iterator().next().getFullName(), "Did not get the committer as the change author with authorOrCommitter==false"); } @Test - public void testAuthorOrCommitterTrue() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testAuthorOrCommitterTrue() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); // Next, test with authorOrCommitter set to true and make sure we get the author. FreeStyleProject project = setupSimpleProject("master"); ((GitSCM)project.getScm()).getExtensions().add(new AuthorInChangelog()); @@ -1462,26 +1453,26 @@ public void testAuthorOrCommitterTrue() throws Exception { commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final Set secondCulprits = secondBuild.getCulprits(); - assertEquals("The build should have only one culprit", 1, secondCulprits.size()); - assertEquals("Did not get the author as the change author with authorOrCommitter==true", - johnDoe.getName(), secondCulprits.iterator().next().getFullName()); + assertEquals(1, secondCulprits.size(), "The build should have only one culprit"); + assertEquals(johnDoe.getName(), + secondCulprits.iterator().next().getFullName(), "Did not get the author as the change author with authorOrCommitter==true"); } @Test - public void testNewCommitToUntrackedBranchDoesNotTriggerBuild() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testNewCommitToUntrackedBranchDoesNotTriggerBuild() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: @@ -1494,7 +1485,7 @@ public void testNewCommitToUntrackedBranchDoesNotTriggerBuild() throws Exception //.. and commit to it: final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); - assertFalse("scm polling should not detect commit2 change because it is not in the branch we are tracking.", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect commit2 change because it is not in the branch we are tracking."); } private String checkoutString(FreeStyleProject project, String envVar) { @@ -1502,8 +1493,8 @@ private String checkoutString(FreeStyleProject project, String envVar) { } @Test - public void testEnvVarsAvailable() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testEnvVarsAvailable() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; @@ -1527,8 +1518,8 @@ public void testEnvVarsAvailable() throws Exception { } @Test - public void testNodeOverrideGit() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testNodeOverrideGit() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); GitSCM scm = new GitSCM(null); DumbSlave agent = r.createSlave(); @@ -1551,8 +1542,8 @@ public void testNodeOverrideGit() throws Exception { * regression has been fixed. */ @Test - public void testGitSCMCanBuildAgainstTags() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testGitSCMCanBuildAgainstTags() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); final String mytag = "mytag"; FreeStyleProject project = setupSimpleProject(mytag); build(project, Result.FAILURE); // fail, because there's nothing to be checked out here @@ -1572,7 +1563,7 @@ public void testGitSCMCanBuildAgainstTags() throws Exception { // commit to it final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); - assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes since mytag is untouched right now"); build(project, Result.FAILURE); // fail, because there's nothing to be checked out here // tag it, then delete the tmp branch @@ -1582,9 +1573,9 @@ public void testGitSCMCanBuildAgainstTags() throws Exception { // at this point we're back on master, there are no other branches, tag "mytag" exists but is // not part of "master" - assertTrue("scm polling should detect commit2 change in 'mytag'", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling should detect commit2 change in 'mytag'"); build(project, Result.SUCCESS, commitFile2); - assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after last build"); // now, create tmp branch again against mytag: git.checkout(mytag); @@ -1592,7 +1583,7 @@ public void testGitSCMCanBuildAgainstTags() throws Exception { // another commit: final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); - assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes since mytag is untouched right now"); // now we're going to force mytag to point to the new commit, if everything goes well, gitSCM should pick the change up: git.tag(mytag, "mytag moved"); @@ -1600,9 +1591,9 @@ public void testGitSCMCanBuildAgainstTags() throws Exception { git.deleteBranch(tmpBranch); // at this point we're back on master, there are no other branches, "mytag" has been updated to a new commit: - assertTrue("scm polling should detect commit3 change in 'mytag'", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling should detect commit3 change in 'mytag'"); build(project, Result.SUCCESS, commitFile3); - assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after last build"); } /* @@ -1610,8 +1601,8 @@ public void testGitSCMCanBuildAgainstTags() throws Exception { * all branches. */ @Test - public void testMultipleBranchBuild() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMultipleBranchBuild() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); // empty string will result in a project that tracks against changes in all branches: final FreeStyleProject project = setupSimpleProject(""); final String commitFile1 = "commitFile1"; @@ -1626,9 +1617,9 @@ public void testMultipleBranchBuild() throws Exception { commit(commitFile2, johnDoe, "Commit number 2"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); - assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling should detect changes in 'master' branch"); build(project, Result.SUCCESS, commitFile1, commitFile2); - assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after last build"); // now jump back... git.checkout(fork); @@ -1638,14 +1629,14 @@ public void testMultipleBranchBuild() throws Exception { commit(forkFile1, johnDoe, "Fork commit number 1"); final String forkFile2 = "forkFile2"; commit(forkFile2, johnDoe, "Fork commit number 2"); - assertTrue("scm polling should detect changes in 'fork' branch", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling should detect changes in 'fork' branch"); build(project, Result.SUCCESS, forkFile1, forkFile2); - assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after last build"); } @Test - public void testMultipleBranchesWithTags() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMultipleBranchesWithTags() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); List branchSpecs = Arrays.asList( new BranchSpec("refs/tags/v*"), new BranchSpec("refs/remotes/origin/non-existent")); @@ -1661,10 +1652,10 @@ public void testMultipleBranchesWithTags() throws Exception { final String v1 = "v1"; git.tag(v1, "version 1"); - assertTrue("v1 tag exists", git.tagExists(v1)); + assertTrue(git.tagExists(v1), "v1 tag exists"); freeStyleBuild = build(project, Result.SUCCESS); - assertTrue("change set is empty", freeStyleBuild.getChangeSet().isEmptySet()); + assertTrue(freeStyleBuild.getChangeSet().isEmptySet(), "change set is empty"); commit("file1", johnDoe, "change to file1"); git.tag("none", "latest"); @@ -1675,22 +1666,22 @@ public void testMultipleBranchesWithTags() throws Exception { GitSCM scm = (GitSCM)project.getScm(); BuildData buildData = scm.getBuildData(freeStyleBuild); - assertEquals("last build matches the v1 tag revision", tag, buildData.lastBuild.getSHA1()); + assertEquals(tag, buildData.lastBuild.getSHA1(), "last build matches the v1 tag revision"); } @Issue("JENKINS-19037") @SuppressWarnings("ResultOfObjectAllocationIgnored") @Test - public void testBlankRepositoryName() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBlankRepositoryName() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); new GitSCM(null); } @Issue("JENKINS-10060") @Test - public void testSubmoduleFixup() throws Exception { + void testSubmoduleFixup() throws Exception { /* Unreliable on Windows and not a platform specific test */ - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); File repo = secondRepo.getRoot(); FilePath moduleWs = new FilePath(repo); org.jenkinsci.plugins.gitclient.GitClient moduleRepo = Git.with(listener, new EnvVars()).in(repo).getClient(); @@ -1722,7 +1713,7 @@ public void testSubmoduleFixup() throws Exception { Thread.sleep(100); FreeStyleBuild db = d.getLastBuild(); - assertNotNull("downstream build didn't happen",db); + assertNotNull(db,"downstream build didn't happen"); db = r.waitForCompletion(db); r.assertBuildStatusSuccess(db); @@ -1732,17 +1723,17 @@ public void testSubmoduleFixup() throws Exception { static public void assertCulprits(String assertMsg, Set actual, PersonIdent[] expected) { List fullNames = - actual.stream().map(User::getFullName).collect(Collectors.toList()); + actual.stream().map(User::getFullName).toList(); for(PersonIdent p : expected) { - assertTrue(assertMsg, fullNames.contains(p.getName())); + assertTrue(fullNames.contains(p.getName()), assertMsg); } } @Test - public void testHideCredentials() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testHideCredentials() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github")); // setup global config @@ -1752,9 +1743,9 @@ public void testHideCredentials() throws Exception { GitSCM scm = (GitSCM) project.getScm(); final DescriptorImpl descriptor = scm.getDescriptor(); - assertFalse("Wrong initial value for hide credentials", scm.isHideCredentials()); + assertFalse(scm.isHideCredentials(), "Wrong initial value for hide credentials"); descriptor.setHideCredentials(true); - assertTrue("Hide credentials not set", scm.isHideCredentials()); + assertTrue(scm.isHideCredentials(), "Hide credentials not set"); /* Exit test early if running on Windows and path will be too long */ /* Known limitation of git for Windows 2.28.0 and earlier */ @@ -1780,50 +1771,50 @@ public void testHideCredentials() throws Exception { @Test - public void testEmailCommitter() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testEmailCommitter() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); // setup global config GitSCM scm = (GitSCM) project.getScm(); final DescriptorImpl descriptor = scm.getDescriptor(); - assertFalse("Wrong initial value for create account based on e-mail", scm.isCreateAccountBasedOnEmail()); + assertFalse(scm.isCreateAccountBasedOnEmail(), "Wrong initial value for create account based on e-mail"); descriptor.setCreateAccountBasedOnEmail(true); - assertTrue("Create account based on e-mail not set", scm.isCreateAccountBasedOnEmail()); + assertTrue(scm.isCreateAccountBasedOnEmail(), "Create account based on e-mail not set"); - assertFalse("Wrong initial value for use existing user if same e-mail already found", scm.isUseExistingAccountWithSameEmail()); + assertFalse(scm.isUseExistingAccountWithSameEmail(), "Wrong initial value for use existing user if same e-mail already found"); descriptor.setUseExistingAccountWithSameEmail(true); - assertTrue("Use existing user if same e-mail already found is not set", scm.isUseExistingAccountWithSameEmail()); + assertTrue(scm.isUseExistingAccountWithSameEmail(), "Use existing user if same e-mail already found is not set"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); final String commitFile2 = "commitFile2"; final PersonIdent jeffDoe = new PersonIdent("Jeff Doe", "jeff@doe.com"); commit(commitFile2, jeffDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set culprits = build2.getCulprits(); - assertEquals("The build should have only one culprit", 1, culprits.size()); + assertEquals(1, culprits.size(), "The build should have only one culprit"); User culprit = culprits.iterator().next(); - assertEquals("", jeffDoe.getEmailAddress(), culprit.getId()); - assertEquals("", jeffDoe.getName(), culprit.getFullName()); + assertEquals(jeffDoe.getEmailAddress(), culprit.getId(), ""); + assertEquals(jeffDoe.getName(), culprit.getFullName(), ""); r.assertBuildStatusSuccess(build); } - + @Issue("JENKINS-59868") @Test - public void testNonExistentWorkingDirectoryPoll() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testNonExistentWorkingDirectoryPoll() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it @@ -1854,10 +1845,10 @@ public void testNonExistentWorkingDirectoryPoll() throws Exception { m.getMessage().contains("[poll] Working Directory does not exist"))); } - // Disabled - consistently fails, needs more analysis - // @Test - public void testFetchFromMultipleRepositories() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + @Disabled("consistently fails, needs more analysis") + @Test + void testFetchFromMultipleRepositories() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("second", secondRepo.getRoot(), listener); @@ -1881,16 +1872,16 @@ public void testFetchFromMultipleRepositories() throws Exception { Change change = project.poll(listener).change; SCMRevisionState remote = project.poll(listener).remote; String assertionMessage = MessageFormat.format("polling incorrectly detected change after build. Baseline: {0}, Change: {1}, Remote: {2}", baseline, change, remote); - assertFalse(assertionMessage, project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), assertionMessage); final String commitFile2 = "commitFile2"; secondTestRepo.commit(commitFile2, janeDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } private void branchSpecWithMultipleRepositories(String branchName) throws Exception { @@ -1917,7 +1908,7 @@ private void branchSpecWithMultipleRepositories(String branchName) throws Except @Issue("JENKINS-26268") @Test - public void testBranchSpecAsSHA1WithMultipleRepositories() throws Exception { + void testBranchSpecAsSHA1WithMultipleRepositories() throws Exception { String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit 1 from testBranchSpecAsSHA1WithMultipleRepositories"); branchSpecWithMultipleRepositories(testRepo.git.revParse("HEAD").getName()); @@ -1925,7 +1916,7 @@ public void testBranchSpecAsSHA1WithMultipleRepositories() throws Exception { @Issue("JENKINS-26268") @Test - public void testBranchSpecAsRemotesOriginMasterWithMultipleRepositories() throws Exception { + void testBranchSpecAsRemotesOriginMasterWithMultipleRepositories() throws Exception { String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit 1 from testBranchSpecAsSHA1WithMultipleRepositories"); branchSpecWithMultipleRepositories("remotes/origin/master"); @@ -1933,8 +1924,8 @@ public void testBranchSpecAsRemotesOriginMasterWithMultipleRepositories() throws @Issue("JENKINS-25639") @Test - public void testCommitDetectedOnlyOnceInMultipleRepositories() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testCommitDetectedOnlyOnceInMultipleRepositories() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("secondRepo", secondRepo.getRoot(), listener); @@ -1983,8 +1974,8 @@ private void addChangelogToBranchExtension(GitSCM scm) { } @Test - public void testMerge() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMerge() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( @@ -2007,7 +1998,7 @@ public void testMerge() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); @@ -2015,17 +2006,17 @@ public void testMerge() throws Exception { testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); r.assertBuildStatusSuccess(build2); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } @Issue("JENKINS-20392") @Test - public void testMergeChangelog() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeChangelog() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( @@ -2052,15 +2043,15 @@ public void testMergeChangelog() throws Exception { final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); ChangeLogSet changeLog = build2.getChangeSet(); - assertEquals("Changelog should contain one item", 1, changeLog.getItems().length); + assertEquals(1, changeLog.getItems().length, "Changelog should contain one item"); GitChangeSet singleChange = (GitChangeSet) changeLog.getItems()[0]; - assertEquals("Changelog should contain commit number 2", commitMessage, singleChange.getComment().trim()); + assertEquals(commitMessage, singleChange.getComment().trim(), "Changelog should contain commit number 2"); } @Test - public void testMergeFailed() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMergeFailed() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( @@ -2083,22 +2074,22 @@ public void testMergeFailed() throws Exception { final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); - assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling did not detect commit2 change"); r.buildAndAssertStatus(Result.FAILURE, project); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } - + @Issue("JENKINS-25191") @Test - public void testMultipleMergeFailed() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testMultipleMergeFailed() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( @@ -2125,12 +2116,12 @@ public void testMultipleMergeFailed() throws Exception { final FreeStyleBuild build = build(project, Result.FAILURE); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } @Test - public void testEnvironmentVariableExpansion() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testEnvironmentVariableExpansion() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = createFreeStyleProject(); project.setScm(new GitSCM("${CAT}"+testRepo.gitDir.getPath())); @@ -2162,8 +2153,8 @@ public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) thro * Sample configuration that should result in no extensions at all */ @Test - public void testDataCompatibility1() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testDataCompatibility1() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject p = (FreeStyleProject) r.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml")); GitSCM oldGit = (GitSCM) p.getScm(); assertEquals(Collections.emptyList(), oldGit.getExtensions().toList()); @@ -2171,7 +2162,7 @@ public void testDataCompatibility1() throws Exception { assertEquals("git https://github.com/jenkinsci/model-ant-project.git", oldGit.getKey()); assertThat(oldGit.getEffectiveBrowser(), instanceOf(GithubWeb.class)); GithubWeb browser = (GithubWeb) oldGit.getEffectiveBrowser(); - assertEquals(browser.getRepoUrl(), "https://github.com/jenkinsci/model-ant-project.git/"); + assertEquals("https://github.com/jenkinsci/model-ant-project.git/", browser.getRepoUrl()); } /** @@ -2180,7 +2171,7 @@ public void testDataCompatibility1() throws Exception { */ @Issue("JENKINS-53346") @Test - public void testCheckoutReturnsLatestValues() throws Exception { + void testCheckoutReturnsLatestValues() throws Exception { /* Exit test early if running on Windows and path will be too long */ /* Known limitation of git for Windows 2.28.0 and earlier */ @@ -2189,7 +2180,7 @@ public void testCheckoutReturnsLatestValues() throws Exception { if (isWindows() && currentDirectoryPath.length() > 95) { return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "pipeline-checkout-3-tags"); p.setDefinition(new CpsFlowDefinition( @@ -2243,16 +2234,16 @@ private String getLineStartsWith(String text, String startOfLine) { } return ""; } - + @Test - public void testPleaseDontContinueAnyway() throws Exception { + void testPleaseDontContinueAnyway() throws Exception { /* Wastes time waiting for the build to fail */ /* Only run on non-Windows and approximately 50% of test runs */ /* On Windows, it requires 150 seconds before test finishes */ if (isWindows() || random.nextBoolean()) { return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); // create an empty repository with some commits testRepo.commit("a","foo",johnDoe, "added"); @@ -2268,8 +2259,8 @@ public void testPleaseDontContinueAnyway() throws Exception { @Issue("JENKINS-19108") @Test - public void testCheckoutToSpecificBranch() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testCheckoutToSpecificBranch() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject p = createFreeStyleProject(); GitSCM oldGit = new GitSCM("https://github.com/jenkinsci/model-ant-project.git/"); setupJGit(oldGit); @@ -2280,14 +2271,14 @@ public void testCheckoutToSpecificBranch() throws Exception { GitClient gc = Git.with(StreamTaskListener.fromStdout(),null).in(b.getWorkspace()).getClient(); gc.withRepository((RepositoryCallback) (repo, channel) -> { Ref head = repo.findRef("HEAD"); - assertTrue("Detached HEAD",head.isSymbolic()); + assertTrue(head.isSymbolic(),"Detached HEAD"); Ref t = head.getTarget(); - assertEquals(t.getName(),"refs/heads/master"); + assertEquals("refs/heads/master", t.getName()); return null; }); } - + /** * Verifies that if project specifies LocalBranch with value of "**" * that the checkout to a local branch using remote branch name sans 'origin'. @@ -2299,8 +2290,8 @@ public void testCheckoutToSpecificBranch() throws Exception { * @throws Exception on error */ @Test - public void testCheckoutToDefaultLocalBranch_StarStar() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testCheckoutToDefaultLocalBranch_StarStar() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; @@ -2309,8 +2300,8 @@ public void testCheckoutToDefaultLocalBranch_StarStar() throws Exception { git.getExtensions().add(new LocalBranch("**")); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); - assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); - assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); + assertEquals("origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH), "GIT_BRANCH"); + assertEquals("master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH), "GIT_LOCAL_BRANCH"); } /** @@ -2324,8 +2315,8 @@ public void testCheckoutToDefaultLocalBranch_StarStar() throws Exception { * @throws Exception on error */ @Test - public void testCheckoutToDefaultLocalBranch_NULL() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testCheckoutToDefaultLocalBranch_NULL() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; @@ -2334,8 +2325,8 @@ public void testCheckoutToDefaultLocalBranch_NULL() throws Exception { git.getExtensions().add(new LocalBranch("")); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); - assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); - assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); + assertEquals("origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH), "GIT_BRANCH"); + assertEquals("master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH), "GIT_LOCAL_BRANCH"); } /* @@ -2343,25 +2334,25 @@ public void testCheckoutToDefaultLocalBranch_NULL() throws Exception { * is not configured. */ @Test - public void testCheckoutSansLocalBranchExtension() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testCheckoutSansLocalBranchExtension() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); - assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); - assertNull("GIT_LOCAL_BRANCH", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); + assertEquals("origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH), "GIT_BRANCH"); + assertNull(getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH), "GIT_LOCAL_BRANCH"); } - + /* * Verifies that GIT_CHECKOUT_DIR is set to "checkoutDir" if RelativeTargetDirectory extension * is configured. */ @Test - public void testCheckoutRelativeTargetDirectoryExtension() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testCheckoutRelativeTargetDirectoryExtension() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupProject("master", false, "checkoutDir"); final String commitFile1 = "commitFile1"; @@ -2370,7 +2361,7 @@ public void testCheckoutRelativeTargetDirectoryExtension() throws Exception { git.getExtensions().add(new RelativeTargetDirectory("checkoutDir")); FreeStyleBuild build1 = build(project, "checkoutDir", Result.SUCCESS, commitFile1); - assertEquals("GIT_CHECKOUT_DIR", "checkoutDir", getEnvVars(project).get(GitSCM.GIT_CHECKOUT_DIR)); + assertEquals("checkoutDir", getEnvVars(project).get(GitSCM.GIT_CHECKOUT_DIR), "GIT_CHECKOUT_DIR"); } /* @@ -2378,19 +2369,20 @@ public void testCheckoutRelativeTargetDirectoryExtension() throws Exception { * is not configured. */ @Test - public void testCheckoutSansRelativeTargetDirectoryExtension() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testCheckoutSansRelativeTargetDirectoryExtension() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); - assertNull("GIT_CHECKOUT_DIR", getEnvVars(project).get(GitSCM.GIT_CHECKOUT_DIR)); + assertNull(getEnvVars(project).get(GitSCM.GIT_CHECKOUT_DIR), "GIT_CHECKOUT_DIR"); } + @Test - public void testCheckoutFailureIsRetryable() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testCheckoutFailureIsRetryable() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); // run build first to create workspace @@ -2413,8 +2405,8 @@ public void testCheckoutFailureIsRetryable() throws Exception { } @Test - public void testSparseCheckoutAfterNormalCheckout() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testSparseCheckoutAfterNormalCheckout() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); // run build first to create workspace @@ -2439,8 +2431,8 @@ public void testSparseCheckoutAfterNormalCheckout() throws Exception { } @Test - public void testNormalCheckoutAfterSparseCheckout() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testNormalCheckoutAfterSparseCheckout() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupProject("master", Collections.singletonList(new SparseCheckoutPath("titi"))); // run build first to create workspace @@ -2467,8 +2459,8 @@ public void testNormalCheckoutAfterSparseCheckout() throws Exception { @Test @Issue("JENKINS-22009") - public void testPolling_environmentValueInBranchSpec() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testPolling_environmentValueInBranchSpec() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( @@ -2485,7 +2477,7 @@ public void testPolling_environmentValueInBranchSpec() throws Exception { // build the project build(project, Result.SUCCESS); - assertFalse("No changes to git since last build, thus no new build is expected", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "No changes to git since last build, thus no new build is expected"); } public void baseTestPolling_parentHead(List extensions) throws Exception { @@ -2503,7 +2495,7 @@ public void baseTestPolling_parentHead(List extensions) throws git.branch("someBranch"); commit("toto/commitFile2", johnDoe, "Commit number 2"); - assertTrue("polling should detect changes",project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(),"polling should detect changes"); // build the project build(project, Result.SUCCESS); @@ -2511,28 +2503,28 @@ public void baseTestPolling_parentHead(List extensions) throws /* Expects 1 build because the build of someBranch incorporates all * the changes from the master branch as well as the changes from someBranch. */ - assertEquals("Wrong number of builds", 1, project.getBuilds().size()); + assertEquals(1, project.getBuilds().size(), "Wrong number of builds"); - assertFalse("polling should not detect changes",project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(),"polling should not detect changes"); } @Issue("JENKINS-29066") @Test - public void testPolling_parentHead() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testPolling_parentHead() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); baseTestPolling_parentHead(Collections.emptyList()); } @Issue("JENKINS-29066") @Test - public void testPolling_parentHead_DisableRemotePoll() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testPolling_parentHead_DisableRemotePoll() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); baseTestPolling_parentHead(Collections.singletonList(new DisableRemotePoll())); } @Test - public void testPollingAfterManualBuildWithParametrizedBranchSpec() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testPollingAfterManualBuildWithParametrizedBranchSpec() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( @@ -2555,19 +2547,19 @@ public void testPollingAfterManualBuildWithParametrizedBranchSpec() throws Excep FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserIdCause(), actions).get(); r.assertBuildStatus(Result.SUCCESS, build); - assertFalse("No changes to git since last build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "No changes to git since last build"); git.checkout("manualbranch"); commit("file2", johnDoe, "Commit to manually build branch"); - assertFalse("No changes to tracked branch", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "No changes to tracked branch"); git.checkout("trackedbranch"); commit("file3", johnDoe, "Commit to tracked branch"); - assertTrue("A change should be detected in tracked branch", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "A change should be detected in tracked branch"); } - private final class FakeParametersAction implements EnvironmentContributingAction, Serializable { + private static final class FakeParametersAction implements EnvironmentContributingAction, Serializable { // Test class for testPolling_environmentValueAsEnvironmentContributingAction test case final ParametersAction m_forwardingAction; @@ -2596,19 +2588,22 @@ public List getParameters() { return this.m_forwardingAction.getParameters(); } + @Serial private void writeObject(java.io.ObjectOutputStream out) throws IOException { } + @Serial private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { } + @Serial private void readObjectNoData() throws ObjectStreamException { } } @Test - public void testPolling_CanDoRemotePollingIfOneBranchButMultipleRepositories() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testPolling_CanDoRemotePollingIfOneBranchButMultipleRepositories() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = createFreeStyleProject(); List remoteConfigs = new ArrayList<>(); remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "", null)); @@ -2630,8 +2625,8 @@ public void testPolling_CanDoRemotePollingIfOneBranchButMultipleRepositories() t @Issue("JENKINS-24467") @Test - public void testPolling_environmentValueAsEnvironmentContributingAction() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testPolling_environmentValueAsEnvironmentContributingAction() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); // branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( @@ -2658,25 +2653,26 @@ public void testPolling_environmentValueAsEnvironmentContributingAction() throws Launcher launcher = workspace.createLauncher(listener); final EnvVars environment = GitUtils.getPollEnvironment(project, workspace, launcher, listener); - assertEquals(environment.get("MY_BRANCH"), "master"); - assertNotSame("Environment path should not be broken path", environment.get("PATH"), brokenPath); + assertEquals("master", environment.get("MY_BRANCH")); + assertNotSame(brokenPath, environment.get("PATH"), "Environment path should not be broken path"); } private void checkNumberedBuildScmName(FreeStyleProject project, int buildNumber, String expectedScmName, GitSCM git) throws Exception { final BuildData buildData = git.getBuildData(project.getBuildByNumber(buildNumber)); - assertEquals("Wrong SCM Name", expectedScmName, buildData.getScmName()); + assertEquals(expectedScmName, buildData.getScmName(), "Wrong SCM Name"); } /* A null pointer exception was detected because the plugin failed to * write a branch name to the build data, so there was a SHA1 recorded * in the build data, but no branch name. */ + // Testing deprecated buildEnvVars @Test - @Deprecated // Testing deprecated buildEnvVars - public void testNoNullPointerExceptionWithNullBranch() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + @Deprecated + void testNoNullPointerExceptionWithNullBranch() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ @@ -2710,10 +2706,11 @@ public void testNoNullPointerExceptionWithNullBranch() throws Exception { verify(build, times(1)).getActions(BuildData.class); } + // Testing deprecated buildEnvVars @Test - @Deprecated // Testing deprecated buildEnvVars - public void testBuildEnvVarsLocalBranchStarStar() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + @Deprecated + void testBuildEnvVarsLocalBranchStarStar() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ @@ -2744,8 +2741,8 @@ public void testBuildEnvVarsLocalBranchStarStar() throws Exception { EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied - assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); - assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); + assertEquals("origin/master", env.get("GIT_BRANCH"), "GIT_BRANCH"); + assertEquals("master", env.get("GIT_LOCAL_BRANCH"), "GIT_LOCAL_BRANCH"); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); @@ -2753,10 +2750,11 @@ public void testBuildEnvVarsLocalBranchStarStar() throws Exception { verify(build, times(1)).getActions(BuildData.class); } + // Testing deprecated buildEnvVars @Test - @Deprecated // Testing deprecated buildEnvVars - public void testBuildEnvVarsLocalBranchNull() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + @Deprecated + void testBuildEnvVarsLocalBranchNull() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ @@ -2787,8 +2785,8 @@ public void testBuildEnvVarsLocalBranchNull() throws Exception { EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied - assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); - assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); + assertEquals("origin/master", env.get("GIT_BRANCH"), "GIT_BRANCH"); + assertEquals("master", env.get("GIT_LOCAL_BRANCH"), "GIT_LOCAL_BRANCH"); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); @@ -2796,10 +2794,11 @@ public void testBuildEnvVarsLocalBranchNull() throws Exception { verify(build, times(1)).getActions(BuildData.class); } + // testing deprecated buildEnvVars @Test - @Deprecated // testing deprecated buildEnvVars - public void testBuildEnvVarsLocalBranchNotSet() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + @Deprecated + void testBuildEnvVarsLocalBranchNotSet() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ @@ -2829,8 +2828,8 @@ public void testBuildEnvVarsLocalBranchNotSet() throws Exception { EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied - assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); - assertNull("GIT_LOCAL_BRANCH", env.get("GIT_LOCAL_BRANCH")); + assertEquals("origin/master", env.get("GIT_BRANCH"), "GIT_BRANCH"); + assertNull(env.get("GIT_LOCAL_BRANCH"), "GIT_LOCAL_BRANCH"); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); @@ -2839,8 +2838,8 @@ public void testBuildEnvVarsLocalBranchNotSet() throws Exception { } @Test - public void testBuildEnvironmentVariablesSingleRemote() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBuildEnvironmentVariablesSingleRemote() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); List branchList = new ArrayList<>(); @@ -2868,16 +2867,16 @@ public void testBuildEnvironmentVariablesSingleRemote() throws Exception { Map env = new HashMap<>(); scm.buildEnvironment(build, env); - assertEquals("GIT_BRANCH is invalid", "origin/master", env.get("GIT_BRANCH")); - assertNull("GIT_LOCAL_BRANCH is invalid", env.get("GIT_LOCAL_BRANCH")); - assertEquals("GIT_COMMIT is invalid", sha1.getName(), env.get("GIT_COMMIT")); - assertEquals("GIT_URL is invalid", testRepo.gitDir.getAbsolutePath(), env.get("GIT_URL")); - assertNull("GIT_URL_1 should not have been set", env.get("GIT_URL_1")); + assertEquals("origin/master", env.get("GIT_BRANCH"), "GIT_BRANCH is invalid"); + assertNull(env.get("GIT_LOCAL_BRANCH"), "GIT_LOCAL_BRANCH is invalid"); + assertEquals(sha1.getName(), env.get("GIT_COMMIT"), "GIT_COMMIT is invalid"); + assertEquals(testRepo.gitDir.getAbsolutePath(), env.get("GIT_URL"), "GIT_URL is invalid"); + assertNull(env.get("GIT_URL_1"), "GIT_URL_1 should not have been set"); } @Test - public void testBuildEnvironmentVariablesMultipleRemotes() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testBuildEnvironmentVariablesMultipleRemotes() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); List branchList = new ArrayList<>(); @@ -2915,19 +2914,19 @@ public void testBuildEnvironmentVariablesMultipleRemotes() throws Exception { Map env = new HashMap<>(); scm.buildEnvironment(build, env); - assertEquals("GIT_BRANCH is invalid", "origin/master", env.get("GIT_BRANCH")); - assertNull("GIT_LOCAL_BRANCH is invalid", env.get("GIT_LOCAL_BRANCH")); - assertEquals("GIT_COMMIT is invalid", sha1.getName(), env.get("GIT_COMMIT")); - assertEquals("GIT_URL is invalid", testRepo.gitDir.getAbsolutePath(), env.get("GIT_URL")); - assertEquals("GIT_URL_1 is invalid", testRepo.gitDir.getAbsolutePath(), env.get("GIT_URL_1")); - assertEquals("GIT_URL_2 is invalid", upstreamRepoUrl, env.get("GIT_URL_2")); - assertNull("GIT_URL_3 should not have been set", env.get("GIT_URL_3")); + assertEquals("origin/master", env.get("GIT_BRANCH"), "GIT_BRANCH is invalid"); + assertNull(env.get("GIT_LOCAL_BRANCH"), "GIT_LOCAL_BRANCH is invalid"); + assertEquals(sha1.getName(), env.get("GIT_COMMIT"), "GIT_COMMIT is invalid"); + assertEquals(testRepo.gitDir.getAbsolutePath(), env.get("GIT_URL"), "GIT_URL is invalid"); + assertEquals(testRepo.gitDir.getAbsolutePath(), env.get("GIT_URL_1"), "GIT_URL_1 is invalid"); + assertEquals(upstreamRepoUrl, env.get("GIT_URL_2"), "GIT_URL_2 is invalid"); + assertNull(env.get("GIT_URL_3"), "GIT_URL_3 should not have been set"); } @Issue("JENKINS-38241") @Test - public void testCommitMessageIsPrintedToLogs() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testCommitMessageIsPrintedToLogs() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=test commit"); @@ -2938,8 +2937,8 @@ public void testCommitMessageIsPrintedToLogs() throws Exception { @Issue("JENKINS-73677") @Test - public void testExtensionsDecorateClientAfterSettingCredentials() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testExtensionsDecorateClientAfterSettingCredentials() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject project = setupSimpleProject("master"); StandardCredentials extensionCredentials = createCredential(CredentialsScope.GLOBAL, "github"); store.addCredentials(Domain.global(), extensionCredentials); @@ -2985,11 +2984,6 @@ private boolean cleanupIsUnreliable() { return isWindows() && jobUrl != null && jobUrl.contains("ci.jenkins.io"); } - /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ - private boolean isWindows() { - return java.io.File.pathSeparatorChar==';'; - } - private StandardCredentials createCredential(CredentialsScope scope, String id) throws FormException { return new UsernamePasswordCredentialsImpl(scope, id, "desc: " + id, "username", "password-needs-to-be-14"); } diff --git a/src/test/java/hudson/plugins/git/GitSCMUnitTest.java b/src/test/java/hudson/plugins/git/GitSCMUnitTest.java index 96533247c7..b2cb1be512 100644 --- a/src/test/java/hudson/plugins/git/GitSCMUnitTest.java +++ b/src/test/java/hudson/plugins/git/GitSCMUnitTest.java @@ -23,7 +23,6 @@ */ package hudson.plugins.git; -import hudson.AbortException; import hudson.EnvVars; import static hudson.plugins.git.GitSCM.createRepoList; import hudson.plugins.git.browser.GitRepositoryBrowser; @@ -33,6 +32,8 @@ import hudson.plugins.git.util.BuildChooser; import hudson.plugins.git.util.DefaultBuildChooser; import hudson.scm.RepositoryBrowser; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -40,33 +41,28 @@ import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; -import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; + import org.jvnet.hudson.test.Issue; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -public class GitSCMUnitTest { +class GitSCMUnitTest { private final String gitDir = "."; private final GitSCM gitSCM = new GitSCM(gitDir); private final String repoURL = "https://github.com/jenkinsci/git-plugin"; - public GitSCMUnitTest() throws Exception { - } - @Test @Deprecated - public void testGetSubmoduleCfg() { + void testGetSubmoduleCfg() { Collection emptySubmoduleConfigList = new ArrayList<>(); assertThat(gitSCM.getSubmoduleCfg(), is(emptySubmoduleConfigList)); } @Test @Deprecated - public void testSetSubmoduleCfg() { + void testSetSubmoduleCfg() { Collection emptySubmoduleConfigList = new ArrayList<>(); Collection submoduleConfigList = new ArrayList<>(); SubmoduleConfig config = new SubmoduleConfig(); @@ -76,7 +72,7 @@ public void testSetSubmoduleCfg() { } @Test - public void testCreateRepoList() { + void testCreateRepoList() { String name = null; String refspec = null; String credentialsId = null; @@ -98,38 +94,38 @@ private void assertUserRemoteConfigListEquals(List remoteConfi } @Test - public void testGetBrowser() { + void testGetBrowser() { assertThat(gitSCM.getBrowser(), is(nullValue())); } @Test - public void testSetBrowser() { + void testSetBrowser() { GitRepositoryBrowser browser = new GithubWeb(repoURL); gitSCM.setBrowser(browser); assertThat(gitSCM.getBrowser(), is(browser)); } @Test - public void testGuessBrowser() { + void testGuessBrowser() { /* Well tested in other classes */ RepositoryBrowser result = gitSCM.guessBrowser(); assertThat(result, is(nullValue())); } @Test - public void testGetBuildChooser() { + void testGetBuildChooser() { assertThat(gitSCM.getBuildChooser(), is(instanceOf(DefaultBuildChooser.class))); } @Test - public void testSetBuildChooser() throws Exception { + void testSetBuildChooser() throws Exception { BuildChooser ancestryBuildChooser = new AncestryBuildChooser(1, "string"); gitSCM.setBuildChooser(ancestryBuildChooser); assertThat(gitSCM.getBuildChooser(), is(ancestryBuildChooser)); } @Test - public void testSetBuildChooserDefault() throws Exception { + void testSetBuildChooserDefault() throws Exception { BuildChooser ancestryBuildChooser = new AncestryBuildChooser(1, "string"); gitSCM.setBuildChooser(ancestryBuildChooser); BuildChooser defaultBuildChooser = new DefaultBuildChooser(); @@ -138,7 +134,7 @@ public void testSetBuildChooserDefault() throws Exception { } @Test - public void testGetRepositoryByName() throws Exception { + void testGetRepositoryByName() throws Exception { RemoteConfig expected = new RemoteConfig(new Config(), "origin"); expected.addURI(new URIish(gitDir)); assertRemoteConfigEquals(gitSCM.getRepositoryByName("origin"), expected); @@ -157,22 +153,22 @@ private void assertRemoteConfigListEquals(List remoteConfigList, L } @Test - public void testGetRepositoryByNameNoSuchName() { + void testGetRepositoryByNameNoSuchName() { assertThat(gitSCM.getRepositoryByName("no-such-name"), is(nullValue())); } @Test - public void testGetRepositoryByNameEmptyName() { + void testGetRepositoryByNameEmptyName() { assertThat(gitSCM.getRepositoryByName(""), is(nullValue())); } @Test - public void testGetRepositoryByNameNullName() { + void testGetRepositoryByNameNullName() { assertThat(gitSCM.getRepositoryByName(null), is(nullValue())); } @Test - public void testGetUserRemoteConfigs() { + void testGetUserRemoteConfigs() { String name = null; String refspec = null; String credentialsId = null; @@ -183,7 +179,7 @@ public void testGetUserRemoteConfigs() { } @Test - public void testGetRepositories() throws Exception { + void testGetRepositories() throws Exception { List expectedRemoteConfigList = new ArrayList<>(); RemoteConfig remoteConfig = new RemoteConfig(new Config(), "origin"); remoteConfig.addURI(new URIish(gitDir)); @@ -192,7 +188,7 @@ public void testGetRepositories() throws Exception { } @Test - public void testDeriveLocalBranchName() { + void testDeriveLocalBranchName() { assertThat(gitSCM.deriveLocalBranchName("origin/master"), is("master")); assertThat(gitSCM.deriveLocalBranchName("master"), is("master")); assertThat(gitSCM.deriveLocalBranchName("origin/feature/xyzzy"), is("feature/xyzzy")); @@ -200,12 +196,12 @@ public void testDeriveLocalBranchName() { } @Test - public void testGetGitTool() { + void testGetGitTool() { assertThat(gitSCM.getGitTool(), is(nullValue())); } @Test - public void testGetParameterString() { + void testGetParameterString() { String original = "${A}/${B} ${A}/${C}"; EnvVars env = new EnvVars(); env.put("A", "A-value"); @@ -214,13 +210,13 @@ public void testGetParameterString() { } @Test - public void testRequiresWorkspaceForPolling() { + void testRequiresWorkspaceForPolling() { /* Assumes workspace is required */ assertTrue(gitSCM.requiresWorkspaceForPolling()); } @Test - public void testRequiresWorkspaceForPollingSingleBranch() throws Exception { + void testRequiresWorkspaceForPollingSingleBranch() throws Exception { /* Force single-branch use case */ GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("master")), @@ -229,7 +225,7 @@ public void testRequiresWorkspaceForPollingSingleBranch() throws Exception { } @Test - public void testRequiresWorkspaceForPollingSingleBranchWithRemoteName() throws Exception { + void testRequiresWorkspaceForPollingSingleBranchWithRemoteName() throws Exception { /* Force single-branch use case */ GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("origin/master")), @@ -238,7 +234,7 @@ public void testRequiresWorkspaceForPollingSingleBranchWithRemoteName() throws E } @Test - public void testRequiresWorkspaceForPollingSingleBranchWithWildcardRemoteName() throws Exception { + void testRequiresWorkspaceForPollingSingleBranchWithWildcardRemoteName() throws Exception { /* Force single-branch use case */ GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("*/master")), @@ -247,7 +243,7 @@ public void testRequiresWorkspaceForPollingSingleBranchWithWildcardRemoteName() } @Test - public void testRequiresWorkspaceForPollingSingleBranchWithWildcardSuffix() throws Exception { + void testRequiresWorkspaceForPollingSingleBranchWithWildcardSuffix() throws Exception { /* Force single-branch use case */ GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("master*")), @@ -256,7 +252,7 @@ public void testRequiresWorkspaceForPollingSingleBranchWithWildcardSuffix() thro } @Test - public void testRequiresWorkspaceForPollingMultiBranch() throws Exception { + void testRequiresWorkspaceForPollingMultiBranch() throws Exception { /* Multi-branch use case */ List branches = new ArrayList<>(); branches.add(new BranchSpec("master")); @@ -268,7 +264,7 @@ public void testRequiresWorkspaceForPollingMultiBranch() throws Exception { } @Test - public void testRequiresWorkspaceForPollingEmptyBranchName() throws Exception { + void testRequiresWorkspaceForPollingEmptyBranchName() throws Exception { /* Multi-branch use case */ EnvVars env = new EnvVars(); env.put("A", ""); @@ -279,19 +275,19 @@ public void testRequiresWorkspaceForPollingEmptyBranchName() throws Exception { } @Test - public void testCreateChangeLogParser() { + void testCreateChangeLogParser() { assertThat(gitSCM.createChangeLogParser(), is(instanceOf(GitChangeLogParser.class))); } @Test @Deprecated - public void testIsDoGenerateSubmoduleConfigurations() { + void testIsDoGenerateSubmoduleConfigurations() { assertFalse(gitSCM.isDoGenerateSubmoduleConfigurations()); } @Test @Deprecated - public void testIsDoGenerateSubmoduleConfigurationsTrue() throws Exception { + void testIsDoGenerateSubmoduleConfigurationsTrue() throws Exception { GitSCM bigGitSCM = new GitSCM(createRepoList(repoURL, null), Collections.singletonList(new BranchSpec("master")), null, null, Collections.emptyList()); @@ -299,7 +295,7 @@ public void testIsDoGenerateSubmoduleConfigurationsTrue() throws Exception { } @Test - public void testGetBranches() { + void testGetBranches() { List expectedBranchList = new ArrayList<>(); expectedBranchList.add(new BranchSpec("**")); assertBranchSpecListEquals(gitSCM.getBranches(), expectedBranchList); @@ -314,13 +310,13 @@ private void assertBranchSpecListEquals(List branchList, List setupParameterMap(String extraValue) { } @Test - public void testDoNotifyCommit() throws Exception { /* No parameters */ + void testDoNotifyCommit() throws Exception { /* No parameters */ setupNotifyProject(); this.gitStatus.doNotifyCommit(requestWithNoParameter, repoURL, branch, sha1, notifyCommitApiToken); assertEquals("URL: " + repoURL @@ -378,22 +376,22 @@ public void testDoNotifyCommit() throws Exception { /* No parameters */ } @Test - public void testDoNotifyCommitWithExtraParameterAllowed() throws Exception { + void testDoNotifyCommitWithExtraParameterAllowed() throws Exception { doNotifyCommitWithExtraParameterAllowed(true, null); } @Test - public void testDoNotifyCommitWithExtraParameter() throws Exception { + void testDoNotifyCommitWithExtraParameter() throws Exception { doNotifyCommitWithExtraParameterAllowed(false, null); } @Test - public void testDoNotifyCommitWithExtraSafeParameter() throws Exception { + void testDoNotifyCommitWithExtraSafeParameter() throws Exception { doNotifyCommitWithExtraParameterAllowed(false, "something,extra,is,here"); } @Test - public void testDoNotifyCommitWithExtraUnsafeParameter() throws Exception { + void testDoNotifyCommitWithExtraUnsafeParameter() throws Exception { doNotifyCommitWithExtraParameterAllowed(false, "something,is,not,here"); } @@ -423,7 +421,7 @@ private void doNotifyCommitWithExtraParameterAllowed(final boolean allowed, Stri } @Test - public void testDoNotifyCommitWithNullValueExtraParameter() throws Exception { + void testDoNotifyCommitWithNullValueExtraParameter() throws Exception { setupNotifyProject(); when(requestWithParameter.getParameterMap()).thenReturn(setupParameterMap(null)); this.gitStatus.doNotifyCommit(requestWithParameter, repoURL, branch, sha1, notifyCommitApiToken); @@ -433,27 +431,27 @@ public void testDoNotifyCommitWithNullValueExtraParameter() throws Exception { } @Test - public void testDoNotifyCommitWithDefaultParameterAllowed() throws Exception { + void testDoNotifyCommitWithDefaultParameterAllowed() throws Exception { doNotifyCommitWithDefaultParameter(true, null); } @Test - public void testDoNotifyCommitWithDefaultParameter() throws Exception { + void testDoNotifyCommitWithDefaultParameter() throws Exception { doNotifyCommitWithDefaultParameter(false, null); } @Test - public void testDoNotifyCommitWithDefaultSafeParameter() throws Exception { + void testDoNotifyCommitWithDefaultSafeParameter() throws Exception { doNotifyCommitWithDefaultParameter(false, "A,B,C,extra"); } @Test - public void testDoNotifyCommitWithDefaultUnsafeParameterC() throws Exception { + void testDoNotifyCommitWithDefaultUnsafeParameterC() throws Exception { doNotifyCommitWithDefaultParameter(false, "A,B,extra"); } @Test - public void testDoNotifyCommitWithDefaultUnsafeParameterExtra() throws Exception { + void testDoNotifyCommitWithDefaultUnsafeParameterExtra() throws Exception { doNotifyCommitWithDefaultParameter(false, "A,B,C"); } @@ -517,17 +515,9 @@ private boolean runUnreliableTests() { return !jobUrl.contains("ci.jenkins.io"); // Skip some tests on ci.jenkins.io, windows cleanup is unreliable on those machines } - /** - * inline ${@link hudson.Functions#isWindows()} to prevent a transient - * remote classloader issue - */ - private boolean isWindows() { - return File.pathSeparatorChar == ';'; - } - @Test @Issue("JENKINS-46929") - public void testDoNotifyCommitTriggeredHeadersLimited() throws Exception { + void testDoNotifyCommitTriggeredHeadersLimited() throws Exception { SCMTrigger[] projectTriggers = new SCMTrigger[50]; for (int i = 0; i < projectTriggers.length; i++) { projectTriggers[i] = setupProjectWithTrigger("a", "master", false); @@ -552,7 +542,7 @@ public void testDoNotifyCommitTriggeredHeadersLimited() throws Exception { @Test @Issue("SECURITY-2499") - public void testDoNotifyCommitWithWrongSha1Content() throws Exception { + void testDoNotifyCommitWithWrongSha1Content() throws Exception { setupProjectWithTrigger("a", "master", false); String content = ""; @@ -567,7 +557,7 @@ public void testDoNotifyCommitWithWrongSha1Content() throws Exception { @Test @Issue("SECURITY-284") - public void testDoNotifyCommitWithValidSha1AndValidApiToken() throws Exception { + void testDoNotifyCommitWithValidSha1AndValidApiToken() throws Exception { // when sha1 is provided build is scheduled right away instead of repo polling, so we do not check for trigger FreeStyleProject project = setupNotifyProject(); @@ -577,12 +567,12 @@ public void testDoNotifyCommitWithValidSha1AndValidApiToken() throws Exception { FreeStyleBuild lastBuild = project.getLastBuild(); assertNotNull(lastBuild); - assertEquals(lastBuild.getNumber(), 1); + assertEquals(1, lastBuild.getNumber()); } @Test @Issue("SECURITY-284") - public void testDoNotifyCommitWithUnauthenticatedPollingAllowed() throws Exception { + void testDoNotifyCommitWithUnauthenticatedPollingAllowed() throws Exception { GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL = "disabled-for-polling"; SCMTrigger trigger = setupProjectWithTrigger("a", "master", false); @@ -593,7 +583,7 @@ public void testDoNotifyCommitWithUnauthenticatedPollingAllowed() throws Excepti @Test @Issue("SECURITY-284") - public void testDoNotifyCommitWithAllowModeSha1() throws Exception { + void testDoNotifyCommitWithAllowModeSha1() throws Exception { GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL = "disabled"; // when sha1 is provided build is scheduled right away instead of repo polling, so we do not check for trigger FreeStyleProject project = setupNotifyProject(); @@ -604,6 +594,6 @@ public void testDoNotifyCommitWithAllowModeSha1() throws Exception { FreeStyleBuild lastBuild = project.getLastBuild(); assertNotNull(lastBuild); - assertEquals(lastBuild.getNumber(), 1); + assertEquals(1, lastBuild.getNumber()); } } diff --git a/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java b/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java index 42a2a03fac..8cc744a560 100644 --- a/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java +++ b/src/test/java/hudson/plugins/git/GitStatusTheoriesTest.java @@ -9,22 +9,20 @@ import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; + +import static hudson.Functions.isWindows; import static org.mockito.Mockito.mock; -import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.experimental.theories.DataPoints; -import org.junit.experimental.theories.FromDataPoints; -import org.junit.experimental.theories.Theories; -import org.junit.experimental.theories.Theory; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import jakarta.servlet.http.HttpServletRequest; -@RunWith(Theories.class) -public class GitStatusTheoriesTest extends AbstractGitProject { +class GitStatusTheoriesTest extends AbstractGitProject { private GitStatus gitStatus; private HttpServletRequest requestWithNoParameter; @@ -34,8 +32,8 @@ public class GitStatusTheoriesTest extends AbstractGitProject { private String sha1; private String notifyCommitApiToken; - @Before - public void setUp() throws Exception { + @BeforeEach + void beforeEach() throws Exception { GitStatus.setAllowNotifyCommitParameters(false); GitStatus.setSafeParametersForTest(null); this.gitStatus = new GitStatus(); @@ -49,14 +47,14 @@ public void setUp() throws Exception { } } - @After - public void resetAllowNotifyCommitParameters() throws Exception { + @AfterEach + @Override + void afterEach() throws Exception { + super.afterEach(); + GitStatus.setAllowNotifyCommitParameters(false); GitStatus.setSafeParametersForTest(null); - } - @After - public void waitForAllJobsToComplete() throws Exception { // Put JenkinsRule into shutdown state, trying to reduce Windows cleanup exceptions if (r != null && r.jenkins != null) { r.jenkins.doQuietDown(); @@ -93,33 +91,37 @@ public void waitForAllJobsToComplete() throws Exception { }); } - @DataPoints("branchSpecPrefixes") - public static final String[] BRANCH_SPEC_PREFIXES = new String[] { - "", - "refs/remotes/", - "refs/heads/", - "origin/", - "remotes/origin/" - }; - - @Theory - public void testDoNotifyCommitBranchWithSlash(@FromDataPoints("branchSpecPrefixes") String branchSpecPrefix) throws Exception { + static String[] branchSpecPrefixes() { + return new String[]{ + "", + "refs/remotes/", + "refs/heads/", + "origin/", + "remotes/origin/" + }; + } + + @ParameterizedTest + @MethodSource("branchSpecPrefixes") + void testDoNotifyCommitBranchWithSlash(String branchSpecPrefix) throws Exception { SCMTrigger trigger = setupProjectWithTrigger("remote", branchSpecPrefix + "feature/awesome-feature", false); this.gitStatus.doNotifyCommit(requestWithNoParameter, "remote", "feature/awesome-feature", null, notifyCommitApiToken); Mockito.verify(trigger).run(); } - @Theory - public void testDoNotifyCommitBranchWithoutSlash(@FromDataPoints("branchSpecPrefixes") String branchSpecPrefix) throws Exception { + @ParameterizedTest + @MethodSource("branchSpecPrefixes") + void testDoNotifyCommitBranchWithoutSlash(String branchSpecPrefix) throws Exception { SCMTrigger trigger = setupProjectWithTrigger("remote", branchSpecPrefix + "awesome-feature", false); this.gitStatus.doNotifyCommit(requestWithNoParameter, "remote", "awesome-feature", null, notifyCommitApiToken); Mockito.verify(trigger).run(); } - @Theory - public void testDoNotifyCommitBranchByBranchRef(@FromDataPoints("branchSpecPrefixes") String branchSpecPrefix) throws Exception { + @ParameterizedTest + @MethodSource("branchSpecPrefixes") + void testDoNotifyCommitBranchByBranchRef(String branchSpecPrefix) throws Exception { SCMTrigger trigger = setupProjectWithTrigger("remote", branchSpecPrefix + "awesome-feature", false); this.gitStatus.doNotifyCommit(requestWithNoParameter, "remote", "refs/heads/awesome-feature", null, notifyCommitApiToken); @@ -144,11 +146,4 @@ private void setupProject(String url, String branchString, SCMTrigger trigger) t if (trigger != null) project.addTrigger(trigger); } - /** - * inline ${@link hudson.Functions#isWindows()} to prevent a transient - * remote classloader issue - */ - private boolean isWindows() { - return File.pathSeparatorChar == ';'; - } } diff --git a/src/test/java/hudson/plugins/git/GitStepSnippetizerTest.java b/src/test/java/hudson/plugins/git/GitStepSnippetizerTest.java index d8f40a628c..078a1e9ce1 100644 --- a/src/test/java/hudson/plugins/git/GitStepSnippetizerTest.java +++ b/src/test/java/hudson/plugins/git/GitStepSnippetizerTest.java @@ -27,9 +27,10 @@ import java.util.Random; import jenkins.plugins.git.GitStep; import org.jenkinsci.plugins.workflow.cps.SnippetizerTester; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Test workflow snippet generation for the git step. Workflow snippets should not @@ -37,10 +38,10 @@ * * @author Mark Waite */ -public class GitStepSnippetizerTest { +@WithJenkins +class GitStepSnippetizerTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; private final Random random = new Random(); private final SnippetizerTester tester = new SnippetizerTester(r); @@ -48,6 +49,11 @@ public class GitStepSnippetizerTest { private final String url = "https://github.com/jenkinsci/git-plugin.git"; private final GitStep gitStep = new GitStep(url); + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; + } + /* Adding the default values to the step should not alter the output of the * round trip. */ @@ -68,13 +74,13 @@ private void addRandomDefaultValues(GitStep step, @NonNull String skipThese) { /* Check that a minimal `git '..url..'` step is correctly parsed */ @Test - public void gitSimplest() throws Exception { + void gitSimplest() throws Exception { addRandomDefaultValues(gitStep, ""); tester.assertRoundTrip(gitStep, "git '" + url + "'"); } @Test - public void gitCredentials() throws Exception { + void gitCredentials() throws Exception { String credentialsId = "my-credential"; gitStep.setCredentialsId(credentialsId); addRandomDefaultValues(gitStep, "credentialsId"); @@ -82,7 +88,7 @@ public void gitCredentials() throws Exception { } @Test - public void gitBranch() throws Exception { + void gitBranch() throws Exception { String branch = "4.10.x"; gitStep.setBranch(branch); addRandomDefaultValues(gitStep, "branch"); @@ -90,14 +96,14 @@ public void gitBranch() throws Exception { } @Test - public void gitNoPoll() throws Exception { + void gitNoPoll() throws Exception { gitStep.setPoll(false); addRandomDefaultValues(gitStep, "poll"); tester.assertRoundTrip(gitStep, "git poll: false, url: '" + url + "'"); } @Test - public void gitNoChangelog() throws Exception { + void gitNoChangelog() throws Exception { gitStep.setChangelog(false); addRandomDefaultValues(gitStep, "changelog"); tester.assertRoundTrip(gitStep, "git changelog: false, url: '" + url + "'"); diff --git a/src/test/java/hudson/plugins/git/GitStepTest.java b/src/test/java/hudson/plugins/git/GitStepTest.java index d0c50efae9..f1b84cb5f1 100644 --- a/src/test/java/hudson/plugins/git/GitStepTest.java +++ b/src/test/java/hudson/plugins/git/GitStepTest.java @@ -37,13 +37,17 @@ import hudson.scm.ChangeLogSet; import hudson.scm.SCM; import hudson.triggers.SCMTrigger; + +import java.time.Duration; +import java.time.Instant; import java.util.Iterator; import java.util.List; + +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import jenkins.util.VirtualFile; import jenkins.plugins.git.CliGitCommand; import jenkins.plugins.git.GitSampleRepoRule; import jenkins.plugins.git.GitStep; -import jenkins.plugins.git.RandomOrder; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; @@ -51,78 +55,76 @@ import org.jenkinsci.plugins.workflow.steps.StepConfigTester; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assume.assumeTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Stopwatch; -import org.junit.rules.TestName; -import org.junit.runner.OrderWith; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; -import static java.util.concurrent.TimeUnit.SECONDS; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * @author Nicolas De Loof */ -@OrderWith(RandomOrder.class) -public class GitStepTest { +@TestMethodOrder(MethodOrderer.Random.class) +@WithJenkins +@WithGitSampleRepo +class GitStepTest { - @Rule - public JenkinsRule r = new JenkinsRule(); - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); - @Rule - public GitSampleRepoRule otherRepo = new GitSampleRepoRule(); + private JenkinsRule r; - @BeforeClass - public static void setGitDefaults() throws Exception { + private GitSampleRepoRule sampleRepo; + private GitSampleRepoRule otherRepo; + + @BeforeAll + static void beforeAll() throws Exception { CliGitCommand gitCmd = new CliGitCommand(null); gitCmd.setDefaults(); } - @ClassRule - public static Stopwatch stopwatch = new Stopwatch(); - @Rule - public TestName testName = new TestName(); + @BeforeEach + void beforeEach(JenkinsRule rule, GitSampleRepoRule repo1, GitSampleRepoRule repo2) { + r = rule; + sampleRepo = repo1; + otherRepo = repo2; + } + + private static final Instant START_TIME = Instant.now(); private static final int MAX_SECONDS_FOR_THESE_TESTS = 200; private boolean isTimeAvailable() { String env = System.getenv("CI"); - if (env == null || !Boolean.parseBoolean(env)) { + if (!Boolean.parseBoolean(env)) { // Run all tests when not in CI environment return true; } - return stopwatch.runtime(SECONDS) <= MAX_SECONDS_FOR_THESE_TESTS; + return Duration.between(START_TIME, Instant.now()).toSeconds() <= MAX_SECONDS_FOR_THESE_TESTS; } private static String NOTIFY_COMMIT_ACCESS_CONTROL_ORIGINAL = GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL; - @After - public void resetNotifyCommitAccessControl() { + @AfterEach + void afterEach() { GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL = NOTIFY_COMMIT_ACCESS_CONTROL_ORIGINAL; } @Test - public void roundtrip() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void roundtrip() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); GitStep step = new GitStep("git@github.com:jenkinsci/workflow-plugin.git"); Step roundtrip = new StepConfigTester(r).configRoundTrip(step); r.assertEqualDataBoundBeans(step, roundtrip); } @Test - public void roundtrip_withcredentials() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void roundtrip_withcredentials() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); IdCredentials c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, null, "user", "password-needs-to-be-14"); CredentialsProvider.lookupStores(r.jenkins).iterator().next() .addCredentials(Domain.global(), c); @@ -133,8 +135,8 @@ public void roundtrip_withcredentials() throws Exception { } @Test - public void basicCloneAndUpdate() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void basicCloneAndUpdate() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "demo"); r.createOnlineSlave(Label.get("remote")); @@ -157,8 +159,8 @@ public void basicCloneAndUpdate() throws Exception { } @Test - public void changelogAndPolling() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void changelogAndPolling() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "demo"); p.addTrigger(new SCMTrigger("")); // no schedule, use notifyCommit only @@ -194,8 +196,8 @@ public void changelogAndPolling() throws Exception { } @Test - public void multipleSCMs() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void multipleSCMs() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); otherRepo.init(); otherRepo.write("otherfile", ""); @@ -259,8 +261,8 @@ public void multipleSCMs() throws Exception { @Issue("JENKINS-29326") @Test - public void identicalGitSCMs() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void identicalGitSCMs() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); otherRepo.init(); otherRepo.write("firstfile", ""); @@ -294,8 +296,8 @@ public void identicalGitSCMs() throws Exception { } @Test - public void commitToWorkspace() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void commitToWorkspace() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( @@ -327,8 +329,8 @@ private WorkflowJob createJob() throws Exception { @Test @Issue("SECURITY-284") - public void testDoNotifyCommitWithInvalidApiToken() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testDoNotifyCommitWithInvalidApiToken() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); createJob(); String response = sampleRepo.notifyCommitWithResults(r, GitSampleRepoRule.INVALID_NOTIFY_COMMIT_TOKEN); assertThat(response, containsString("Invalid access token")); @@ -336,8 +338,8 @@ public void testDoNotifyCommitWithInvalidApiToken() throws Exception { @Test @Issue("SECURITY-284") - public void testDoNotifyCommitWithAllowModeRandomValue() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testDoNotifyCommitWithAllowModeRandomValue() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); createJob(); String response = sampleRepo.notifyCommitWithResults(r, null); assertThat(response, containsString("An access token is required. Please refer to Git plugin documentation (https://plugins.jenkins.io/git/#plugin-content-push-notification-from-repository) for details.")); @@ -345,8 +347,8 @@ public void testDoNotifyCommitWithAllowModeRandomValue() throws Exception { @Test @Issue("SECURITY-284") - public void testDoNotifyCommitWithSha1AndAllowModePollWithInvalidToken() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testDoNotifyCommitWithSha1AndAllowModePollWithInvalidToken() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL = "disabled-for-polling"; createJob(); /* sha1 is ignored because invalid access token is provided */ @@ -357,8 +359,8 @@ public void testDoNotifyCommitWithSha1AndAllowModePollWithInvalidToken() throws @Test @Issue("SECURITY-284") - public void testDoNotifyCommitWithSha1AndAllowModePoll() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testDoNotifyCommitWithSha1AndAllowModePoll() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL = "disabled-for-polling"; createJob(); /* sha1 is ignored because no access token is provided */ diff --git a/src/test/java/hudson/plugins/git/GitTagActionTest.java b/src/test/java/hudson/plugins/git/GitTagActionTest.java index 3623053407..eb08324d5d 100644 --- a/src/test/java/hudson/plugins/git/GitTagActionTest.java +++ b/src/test/java/hudson/plugins/git/GitTagActionTest.java @@ -16,7 +16,6 @@ import java.util.Set; import hudson.EnvVars; -import hudson.Extension; import hudson.FilePath; import hudson.model.Descriptor; import hudson.model.FreeStyleProject; @@ -25,30 +24,30 @@ import hudson.plugins.git.GitSCM.DescriptorImpl; import hudson.plugins.git.extensions.impl.LocalBranch; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.util.SystemReader; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import jenkins.plugins.git.GitSampleRepoRule; +import static hudson.Functions.isWindows; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.htmlunit.html.HtmlForm; import org.htmlunit.html.HtmlPage; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; import jakarta.servlet.ServletException; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Test git tag action. Low value test that was created as part of @@ -61,7 +60,9 @@ * * @author Mark Waite */ -public class GitTagActionTest { +@WithJenkins +@WithGitSampleRepo +class GitTagActionTest { private static GitTagAction noTagAction; private static GitTagAction tagOneAction; @@ -71,17 +72,9 @@ public class GitTagActionTest { private static final String NO_BRANCHES = "tagRevision-with-no-branches"; - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; - @ClassRule - public static TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @ClassRule - public static GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); - - public GitTagActionTest() { - } + private static GitSampleRepoRule sampleRepo; private static FreeStyleProject p; private static GitClient workspaceGitClient = null; @@ -94,11 +87,16 @@ public GitTagActionTest() { private static String sampleRepoHead = null; private static DescriptorImpl gitSCMDescriptor = null; - @BeforeClass - public static void deleteMatchingTags() throws Exception { + @BeforeAll + static void beforeAll(JenkinsRule rule, GitSampleRepoRule repo) throws Exception { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further + /* Do not distract warnings system by using assumeThat to skip tests */ return; } + + r = rule; + sampleRepo = repo; + /* Remove tags from working repository that start with TAG_PREFIX and don't contain TAG_SUFFIX */ GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()) .in(new File(".")) @@ -109,13 +107,7 @@ public static void deleteMatchingTags() throws Exception { gitClient.deleteTag(tag.getName()); } } - } - @BeforeClass - public static void createThreeGitTagActions() throws Exception { - if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further - return; - } sampleRepo.init(); sampleRepo.write("file", INITIAL_COMMIT_MESSAGE); sampleRepo.git("commit", "--all", "--message=" + INITIAL_COMMIT_MESSAGE); @@ -160,8 +152,8 @@ public static void createThreeGitTagActions() throws Exception { assertThat(tagNullBranchesAction, is(not(nullValue()))); } - @AfterClass - public static void disableAddGitTagAction() { + @AfterAll + static void afterAll() { /* Do not add git tag action to builds for other tests */ if (gitSCMDescriptor != null) { gitSCMDescriptor.setAddGitTagAction(false); @@ -239,7 +231,7 @@ private static GitTagAction createTagAction(String message) throws Exception { foundMasterBranch = true; } } - assertTrue("master branch not found, last branch name was " + lastBranchName, foundMasterBranch); + assertTrue(foundMasterBranch, "master branch not found, last branch name was " + lastBranchName); /* Create the GitTagAction */ GitTagAction tagAction; @@ -325,7 +317,7 @@ private static void waitForTagCreation(GitTagAction tagAction, String message) t } @Test - public void testDoPost() throws Exception { + void testDoPost() throws Exception { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -340,7 +332,7 @@ public void testDoPost() throws Exception { } @Test - public void testGetDescriptor() { + void testGetDescriptor() { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -350,7 +342,7 @@ public void testGetDescriptor() { } @Test - public void testIsNotTagged() { + void testIsNotTagged() { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -359,7 +351,7 @@ public void testIsNotTagged() { } @Test - public void testGetDisplayNameNoTagAction() { + void testGetDisplayNameNoTagAction() { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -368,7 +360,7 @@ public void testGetDisplayNameNoTagAction() { } @Test - public void testGetIconFileName() { + void testGetIconFileName() { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -377,7 +369,7 @@ public void testGetIconFileName() { } @Test - public void testGetTagsNoTagAction() { + void testGetTagsNoTagAction() { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -389,7 +381,7 @@ public void testGetTagsNoTagAction() { } @Test - public void testGetTagsOneTagAction() { + void testGetTagsOneTagAction() { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -401,7 +393,7 @@ public void testGetTagsOneTagAction() { } @Test - public void testGetTagsTwoTagAction() { + void testGetTagsTwoTagAction() { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -413,7 +405,7 @@ public void testGetTagsTwoTagAction() { } @Test - public void testGetTagInfo() { + void testGetTagInfo() { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -422,7 +414,7 @@ public void testGetTagInfo() { } @Test - public void testGetTooltipNoTagAction() { + void testGetTooltipNoTagAction() { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -431,7 +423,7 @@ public void testGetTooltipNoTagAction() { } @Test - public void testGetPermission() { + void testGetPermission() { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -444,11 +436,4 @@ private static String chooseGitImplementation() { return random.nextBoolean() ? "git" : "jgit"; } - /** - * inline ${@link hudson.Functions#isWindows()} to prevent a transient - * remote classloader issue - */ - private static boolean isWindows() { - return File.pathSeparatorChar == ';'; - } } diff --git a/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java b/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java index 8fe98e3bf4..bb08fbc9c5 100644 --- a/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java +++ b/src/test/java/hudson/plugins/git/JGitSCMTriggerLocalPollTest.java @@ -3,8 +3,7 @@ import hudson.plugins.git.extensions.GitClientType; import hudson.plugins.git.extensions.impl.EnforceGitClient; -public class JGitSCMTriggerLocalPollTest extends SCMTriggerTest -{ +class JGitSCMTriggerLocalPollTest extends SCMTriggerTest { @Override protected EnforceGitClient getGitClient() diff --git a/src/test/java/hudson/plugins/git/JGitSCMTriggerRemotePollTest.java b/src/test/java/hudson/plugins/git/JGitSCMTriggerRemotePollTest.java index b8f8d6108a..f8cf83d00d 100644 --- a/src/test/java/hudson/plugins/git/JGitSCMTriggerRemotePollTest.java +++ b/src/test/java/hudson/plugins/git/JGitSCMTriggerRemotePollTest.java @@ -9,8 +9,8 @@ * The isChangeExpected() method adjusts the tests to the difference between * local and remote polling. */ -public class JGitSCMTriggerRemotePollTest extends SCMTriggerTest -{ +class JGitSCMTriggerRemotePollTest extends SCMTriggerTest { + @Override protected EnforceGitClient getGitClient() { diff --git a/src/test/java/hudson/plugins/git/RevisionParameterActionRemoteUrlTest.java b/src/test/java/hudson/plugins/git/RevisionParameterActionRemoteUrlTest.java index 545c4fecc7..230684554b 100644 --- a/src/test/java/hudson/plugins/git/RevisionParameterActionRemoteUrlTest.java +++ b/src/test/java/hudson/plugins/git/RevisionParameterActionRemoteUrlTest.java @@ -5,49 +5,50 @@ import java.util.List; import org.eclipse.jgit.transport.RemoteConfig; + +import org.junit.jupiter.api.Test; import org.eclipse.jgit.transport.URIish; -import org.junit.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class RevisionParameterActionRemoteUrlTest { +class RevisionParameterActionRemoteUrlTest { @Test - public void noRemoteURLSet() throws Exception { + void noRemoteURLSet() throws Exception { RevisionParameterAction target = new RevisionParameterAction("sha1"); URIish remoteURL = new URIish("https://github.com/jenkinsci/git-plugin.git"); - assertTrue("should always return true when no remote set", target.canOriginateFrom(remotes(remoteURL))); + assertTrue(target.canOriginateFrom(remotes(remoteURL)), "should always return true when no remote set"); } @Test - public void remoteURLSetButDoesntMatch() throws Exception { + void remoteURLSetButDoesntMatch() throws Exception { URIish actionURL = new URIish("https://github.com/jenkinsci/multiple-scms-plugin.git"); RevisionParameterAction target = new RevisionParameterAction("sha1", actionURL); URIish remoteURL = new URIish("https://github.com/jenkinsci/git-plugin.git"); - assertFalse("should return false on different remotes", target.canOriginateFrom(remotes(remoteURL))); + assertFalse(target.canOriginateFrom(remotes(remoteURL)), "should return false on different remotes"); } @Test - public void remoteURLSetAndMatches() throws Exception { + void remoteURLSetAndMatches() throws Exception { URIish actionURL = new URIish("https://github.com/jenkinsci/git-plugin.git"); RevisionParameterAction target = new RevisionParameterAction("sha1", actionURL); URIish remoteURL = new URIish("https://github.com/jenkinsci/git-plugin.git"); - assertTrue("should return true on same remotes", target.canOriginateFrom(remotes(remoteURL))); + assertTrue(target.canOriginateFrom(remotes(remoteURL)), "should return true on same remotes"); } @Test - public void multipleRemoteURLsSetAndOneMatches() throws Exception { + void multipleRemoteURLsSetAndOneMatches() throws Exception { URIish actionURL = new URIish("https://github.com/jenkinsci/git-plugin.git"); RevisionParameterAction target = new RevisionParameterAction("sha1", actionURL); URIish remoteURL1 = new URIish("https://github.com/jenkinsci/multiple-scms-plugin.git"); URIish remoteURL2 = new URIish("https://github.com/jenkinsci/git-plugin.git"); - assertTrue("should return true when any remote matches", target.canOriginateFrom(remotes(remoteURL1, remoteURL2))); + assertTrue(target.canOriginateFrom(remotes(remoteURL1, remoteURL2)), "should return true when any remote matches"); } private List remotes(URIish... remoteURLs) { diff --git a/src/test/java/hudson/plugins/git/RevisionParameterActionTest.java b/src/test/java/hudson/plugins/git/RevisionParameterActionTest.java index b0e2628163..b5ccde471f 100644 --- a/src/test/java/hudson/plugins/git/RevisionParameterActionTest.java +++ b/src/test/java/hudson/plugins/git/RevisionParameterActionTest.java @@ -28,20 +28,21 @@ import hudson.model.FreeStyleBuild; import hudson.model.Result; import hudson.plugins.git.util.BuildData; +import org.junit.jupiter.api.Test; import java.util.Collections; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; /** * Tests for {@link RevisionParameterAction} * * @author Chris Johnson */ -public class RevisionParameterActionTest extends AbstractGitProject { +class RevisionParameterActionTest extends AbstractGitProject { @Test - public void testProvidingRevision() throws Exception { + void testProvidingRevision() throws Exception { FreeStyleProject p1 = setupSimpleProject("master"); diff --git a/src/test/java/hudson/plugins/git/SCMTriggerTest.java b/src/test/java/hudson/plugins/git/SCMTriggerTest.java index 7a4fc49fec..698123b4c9 100644 --- a/src/test/java/hudson/plugins/git/SCMTriggerTest.java +++ b/src/test/java/hudson/plugins/git/SCMTriggerTest.java @@ -1,8 +1,9 @@ package hudson.plugins.git; +import static hudson.Functions.isWindows; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.junit.Assert.*; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.junit.jupiter.api.Assertions.*; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; @@ -17,6 +18,8 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.time.Duration; +import java.time.Instant; import java.util.Collections; import java.util.Enumeration; import java.util.Properties; @@ -28,41 +31,39 @@ import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import jenkins.plugins.git.RandomOrder; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Stopwatch; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.OrderWith; - -@OrderWith(RandomOrder.class) + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.io.TempDir; + +@TestMethodOrder(MethodOrderer.Random.class) public abstract class SCMTriggerTest extends AbstractGitProject { + private ZipFile namespaceRepoZip; private Properties namespaceRepoCommits; private ExecutorService singleThreadExecutor; protected boolean expectChanges = false; - @ClassRule - public static Stopwatch stopwatch = new Stopwatch(); + private static final Instant START_TIME = Instant.now(); private static final int MAX_SECONDS_FOR_THESE_TESTS = 120; private boolean isTimeAvailable() { String env = System.getenv("CI"); - if (env == null || !Boolean.parseBoolean(env)) { + if (!Boolean.parseBoolean(env)) { // Run all tests when not in CI environment return true; } - return stopwatch.runtime(SECONDS) <= MAX_SECONDS_FOR_THESE_TESTS; + return Duration.between(START_TIME, Instant.now()).toSeconds() <= MAX_SECONDS_FOR_THESE_TESTS; } - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; - @Before - public void setUp() throws Exception { + @BeforeEach + public void beforeEach() throws Exception { expectChanges = false; namespaceRepoZip = new ZipFile("src/test/resources/namespaceBranchRepo.zip"); namespaceRepoCommits = parseLsRemote(new File("src/test/resources/namespaceBranchRepo.ls-remote")); @@ -91,7 +92,7 @@ public void testNamespaces_with_remotesOriginMaster() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -105,7 +106,7 @@ public void testNamespaces_with_refsRemotesOriginMaster() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -119,7 +120,7 @@ public void testNamespaces_with_master() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -133,7 +134,7 @@ public void testNamespaces_with_namespace1Master() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -147,7 +148,7 @@ public void testNamespaces_with_refsHeadsNamespace1Master() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -161,7 +162,7 @@ public void testNamespaces_with_namespace2Master() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -175,7 +176,7 @@ public void testNamespaces_with_refsHeadsNamespace2Master() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -189,7 +190,7 @@ public void testNamespaces_with_namespace3_feature3_sha1() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -203,7 +204,7 @@ public void testNamespaces_with_namespace3_feature3_branchName() throws Exceptio if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -217,7 +218,7 @@ public void testNamespaces_with_refsHeadsNamespace3_feature3_sha1() throws Excep if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -231,7 +232,7 @@ public void testNamespaces_with_refsHeadsNamespace3_feature3_branchName() throws if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -245,7 +246,7 @@ public void testTags_with_TagA() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -259,7 +260,7 @@ public void testTags_with_TagBAnnotated() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -273,7 +274,7 @@ public void testTags_with_refsTagsTagA() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -287,7 +288,7 @@ public void testTags_with_refsTagsTagBAnnotated() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -301,7 +302,7 @@ public void testCommitAsBranchSpec_feature4_sha1() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -315,7 +316,7 @@ public void testCommitAsBranchSpec_feature4_branchName() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -329,7 +330,7 @@ public void testCommitAsBranchSpec() throws Exception { if (isWindows()) { // Low value test - skip on Windows return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); check( namespaceRepoZip, namespaceRepoCommits, @@ -359,30 +360,30 @@ public void check( triggerSCMTrigger(project.getTrigger(SCMTrigger.class)); FreeStyleBuild build1 = waitForBuildFinished(project, 1, 60000); - assertNotNull("Job has not been triggered", build1); + assertNotNull(build1, "Job has not been triggered"); TaskListener listener = StreamTaskListener.fromStderr(); PollingResult poll = project.poll(listener); - assertFalse("Expected and actual polling results disagree", poll.hasChanges()); + assertFalse(poll.hasChanges(), "Expected and actual polling results disagree"); // Speedup test - avoid waiting 1 minute triggerSCMTrigger(project.getTrigger(SCMTrigger.class)).get(20, SECONDS); FreeStyleBuild build2 = waitForBuildFinished(project, 2, 2000); - assertNull("Found build 2 although no new changes and no multi candidate build", build2); + assertNull(build2, "Found build 2 although no new changes and no multi candidate build"); assertEquals( - "Unexpected GIT_COMMIT", expected_GIT_COMMIT, - build1.getEnvironment(null).get("GIT_COMMIT")); + build1.getEnvironment(null).get("GIT_COMMIT"), + "Unexpected GIT_COMMIT"); assertEquals( - "Unexpected GIT_BRANCH", expected_GIT_BRANCH, - build1.getEnvironment(null).get("GIT_BRANCH")); + build1.getEnvironment(null).get("GIT_BRANCH"), + "Unexpected GIT_BRANCH"); } private String prepareRepo(ZipFile repoZip) throws IOException { - File tempRemoteDir = tempFolder.newFolder(); + File tempRemoteDir = newFolder(tempFolder, "junit"); extract(repoZip, tempRemoteDir); return tempRemoteDir.getAbsolutePath(); } @@ -442,8 +443,12 @@ private void extract(ZipFile zipFile, File outputDir) throws IOException { } } - /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ - private boolean isWindows() { - return File.pathSeparatorChar == ';'; + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; } } diff --git a/src/test/java/hudson/plugins/git/Security2478Test.java b/src/test/java/hudson/plugins/git/Security2478Test.java index b7476342e1..58e0346cff 100644 --- a/src/test/java/hudson/plugins/git/Security2478Test.java +++ b/src/test/java/hudson/plugins/git/Security2478Test.java @@ -2,43 +2,45 @@ import hudson.model.Result; import jenkins.plugins.git.GitSampleRepoRule; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.io.File; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; -public class Security2478Test { +@WithJenkins +@WithGitSampleRepo +class Security2478Test { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + private GitSampleRepoRule sampleRepo; - - @Before - public void setUpAllowNonRemoteCheckout() { + @BeforeEach + void beforeEach(JenkinsRule rule, GitSampleRepoRule repo) { + r = rule; + sampleRepo = repo; GitSCM.ALLOW_LOCAL_CHECKOUT = false; } - @After - public void disallowNonRemoteCheckout() { + @AfterEach + void afterEach() { GitSCM.ALLOW_LOCAL_CHECKOUT = false; } @Issue("SECURITY-2478") @Test - public void checkoutShouldNotAbortWhenLocalSourceAndRunningOnAgent() throws Exception { - assertFalse("Non Remote checkout should be disallowed", GitSCM.ALLOW_LOCAL_CHECKOUT); + void checkoutShouldNotAbortWhenLocalSourceAndRunningOnAgent() throws Exception { + assertFalse(GitSCM.ALLOW_LOCAL_CHECKOUT, "Non Remote checkout should be disallowed"); r.createOnlineSlave(); sampleRepo.init(); sampleRepo.write("file", "v1"); @@ -56,8 +58,8 @@ public void checkoutShouldNotAbortWhenLocalSourceAndRunningOnAgent() throws Exce @Issue("SECURITY-2478") @Test - public void checkoutShouldAbortWhenSourceIsNonRemoteAndRunningOnController() throws Exception { - assertFalse("Non Remote checkout should be disallowed", GitSCM.ALLOW_LOCAL_CHECKOUT); + void checkoutShouldAbortWhenSourceIsNonRemoteAndRunningOnController() throws Exception { + assertFalse(GitSCM.ALLOW_LOCAL_CHECKOUT, "Non Remote checkout should be disallowed"); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "pipeline"); String workspaceDir = r.jenkins.getRootDir().getAbsolutePath(); diff --git a/src/test/java/hudson/plugins/git/SubmoduleCombinatorTest.java b/src/test/java/hudson/plugins/git/SubmoduleCombinatorTest.java index a53c348d0a..b3bcb63e83 100644 --- a/src/test/java/hudson/plugins/git/SubmoduleCombinatorTest.java +++ b/src/test/java/hudson/plugins/git/SubmoduleCombinatorTest.java @@ -3,6 +3,8 @@ import hudson.EnvVars; import hudson.model.TaskListener; import hudson.util.StreamTaskListener; +import org.junit.jupiter.api.BeforeEach; + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -13,20 +15,17 @@ import org.eclipse.jgit.lib.ObjectId; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; @Deprecated -public class SubmoduleCombinatorTest { +class SubmoduleCombinatorTest { private SubmoduleCombinator combinator = null; - public SubmoduleCombinatorTest() { - } - - @Before - public void setUp() throws IOException, InterruptedException { + @BeforeEach + void beforeEach() throws IOException, InterruptedException { TaskListener listener = StreamTaskListener.fromStderr(); GitClient gitClient = Git.with(listener, new EnvVars()).in(new File(".")).getClient(); Collection cfg = null; @@ -34,14 +33,14 @@ public void setUp() throws IOException, InterruptedException { } @Test - public void testDifferenceNulls() { + void testDifferenceNulls() { Map item = new HashMap<>(); List entries = new ArrayList<>(); assertEquals(0, combinator.difference(item, entries)); } @Test - public void testDifferenceDifferentSize() { + void testDifferenceDifferentSize() { Map item = new HashMap<>(); List entries = new ArrayList<>(); assertTrue(entries.add(new IndexEntry("mode", "type", "object", "file"))); @@ -50,30 +49,30 @@ public void testDifferenceDifferentSize() { } @Test - public void testDifferenceNoDifference() { + void testDifferenceNoDifference() { Map items = new HashMap<>(); List entries = new ArrayList<>(); ObjectId sha1 = ObjectId.fromString("1c2a9e6194e6ede0805cda4c9ccc7e373e835414"); IndexEntry indexEntry1 = new IndexEntry("mode-1", "type-1", sha1.getName(), "file-1"); - assertTrue("Failed to add indexEntry1 to entries", entries.add(indexEntry1)); + assertTrue(entries.add(indexEntry1), "Failed to add indexEntry1 to entries"); Revision revision = new Revision(sha1); - assertNull("items[indexEntry1] had existing value", items.put(indexEntry1, revision)); - assertEquals("entries and items[entries] don't match", 0, combinator.difference(items, entries)); + assertNull(items.put(indexEntry1, revision), "items[indexEntry1] had existing value"); + assertEquals(0, combinator.difference(items, entries), "entries and items[entries] don't match"); } @Test - public void testDifferenceOneDifference() { + void testDifferenceOneDifference() { Map items = new HashMap<>(); List entries = new ArrayList<>(); ObjectId sha1 = ObjectId.fromString("1c2a9e6194e6ede0805cda4c9ccc7e373e835414"); String fileName = "fileName"; IndexEntry indexEntry1 = new IndexEntry("mode-1", "type-1", sha1.getName(), fileName); - assertTrue("Failed to add indexEntry1 to entries", entries.add(indexEntry1)); + assertTrue(entries.add(indexEntry1), "Failed to add indexEntry1 to entries"); ObjectId sha2 = ObjectId.fromString("54094393c170c94d330b1ae52101922092b0abd2"); Revision revision = new Revision(sha2); IndexEntry indexEntry2 = new IndexEntry("mode-2", "type-2", sha2.getName(), fileName); - assertNull("items[indexEntry2] had existing value", items.put(indexEntry2, revision)); + assertNull(items.put(indexEntry2, revision), "items[indexEntry2] had existing value"); /* Deprecated - no differences even when differences exist */ - assertEquals("entries and items[entries] wrong diff count", 0, combinator.difference(items, entries)); + assertEquals(0, combinator.difference(items, entries), "entries and items[entries] wrong diff count"); } } diff --git a/src/test/java/hudson/plugins/git/SubmoduleConfigTest.java b/src/test/java/hudson/plugins/git/SubmoduleConfigTest.java index 82df452e5d..910223547a 100644 --- a/src/test/java/hudson/plugins/git/SubmoduleConfigTest.java +++ b/src/test/java/hudson/plugins/git/SubmoduleConfigTest.java @@ -27,14 +27,16 @@ import java.util.Arrays; import java.util.List; import org.eclipse.jgit.lib.ObjectId; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; @Deprecated -public class SubmoduleConfigTest { +class SubmoduleConfigTest { private SubmoduleConfig config = new SubmoduleConfig(); private SubmoduleConfig configWithBranchArray; @@ -73,20 +75,20 @@ public SubmoduleConfigTest() { branchNameList.add("develop"); } - @Before - public void setUp() { + @BeforeEach + void beforeEach() { config = new SubmoduleConfig(); configWithBranchArray = new SubmoduleConfig("submodule-branch-names-from-array", branchNames); configWithBranchList = new SubmoduleConfig("submodule-branch-names-from-list", branchNameList); } @Test - public void testGetSubmoduleName() { + void testGetSubmoduleName() { assertThat(config.getSubmoduleName(), is(nullValue())); } @Test - public void testSetSubmoduleName() { + void testSetSubmoduleName() { String name = "name-of-submodule"; config.setSubmoduleName(name); assertThat(config.getSubmoduleName(), is(nullValue())); @@ -96,22 +98,22 @@ public void testSetSubmoduleName() { } @Test - public void testGetBranches() { + void testGetBranches() { assertThat(config.getBranches(), is(arrayWithSize(0))); } @Test - public void testGetBranchesFromArray() { + void testGetBranchesFromArray() { assertThat(configWithBranchArray.getBranches(), is(arrayWithSize(0))); } @Test - public void testGetBranchesFromList() { + void testGetBranchesFromList() { assertThat(configWithBranchList.getBranches(), is(arrayWithSize(0))); } @Test - public void testSetBranches() { + void testSetBranches() { config.setBranches(branchNames); assertThat(config.getBranches(), is(arrayWithSize(0))); String[] newBranchNames = Arrays.copyOf(branchNames, branchNames.length); @@ -121,51 +123,51 @@ public void testSetBranches() { } @Test - public void testGetBranchesStringEmpty() { + void testGetBranchesStringEmpty() { assertThat(config.getBranchesString(), is("")); } @Test - public void testGetBranchesString() { + void testGetBranchesString() { config.setBranches(branchNames); assertThat(config.getBranchesString(), is("")); } @Test - public void testGetBranchesStringFromList() { + void testGetBranchesStringFromList() { assertThat(configWithBranchList.getBranchesString(), is("")); configWithBranchList.setBranches(branchNames); assertThat(configWithBranchList.getBranchesString(), is("")); } @Test - public void testGetBranchesStringFromArray() { + void testGetBranchesStringFromArray() { assertThat(configWithBranchArray.getBranchesString(), is("")); configWithBranchArray.setBranches(branchNames); assertThat(configWithBranchArray.getBranchesString(), is("")); } @Test - public void testRevisionMatchesInterestNoBranches() { + void testRevisionMatchesInterestNoBranches() { assertFalse(config.revisionMatchesInterest(noBranchesRevision)); assertFalse(configWithBranchList.revisionMatchesInterest(noBranchesRevision)); assertFalse(configWithBranchArray.revisionMatchesInterest(noBranchesRevision)); } @Test - public void testRevisionMatchesInterestEmptyBranchList() { + void testRevisionMatchesInterestEmptyBranchList() { assertFalse(config.revisionMatchesInterest(emptyRevision)); assertFalse(configWithBranchList.revisionMatchesInterest(emptyRevision)); assertFalse(configWithBranchArray.revisionMatchesInterest(emptyRevision)); } @Test - public void testRevisionMatchesInterestNPE() { + void testRevisionMatchesInterestNPE() { assertFalse(config.revisionMatchesInterest(multipleBranchesRevision)); } @Test - public void testRevisionMatchesInterestMasterOnly() { + void testRevisionMatchesInterestMasterOnly() { String[] masterOnly = {"master"}; config.setBranches(masterOnly); assertFalse(config.revisionMatchesInterest(multipleBranchesRevision)); @@ -180,7 +182,7 @@ public void testRevisionMatchesInterestMasterOnly() { } @Test - public void testRevisionMatchesInterestAlias() { + void testRevisionMatchesInterestAlias() { String[] aliasName = {"masterAlias"}; config.setBranches(aliasName); assertFalse(config.revisionMatchesInterest(multipleBranchesRevision)); @@ -195,7 +197,7 @@ public void testRevisionMatchesInterestAlias() { } @Test - public void testRevisionMatchesInterest() { + void testRevisionMatchesInterest() { String[] masterDevelop = {"master", "develop"}; config.setBranches(masterDevelop); assertFalse(config.revisionMatchesInterest(multipleBranchesRevision)); @@ -204,7 +206,7 @@ public void testRevisionMatchesInterest() { } @Test - public void testBranchMatchesInterest() { + void testBranchMatchesInterest() { String[] masterOnly = {"master"}; config.setBranches(masterOnly); assertFalse(config.branchMatchesInterest(masterBranch)); @@ -221,7 +223,7 @@ public void testBranchMatchesInterest() { } @Test - public void testBranchMatchesInterestWithRegex() { + void testBranchMatchesInterestWithRegex() { String[] masterOnlyRegex = {"m.st.r"}; config.setBranches(masterOnlyRegex); assertFalse(config.branchMatchesInterest(masterBranch)); @@ -230,7 +232,7 @@ public void testBranchMatchesInterestWithRegex() { } @Test - public void testBranchMatchesInterestMasterDevelop() { + void testBranchMatchesInterestMasterDevelop() { String[] masterDevelop = {"master", "develop"}; config.setBranches(masterDevelop); assertFalse(config.branchMatchesInterest(masterBranch)); @@ -239,7 +241,7 @@ public void testBranchMatchesInterestMasterDevelop() { } @Test - public void testBranchMatchesInterestCommaInBranchName() { + void testBranchMatchesInterestCommaInBranchName() { config.setBranches(branchNames); assertFalse(config.branchMatchesInterest(masterBranch)); assertFalse(config.branchMatchesInterest(masterAliasBranch)); diff --git a/src/test/java/hudson/plugins/git/TestGitRepo.java b/src/test/java/hudson/plugins/git/TestGitRepo.java index 886dc34473..aede043454 100644 --- a/src/test/java/hudson/plugins/git/TestGitRepo.java +++ b/src/test/java/hudson/plugins/git/TestGitRepo.java @@ -19,7 +19,8 @@ import org.jenkinsci.plugins.gitclient.GitClient; public class TestGitRepo { - protected String name; // The name of this repository. + + protected String name; // The name of this repository. protected TaskListener listener; /** diff --git a/src/test/java/hudson/plugins/git/UserMergeOptionsTest.java b/src/test/java/hudson/plugins/git/UserMergeOptionsTest.java index ad1a230859..0899fb304e 100644 --- a/src/test/java/hudson/plugins/git/UserMergeOptionsTest.java +++ b/src/test/java/hudson/plugins/git/UserMergeOptionsTest.java @@ -9,18 +9,23 @@ import nl.jqno.equalsverifier.Warning; import org.jenkinsci.plugins.gitclient.MergeCommand; import org.jenkinsci.plugins.structs.describable.DescribableModel; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.ClassRule; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -@RunWith(Parameterized.class) -public class UserMergeOptionsTest { +@ParameterizedClass(name = "{0}+{1}+{2}+{3}") +@MethodSource("mergeOptionVariants") +@WithJenkins +class UserMergeOptionsTest { - public static @ClassRule JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; private final UserMergeOptions options; private final UserMergeOptions deprecatedOptions; @@ -30,6 +35,11 @@ public class UserMergeOptionsTest { private final MergeCommand.Strategy expectedMergeStrategy; private final MergeCommand.GitPluginFastForwardMode expectedFastForwardMode; + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; + } + @Deprecated private UserMergeOptions defineDeprecatedOptions(String mergeRemote, String mergeTarget, MergeCommand.Strategy mergeStrategy) { return new UserMergeOptions( @@ -55,8 +65,7 @@ public UserMergeOptionsTest( deprecatedOptions = defineDeprecatedOptions(mergeRemote, mergeTarget, mergeStrategy); } - @Parameterized.Parameters(name = "{0}+{1}+{2}+{3}") - public static Collection mergeOptionVariants() { + static Collection mergeOptionVariants() { List mergeOptions = new ArrayList<>(); String[] remotes = new String[]{null, "src_remote"}; String[] targets = new String[]{null, "dst_remote"}; @@ -89,32 +98,32 @@ public static Collection mergeOptionVariants() { } @Test - public void testGetMergeRemote() { + void testGetMergeRemote() { assertEquals(expectedMergeRemote, options.getMergeRemote()); } @Test - public void testGetMergeTarget() { + void testGetMergeTarget() { assertEquals(expectedMergeTarget, options.getMergeTarget()); } @Test - public void testGetRef() { + void testGetRef() { assertEquals(expectedMergeRemote + "/" + expectedMergeTarget, options.getRef()); } @Test - public void testGetMergeStrategy() { + void testGetMergeStrategy() { assertEquals(expectedMergeStrategy == null ? MergeCommand.Strategy.DEFAULT : expectedMergeStrategy, options.getMergeStrategy()); } @Test - public void testGetFastForwardMode() { + void testGetFastForwardMode() { assertEquals(expectedFastForwardMode == null ? MergeCommand.GitPluginFastForwardMode.FF : expectedFastForwardMode, options.getFastForwardMode()); } @Test - public void testToString() { + void testToString() { final String expected = "UserMergeOptions{" + "mergeRemote='" + expectedMergeRemote + "', " + "mergeTarget='" + expectedMergeTarget + "', " @@ -125,7 +134,7 @@ public void testToString() { } @Test - public void testEqualsSymmetric() { + void testEqualsSymmetric() { UserMergeOptions expected = new UserMergeOptions( this.expectedMergeRemote, this.expectedMergeTarget, @@ -136,7 +145,7 @@ public void testEqualsSymmetric() { } @Test - public void testEqualsReflexive() { + void testEqualsReflexive() { UserMergeOptions expected = new UserMergeOptions( this.expectedMergeRemote, this.expectedMergeTarget, @@ -148,7 +157,7 @@ public void testEqualsReflexive() { } @Test - public void testEqualsTransitive() { + void testEqualsTransitive() { UserMergeOptions expected = new UserMergeOptions( this.expectedMergeRemote, this.expectedMergeTarget, @@ -165,7 +174,7 @@ public void testEqualsTransitive() { } @Test - public void testEqualsDeprecatedConstructor() { + void testEqualsDeprecatedConstructor() { if (this.expectedFastForwardMode == MergeCommand.GitPluginFastForwardMode.FF) { assertEquals(options, deprecatedOptions); } else { @@ -174,7 +183,7 @@ public void testEqualsDeprecatedConstructor() { } @Test - public void testNotEquals() { + void testNotEquals() { UserMergeOptions notExpected1 = new UserMergeOptions( "x" + this.expectedMergeRemote, this.expectedMergeTarget, @@ -187,11 +196,11 @@ public void testNotEquals() { this.expectedMergeStrategy == null ? null : this.expectedMergeStrategy.toString(), this.expectedFastForwardMode); assertNotEquals(notExpected2, options); - assertNotEquals(options, "A different data type"); + assertNotEquals("A different data type", options); } @Test - public void testHashCode() { + void testHashCode() { UserMergeOptions expected = new UserMergeOptions( this.expectedMergeRemote, this.expectedMergeTarget, @@ -202,17 +211,18 @@ public void testHashCode() { } @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(UserMergeOptions.class) .usingGetClass() .suppress(Warning.NONFINAL_FIELDS) .verify(); } + // Testing deprecated method instantiate @Issue({"JENKINS-51638", "JENKINS-34070"}) @Test - @Deprecated // Testing deprecated method instantiate - public void mergeStrategyCase() throws Exception { + @Deprecated + void mergeStrategyCase() throws Exception { Map args = new HashMap<>(); if (expectedMergeTarget != null) { args.put("mergeTarget", expectedMergeTarget); diff --git a/src/test/java/hudson/plugins/git/UserRemoteConfigRefSpecTest.java b/src/test/java/hudson/plugins/git/UserRemoteConfigRefSpecTest.java index d96eb41ef1..4ee4adf364 100644 --- a/src/test/java/hudson/plugins/git/UserRemoteConfigRefSpecTest.java +++ b/src/test/java/hudson/plugins/git/UserRemoteConfigRefSpecTest.java @@ -1,20 +1,20 @@ package hudson.plugins.git; import hudson.util.FormValidation; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class UserRemoteConfigRefSpecTest { +class UserRemoteConfigRefSpecTest { @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecSuccessWithoutWildcards(){ + void testdoCheckRefspecSuccessWithoutWildcards(){ String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); @@ -31,7 +31,7 @@ public void testdoCheckRefspecSuccessWithoutWildcards(){ @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecSuccessWithMatchedWildCards(){ + void testdoCheckRefspecSuccessWithMatchedWildCards(){ String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); @@ -46,7 +46,7 @@ public void testdoCheckRefspecSuccessWithMatchedWildCards(){ @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecFailureWithUnMatchedWildCards(){ + void testdoCheckRefspecFailureWithUnMatchedWildCards(){ String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); @@ -62,7 +62,7 @@ public void testdoCheckRefspecFailureWithUnMatchedWildCards(){ @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecSuccessWithEmptyString(){ + void testdoCheckRefspecSuccessWithEmptyString(){ String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); @@ -77,7 +77,7 @@ public void testdoCheckRefspecSuccessWithEmptyString(){ @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecSuccessWithPartialGlobs(){ + void testdoCheckRefspecSuccessWithPartialGlobs(){ String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); @@ -91,7 +91,7 @@ public void testdoCheckRefspecSuccessWithPartialGlobs(){ @Issue("JENKINS-57660") @Test - public void testdoCheckRefspecSuccessWithEnvironmentVariable(){ + void testdoCheckRefspecSuccessWithEnvironmentVariable(){ String url = "git://git.example.com/repository-that-does-not-exist"; String name = "origin"; List refSpec = new ArrayList<>(); diff --git a/src/test/java/hudson/plugins/git/UserRemoteConfigTest.java b/src/test/java/hudson/plugins/git/UserRemoteConfigTest.java index a756690dbc..c0ee512e69 100644 --- a/src/test/java/hudson/plugins/git/UserRemoteConfigTest.java +++ b/src/test/java/hudson/plugins/git/UserRemoteConfigTest.java @@ -14,21 +14,28 @@ import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import jenkins.model.Jenkins; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Rule; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +@WithJenkins +class UserRemoteConfigTest { -public class UserRemoteConfigTest { + private JenkinsRule r; - @Rule - public JenkinsRule r = new JenkinsRule(); + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } @Issue("JENKINS-38048") @Test - public void credentialsDropdown() throws Exception { + void credentialsDropdown() throws Exception { SystemCredentialsProvider.getInstance().getCredentials().add(new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "mycreds", null, "jenkins", "s3cr3t-that-needs-to-be-long")); SystemCredentialsProvider.getInstance().save(); FreeStyleProject p1 = r.createFreeStyleProject("p1"); @@ -57,8 +64,8 @@ private void assertCredentials(@CheckForNull final Item project, @CheckForNull f actual.add(option.value); } }); - assertEquals("expected completions on " + project + " as " + user + " starting with " + currentCredentialsId, - new TreeSet<>(Arrays.asList(expectedCredentialsIds)), actual); + assertEquals(new TreeSet<>(Arrays.asList(expectedCredentialsIds)), + actual, "expected completions on " + project + " as " + user + " starting with " + currentCredentialsId); } } diff --git a/src/test/java/hudson/plugins/git/browser/AssemblaWebDoCheckURLTest.java b/src/test/java/hudson/plugins/git/browser/AssemblaWebDoCheckURLTest.java index 02eab758e8..f68a05d2f8 100644 --- a/src/test/java/hudson/plugins/git/browser/AssemblaWebDoCheckURLTest.java +++ b/src/test/java/hudson/plugins/git/browser/AssemblaWebDoCheckURLTest.java @@ -2,43 +2,49 @@ import hudson.model.FreeStyleProject; import hudson.util.FormValidation; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -public class AssemblaWebDoCheckURLTest { +@WithJenkins +class AssemblaWebDoCheckURLTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; private static int counter = 0; private FreeStyleProject project; private AssemblaWeb.AssemblaWebDescriptor assemblaWebDescriptor; - @Before - public void setProject() throws Exception { + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; + } + + @BeforeEach + void beforeEach() throws Exception { project = r.createFreeStyleProject("assembla-project-" + counter++); assemblaWebDescriptor = new AssemblaWeb.AssemblaWebDescriptor(); } @Test - public void testInitialChecksOnRepoUrlEmpty() throws Exception { + void testInitialChecksOnRepoUrlEmpty() throws Exception { String url = ""; assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url), is(FormValidation.ok())); } @Test - public void testInitialChecksOnRepoUrlWithVariable() throws Exception { + void testInitialChecksOnRepoUrlWithVariable() throws Exception { String url = "https://www.assembla.com/spaces/$"; assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url), is(FormValidation.ok())); } @Test - public void testDomainLevelChecksOnRepoUrl() throws Exception { + void testDomainLevelChecksOnRepoUrl() throws Exception { // Invalid URL, missing '/' character - Earlier it would open connection for such mistakes but now check resolves it beforehand. String url = "https:/assembla.com"; assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), @@ -46,14 +52,14 @@ public void testDomainLevelChecksOnRepoUrl() throws Exception { } @Test - public void testDomainLevelChecksOnRepoUrlInvalidURL() throws Exception { + void testDomainLevelChecksOnRepoUrlInvalidURL() throws Exception { // Invalid URL, missing ':' character - Earlier it would open connection for such mistakes but now check resolves it beforehand. String url = "http//assmebla"; assertThat(assemblaWebDescriptor.doCheckRepoUrl(project, url).getLocalizedMessage(), is("Invalid URL")); } @Test - public void testPathLevelChecksOnRepoUrlInvalidPathSyntax() throws Exception { + void testPathLevelChecksOnRepoUrlInvalidPathSyntax() throws Exception { // Invalid hostname in URL String hostname = "assembla.comspaces"; String url = "https://" + hostname + "/git-plugin/git/source"; @@ -61,7 +67,7 @@ public void testPathLevelChecksOnRepoUrlInvalidPathSyntax() throws Exception { } @Test - public void testPathLevelChecksOnRepoUrlSupersetOfAssembla() throws Exception { + void testPathLevelChecksOnRepoUrlSupersetOfAssembla() throws Exception { java.util.Random random = new java.util.Random(); String [] urls = { "http://assemblage.com/", @@ -78,7 +84,7 @@ public void testPathLevelChecksOnRepoUrlSupersetOfAssembla() throws Exception { } @Test - public void testDomainLevelChecksOnRepoUrlAllowDNSLocalHostnamesLocalNet() throws Exception { + void testDomainLevelChecksOnRepoUrlAllowDNSLocalHostnamesLocalNet() throws Exception { String hostname = "assembla.example.localnet"; String url = "https://" + hostname + "/space/git-plugin/git/source"; FormValidation validation = assemblaWebDescriptor.doCheckRepoUrl(project, url); @@ -87,7 +93,7 @@ public void testDomainLevelChecksOnRepoUrlAllowDNSLocalHostnamesLocalNet() throw } @Test - public void testDomainLevelChecksOnRepoUrlAllowDNSLocalHostnamesHome() throws Exception { + void testDomainLevelChecksOnRepoUrlAllowDNSLocalHostnamesHome() throws Exception { String hostname = "assembla.example.home"; String url = "https://" + hostname + "/space/git-plugin/git/source"; FormValidation validation = assemblaWebDescriptor.doCheckRepoUrl(project, url); @@ -96,7 +102,7 @@ public void testDomainLevelChecksOnRepoUrlAllowDNSLocalHostnamesHome() throws Ex } @Test - public void testDomainLevelChecksOnRepoUrlCorpDomainMustBeValid() throws Exception { + void testDomainLevelChecksOnRepoUrlCorpDomainMustBeValid() throws Exception { String hostname = "assembla.myorg.corp"; String url = "https://" + hostname + "/space/git-plugin/git/source"; FormValidation validation = assemblaWebDescriptor.doCheckRepoUrl(project, url); diff --git a/src/test/java/hudson/plugins/git/browser/AssemblaWebTest.java b/src/test/java/hudson/plugins/git/browser/AssemblaWebTest.java index dcec85f797..2bdfc20780 100644 --- a/src/test/java/hudson/plugins/git/browser/AssemblaWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/AssemblaWebTest.java @@ -2,33 +2,36 @@ import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; +import org.junit.jupiter.api.Test; + import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -public class AssemblaWebTest { +@ParameterizedClass(name = "{0}") +@MethodSource("permuteAuthorName") +class AssemblaWebTest { private final String repoUrl = "http://assembla.example.com/"; private final boolean useAuthorName; private final GitChangeSetSample sample; - public AssemblaWebTest(String useAuthorName) { - this.useAuthorName = Boolean.valueOf(useAuthorName); + public AssemblaWebTest(boolean useAuthorName) { + this.useAuthorName = useAuthorName; sample = new GitChangeSetSample(this.useAuthorName); } - @Parameterized.Parameters(name = "{0}") - public static Collection permuteAuthorName() { + static Collection permuteAuthorName() { List values = new ArrayList<>(); - String[] allowed = {"true", "false"}; - for (String authorName : allowed) { + boolean[] allowed = { true, false}; + for (boolean authorName : allowed) { Object[] combination = {authorName}; values.add(combination); } @@ -36,25 +39,25 @@ public static Collection permuteAuthorName() { } @Test - public void testGetChangeSetLink() throws Exception { + void testGetChangeSetLink() throws Exception { URL result = (new AssemblaWeb(repoUrl)).getChangeSetLink(sample.changeSet); assertEquals(new URL(repoUrl + "commits/" + sample.id), result); } @Test - public void testGetDiffLink() throws Exception { + void testGetDiffLink() throws Exception { AssemblaWeb assemblaWeb = new AssemblaWeb(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL diffLink = assemblaWeb.getDiffLink(path); EditType editType = path.getEditType(); URL expectedDiffLink = new URL(repoUrl + "commits/" + sample.id); String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedDiffLink, diffLink); + assertEquals(expectedDiffLink, diffLink, msg); } } @Test - public void testGetFileLink() throws Exception { + void testGetFileLink() throws Exception { AssemblaWeb assemblaWeb = new AssemblaWeb(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL fileLink = assemblaWeb.getFileLink(path); @@ -68,7 +71,7 @@ public void testGetFileLink() throws Exception { fail("Unexpected edit type " + editType.getName()); } String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedFileLink, fileLink); + assertEquals(expectedFileLink, fileLink, msg); } } diff --git a/src/test/java/hudson/plugins/git/browser/BitbucketServerTest.java b/src/test/java/hudson/plugins/git/browser/BitbucketServerTest.java index bbfad4818e..dc6d84ba2f 100644 --- a/src/test/java/hudson/plugins/git/browser/BitbucketServerTest.java +++ b/src/test/java/hudson/plugins/git/browser/BitbucketServerTest.java @@ -9,6 +9,8 @@ import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -19,34 +21,34 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; /** */ -public class BitbucketServerTest { +class BitbucketServerTest { private static final String BITBUCKET_URL = "http://bitbucket-server:7990/USER/REPO"; private final BitbucketServer bitbucketServer = new BitbucketServer(BITBUCKET_URL); @Test - public void testGetUrl() throws IOException { - assertEquals(String.valueOf(bitbucketServer.getUrl()), BITBUCKET_URL + "/"); + void testGetUrl() throws IOException { + assertEquals(BITBUCKET_URL + "/", String.valueOf(bitbucketServer.getUrl())); } @Test - public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new BitbucketServer(BITBUCKET_URL + "/").getUrl()), BITBUCKET_URL + "/"); + void testGetUrlForRepoWithTrailingSlash() throws IOException { + assertEquals(BITBUCKET_URL + "/", String.valueOf(new BitbucketServer(BITBUCKET_URL + "/").getUrl())); } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = bitbucketServer.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals(BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final String path1Str = "src/main/java/hudson/plugins/git/browser/GithubWeb.java"; final Path path1 = pathMap.get(path1Str); @@ -58,11 +60,11 @@ public void testGetDiffLinkPath() throws Exception { assertEquals(BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#" + path2Str, bitbucketServer.getDiffLink(path2).toString()); final String path3Str = "src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"; final Path path3 = pathMap.get(path3Str); - assertNull("Do not return a diff link for added files.", bitbucketServer.getDiffLink(path3)); + assertNull(bitbucketServer.getDiffLink(path3), "Do not return a diff link for added files."); } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = bitbucketServer.getFileLink(path); @@ -70,7 +72,7 @@ public void testGetFileLinkPath() throws Exception { } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = bitbucketServer.getFileLink(path); diff --git a/src/test/java/hudson/plugins/git/browser/BitbucketWebTest.java b/src/test/java/hudson/plugins/git/browser/BitbucketWebTest.java index 130924f9b1..42880b6a11 100644 --- a/src/test/java/hudson/plugins/git/browser/BitbucketWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/BitbucketWebTest.java @@ -9,6 +9,8 @@ import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -19,35 +21,35 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author mattsemar */ -public class BitbucketWebTest { +class BitbucketWebTest { private static final String BITBUCKET_URL = "http://bitbucket.org/USER/REPO"; private final BitbucketWeb bitbucketWeb = new BitbucketWeb(BITBUCKET_URL); @Test - public void testGetUrl() throws IOException { - assertEquals(String.valueOf(bitbucketWeb.getUrl()), BITBUCKET_URL + "/"); + void testGetUrl() throws IOException { + assertEquals(BITBUCKET_URL + "/", String.valueOf(bitbucketWeb.getUrl())); } @Test - public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new BitbucketWeb(BITBUCKET_URL + "/").getUrl()), BITBUCKET_URL + "/"); + void testGetUrlForRepoWithTrailingSlash() throws IOException { + assertEquals(BITBUCKET_URL + "/", String.valueOf(new BitbucketWeb(BITBUCKET_URL + "/").getUrl())); } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = bitbucketWeb.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals(BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final String path1Str = "src/main/java/hudson/plugins/git/browser/GithubWeb.java"; final Path path1 = pathMap.get(path1Str); @@ -59,11 +61,11 @@ public void testGetDiffLinkPath() throws Exception { assertEquals(BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#chg-" + path2Str, bitbucketWeb.getDiffLink(path2).toString()); final String path3Str = "src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"; final Path path3 = pathMap.get(path3Str); - assertNull("Do not return a diff link for added files.", bitbucketWeb.getDiffLink(path3)); + assertNull(bitbucketWeb.getDiffLink(path3), "Do not return a diff link for added files."); } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = bitbucketWeb.getFileLink(path); @@ -71,7 +73,7 @@ public void testGetFileLinkPath() throws Exception { } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = bitbucketWeb.getFileLink(path); diff --git a/src/test/java/hudson/plugins/git/browser/CGitTest.java b/src/test/java/hudson/plugins/git/browser/CGitTest.java index 3469f6d91f..8a4ab5d2b4 100644 --- a/src/test/java/hudson/plugins/git/browser/CGitTest.java +++ b/src/test/java/hudson/plugins/git/browser/CGitTest.java @@ -2,33 +2,36 @@ import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; +import org.junit.jupiter.api.Test; + import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -public class CGitTest { +@ParameterizedClass(name = "{0}") +@MethodSource("permuteAuthorName") +class CGitTest { private final String repoUrl = "http://cgit.example.com/"; private final boolean useAuthorName; private final GitChangeSetSample sample; - public CGitTest(String useAuthorName) { - this.useAuthorName = Boolean.valueOf(useAuthorName); + public CGitTest(boolean useAuthorName) { + this.useAuthorName = useAuthorName; sample = new GitChangeSetSample(this.useAuthorName); } - @Parameterized.Parameters(name = "{0}") - public static Collection permuteAuthorName() { + static Collection permuteAuthorName() { List values = new ArrayList<>(); - String[] allowed = {"true", "false"}; - for (String authorName : allowed) { + boolean[] allowed = {true, false}; + for (boolean authorName : allowed) { Object[] combination = {authorName}; values.add(combination); } @@ -36,13 +39,13 @@ public static Collection permuteAuthorName() { } @Test - public void testGetChangeSetLink() throws Exception { + void testGetChangeSetLink() throws Exception { URL result = (new CGit(repoUrl)).getChangeSetLink(sample.changeSet); assertEquals(new URL(repoUrl + "commit/?id=" + sample.id), result); } @Test - public void testGetDiffLink() throws Exception { + void testGetDiffLink() throws Exception { CGit cgit = new CGit(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL diffLink = cgit.getDiffLink(path); @@ -57,12 +60,12 @@ public void testGetDiffLink() throws Exception { fail("Unexpected edit type " + editType.getName()); } String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedDiffLink, diffLink); + assertEquals(expectedDiffLink, diffLink, msg); } } @Test - public void testGetFileLink() throws Exception { + void testGetFileLink() throws Exception { CGit cgit = new CGit(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL fileLink = cgit.getFileLink(path); @@ -76,7 +79,7 @@ public void testGetFileLink() throws Exception { fail("Unexpected edit type " + editType.getName()); } String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedFileLink, fileLink); + assertEquals(expectedFileLink, fileLink, msg); } } diff --git a/src/test/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowserTest.java b/src/test/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowserTest.java index 3d439a2eff..1136f2128d 100644 --- a/src/test/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/FisheyeGitRepositoryBrowserTest.java @@ -2,17 +2,21 @@ import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; +import org.junit.jupiter.api.Test; + import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -public class FisheyeGitRepositoryBrowserTest { +@ParameterizedClass(name = "{0}-{1}") +@MethodSource("permuteAuthorNameAndRepoUrl") +class FisheyeGitRepositoryBrowserTest { private static final String projectName = "fisheyeProjectName"; @@ -21,20 +25,19 @@ public class FisheyeGitRepositoryBrowserTest { private final boolean useAuthorName; private final GitChangeSetSample sample; - public FisheyeGitRepositoryBrowserTest(String useAuthorName, String repoUrl) { - this.useAuthorName = Boolean.valueOf(useAuthorName); + public FisheyeGitRepositoryBrowserTest(boolean useAuthorName, String repoUrl) { + this.useAuthorName = useAuthorName; this.repoUrl = repoUrl; this.repoUrlNoTrailingSlash = this.repoUrl.endsWith("/") ? repoUrl.substring(0, repoUrl.length() - 1) : repoUrl; sample = new GitChangeSetSample(this.useAuthorName); } - @Parameterized.Parameters(name = "{0}-{1}") - public static Collection permuteAuthorNameAndRepoUrl() { + static Collection permuteAuthorNameAndRepoUrl() { List values = new ArrayList<>(); String fisheyeUrl = "http://fisheye.example.com/site/browse/" + projectName; String[] allowedUrls = {fisheyeUrl, fisheyeUrl + "/"}; - String[] allowed = {"true", "false"}; - for (String authorName : allowed) { + boolean[] allowed = {true, false}; + for (boolean authorName : allowed) { for (String repoUrl : allowedUrls) { Object[] combination = {authorName, repoUrl}; values.add(combination); @@ -44,13 +47,13 @@ public static Collection permuteAuthorNameAndRepoUrl() { } @Test - public void testGetChangeSetLink() throws Exception { + void testGetChangeSetLink() throws Exception { URL result = (new FisheyeGitRepositoryBrowser(repoUrl)).getChangeSetLink(sample.changeSet); assertEquals(new URL(repoUrlNoTrailingSlash.replace("browse", "changelog") + "?cs=" + sample.id), result); } @Test - public void testGetDiffLink() throws Exception { + void testGetDiffLink() throws Exception { FisheyeGitRepositoryBrowser fisheye = new FisheyeGitRepositoryBrowser(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL diffLink = fisheye.getDiffLink(path); @@ -61,12 +64,12 @@ public void testGetDiffLink() throws Exception { expectedDiffLink = null; } String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedDiffLink, diffLink); + assertEquals(expectedDiffLink, diffLink, msg); } } @Test - public void testGetFileLink() throws Exception { + void testGetFileLink() throws Exception { FisheyeGitRepositoryBrowser fisheye = new FisheyeGitRepositoryBrowser(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL fileLink = fisheye.getFileLink(path); @@ -81,7 +84,7 @@ public void testGetFileLink() throws Exception { fail("Unexpected edit type " + editType.getName()); } String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedFileLink, fileLink); + assertEquals(expectedFileLink, fileLink, msg); } } } diff --git a/src/test/java/hudson/plugins/git/browser/GitBlitRepositoryBrowserTest.java b/src/test/java/hudson/plugins/git/browser/GitBlitRepositoryBrowserTest.java index f61278189d..7260db0b93 100644 --- a/src/test/java/hudson/plugins/git/browser/GitBlitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitBlitRepositoryBrowserTest.java @@ -2,19 +2,22 @@ import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; +import org.junit.jupiter.api.Test; + import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -public class GitBlitRepositoryBrowserTest { +@ParameterizedClass(name = "{0}") +@MethodSource("permuteAuthorName") +class GitBlitRepositoryBrowserTest { private final String repoUrl = "http://gitblit.example.com/"; @@ -22,16 +25,15 @@ public class GitBlitRepositoryBrowserTest { private final GitChangeSetSample sample; private final String projectName = "gitBlitProjectName"; - public GitBlitRepositoryBrowserTest(String useAuthorName) { - this.useAuthorName = Boolean.valueOf(useAuthorName); + public GitBlitRepositoryBrowserTest(boolean useAuthorName) { + this.useAuthorName = useAuthorName; sample = new GitChangeSetSample(this.useAuthorName); } - @Parameterized.Parameters(name = "{0}") - public static Collection permuteAuthorName() { + static Collection permuteAuthorName() { List values = new ArrayList<>(); - String[] allowed = {"true", "false"}; - for (String authorName : allowed) { + boolean[] allowed = {true, false}; + for (boolean authorName : allowed) { Object[] combination = {authorName}; values.add(combination); } @@ -39,26 +41,26 @@ public static Collection permuteAuthorName() { } @Test - public void testGetChangeSetLink() throws Exception { + void testGetChangeSetLink() throws Exception { URL result = (new GitBlitRepositoryBrowser(repoUrl, projectName)).getChangeSetLink(sample.changeSet); assertEquals(new URL(repoUrl + "commit?r=" + projectName + "&h=" + sample.id), result); } @Test - public void testGetDiffLink() throws Exception { + void testGetDiffLink() throws Exception { GitBlitRepositoryBrowser gitblit = new GitBlitRepositoryBrowser(repoUrl, projectName); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { EditType editType = path.getEditType(); - assertTrue("Unexpected edit type " + editType.getName(), editType == EditType.ADD || editType == EditType.EDIT || editType == EditType.DELETE); + assertTrue(editType == EditType.ADD || editType == EditType.EDIT || editType == EditType.DELETE, "Unexpected edit type " + editType.getName()); URL diffLink = gitblit.getDiffLink(path); URL expectedDiffLink = new URL(repoUrl + "blobdiff?r=" + projectName + "&h=" + sample.id + "&hb=" + sample.parent); String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedDiffLink, diffLink); + assertEquals(expectedDiffLink, diffLink, msg); } } @Test - public void testGetFileLink() throws Exception { + void testGetFileLink() throws Exception { GitBlitRepositoryBrowser gitblit = new GitBlitRepositoryBrowser(repoUrl, projectName); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL fileLink = gitblit.getFileLink(path); @@ -72,12 +74,12 @@ public void testGetFileLink() throws Exception { fail("Unexpected edit type " + editType.getName()); } String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedFileLink, fileLink); + assertEquals(expectedFileLink, fileLink, msg); } } @Test - public void testGetProjectName() { + void testGetProjectName() { GitBlitRepositoryBrowser gitblit = new GitBlitRepositoryBrowser(repoUrl, projectName); assertEquals(projectName, gitblit.getProjectName()); } diff --git a/src/test/java/hudson/plugins/git/browser/GitLabTest.java b/src/test/java/hudson/plugins/git/browser/GitLabTest.java index f5880e736d..44d91b12fb 100644 --- a/src/test/java/hudson/plugins/git/browser/GitLabTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitLabTest.java @@ -5,6 +5,8 @@ import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -14,11 +16,11 @@ import java.util.List; import java.util.Random; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; @Deprecated -public class GitLabTest { +class GitLabTest { private static final String GITLAB_URL = "https://SERVER/USER/REPO/"; private final GitLab gitlab29 = new GitLab(GITLAB_URL, "2.9"); @@ -40,7 +42,7 @@ public class GitLabTest { private final String fileName = "src/main/java/hudson/plugins/git/browser/GithubWeb.java"; @Test - public void testGetVersion() { + void testGetVersion() { assertEquals("2.9", gitlab29.getVersion()); assertEquals("4.2", gitlab42.getVersion()); assertEquals("5.0", gitlab50.getVersion()); @@ -54,7 +56,7 @@ public void testGetVersion() { } @Test - public void testGetVersionDouble() { + void testGetVersionDouble() { assertEquals(2.9, gitlab29.getVersionDouble(), .001); assertEquals(4.2, gitlab42.getVersionDouble(), .001); assertEquals(5.0, gitlab50.getVersionDouble(), .001); @@ -68,7 +70,7 @@ public void testGetVersionDouble() { } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final GitChangeSet changeSet = createChangeSet("rawchangelog"); final String expectedURL = GITLAB_URL + "commit/" + SHA1; assertEquals(expectedURL.replace("commit/", "commits/"), gitlab29.getChangeSetLink(changeSet).toString()); @@ -85,7 +87,7 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path modified1 = pathMap.get(fileName); final String expectedPre30 = GITLAB_URL + "commits/" + SHA1 + "#" + fileName; @@ -108,7 +110,7 @@ public void testGetDiffLinkPath() throws Exception { } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get(fileName); final String expectedURL = GITLAB_URL + "blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/" + fileName; @@ -128,7 +130,7 @@ public void testGetFileLinkPath() throws Exception { } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final String fileName = "bar"; final Path path = pathMap.get(fileName); diff --git a/src/test/java/hudson/plugins/git/browser/GitLabWorkflowTest.java b/src/test/java/hudson/plugins/git/browser/GitLabWorkflowTest.java index 3f94625476..96de4a74d3 100644 --- a/src/test/java/hudson/plugins/git/browser/GitLabWorkflowTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitLabWorkflowTest.java @@ -1,22 +1,30 @@ package hudson.plugins.git.browser; import jenkins.plugins.git.GitSampleRepoRule; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class GitLabWorkflowTest { +@WithJenkins +@WithGitSampleRepo +class GitLabWorkflowTest { - @Rule - public JenkinsRule r = new JenkinsRule(); - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + private JenkinsRule r; + private GitSampleRepoRule sampleRepo; + + @BeforeEach + void beforeEach(JenkinsRule rule, GitSampleRepoRule repo) { + r = rule; + sampleRepo = repo; + } @Test - public void checkoutWithVersion() throws Exception { + void checkoutWithVersion() throws Exception { sampleRepo.init(); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( @@ -34,7 +42,7 @@ public void checkoutWithVersion() throws Exception { } @Test - public void checkoutWithoutVersion() throws Exception { + void checkoutWithoutVersion() throws Exception { sampleRepo.init(); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( diff --git a/src/test/java/hudson/plugins/git/browser/GitListTest.java b/src/test/java/hudson/plugins/git/browser/GitListTest.java index 18af537757..19f8186895 100644 --- a/src/test/java/hudson/plugins/git/browser/GitListTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitListTest.java @@ -9,6 +9,8 @@ import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -20,47 +22,47 @@ import java.util.List; import java.util.Random; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author mirko * @author fauxpark */ -public class GitListTest { +class GitListTest { private static final String GITLIST_URL = "http://gitlist.org/REPO"; private final GitList gitlist = new GitList(GITLIST_URL); @Test - public void testGetUrl() throws IOException { - assertEquals(String.valueOf(gitlist.getUrl()), GITLIST_URL + "/"); + void testGetUrl() throws IOException { + assertEquals(GITLIST_URL + "/", String.valueOf(gitlist.getUrl())); } @Test - public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new GitList(GITLIST_URL + "/").getUrl()), GITLIST_URL + "/"); + void testGetUrlForRepoWithTrailingSlash() throws IOException { + assertEquals(GITLIST_URL + "/", String.valueOf(new GitList(GITLIST_URL + "/").getUrl())); } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = gitlist.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals(GITLIST_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); assertEquals(GITLIST_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#1", gitlist.getDiffLink(path1).toString()); final Path path2 = pathMap.get("src/test/java/hudson/plugins/git/browser/GithubWebTest.java"); assertEquals(GITLIST_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#2", gitlist.getDiffLink(path2).toString()); final Path path3 = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); - assertNull("Do not return a diff link for added files.", gitlist.getDiffLink(path3)); + assertNull(gitlist.getDiffLink(path3), "Do not return a diff link for added files."); } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = gitlist.getFileLink(path); @@ -68,7 +70,7 @@ public void testGetFileLinkPath() throws Exception { } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = gitlist.getFileLink(path); diff --git a/src/test/java/hudson/plugins/git/browser/GitRepositoryBrowserTest.java b/src/test/java/hudson/plugins/git/browser/GitRepositoryBrowserTest.java index 7d33ad2554..6dc1557ee2 100644 --- a/src/test/java/hudson/plugins/git/browser/GitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitRepositoryBrowserTest.java @@ -5,6 +5,7 @@ import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSetUtil; import hudson.plugins.git.GitException; +import org.junit.jupiter.api.BeforeEach; import org.eclipse.jgit.lib.ObjectId; @@ -19,15 +20,17 @@ import java.util.Collection; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -@RunWith(Parameterized.class) -public class GitRepositoryBrowserTest { +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; + +@ParameterizedClass(name = "{0},{1},{2}") +@MethodSource("permuteAuthorNameAndGitImplementationAndObjectId") +class GitRepositoryBrowserTest { private GitRepositoryBrowser browser; private GitChangeSet changeSet; @@ -39,18 +42,17 @@ public class GitRepositoryBrowserTest { private final String gitImplementation; private final ObjectId sha1; - public GitRepositoryBrowserTest(String useAuthorName, String gitImplementation, ObjectId sha1) { - this.useAuthorName = Boolean.valueOf(useAuthorName); + public GitRepositoryBrowserTest(boolean useAuthorName, String gitImplementation, ObjectId sha1) { + this.useAuthorName = useAuthorName; this.gitImplementation = gitImplementation; this.sha1 = sha1; } private static final ObjectId HEAD = getMostRecentCommit(); - @Parameterized.Parameters(name = "{0},{1},{2}") - public static Collection permuteAuthorNameAndGitImplementationAndObjectId() { + static Collection permuteAuthorNameAndGitImplementationAndObjectId() { List values = new ArrayList<>(); - String[] allowed = {"true", "false"}; + boolean[] allowed = {true, false}; String[] implementations = {"git", "jgit"}; ObjectId[] sha1Array = { // Use commits from git-plugin repo history ObjectId.fromString("016407404eeda093385ba2ebe9557068b519b669"), // simple commit @@ -60,7 +62,7 @@ public static Collection permuteAuthorNameAndGitImplementationAndObjectId() { ObjectId.fromString("8e4ef541b8f319fd2019932a6cddfc480fc7ca28"), // Old commit ObjectId.fromString("75ef0cde74e01f16b6da075d67cf88b3503067f5"), // First commit - no files, no parent }; - for (String authorName : allowed) { + for (boolean authorName : allowed) { for (String gitImplementation : implementations) { Object[] headCommitCombination = {authorName, gitImplementation, HEAD}; values.add(headCommitCombination); @@ -91,39 +93,39 @@ private static ObjectId getMostRecentCommit() { return headCommit; } - @Before - public void setUp() throws Exception { + @BeforeEach + void beforeEach() throws Exception { browser = new GitRepositoryBrowserImpl(null); changeSet = GitChangeSetUtil.genChangeSet(sha1, gitImplementation, useAuthorName); paths = changeSet.getPaths(); } @Test - public void testGetRepoUrl() { + void testGetRepoUrl() { assertThat(browser.getRepoUrl(), is(nullValue())); } @Test - public void testGetDiffLink() throws Exception { + void testGetDiffLink() throws Exception { for (GitChangeSet.Path path : paths) { assertThat(browser.getDiffLink(path), is(getURL(path, true))); } } @Test - public void testGetFileLink() throws Exception { + void testGetFileLink() throws Exception { for (GitChangeSet.Path path : paths) { assertThat(browser.getFileLink(path), is(getURL(path, false))); } } @Test - public void testGetNormalizeUrl() { + void testGetNormalizeUrl() { assertThat(browser.getNormalizeUrl(), is(true)); } @Test - public void testGetIndexOfPath() throws Exception { + void testGetIndexOfPath() throws Exception { for (GitChangeSet.Path path : paths) { int location = browser.getIndexOfPath(path); diff --git a/src/test/java/hudson/plugins/git/browser/GitWebTest.java b/src/test/java/hudson/plugins/git/browser/GitWebTest.java index 615868a630..92a620e567 100644 --- a/src/test/java/hudson/plugins/git/browser/GitWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitWebTest.java @@ -5,6 +5,8 @@ import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -16,34 +18,33 @@ import java.util.List; import java.util.Random; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class GitWebTest { +class GitWebTest { private static final String GITWEB_URL = "https://SERVER/gitweb?repo.git"; private final GitWeb gitwebWeb = new GitWeb(GITWEB_URL); @Test - public void testGetUrl() throws IOException { - assertEquals(String.valueOf(gitwebWeb.getUrl()), GITWEB_URL); + void testGetUrl() throws IOException { + assertEquals(GITWEB_URL, String.valueOf(gitwebWeb.getUrl())); } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = gitwebWeb.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals(GITWEB_URL + "&a=commit&h=396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path modified1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); assertEquals(GITWEB_URL + "&a=blobdiff&f=src/main/java/hudson/plugins/git/browser/GithubWeb.java&fp=src/main/java/hudson/plugins/git/browser/GithubWeb.java&h=3f28ad75f5ecd5e0ea9659362e2eef18951bd451&hp=2e0756cd853dccac638486d6aab0e74bc2ef4041&hb=396fc230a3db05c427737aa5c2eb7856ba72b05d&hpb=f28f125f4cc3e5f6a32daee6a26f36f7b788b8ff", gitwebWeb.getDiffLink(modified1).toString()); } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = gitwebWeb.getFileLink(path); @@ -51,7 +52,7 @@ public void testGetFileLinkPath() throws Exception { } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = gitwebWeb.getFileLink(path); diff --git a/src/test/java/hudson/plugins/git/browser/GithubWebTest.java b/src/test/java/hudson/plugins/git/browser/GithubWebTest.java index 13b6810e58..3ca02ec139 100644 --- a/src/test/java/hudson/plugins/git/browser/GithubWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/GithubWebTest.java @@ -24,32 +24,35 @@ import java.util.List; import java.util.Random; import jenkins.scm.api.SCMHead; +import org.junit.jupiter.api.Test; + import org.eclipse.jgit.transport.RefSpec; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.jvnet.hudson.test.Issue; /** * @author mirko */ -public class GithubWebTest { +class GithubWebTest { private static final String GITHUB_URL = "http://github.com/USER/REPO"; private final GithubWeb githubWeb = new GithubWeb(GITHUB_URL); @Test - public void testGetUrl() throws IOException { - assertEquals(String.valueOf(githubWeb.getUrl()), GITHUB_URL + "/"); + void testGetUrl() throws IOException { + assertEquals(GITHUB_URL + "/", String.valueOf(githubWeb.getUrl())); } @Test - public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new GithubWeb(GITHUB_URL + "/").getUrl()), GITHUB_URL + "/"); + void testGetUrlForRepoWithTrailingSlash() throws IOException { + assertEquals(GITHUB_URL + "/", String.valueOf(new GithubWeb(GITHUB_URL + "/").getUrl())); } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = githubWeb.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals(GITHUB_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); @@ -61,18 +64,18 @@ public void testGetChangeSetLinkGitChangeSet() throws Exception { } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); assertEquals(GITHUB_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-0", githubWeb.getDiffLink(path1).toString()); final Path path2 = pathMap.get("src/test/java/hudson/plugins/git/browser/GithubWebTest.java"); assertEquals(GITHUB_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-1", githubWeb.getDiffLink(path2).toString()); final Path path3 = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); - assertNull("Do not return a diff link for added files.", githubWeb.getDiffLink(path3)); + assertNull(githubWeb.getDiffLink(path3), "Do not return a diff link for added files."); } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = githubWeb.getFileLink(path); @@ -81,15 +84,16 @@ public void testGetFileLinkPath() throws Exception { @Issue("JENKINS-42597") @Test - public void testGetFileLinkPathWithEscape() throws Exception { + void testGetFileLinkPathWithEscape() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-escape"); final Path path = pathMap.get("src/test/java/hudson/plugins/git/browser/conf%.txt"); final URL fileLink = githubWeb.getFileLink(path); assertEquals(GITHUB_URL + "/blob/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/test/java/hudson/plugins/git/browser/conf%25.txt", String.valueOf(fileLink)); } + @Issue("JENKINS-42597") @Test - public void testGetFileLinkPathWithWindowsUnescapeChar() throws Exception { + void testGetFileLinkPathWithWindowsUnescapeChar() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-escape"); final Path path = pathMap.get("src/test/java/hudson/plugins/git/browser/conf^%.txt"); final URL fileLink = githubWeb.getFileLink(path); @@ -98,7 +102,7 @@ public void testGetFileLinkPathWithWindowsUnescapeChar() throws Exception { @Issue("JENKINS-42597") @Test - public void testGetFileLinkPathWithDoubleEscape() throws Exception { + void testGetFileLinkPathWithDoubleEscape() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-escape"); final Path path = pathMap.get("src/test/java/hudson/plugins/git/browser/conf%%.txt"); final URL fileLink = githubWeb.getFileLink(path); @@ -107,7 +111,7 @@ public void testGetFileLinkPathWithDoubleEscape() throws Exception { @Issue("JENKINS-42597") @Test - public void testGetFileLinkPathWithWindowsEnvironmentalVariable() throws Exception { + void testGetFileLinkPathWithWindowsEnvironmentalVariable() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-escape"); final Path path = pathMap.get("src/test/java/hudson/plugins/git/browser/conf%abc%.txt"); final URL fileLink = githubWeb.getFileLink(path); @@ -116,7 +120,7 @@ public void testGetFileLinkPathWithWindowsEnvironmentalVariable() throws Excepti @Issue("JENKINS-42597") @Test - public void testGetFileLinkPathWithSpaceInName() throws Exception { + void testGetFileLinkPathWithSpaceInName() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-escape"); final Path path = pathMap.get("src/test/java/hudson/plugins/git/browser/config file.txt"); final URL fileLink = githubWeb.getFileLink(path); @@ -124,7 +128,7 @@ public void testGetFileLinkPathWithSpaceInName() throws Exception { } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = githubWeb.getFileLink(path); @@ -136,13 +140,13 @@ private String repoUrl(String baseUrl, boolean add_git_suffix, boolean add_slash } @Test - public void testGuessBrowser() throws Exception { + void testGuessBrowser() throws Exception { assertGuessURL("https://github.com/kohsuke/msv.git", "https://github.com/kohsuke/msv/"); assertGuessURL("https://github.com/kohsuke/msv/", "https://github.com/kohsuke/msv/"); assertGuessURL("https://github.com/kohsuke/msv", "https://github.com/kohsuke/msv/"); assertGuessURL("git@github.com:kohsuke/msv.git", "https://github.com/kohsuke/msv/"); assertGuessURL("git@git.apache.org:whatever.git", null); - final boolean allowed [] = { Boolean.TRUE, Boolean.FALSE }; + final boolean[] allowed = { Boolean.TRUE, Boolean.FALSE }; for (final boolean add_git_suffix : allowed) { for (final boolean add_slash_suffix : allowed) { assertGuessURL(repoUrl("git@github.com:kohsuke/msv", add_git_suffix, add_slash_suffix), "https://github.com/kohsuke/msv/"); @@ -156,12 +160,12 @@ public void testGuessBrowser() throws Exception { private void assertGuessURL(String repo, String web) throws Exception { RepositoryBrowser guess = new GitSCM(repo).guessBrowser(); String actual = guess instanceof GithubWeb gw ? gw.getRepoUrl() : null; - assertEquals("For repo '" + repo + "':", web, actual); + assertEquals(web, actual, "For repo '" + repo + "':"); } @Issue("JENKINS-33409") @Test - public void guessBrowserSCMSource() throws Exception { + void guessBrowserSCMSource() throws Exception { // like GitSCMSource: assertGuessURL("https://github.com/kohsuke/msv.git", "https://github.com/kohsuke/msv/", "+refs/heads/*:refs/remotes/origin/*"); // like GitHubSCMSource: diff --git a/src/test/java/hudson/plugins/git/browser/GitilesTest.java b/src/test/java/hudson/plugins/git/browser/GitilesTest.java index ba7018164b..b8fa6e1219 100644 --- a/src/test/java/hudson/plugins/git/browser/GitilesTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitilesTest.java @@ -1,33 +1,35 @@ package hudson.plugins.git.browser; import hudson.plugins.git.GitChangeSet; +import org.junit.jupiter.api.Test; + import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -public class GitilesTest { +@ParameterizedClass(name = "{0}") +@MethodSource("permuteAuthorName") +class GitilesTest { private final String repoUrl = "https://gwt.googlesource.com/gwt/"; private final boolean useAuthorName; private final GitChangeSetSample sample; - public GitilesTest(String useAuthorName) { - this.useAuthorName = Boolean.valueOf(useAuthorName); + public GitilesTest(boolean useAuthorName) { + this.useAuthorName = useAuthorName; sample = new GitChangeSetSample(this.useAuthorName); } - @Parameterized.Parameters(name = "{0}") - public static Collection permuteAuthorName() { + static Collection permuteAuthorName() { List values = new ArrayList<>(); - String[] allowed = {"true", "false"}; - for (String authorName : allowed) { + boolean[] allowed = {true, false}; + for (boolean authorName : allowed) { Object[] combination = {authorName}; values.add(combination); } @@ -35,30 +37,30 @@ public static Collection permuteAuthorName() { } @Test - public void testGetChangeSetLink() throws Exception { + void testGetChangeSetLink() throws Exception { URL result = (new Gitiles(repoUrl)).getChangeSetLink(sample.changeSet); assertEquals(new URL(repoUrl + "+/" + sample.id + "%5E%21"), result); } @Test - public void testGetDiffLink() throws Exception { + void testGetDiffLink() throws Exception { Gitiles gitiles = new Gitiles(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL diffLink = gitiles.getDiffLink(path); URL expectedDiffLink = new URL(repoUrl + "+/" + sample.id + "%5E%21"); String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + path.getEditType().getName(); - assertEquals(msg, expectedDiffLink, diffLink); + assertEquals(expectedDiffLink, diffLink, msg); } } @Test - public void testGetFileLink() throws Exception { + void testGetFileLink() throws Exception { Gitiles gitiles = new Gitiles(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL fileLink = gitiles.getFileLink(path); URL expectedFileLink = new URL(repoUrl + "+blame/" + sample.id + "/" + path.getPath()); String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + path.getEditType().getName(); - assertEquals(msg, expectedFileLink, fileLink); + assertEquals(expectedFileLink, fileLink, msg); } } } diff --git a/src/test/java/hudson/plugins/git/browser/GitoriousWebTest.java b/src/test/java/hudson/plugins/git/browser/GitoriousWebTest.java index 09b44e6fab..1ff3f773a1 100644 --- a/src/test/java/hudson/plugins/git/browser/GitoriousWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/GitoriousWebTest.java @@ -5,6 +5,8 @@ import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -16,32 +18,31 @@ import java.util.List; import java.util.Random; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class GitoriousWebTest { +class GitoriousWebTest { private static final String GITORIOUS_URL = "https://SERVER/PROJECT"; private final GitoriousWeb gitoriousWeb = new GitoriousWeb(GITORIOUS_URL); @Test - public void testGetUrl() throws IOException { - assertEquals(String.valueOf(gitoriousWeb.getUrl()), GITORIOUS_URL + "/"); + void testGetUrl() throws IOException { + assertEquals(GITORIOUS_URL + "/", String.valueOf(gitoriousWeb.getUrl())); } @Test - public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new GitoriousWeb(GITORIOUS_URL + "/").getUrl()), GITORIOUS_URL + "/"); + void testGetUrlForRepoWithTrailingSlash() throws IOException { + assertEquals(GITORIOUS_URL + "/", String.valueOf(new GitoriousWeb(GITORIOUS_URL + "/").getUrl())); } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = gitoriousWeb.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals(GITORIOUS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path modified1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); assertEquals(GITORIOUS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d/diffs?diffmode=sidebyside&fragment=1#src/main/java/hudson/plugins/git/browser/GithubWeb.java", gitoriousWeb.getDiffLink(modified1).toString()); @@ -51,7 +52,7 @@ public void testGetDiffLinkPath() throws Exception { } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = gitoriousWeb.getFileLink(path); @@ -59,7 +60,7 @@ public void testGetFileLinkPath() throws Exception { } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = gitoriousWeb.getFileLink(path); diff --git a/src/test/java/hudson/plugins/git/browser/GogsGitTest.java b/src/test/java/hudson/plugins/git/browser/GogsGitTest.java index 81d1806eca..cfcd143dd4 100644 --- a/src/test/java/hudson/plugins/git/browser/GogsGitTest.java +++ b/src/test/java/hudson/plugins/git/browser/GogsGitTest.java @@ -5,6 +5,8 @@ import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -16,46 +18,46 @@ import java.util.List; import java.util.Random; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Norbert Lange (nolange79@gmail.com) */ -public class GogsGitTest { +class GogsGitTest { private static final String GOGS_URL = "http://USER.kilnhg.com/Code/PROJECT/Group/REPO"; private final GogsGit GogsGit = new GogsGit(GOGS_URL); @Test - public void testGetUrl() throws IOException { - assertEquals(String.valueOf(GogsGit.getUrl()), GOGS_URL + "/"); + void testGetUrl() throws IOException { + assertEquals(GOGS_URL + "/", String.valueOf(GogsGit.getUrl())); } @Test - public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new GogsGit(GOGS_URL + "/").getUrl()), GOGS_URL + "/"); + void testGetUrlForRepoWithTrailingSlash() throws IOException { + assertEquals(GOGS_URL + "/", String.valueOf(new GogsGit(GOGS_URL + "/").getUrl())); } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = GogsGit.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals(GOGS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); assertEquals(GOGS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-1", GogsGit.getDiffLink(path1).toString()); final Path path2 = pathMap.get("src/test/java/hudson/plugins/git/browser/GithubWebTest.java"); assertEquals(GOGS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-2", GogsGit.getDiffLink(path2).toString()); final Path path3 = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); - assertNull("Do not return a diff link for added files.", GogsGit.getDiffLink(path3)); + assertNull(GogsGit.getDiffLink(path3), "Do not return a diff link for added files."); } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = GogsGit.getFileLink(path); @@ -63,7 +65,7 @@ public void testGetFileLinkPath() throws Exception { } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = GogsGit.getFileLink(path); diff --git a/src/test/java/hudson/plugins/git/browser/KilnGitTest.java b/src/test/java/hudson/plugins/git/browser/KilnGitTest.java index 61f75c1a5b..24b10e720e 100644 --- a/src/test/java/hudson/plugins/git/browser/KilnGitTest.java +++ b/src/test/java/hudson/plugins/git/browser/KilnGitTest.java @@ -5,6 +5,8 @@ import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -16,46 +18,46 @@ import java.util.List; import java.util.Random; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Chris Klaiber (cklaiber@gmail.com) */ -public class KilnGitTest { +class KilnGitTest { private static final String KILN_URL = "http://USER.kilnhg.com/Code/PROJECT/Group/REPO"; private final KilnGit kilnGit = new KilnGit(KILN_URL); @Test - public void testGetUrl() throws IOException { - assertEquals(String.valueOf(kilnGit.getUrl()), KILN_URL + "/"); + void testGetUrl() throws IOException { + assertEquals(KILN_URL + "/", String.valueOf(kilnGit.getUrl())); } @Test - public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new KilnGit(KILN_URL + "/").getUrl()), KILN_URL + "/"); + void testGetUrlForRepoWithTrailingSlash() throws IOException { + assertEquals(KILN_URL + "/", String.valueOf(new KilnGit(KILN_URL + "/").getUrl())); } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = kilnGit.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals(KILN_URL + "/History/396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); assertEquals(KILN_URL + "/History/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-1", kilnGit.getDiffLink(path1).toString()); final Path path2 = pathMap.get("src/test/java/hudson/plugins/git/browser/GithubWebTest.java"); assertEquals(KILN_URL + "/History/396fc230a3db05c427737aa5c2eb7856ba72b05d#diff-2", kilnGit.getDiffLink(path2).toString()); final Path path3 = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); - assertNull("Do not return a diff link for added files.", kilnGit.getDiffLink(path3)); + assertNull(kilnGit.getDiffLink(path3), "Do not return a diff link for added files."); } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = kilnGit.getFileLink(path); @@ -63,7 +65,7 @@ public void testGetFileLinkPath() throws Exception { } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = kilnGit.getFileLink(path); diff --git a/src/test/java/hudson/plugins/git/browser/PhabricatorTest.java b/src/test/java/hudson/plugins/git/browser/PhabricatorTest.java index 904404e43d..96d89fa0b2 100644 --- a/src/test/java/hudson/plugins/git/browser/PhabricatorTest.java +++ b/src/test/java/hudson/plugins/git/browser/PhabricatorTest.java @@ -1,52 +1,48 @@ package hudson.plugins.git.browser; import hudson.plugins.git.GitChangeSet; +import org.junit.jupiter.api.Test; + import java.io.IOException; import java.net.URL; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class PhabricatorTest { +class PhabricatorTest { private final String repoName = "phabricatorRepo"; private final String repoUrl = "http://phabricator.example.com/"; - private final Phabricator phabricator; - - private final GitChangeSetSample sample; + private final Phabricator phabricator = new Phabricator(repoUrl, repoName); - public PhabricatorTest() { - phabricator = new Phabricator(repoUrl, repoName); - sample = new GitChangeSetSample(true); - } + private final GitChangeSetSample sample = new GitChangeSetSample(true); @Test - public void testGetRepo() throws IOException { + void testGetRepo() throws IOException { assertEquals(repoName, phabricator.getRepo()); } @Test - public void testGetChangeSetLink() throws Exception { + void testGetChangeSetLink() throws Exception { URL result = phabricator.getChangeSetLink(sample.changeSet); assertEquals(new URL(repoUrl + "r" + repoName + sample.id), result); } @Test - public void testGetDiffLink() throws Exception { + void testGetDiffLink() throws Exception { for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL diffLink = phabricator.getDiffLink(path); URL expectedDiffLink = new URL(repoUrl + "diffusion/" + repoName + "/change/master/" + path.getPath() + ";" + sample.id); String msg = "Wrong link for path: " + path.getPath(); - assertEquals(msg, expectedDiffLink, diffLink); + assertEquals(expectedDiffLink, diffLink, msg); } } @Test - public void testGetFileLink() throws Exception { + void testGetFileLink() throws Exception { for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL fileLink = phabricator.getDiffLink(path); URL expectedFileLink = new URL(repoUrl + "diffusion/" + repoName + "/change/master/" + path.getPath() + ";" + sample.id); String msg = "Wrong link for path: " + path.getPath(); - assertEquals(msg, expectedFileLink, fileLink); + assertEquals(expectedFileLink, fileLink, msg); } } diff --git a/src/test/java/hudson/plugins/git/browser/RedmineWebTest.java b/src/test/java/hudson/plugins/git/browser/RedmineWebTest.java index af0fb384de..fdbbd84dc7 100644 --- a/src/test/java/hudson/plugins/git/browser/RedmineWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/RedmineWebTest.java @@ -5,6 +5,8 @@ import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -15,35 +17,34 @@ import java.util.HashMap; import java.util.List; import java.util.Random; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author mfriedenhagen */ -public class RedmineWebTest { +class RedmineWebTest { private static final String REDMINE_URL = "https://SERVER/PATH/projects/PROJECT/repository"; private final RedmineWeb redmineWeb = new RedmineWeb(REDMINE_URL); @Test - public void testGetUrl() throws IOException { - assertEquals(String.valueOf(redmineWeb.getUrl()), REDMINE_URL + "/"); + void testGetUrl() throws IOException { + assertEquals(REDMINE_URL + "/", String.valueOf(redmineWeb.getUrl())); } @Test - public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new RedmineWeb(REDMINE_URL + "/").getUrl()), REDMINE_URL + "/"); + void testGetUrlForRepoWithTrailingSlash() throws IOException { + assertEquals(REDMINE_URL + "/", String.valueOf(new RedmineWeb(REDMINE_URL + "/").getUrl())); } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = redmineWeb.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals(REDMINE_URL + "/diff?rev=396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path modified1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); assertEquals(REDMINE_URL + "/revisions/396fc230a3db05c427737aa5c2eb7856ba72b05d/diff/src/main/java/hudson/plugins/git/browser/GithubWeb.java", redmineWeb.getDiffLink(modified1).toString()); @@ -55,7 +56,7 @@ public void testGetDiffLinkPath() throws Exception { } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = redmineWeb.getFileLink(path); @@ -63,7 +64,7 @@ public void testGetFileLinkPath() throws Exception { } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = redmineWeb.getFileLink(path); diff --git a/src/test/java/hudson/plugins/git/browser/RhodeCodeTest.java b/src/test/java/hudson/plugins/git/browser/RhodeCodeTest.java index f080d4e991..7f10105486 100644 --- a/src/test/java/hudson/plugins/git/browser/RhodeCodeTest.java +++ b/src/test/java/hudson/plugins/git/browser/RhodeCodeTest.java @@ -5,6 +5,8 @@ import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -16,32 +18,31 @@ import java.util.List; import java.util.Random; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class RhodeCodeTest { +class RhodeCodeTest { private static final String RHODECODE_URL = "https://SERVER/r/PROJECT"; private final RhodeCode rhodecode = new RhodeCode(RHODECODE_URL); @Test - public void testGetUrl() throws IOException { - assertEquals(String.valueOf(rhodecode.getUrl()), RHODECODE_URL + "/"); + void testGetUrl() throws IOException { + assertEquals(RHODECODE_URL + "/", String.valueOf(rhodecode.getUrl())); } @Test - public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new RhodeCode(RHODECODE_URL + "/").getUrl()), RHODECODE_URL + "/"); + void testGetUrlForRepoWithTrailingSlash() throws IOException { + assertEquals(RHODECODE_URL + "/", String.valueOf(new RhodeCode(RHODECODE_URL + "/").getUrl())); } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = rhodecode.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals(RHODECODE_URL + "/changeset/396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path modified1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); assertEquals(RHODECODE_URL + "/diff/src/main/java/hudson/plugins/git/browser/GithubWeb.java?diff2=f28f125f4cc3e5f6a32daee6a26f36f7b788b8ff&diff1=396fc230a3db05c427737aa5c2eb7856ba72b05d&diff=diff+to+revision", rhodecode.getDiffLink(modified1).toString()); @@ -51,7 +52,7 @@ public void testGetDiffLinkPath() throws Exception { } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = rhodecode.getFileLink(path); @@ -59,7 +60,7 @@ public void testGetFileLinkPath() throws Exception { } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = rhodecode.getFileLink(path); diff --git a/src/test/java/hudson/plugins/git/browser/StashTest.java b/src/test/java/hudson/plugins/git/browser/StashTest.java index b6398c3f85..ac36c5b84d 100644 --- a/src/test/java/hudson/plugins/git/browser/StashTest.java +++ b/src/test/java/hudson/plugins/git/browser/StashTest.java @@ -2,33 +2,36 @@ import hudson.plugins.git.GitChangeSet; import hudson.scm.EditType; +import org.junit.jupiter.api.Test; + import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -public class StashTest { +@ParameterizedClass(name = "{0}") +@MethodSource("permuteAuthorName") +class StashTest { private final String repoUrl = "http://stash.example.com/"; private final boolean useAuthorName; private final GitChangeSetSample sample; - public StashTest(String useAuthorName) { - this.useAuthorName = Boolean.valueOf(useAuthorName); + public StashTest(boolean useAuthorName) { + this.useAuthorName = useAuthorName; sample = new GitChangeSetSample(this.useAuthorName); } - @Parameterized.Parameters(name = "{0}") - public static Collection permuteAuthorName() { + static Collection permuteAuthorName() { List values = new ArrayList<>(); - String[] allowed = {"true", "false"}; - for (String authorName : allowed) { + boolean[] allowed = {true, false}; + for (boolean authorName : allowed) { Object[] combination = {authorName}; values.add(combination); } @@ -36,13 +39,13 @@ public static Collection permuteAuthorName() { } @Test - public void testGetChangeSetLink() throws Exception { + void testGetChangeSetLink() throws Exception { URL result = (new Stash(repoUrl)).getChangeSetLink(sample.changeSet); assertEquals(new URL(repoUrl + "commits/" + sample.id), result); } @Test - public void testGetDiffLink() throws Exception { + void testGetDiffLink() throws Exception { Stash stash = new Stash(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL diffLink = stash.getDiffLink(path); @@ -56,12 +59,12 @@ public void testGetDiffLink() throws Exception { fail("Unexpected edit type " + editType.getName()); } String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedDiffLink, diffLink); + assertEquals(expectedDiffLink, diffLink, msg); } } @Test - public void testGetFileLink() throws Exception { + void testGetFileLink() throws Exception { Stash stash = new Stash(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL fileLink = stash.getFileLink(path); @@ -75,7 +78,7 @@ public void testGetFileLink() throws Exception { fail("Unexpected edit type " + editType.getName()); } String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedFileLink, fileLink); + assertEquals(expectedFileLink, fileLink, msg); } } } diff --git a/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserTest.java b/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserTest.java index aba12999f9..db7db56de2 100644 --- a/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserTest.java +++ b/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserTest.java @@ -4,27 +4,28 @@ import hudson.plugins.git.*; import hudson.scm.ChangeLogSet; import hudson.scm.EditType; +import org.junit.jupiter.api.BeforeAll; + import org.jenkinsci.plugins.gitclient.JGitTool; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class TFS2013GitRepositoryBrowserTest { +class TFS2013GitRepositoryBrowserTest { private static final String repoUrl = "http://tfs/tfs/project/_git/repo"; private static final GitChangeSetSample sample = new GitChangeSetSample(false); - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void beforeAll() throws Exception { GitSCM scm = new GitSCM( Collections.singletonList(new UserRemoteConfig(repoUrl, null, null, null)), new ArrayList<>(), @@ -42,50 +43,50 @@ public static void setUp() throws Exception { } @Test - public void testResolveURLFromSCM() throws Exception { + void testResolveURLFromSCM() throws Exception { TFS2013GitRepositoryBrowser browser = new TFS2013GitRepositoryBrowser(""); assertThat(browser.getRepoUrl(sample.changeSet).toString(), is("http://tfs/tfs/project/_git/repo/")); } @Test - public void testResolveURLFromConfig() throws Exception { + void testResolveURLFromConfig() throws Exception { TFS2013GitRepositoryBrowser browser = new TFS2013GitRepositoryBrowser("http://url/repo"); assertThat(browser.getRepoUrl(sample.changeSet).toString(), is("http://url/repo/")); } @Test - public void testResolveURLFromConfigWithTrailingSlash() throws Exception { + void testResolveURLFromConfigWithTrailingSlash() throws Exception { TFS2013GitRepositoryBrowser browser = new TFS2013GitRepositoryBrowser("http://url/repo/"); assertThat(browser.getRepoUrl(sample.changeSet).toString(), is("http://url/repo/")); } @Test - public void testGetChangeSetLink() throws Exception { + void testGetChangeSetLink() throws Exception { URL result = new TFS2013GitRepositoryBrowser(repoUrl).getChangeSetLink(sample.changeSet); assertThat(result.toString(), is("http://tfs/tfs/project/_git/repo/commit/" + sample.id)); } @Test - public void testGetDiffLink() throws Exception { + void testGetDiffLink() throws Exception { TFS2013GitRepositoryBrowser browser = new TFS2013GitRepositoryBrowser(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL diffLink = browser.getDiffLink(path); EditType editType = path.getEditType(); URL expectedDiffLink = new URL("http://tfs/tfs/project/_git/repo/commit/" + sample.id + "#path=" + path.getPath() + "&_a=compare"); String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedDiffLink, diffLink); + assertEquals(expectedDiffLink, diffLink, msg); } } @Test - public void testGetFileLink() throws Exception { + void testGetFileLink() throws Exception { TFS2013GitRepositoryBrowser browser = new TFS2013GitRepositoryBrowser(repoUrl); for (GitChangeSet.Path path : sample.changeSet.getPaths()) { URL fileLink = browser.getFileLink(path); EditType editType = path.getEditType(); URL expectedFileLink = new URL("http://tfs/tfs/project/_git/repo/commit/" + sample.id + "#path=" + path.getPath() + "&_a=history"); String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + editType.getName(); - assertEquals(msg, expectedFileLink, fileLink); + assertEquals(expectedFileLink, fileLink, msg); } } } diff --git a/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java b/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java index 10d6198b78..64edf5c20b 100644 --- a/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java +++ b/src/test/java/hudson/plugins/git/browser/TFS2013GitRepositoryBrowserXSSTest.java @@ -5,24 +5,31 @@ import hudson.plugins.git.GitSCM; import hudson.plugins.git.UserRemoteConfig; import org.jenkinsci.plugins.gitclient.JGitTool; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.atomic.AtomicBoolean; -public class TFS2013GitRepositoryBrowserXSSTest { +import static org.junit.jupiter.api.Assertions.assertFalse; - @Rule - public final JenkinsRule r = new JenkinsRule(); +@WithJenkins +class TFS2013GitRepositoryBrowserXSSTest { + + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } @Test @Issue("SECURITY-1723") - public void testXSS() throws Exception { + void testXSS() throws Exception { // setup scm GitSCM scm = new GitSCM( Collections.singletonList(new UserRemoteConfig("http://tfs/tfs/project/_git/repo", null, null, null)), @@ -38,6 +45,6 @@ public void testXSS() throws Exception { JenkinsRule.WebClient wc = r.createWebClient(); wc.setAlertHandler((page, s) -> xss.set(true)); HtmlPage page = wc.getPage(p, "configure"); - Assert.assertFalse(xss.get()); + assertFalse(xss.get()); } } diff --git a/src/test/java/hudson/plugins/git/browser/ViewGitWebTest.java b/src/test/java/hudson/plugins/git/browser/ViewGitWebTest.java index bdd2ac3335..3a5a9e5085 100644 --- a/src/test/java/hudson/plugins/git/browser/ViewGitWebTest.java +++ b/src/test/java/hudson/plugins/git/browser/ViewGitWebTest.java @@ -5,6 +5,8 @@ import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; @@ -16,64 +18,64 @@ import java.util.List; import java.util.Random; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Paul Nyheim (paul.nyheim@gmail.com) */ -public class ViewGitWebTest { +class ViewGitWebTest { private static final String VIEWGIT_URL = "http://SERVER/viewgit"; private static final String PROJECT_NAME = "PROJECT"; private final ViewGitWeb viewGitWeb = new ViewGitWeb(VIEWGIT_URL, PROJECT_NAME); @Test - public void testGetUrl() throws IOException { - assertEquals(String.valueOf(viewGitWeb.getUrl()), VIEWGIT_URL + "/"); + void testGetUrl() throws IOException { + assertEquals(VIEWGIT_URL + "/", String.valueOf(viewGitWeb.getUrl())); } @Test - public void testGetUrlForRepoWithTrailingSlash() throws IOException { - assertEquals(String.valueOf(new ViewGitWeb(VIEWGIT_URL + "/", PROJECT_NAME).getUrl()), VIEWGIT_URL + "/"); + void testGetUrlForRepoWithTrailingSlash() throws IOException { + assertEquals(VIEWGIT_URL + "/", String.valueOf(new ViewGitWeb(VIEWGIT_URL + "/", PROJECT_NAME).getUrl())); } @Test - public void testGetChangeSetLinkGitChangeSet() throws Exception { + void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = viewGitWeb.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals("http://SERVER/viewgit/?p=PROJECT&a=commit&h=396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); } @Test - public void testGetDiffLinkPath() throws Exception { + void testGetDiffLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); assertEquals(VIEWGIT_URL + "/?p=PROJECT&a=commitdiff&h=396fc230a3db05c427737aa5c2eb7856ba72b05d#src%2Fmain%2Fjava%2Fhudson%2Fplugins%2Fgit%2Fbrowser%2FGithubWeb.java", viewGitWeb.getDiffLink(path1).toString()); final Path path2 = pathMap.get("src/test/java/hudson/plugins/git/browser/GithubWebTest.java"); assertEquals(VIEWGIT_URL + "/?p=PROJECT&a=commitdiff&h=396fc230a3db05c427737aa5c2eb7856ba72b05d#src%2Ftest%2Fjava%2Fhudson%2Fplugins%2Fgit%2Fbrowser%2FGithubWebTest.java", viewGitWeb.getDiffLink(path2).toString()); final Path path3 = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"); - assertNull("Do not return a diff link for added files.", viewGitWeb.getDiffLink(path3)); + assertNull(viewGitWeb.getDiffLink(path3), "Do not return a diff link for added files."); } @Test - public void testGetFileLinkPath() throws Exception { + void testGetFileLinkPath() throws Exception { final HashMap pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = viewGitWeb.getFileLink(path); assertEquals(VIEWGIT_URL + "/?p=PROJECT&a=viewblob&h=2e0756cd853dccac638486d6aab0e74bc2ef4041&f=src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink)); } - + @Test - public void testGetDiffLinkForDeletedFile() throws Exception { + void testGetDiffLinkForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); - assertNull("Do not return a diff link for deleted files.", viewGitWeb.getDiffLink(path)); + assertNull(viewGitWeb.getDiffLink(path), "Do not return a diff link for deleted files."); } @Test - public void testGetFileLinkPathForDeletedFile() throws Exception { + void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = viewGitWeb.getFileLink(path); diff --git a/src/test/java/hudson/plugins/git/browser/casc/GitLabConfiguratorTest.java b/src/test/java/hudson/plugins/git/browser/casc/GitLabConfiguratorTest.java index ca8d3e658e..14aed807ce 100644 --- a/src/test/java/hudson/plugins/git/browser/casc/GitLabConfiguratorTest.java +++ b/src/test/java/hudson/plugins/git/browser/casc/GitLabConfiguratorTest.java @@ -3,48 +3,46 @@ import hudson.plugins.git.browser.GitLab; import io.jenkins.plugins.casc.ConfigurationContext; import io.jenkins.plugins.casc.model.Mapping; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; -public class GitLabConfiguratorTest { +class GitLabConfiguratorTest { private final GitLabConfigurator configurator = new GitLabConfigurator(); private static final ConfigurationContext NULL_CONFIGURATION_CONTEXT = null; @Test - public void testGetName() { + void testGetName() { assertEquals("gitLab", configurator.getName()); } @Test - public void testGetTarget() { - assertEquals("Wrong target class", configurator.getTarget(), GitLab.class); + void testGetTarget() { + assertEquals(GitLab.class, configurator.getTarget(), "Wrong target class"); } @Test - public void testCanConfigure() { - assertTrue("Can't configure AdvisorGlobalConfiguration", configurator.canConfigure(GitLab.class)); - assertFalse("Can configure AdvisorRootConfigurator", configurator.canConfigure(GitLabConfigurator.class)); + void testCanConfigure() { + assertTrue(configurator.canConfigure(GitLab.class), "Can't configure AdvisorGlobalConfiguration"); + assertFalse(configurator.canConfigure(GitLabConfigurator.class), "Can configure AdvisorRootConfigurator"); } @Test - public void testGetImplementedAPI() { - assertEquals("Wrong implemented API", configurator.getImplementedAPI(), GitLab.class); + void testGetImplementedAPI() { + assertEquals(GitLab.class, configurator.getImplementedAPI(), "Wrong implemented API"); } @Test - public void testGetConfigurators() { + void testGetConfigurators() { assertThat(configurator.getConfigurators(NULL_CONFIGURATION_CONTEXT), contains(configurator)); } @Test @Deprecated - public void testDescribe() throws Exception { + void testDescribe() throws Exception { final Mapping expectedMapping = new Mapping(); expectedMapping.put("repoUrl", "http://fake"); expectedMapping.put("version", "1.1"); @@ -57,7 +55,7 @@ public void testDescribe() throws Exception { @Test @Deprecated - public void testInstance() throws Exception { + void testInstance() throws Exception { final GitLab expectedConfiguration = new GitLab("http://fake", "2.0"); final Mapping mapping = new Mapping(); mapping.put("repoUrl", "http://fake"); @@ -70,7 +68,7 @@ public void testInstance() throws Exception { @Test @Deprecated - public void testInstanceWithEmptyRepo() throws Exception { + void testInstanceWithEmptyRepo() throws Exception { final GitLab expectedConfiguration = new GitLab("", "2.0"); final Mapping mapping = new Mapping(); mapping.put("repoUrl", ""); @@ -84,7 +82,7 @@ public void testInstanceWithEmptyRepo() throws Exception { @Test @Deprecated - public void testInstanceWithNullRepo() throws Exception { + void testInstanceWithNullRepo() throws Exception { final GitLab expectedConfiguration = new GitLab(null, "2.0"); final Mapping mapping = new Mapping(); mapping.put("version", "2.0"); @@ -97,7 +95,7 @@ public void testInstanceWithNullRepo() throws Exception { @Test @Deprecated - public void testInstanceWithEmptyVersion() throws Exception { + void testInstanceWithEmptyVersion() throws Exception { final GitLab expectedConfiguration = new GitLab("http://fake", ""); final Mapping mapping = new Mapping(); mapping.put("repoUrl", "http://fake"); @@ -110,7 +108,7 @@ public void testInstanceWithEmptyVersion() throws Exception { @Test @Deprecated - public void testInstanceWithNullVersion() throws Exception { + void testInstanceWithNullVersion() throws Exception { // If passing a null, GitLab throws an exception final GitLab expectedConfiguration = new GitLab("http://fake", ""); final Mapping mapping = new Mapping(); @@ -123,7 +121,7 @@ public void testInstanceWithNullVersion() throws Exception { @Test @Deprecated - public void testInstanceWithNullMapping() throws Exception { + void testInstanceWithNullMapping() throws Exception { // A null mapping should create an instance with empty arguments final GitLab expectedConfiguration = new GitLab("", ""); final Mapping mapping = null; @@ -134,7 +132,7 @@ public void testInstanceWithNullMapping() throws Exception { @Test @Deprecated - public void testInstanceWithNaNVersion() throws Exception { + void testInstanceWithNaNVersion() throws Exception { final Mapping mapping = new Mapping(); mapping.put("repoUrl", "http://fake"); mapping.put("version", "NaN"); diff --git a/src/test/java/hudson/plugins/git/extensions/GitSCMExtensionTest.java b/src/test/java/hudson/plugins/git/extensions/GitSCMExtensionTest.java index 60ebf1d205..10ce51359c 100644 --- a/src/test/java/hudson/plugins/git/extensions/GitSCMExtensionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/GitSCMExtensionTest.java @@ -6,48 +6,47 @@ import hudson.plugins.git.TestGitRepo; import hudson.util.StreamTaskListener; import org.eclipse.jgit.util.SystemReader; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; -import org.jvnet.hudson.test.BuildWatcher; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.CaptureEnvironmentBuilder; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.BuildWatcherExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +import java.io.File; import java.util.Collections; import java.util.List; /** * @author Kanstantsin Shautsou */ +@WithJenkins public abstract class GitSCMExtensionTest { protected TaskListener listener; - @ClassRule - public static BuildWatcher buildWatcher = new BuildWatcher(); + @RegisterExtension + protected static final BuildWatcherExtension BUILD_WATCHER = new BuildWatcherExtension(); - @Rule - public JenkinsRule r = new JenkinsRule(); + protected JenkinsRule r; - @Rule - public TemporaryFolder tmp = new TemporaryFolder(); + @TempDir + protected File tmp; - @Before - public void setUp() throws Exception { + @BeforeEach + protected void beforeEach(JenkinsRule rule) throws Exception { + r = rule; SystemReader.getInstance().getUserConfig().clear(); listener = StreamTaskListener.fromStderr(); before(); - } - @Before - public void allowNonRemoteCheckout() { GitSCM.ALLOW_LOCAL_CHECKOUT = true; } - @After - public void disallowNonRemoteCheckout() { + @AfterEach + protected void afterEach() { GitSCM.ALLOW_LOCAL_CHECKOUT = false; } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/AuthorInChangelogTest.java b/src/test/java/hudson/plugins/git/extensions/impl/AuthorInChangelogTest.java index b4ac5866fa..94cc0ccde1 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/AuthorInChangelogTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/AuthorInChangelogTest.java @@ -1,22 +1,22 @@ package hudson.plugins.git.extensions.impl; import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -public class AuthorInChangelogTest { +class AuthorInChangelogTest { @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(AuthorInChangelog.class) .usingGetClass() .verify(); } @Test - public void checkToString() { + void checkToString() { AuthorInChangelog setting = new AuthorInChangelog(); assertThat(setting.toString(), is("AuthorInChangelog{}")); } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java b/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java index 41bc70e0d5..9a4ad7cc27 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/BuildSingleRevisionOnlyTest.java @@ -11,20 +11,21 @@ import hudson.plugins.git.GitSCM; import hudson.plugins.git.GitStatusTest; import hudson.util.RunList; -import java.io.File; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; -import org.junit.After; -public class BuildSingleRevisionOnlyTest extends AbstractGitTestCase { +import static hudson.Functions.isWindows; +import static org.junit.jupiter.api.Assertions.assertFalse; - @After - public void waitForAllJobsToComplete() { +class BuildSingleRevisionOnlyTest extends AbstractGitTestCase { + + @AfterEach + void afterEach() { /* Windows job cleanup fails to delete build logs in some of these tests. * Wait for the jobs to complete before exiting the test so that the * build logs will not be active when the cleanup process tries to @@ -52,7 +53,7 @@ public void waitForAllJobsToComplete() { } @Test - public void testSingleRevision() throws Exception { + void testSingleRevision() throws Exception { // This is the additional behaviour List branchSpec = new ArrayList<>(); branchSpec.add(new BranchSpec("master")); @@ -80,11 +81,11 @@ public void testSingleRevision() throws Exception { r.assertBuildStatusSuccess(build); boolean result = build.getLog(100).contains( "Scheduling another build to catch up with %s".formatted(project.getName())); - Assert.assertFalse("Single revision scheduling did not prevent a build of a different revision", result); + assertFalse(result, "Single revision scheduling did not prevent a build of a different revision"); } @Test - public void testMultiRevision() throws Exception { + void testMultiRevision() throws Exception { // This is the old and now default behaviour List branchSpec = new ArrayList<>(); branchSpec.add(new BranchSpec("master")); @@ -120,11 +121,4 @@ public void testMultiRevision() throws Exception { Thread.sleep(500L + random.nextInt(300)); } - /** - * inline ${@link hudson.Functions#isWindows()} to prevent a transient - * remote class loader issue - */ - private boolean isWindows() { - return File.pathSeparatorChar == ';'; - } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/ChangelogToBranchTest.java b/src/test/java/hudson/plugins/git/extensions/impl/ChangelogToBranchTest.java index 0db3c9bf2d..e1fda837db 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/ChangelogToBranchTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/ChangelogToBranchTest.java @@ -1,16 +1,16 @@ package hudson.plugins.git.extensions.impl; import hudson.plugins.git.ChangelogToBranchOptions; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ChangelogToBranchTest { -public class ChangelogToBranchTest { @Test - public void checkConstructorIllegalArgument() { + void checkConstructorIllegalArgument() { ChangelogToBranchOptions nullOptions = null; IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> new ChangelogToBranch(nullOptions)); diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionTest.java index 1d0822716a..be21f36c7e 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionTest.java @@ -8,37 +8,37 @@ import java.util.List; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; +import org.junit.jupiter.api.BeforeEach; + import org.jenkinsci.plugins.gitclient.CheckoutCommand; import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class CheckoutOptionTest { +class CheckoutOptionTest { private CheckoutOption option; private static final int INITIAL_TIMEOUT = 10; - public CheckoutOptionTest() { - } - - @Before - public void setUp() { + @BeforeEach + void beforeEach() { option = new CheckoutOption(INITIAL_TIMEOUT); } @Test - public void testGetTimeout() { + void testGetTimeout() { assertEquals(INITIAL_TIMEOUT, (int) option.getTimeout()); } @Test - public void testRequiresWorkspaceForPolling() { + void testRequiresWorkspaceForPolling() { assertFalse(option.requiresWorkspaceForPolling()); } @Test - public void testDecorateCheckoutCommand() throws Exception { + void testDecorateCheckoutCommand() throws Exception { final int NEW_TIMEOUT = 13; CheckoutCommandImpl cmd = new CheckoutCommandImpl(); @@ -55,7 +55,7 @@ public void testDecorateCheckoutCommand() throws Exception { } @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(CheckoutOption.class) .usingGetClass() .suppress(Warning.NONFINAL_FIELDS) @@ -63,11 +63,11 @@ public void equalsContract() { } @Test - public void checkToString() { + void checkToString() { assertEquals("CheckoutOption{timeout=" + INITIAL_TIMEOUT + "}", option.toString()); } - public class CheckoutCommandImpl implements CheckoutCommand { + public static class CheckoutCommandImpl implements CheckoutCommand { private int timeout = INITIAL_TIMEOUT; diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionWorkflowTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionWorkflowTest.java index 371a4d3063..9f22ac6f70 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionWorkflowTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CheckoutOptionWorkflowTest.java @@ -1,22 +1,30 @@ package hudson.plugins.git.extensions.impl; import jenkins.plugins.git.GitSampleRepoRule; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class CheckoutOptionWorkflowTest { +@WithJenkins +@WithGitSampleRepo +class CheckoutOptionWorkflowTest { - @Rule - public JenkinsRule r = new JenkinsRule(); - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + private JenkinsRule r; + private GitSampleRepoRule sampleRepo; + + @BeforeEach + void beforeEach(JenkinsRule rule, GitSampleRepoRule repo) { + r = rule; + sampleRepo = repo; + } @Test - public void checkoutTimeout() throws Exception { + void checkoutTimeout() throws Exception { sampleRepo.init(); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CleanBeforeCheckoutTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CleanBeforeCheckoutTest.java index 84e4582bd4..07e75a7c49 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CleanBeforeCheckoutTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CleanBeforeCheckoutTest.java @@ -2,12 +2,12 @@ import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class CleanBeforeCheckoutTest { +class CleanBeforeCheckoutTest { @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(CleanBeforeCheckout.class) .usingGetClass() .suppress(Warning.NONFINAL_FIELDS) diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CleanCheckoutTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CleanCheckoutTest.java index 82e71d7d08..ba615fc217 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CleanCheckoutTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CleanCheckoutTest.java @@ -2,15 +2,15 @@ import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -public class CleanCheckoutTest { +class CleanCheckoutTest { @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(CleanCheckout.class) .usingGetClass() .suppress(Warning.NONFINAL_FIELDS) @@ -18,13 +18,13 @@ public void equalsContract() { } @Test - public void checkToStringFalse() { + void checkToStringFalse() { CleanCheckout setting = new CleanCheckout(); assertThat(setting.toString(), is("CleanCheckout{deleteUntrackedNestedRepositories=false}")); } @Test - public void checkToStringTrue() { + void checkToStringTrue() { CleanCheckout setting = new CleanCheckout(); setting.setDeleteUntrackedNestedRepositories(true); assertThat(setting.toString(), is("CleanCheckout{deleteUntrackedNestedRepositories=true}")); diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionDepthTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionDepthTest.java index f51efc61d7..2fdf1806b6 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionDepthTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionDepthTest.java @@ -15,20 +15,22 @@ import org.jenkinsci.plugins.gitclient.CloneCommand; import org.jenkinsci.plugins.gitclient.FetchCommand; import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mockito; -@RunWith(Parameterized.class) -public class CloneOptionDepthTest { +@ParameterizedClass(name = "depth: configured={0}, used={1}") +@MethodSource("depthCombinations") +@WithJenkins +class CloneOptionDepthTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; private GitSCM scm; private Run build; @@ -43,13 +45,17 @@ public CloneOptionDepthTest(int configuredDepth, int usedDepth) { this.usedDepth = usedDepth; } - @Parameterized.Parameters(name = "depth: configured={0}, used={1}") - public static Object[][] depthCombinations() { + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; + } + + static Object[][] depthCombinations() { return new Object[][] { { 0, 1 }, { 1, 1 }, { 2, 2 } }; } - @Before - public void mockDependencies() throws Exception { + @BeforeEach + void beforeEach() throws Exception { scm = mock(GitSCM.class); build = mock(Run.class); git = mock(GitClient.class); @@ -63,7 +69,7 @@ public void mockDependencies() throws Exception { @Issue("JENKINS-53050") @Test - public void decorateCloneCommandShouldUseValidShallowDepth() throws Exception { + void decorateCloneCommandShouldUseValidShallowDepth() throws Exception { CloneCommand cloneCommand = mock(CloneCommand.class, Mockito.RETURNS_SELF); PrintStream logger = mock(PrintStream.class); @@ -82,7 +88,7 @@ public void decorateCloneCommandShouldUseValidShallowDepth() throws Exception { @Issue("JENKINS-53050") @Test @Deprecated - public void decorateFetchCommandShouldUseValidShallowDepth() throws Exception { + void decorateFetchCommandShouldUseValidShallowDepth() throws Exception { FetchCommand fetchCommand = mock(FetchCommand.class, Mockito.RETURNS_SELF); PrintStream logger = mock(PrintStream.class); diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java index f76050fe35..0d933cd628 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionHonorRefSpecTest.java @@ -12,24 +12,27 @@ import hudson.tasks.BatchFile; import hudson.tasks.Builder; import hudson.tasks.Shell; +import org.junit.jupiter.api.BeforeEach; + import org.jenkinsci.plugins.gitclient.JGitTool; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; -import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Random; + +import static hudson.Functions.isWindows; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -@RunWith(Parameterized.class) -public class CloneOptionHonorRefSpecTest extends AbstractGitTestCase { +@ParameterizedClass(name = "{0}") +@MethodSource("permuteRefSpecVariable") +class CloneOptionHonorRefSpecTest extends AbstractGitTestCase { private final String refSpecName; @@ -41,8 +44,7 @@ public CloneOptionHonorRefSpecTest(String refSpecName) { this.refSpecName = refSpecName; } - @Parameterized.Parameters(name = "{0}") - public static Collection permuteRefSpecVariable() { + static Collection permuteRefSpecVariable() { List values = new ArrayList<>(); String[] keys = { @@ -66,11 +68,8 @@ private static Builder createEnvEchoBuilder(String envVarName) { return new Shell("echo \"%s=${%s}\"".formatted(envVarName, envVarName)); } - @Before - @Override - public void setUp() throws Exception { - super.setUp(); - + @BeforeEach + void beforeEach() throws Exception { // Setup job beforehand to get expected value of the environment variable project = createFreeStyleProject(); project.addProperty(new ParametersDefinitionProperty( @@ -83,7 +82,7 @@ public void setUp() throws Exception { List logs = b.getLog(50); for (String line : logs) { if (line.startsWith(refSpecName + '=')) { - refSpecExpectedValue = line.substring(refSpecName.length() + 1, line.length()); + refSpecExpectedValue = line.substring(refSpecName.length() + 1); } } @@ -101,7 +100,7 @@ public void setUp() throws Exception { */ @Test @Issue("JENKINS-56063") - public void testRefSpecWithExpandedVariables() throws Exception { + void testRefSpecWithExpandedVariables() throws Exception { if (refSpecExpectedValue == null || refSpecExpectedValue.isEmpty()) { /* Test does not support an empty or null expected value. Skip the test if the expected value is empty or null */ @@ -147,8 +146,4 @@ public void testRefSpecWithExpandedVariables() throws Exception { List buildLog = b.getLog(50); assertThat(buildLog, not(hasItem(containsString("${" + refSpecName + "}")))); } - - private static boolean isWindows() { - return File.pathSeparatorChar == ';'; - } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionNoTagsTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionNoTagsTest.java index d659fda8da..9ac073ff46 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionNoTagsTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionNoTagsTest.java @@ -1,31 +1,33 @@ package hudson.plugins.git.extensions.impl; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.io.IOException; import java.util.Set; import hudson.model.Result; import hudson.model.FreeStyleProject; import hudson.plugins.git.TestGitRepo; import hudson.plugins.git.extensions.GitSCMExtensionTest; +import org.junit.jupiter.api.Test; import hudson.plugins.git.extensions.GitSCMExtension; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.Test; /** * @author Ronny Händel */ -public class CloneOptionNoTagsTest extends GitSCMExtensionTest { +class CloneOptionNoTagsTest extends GitSCMExtensionTest { FreeStyleProject project; TestGitRepo repo; @Override - public void before() throws Exception { - repo = new TestGitRepo("repo", tmp.newFolder(), listener); + protected void before() throws Exception { + repo = new TestGitRepo("repo", newFolder(tmp, "junit"), listener); project = setupBasicProject(repo); } @@ -39,38 +41,47 @@ protected GitSCMExtension getExtension() { } @Test - public void cloningShouldNotFetchTags() throws Exception { + void cloningShouldNotFetchTags() throws Exception { repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); repo.tag("v0.0.1", "a tag that should never be fetched"); - assertTrue("scm polling should detect a change after initial commit", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling should detect a change after initial commit"); build(project, Result.SUCCESS); - assertTrue("there should no tags have been cloned from remote", allTagsInProjectWorkspace().isEmpty()); + assertTrue(allTagsInProjectWorkspace().isEmpty(), "there should no tags have been cloned from remote"); } @Test - public void detectNoChangeAfterCreatingATag() throws Exception { + void detectNoChangeAfterCreatingATag() throws Exception { repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); - assertTrue("scm polling should detect a change after initial commit", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling should detect a change after initial commit"); build(project, Result.SUCCESS); repo.tag("v0.0.1", "a tag that should never be fetched"); - assertFalse("scm polling should not detect a change after creating a tag", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect a change after creating a tag"); build(project, Result.SUCCESS); - assertTrue("there should no tags have been fetched from remote", allTagsInProjectWorkspace().isEmpty()); + assertTrue(allTagsInProjectWorkspace().isEmpty(), "there should no tags have been fetched from remote"); } private Set allTagsInProjectWorkspace() throws Exception { GitClient git = Git.with(listener, null).in(project.getSomeWorkspace()).getClient(); return git.getTagNames("*"); } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionShallowDefaultTagsTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionShallowDefaultTagsTest.java index 40d783a1b5..ad7f755752 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionShallowDefaultTagsTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionShallowDefaultTagsTest.java @@ -1,30 +1,33 @@ package hudson.plugins.git.extensions.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import hudson.model.Result; import hudson.model.FreeStyleProject; import hudson.plugins.git.TestGitRepo; import hudson.plugins.git.extensions.GitSCMExtensionTest; +import org.junit.jupiter.api.Test; import hudson.plugins.git.extensions.GitSCMExtension; +import java.io.File; +import java.io.IOException; import java.util.Set; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.Test; /** * @author Ronny Händel */ -public class CloneOptionShallowDefaultTagsTest extends GitSCMExtensionTest { +class CloneOptionShallowDefaultTagsTest extends GitSCMExtensionTest { FreeStyleProject project; TestGitRepo repo; @Override - public void before() throws Exception { - repo = new TestGitRepo("repo", tmp.newFolder(), listener); + protected void before() throws Exception { + repo = new TestGitRepo("repo", newFolder(tmp, "junit"), listener); project = setupBasicProject(repo); } @@ -37,21 +40,30 @@ protected GitSCMExtension getExtension() { } @Test - public void evenShallowCloningFetchesTagsByDefault() throws Exception { + void evenShallowCloningFetchesTagsByDefault() throws Exception { final String tagName = "v0.0.1"; repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); repo.tag(tagName, "a tag that should be fetched by default"); - assertTrue("scm polling should detect a change after initial commit", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling should detect a change after initial commit"); build(project, Result.SUCCESS); - assertEquals("tag " + tagName + " should have been cloned from remote", 1, tagsInProjectWorkspaceWithName(tagName).size()); + assertEquals(1, tagsInProjectWorkspaceWithName(tagName).size(), "tag " + tagName + " should have been cloned from remote"); } private Set tagsInProjectWorkspaceWithName(String tagPattern) throws Exception { GitClient git = Git.with(listener, null).in(project.getSomeWorkspace()).getClient(); return git.getTagNames(tagPattern); } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionTest.java index e10f6e91f2..70307346aa 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/CloneOptionTest.java @@ -3,20 +3,21 @@ import hudson.plugins.git.extensions.GitClientType; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import org.junit.Test; -public class CloneOptionTest { +class CloneOptionTest { @Test - public void getRequiredClient() { + void getRequiredClient() { CloneOption cloneOption = new CloneOption(false, "", 1); assertThat(cloneOption.getRequiredClient(), is(GitClientType.GITCLI)); } @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(CloneOption.class) .usingGetClass() .suppress(Warning.NONFINAL_FIELDS) diff --git a/src/test/java/hudson/plugins/git/extensions/impl/GitLFSPullTest.java b/src/test/java/hudson/plugins/git/extensions/impl/GitLFSPullTest.java index a34b6d30c2..d465baeb44 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/GitLFSPullTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/GitLFSPullTest.java @@ -1,12 +1,12 @@ package hudson.plugins.git.extensions.impl; import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GitLFSPullTest { +class GitLFSPullTest { @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(GitLFSPull.class) .usingGetClass() .verify(); diff --git a/src/test/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommitTest.java b/src/test/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommitTest.java index c8816c0e9e..b7d532e84e 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommitTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/IgnoreNotifyCommitTest.java @@ -1,12 +1,12 @@ package hudson.plugins.git.extensions.impl; import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class IgnoreNotifyCommitTest { +class IgnoreNotifyCommitTest { @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(IgnoreNotifyCommit.class) .usingGetClass() .verify(); diff --git a/src/test/java/hudson/plugins/git/extensions/impl/LocalBranchTest.java b/src/test/java/hudson/plugins/git/extensions/impl/LocalBranchTest.java index a8f046d5f5..9d5ad8c7d3 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/LocalBranchTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/LocalBranchTest.java @@ -1,34 +1,34 @@ package hudson.plugins.git.extensions.impl; import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -public class LocalBranchTest { +class LocalBranchTest { @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(LocalBranch.class) .usingGetClass() .verify(); } @Test - public void checkToString() { + void checkToString() { LocalBranch setting = new LocalBranch("branch-name"); assertThat(setting.toString(), is("LocalBranch{localBranch='branch-name'}")); } @Test - public void checkToStringNull() { + void checkToStringNull() { LocalBranch setting = new LocalBranch(null); assertThat(setting.toString(), is("LocalBranch{same-as-remote}")); } @Test - public void checkToStringWildcards() { + void checkToStringWildcards() { LocalBranch setting = new LocalBranch("**"); assertThat(setting.toString(), is("LocalBranch{same-as-remote}")); } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/MessageExclusionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/MessageExclusionTest.java index b0a072d9d4..2d919dd75f 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/MessageExclusionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/MessageExclusionTest.java @@ -4,17 +4,21 @@ import hudson.plugins.git.TestGitRepo; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import java.io.File; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Kanstantsin Shautsou */ -public class MessageExclusionTest extends GitSCMExtensionTest { - protected FreeStyleProject project; - protected TestGitRepo repo; +class MessageExclusionTest extends GitSCMExtensionTest { + + private FreeStyleProject project; + private TestGitRepo repo; @Override protected GitSCMExtension getExtension() { @@ -22,33 +26,42 @@ protected GitSCMExtension getExtension() { } @Override - public void before() throws Exception { - repo = new TestGitRepo("repo", tmp.newFolder(), listener); + protected void before() throws Exception { + repo = new TestGitRepo("repo", newFolder(tmp, "junit"), listener); project = setupBasicProject(repo); } - @Test - public void test() throws Exception { + @Test + void test() throws Exception { repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); - assertTrue("scm polling should detect a change after initial commit", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling should detect a change after initial commit"); build(project, Result.SUCCESS); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); repo.commit("repo-init", repo.janeDoe, " [maven-release-plugin] excluded message commit"); - assertFalse("scm polling should not detect excluded message", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect excluded message"); repo.commit("repo-init", repo.janeDoe, "first line in excluded commit\nsecond\nthird [maven-release-plugin]\n"); - assertFalse("scm polling should not detect multiline message", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect multiline message"); // should be enough, but let's test more build(project, Result.SUCCESS); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/PathRestrictionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/PathRestrictionTest.java index b8799f51ec..a347f57cfd 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PathRestrictionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PathRestrictionTest.java @@ -8,24 +8,25 @@ import hudson.plugins.git.extensions.GitSCMExtensionTest; import hudson.plugins.git.util.BuildData; +import java.io.File; +import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import org.junit.Test; -import org.junit.experimental.runners.Enclosed; -import org.junit.runner.RunWith; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; // NOTE: isRevExcluded generally returns null instead of false -@RunWith(Enclosed.class) -public class PathRestrictionTest { +class PathRestrictionTest { - public abstract static class PathRestrictionExtensionTest extends GitSCMExtensionTest { + abstract static class PathRestrictionExtensionTest extends GitSCMExtensionTest { protected FreeStyleProject project; protected TestGitRepo repo; @@ -33,13 +34,23 @@ public abstract static class PathRestrictionExtensionTest extends GitSCMExtensio @Override public void before() throws Exception { - repo = new TestGitRepo("repo", tmp.newFolder(), listener); + repo = new TestGitRepo("repo", newFolder(tmp, "junit"), listener); project = setupBasicProject(repo); } + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } + } - public static class NoRulesTest extends PathRestrictionExtensionTest { + @Nested + class NoRulesTest extends PathRestrictionExtensionTest { @Override protected GitSCMExtension getExtension() { @@ -47,13 +58,14 @@ protected GitSCMExtension getExtension() { } @Test - public void test() throws Exception { + void test() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("foo/foo.txt", "bar/bar.txt"))); assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } } - public static class EmptyPathsTest extends PathRestrictionExtensionTest { + @Nested + class EmptyPathsTest extends PathRestrictionExtensionTest { @Override protected GitSCMExtension getExtension() { @@ -61,14 +73,15 @@ protected GitSCMExtension getExtension() { } @Test - public void test() throws Exception { + void test() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>()); assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } } - public static class BasicExcludeTest extends PathRestrictionExtensionTest { + @Nested + class BasicExcludeTest extends PathRestrictionExtensionTest { @Override protected GitSCMExtension getExtension() { @@ -76,19 +89,20 @@ protected GitSCMExtension getExtension() { } @Test - public void testMiss() throws Exception { + void testMiss() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("foo/foo.txt"))); assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } @Test - public void testMatch() throws Exception { + void testMatch() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("bar/bar.txt"))); assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } } - public static class BasicIncludeTest extends PathRestrictionExtensionTest { + @Nested + class BasicIncludeTest extends PathRestrictionExtensionTest { @Override protected GitSCMExtension getExtension() { @@ -96,20 +110,21 @@ protected GitSCMExtension getExtension() { } @Test - public void testMatch() throws Exception { + void testMatch() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("foo/foo.txt"))); assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } @Test - public void testMiss() throws Exception { + void testMiss() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("bar/bar.txt"))); assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); } } - public static class MultiExcludeTest extends PathRestrictionExtensionTest { + @Nested + class MultiExcludeTest extends PathRestrictionExtensionTest { @Override protected GitSCMExtension getExtension() { @@ -117,7 +132,7 @@ protected GitSCMExtension getExtension() { } @Test - public void testAccept() throws Exception { + void testAccept() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("foo/foo.txt"))); assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("foo/foo.txt", "foo.foo", "README.mdown"))); @@ -129,7 +144,7 @@ public void testAccept() throws Exception { } @Test - public void testReject() throws Exception { + void testReject() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("bar/bar.txt", "foo.bax"))); assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("bar/docs.txt", "bar/more-docs.txt"))); @@ -137,7 +152,8 @@ public void testReject() throws Exception { } } - public static class MultiIncludeTest extends PathRestrictionExtensionTest { + @Nested + class MultiIncludeTest extends PathRestrictionExtensionTest { @Override protected GitSCMExtension getExtension() { @@ -145,7 +161,7 @@ protected GitSCMExtension getExtension() { } @Test - public void testAccept() throws Exception { + void testAccept() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("foo/foo.txt", "something/else"))); assertNull(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("foo/foo.txt", "foo.foo", "README.mdown"))); @@ -155,7 +171,7 @@ public void testAccept() throws Exception { } @Test - public void testReject() throws Exception { + void testReject() throws Exception { GitChangeSet commit = new FakePathGitChangeSet(new HashSet<>(Collections.singletonList("bar/bar.txt"))); assertTrue(getExtension().isRevExcluded((hudson.plugins.git.GitSCM) project.getScm(), repo.git, commit, listener, mockBuildData)); commit = new FakePathGitChangeSet(new HashSet<>(Arrays.asList("bar/bar.txt", "bar.bar", "README.mdown"))); diff --git a/src/test/java/hudson/plugins/git/extensions/impl/PreBuildMergeTest.java b/src/test/java/hudson/plugins/git/extensions/impl/PreBuildMergeTest.java index 7f784ed73a..fa67b9077b 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PreBuildMergeTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PreBuildMergeTest.java @@ -11,24 +11,27 @@ import hudson.plugins.git.extensions.GitSCMExtensionTest; import hudson.plugins.git.util.BuildData; import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.MergeCommand; -import org.junit.Test; -import static org.junit.Assert.*; +import java.io.File; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; /** * @author dalvizu */ -public class PreBuildMergeTest extends GitSCMExtensionTest -{ +class PreBuildMergeTest extends GitSCMExtensionTest { private FreeStyleProject project; private TestGitRepo repo; private String MASTER_FILE = "commitFileBase"; - public void before() throws Exception { - repo = new TestGitRepo("repo", tmp.newFolder(), listener); + protected void before() throws Exception { + repo = new TestGitRepo("repo", newFolder(tmp, "junit"), listener); project = setupBasicProject(repo); // make an initial commit to master repo.commit(MASTER_FILE, repo.johnDoe, "Initial Commit"); @@ -37,17 +40,17 @@ public void before() throws Exception { } @Test - public void testBasicPreMerge() throws Exception { + void testBasicPreMerge() throws Exception { FreeStyleBuild firstBuild = build(project, Result.SUCCESS); } @Test - public void testFailedMerge() throws Exception { + void testFailedMerge() throws Exception { FreeStyleBuild firstBuild = build(project, Result.SUCCESS); assertEquals(GitSCM.class, project.getScm().getClass()); GitSCM gitSCM = (GitSCM)project.getScm(); BuildData buildData = gitSCM.getBuildData(firstBuild); - assertNotNull("Build data not found", buildData); + assertNotNull(buildData, "Build data not found"); assertEquals(firstBuild.getNumber(), buildData.lastBuild.getBuildNumber()); Revision firstMarked = buildData.lastBuild.getMarked(); Revision firstRevision = buildData.lastBuild.getRevision(); @@ -61,9 +64,9 @@ public void testFailedMerge() throws Exception { repo.git.checkout().ref("master").execute(); // make a new commit in master branch, this commit should not merge cleanly! - assertFalse("SCM polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "SCM polling should not detect any more changes after build"); String conflictSha1 = repo.commit(MASTER_FILE, "new content - expect a merge conflict!", repo.johnDoe, repo.johnDoe, "Commit which should fail!"); - assertTrue("SCM polling should detect changes", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "SCM polling should detect changes"); FreeStyleBuild secondBuild = build(project, Result.FAILURE); assertEquals(secondBuild.getNumber(), gitSCM.getBuildData(secondBuild).lastBuild.getBuildNumber()); @@ -78,7 +81,7 @@ public void testFailedMerge() throws Exception { } @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(PreBuildMerge.class) .usingGetClass() .verify(); @@ -90,4 +93,13 @@ protected GitSCMExtension getExtension() { MergeCommand.GitPluginFastForwardMode.FF)); } + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } + } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleBranchTest.java b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleBranchTest.java index ee7dc7170a..70c8a3e019 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleBranchTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleBranchTest.java @@ -1,12 +1,12 @@ package hudson.plugins.git.extensions.impl; import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PruneStaleBranchTest { +class PruneStaleBranchTest { @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(PruneStaleBranch.class) .usingGetClass() .verify(); diff --git a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java index bc6d7d0575..a5d7a02631 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagPipelineTest.java @@ -30,59 +30,58 @@ import java.util.logging.Logger; import hudson.plugins.git.GitSCM; + +import static hudson.Functions.isWindows; +import static org.junit.jupiter.api.Assertions.assertFalse; import hudson.plugins.git.util.GitUtilsTest; import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.util.SystemReader; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.TestCliGitAPIImpl; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import hudson.FilePath; -import hudson.Functions; import hudson.model.Result; import hudson.model.TaskListener; import hudson.util.LogTaskListener; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +@WithJenkins +class PruneStaleTagPipelineTest { -public class PruneStaleTagPipelineTest { + @TempDir + private File fileRule; - @Rule - public TemporaryFolder fileRule = new TemporaryFolder(); - @Rule - public JenkinsRule j = new JenkinsRule(); + private JenkinsRule r; private TaskListener listener; - @Before - public void setup() throws Exception { + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + r = rule; listener = new LogTaskListener(Logger.getLogger("prune tags"), Level.FINEST); - } - @Before - public void allowNonRemoteCheckout() throws ConfigInvalidException, IOException { SystemReader.getInstance().getUserConfig().clear(); GitSCM.ALLOW_LOCAL_CHECKOUT = true; } - @After - public void disallowNonRemoteCheckout() { + @AfterEach + void afterEach() { GitSCM.ALLOW_LOCAL_CHECKOUT = false; } @Issue("JENKINS-61869") @Test - public void verify_that_local_tag_is_pruned_when_not_exist_on_remote_using_pipeline() throws Exception { - File remoteRepo = fileRule.newFolder("remote"); + void verify_that_local_tag_is_pruned_when_not_exist_on_remote_using_pipeline() throws Exception { + File remoteRepo = newFolder(fileRule, "remote"); // create a remote repository without one tag GitClient remoteClient = initRepository(remoteRepo); @@ -90,9 +89,9 @@ public void verify_that_local_tag_is_pruned_when_not_exist_on_remote_using_pipel String tagComment = "tag comment"; remoteClient.tag(tagName, tagComment); - WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, "pruneTags"); + WorkflowJob job = r.jenkins.createProject(WorkflowJob.class, "pruneTags"); - FilePath workspace = j.jenkins.getWorkspaceFor(job); + FilePath workspace = r.jenkins.getWorkspaceFor(job); String remoteURL = "file://" + remoteRepo.toURI().getPath(); job.setDefinition(new CpsFlowDefinition("" @@ -108,23 +107,23 @@ public void verify_that_local_tag_is_pruned_when_not_exist_on_remote_using_pipel // first run clone the repository WorkflowRun r = job.scheduleBuild2(0).waitForStart(); - j.assertBuildStatus(Result.SUCCESS, j.waitForCompletion(r)); + this.r.assertBuildStatus(Result.SUCCESS, this.r.waitForCompletion(r)); // Check JENKINS-66651 - token macro expansion in Pipeline - j.waitForMessage("token macro expanded branch is remotes/origin/master", r); // Unexpected but current behavior + this.r.waitForMessage("token macro expanded branch is remotes/origin/master", r); // Unexpected but current behavior // remove tag on remote, tag remains on local cloned repository remoteClient.deleteTag(tagName); // second run it should remove stale tags r = job.scheduleBuild2(0).waitForStart(); - j.assertBuildStatus(Result.SUCCESS, j.waitForCompletion(r)); + this.r.assertBuildStatus(Result.SUCCESS, this.r.waitForCompletion(r)); GitClient localClient = newGitClient(new File(workspace.getRemote())); - Assert.assertFalse("local tag has not been pruned", localClient.tagExists(tagName)); + assertFalse(localClient.tagExists(tagName), "local tag has not been pruned"); } private GitClient newGitClient(File localRepo) { - String gitExe = Functions.isWindows() ? "git.exe" : "git"; + String gitExe = isWindows() ? "git.exe" : "git"; return new TestCliGitAPIImpl(gitExe, localRepo, listener, GitUtilsTest.getConfigNoSystemEnvsVars()); } @@ -139,4 +138,13 @@ private GitClient initRepository(File workspace) throws Exception { return remoteClient; } + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } + } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagTest.java b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagTest.java index ebcb8858c5..ffb002951d 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/PruneStaleTagTest.java @@ -23,11 +23,13 @@ * */ package hudson.plugins.git.extensions.impl; - +import static hudson.Functions.isWindows; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; +import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -35,33 +37,30 @@ import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.TestCliGitAPIImpl; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import hudson.EnvVars; -import hudson.Functions; import hudson.model.Run; import hudson.model.TaskListener; import hudson.plugins.git.GitSCM; import hudson.util.LogTaskListener; -public class PruneStaleTagTest { +class PruneStaleTagTest { - @Rule - public TemporaryFolder fileRule = new TemporaryFolder(); + @TempDir + private File fileRule; private TaskListener listener; private Run run; - @Before - public void setup() throws Exception { + @BeforeEach + void beforeEach() throws Exception { listener = new LogTaskListener(Logger.getLogger("prune tags"), Level.FINEST); run = mock(Run.class); @@ -74,8 +73,8 @@ public void setup() throws Exception { * exists - differ | exists - differ */ @Test - public void verify_local_tag_is_pruned_if_different_than_on_remote() throws Exception { - File remoteRepo = fileRule.newFolder("remote"); + void verify_local_tag_is_pruned_if_different_than_on_remote() throws Exception { + File remoteRepo = newFolder(fileRule, "remote"); // create a remote repository without one tag GitClient remoteClient = initRepository(remoteRepo); @@ -99,10 +98,10 @@ public void verify_local_tag_is_pruned_if_different_than_on_remote() throws Exce localClient.deleteTag(tagName); localClient.tag(tagName, tagComment); String localHashTag = localClient.getTags().stream().filter(t -> tagName.equals(t.getName())).findFirst().get().getSHA1String(); - Assert.assertNotEquals("pre validation failed, local tag must not be the same than remote", remoteTagHash, localHashTag); + assertNotEquals(remoteTagHash, localHashTag, "pre validation failed, local tag must not be the same than remote"); extension.decorateFetchCommand(scm, run, localClient, listener, null); - Assert.assertFalse("local tag differ from remote tag and is not pruned", localClient.tagExists(tagName)); + assertFalse(localClient.tagExists(tagName), "local tag differ from remote tag and is not pruned"); } /* @@ -111,8 +110,8 @@ public void verify_local_tag_is_pruned_if_different_than_on_remote() throws Exce * not exists | exists */ @Test - public void verify_do_nothing_when_remote_tag_do_not_exist_locally() throws Exception { - File remoteRepo = fileRule.newFolder("remote"); + void verify_do_nothing_when_remote_tag_do_not_exist_locally() throws Exception { + File remoteRepo = newFolder(fileRule, "remote"); // create a remote repository without one tag GitClient remoteClient = initRepository(remoteRepo); @@ -128,7 +127,7 @@ public void verify_do_nothing_when_remote_tag_do_not_exist_locally() throws Exce String tagComment = "tag comment"; remoteClient.tag(tagName, tagComment); extension.decorateFetchCommand(scm, run, localClient, listener, null); - Assert.assertFalse("new tags should not be fetched", localClient.tagExists(tagName)); + assertFalse(localClient.tagExists(tagName), "new tags should not be fetched"); } /* @@ -137,8 +136,8 @@ public void verify_do_nothing_when_remote_tag_do_not_exist_locally() throws Exce * exists - same | exists - same */ @Test - public void verify_that_local_tag_is_not_pruned_when_exist_on_remote() throws Exception { - File remoteRepo = fileRule.newFolder("remote"); + void verify_that_local_tag_is_not_pruned_when_exist_on_remote() throws Exception { + File remoteRepo = newFolder(fileRule, "remote"); // create a remote repository without one tag GitClient remoteClient = initRepository(remoteRepo); @@ -153,7 +152,7 @@ public void verify_that_local_tag_is_not_pruned_when_exist_on_remote() throws Ex PruneStaleTag extension = new PruneStaleTag(true); extension.decorateFetchCommand(scm, run, localClient, listener, null); - Assert.assertTrue("local tags must not be pruned when exists on remote", localClient.tagExists(tagName)); + assertTrue(localClient.tagExists(tagName), "local tags must not be pruned when exists on remote"); } /* @@ -162,8 +161,8 @@ public void verify_that_local_tag_is_not_pruned_when_exist_on_remote() throws Ex * exists | not exists */ @Test - public void verify_that_local_tag_is_pruned_when_not_exist_on_remote() throws Exception { - File remoteRepo = fileRule.newFolder("remote"); + void verify_that_local_tag_is_pruned_when_not_exist_on_remote() throws Exception { + File remoteRepo = newFolder(fileRule, "remote"); // create a remote repository without one tag GitClient remoteClient = initRepository(remoteRepo); @@ -180,12 +179,12 @@ public void verify_that_local_tag_is_pruned_when_not_exist_on_remote() throws Ex // remove tag on remote, tag remains on local cloned repository remoteClient.deleteTag(tagName); extension.decorateFetchCommand(scm, run, localClient, listener, null); - Assert.assertFalse("local tag has not been pruned", localClient.tagExists(tagName)); + assertFalse(localClient.tagExists(tagName), "local tag has not been pruned"); } @Test - public void verify_fetch_do_not_prune_local_branches() throws Exception { - File remoteRepo = fileRule.newFolder("remote"); + void verify_fetch_do_not_prune_local_branches() throws Exception { + File remoteRepo = newFolder(fileRule, "remote"); // create a remote repository without one tag initRepository(remoteRepo); @@ -202,17 +201,17 @@ public void verify_fetch_do_not_prune_local_branches() throws Exception { PruneStaleTag extension = new PruneStaleTag(true); extension.decorateFetchCommand(scm, run, localClient, listener, null); - Assert.assertTrue("Local branches must not be pruned", localClient.getBranches().stream().anyMatch(b -> branchName.equals(b.getName()))); + assertTrue(localClient.getBranches().stream().anyMatch(b -> branchName.equals(b.getName())), "Local branches must not be pruned"); } private GitClient newGitClient(File localRepo) { - String gitExe = Functions.isWindows() ? "git.exe" : "git"; + String gitExe = isWindows() ? "git.exe" : "git"; GitClient localClient = new TestCliGitAPIImpl(gitExe, localRepo, listener, new EnvVars()); return localClient; } private GitClient cloneRepository(File remoteRepository) throws Exception { - File localRepo = fileRule.newFolder("local"); + File localRepo = newFolder(fileRule, "local"); GitClient localClient = newGitClient(localRepo); /* * Workaround because File.toURI.toURL returns always one slash after @@ -238,24 +237,24 @@ private GitClient initRepository(File workspace) throws Exception { } @Test - public void testGetPruneTags() { + void testGetPruneTags() { PruneStaleTag pruneEnabled = new PruneStaleTag(true); assertThat(pruneEnabled.getPruneTags(), is(true)); } @Test - public void testGetPruneTagsDisabled() { + void testGetPruneTagsDisabled() { PruneStaleTag pruneEnabled = new PruneStaleTag(false); assertThat(pruneEnabled.getPruneTags(), is(false)); } @Test - public void testEquals() { + void testEquals() { EqualsVerifier.forClass(PruneStaleTag.class).usingGetClass().verify(); } @Test - public void testHashCode() { + void testHashCode() { PruneStaleTag enabledOne = new PruneStaleTag(true); PruneStaleTag enabledTwo = new PruneStaleTag(true); assertThat(enabledOne.equals(enabledTwo), is(true)); @@ -273,14 +272,23 @@ public void testHashCode() { } @Test - public void testToString() { + void testToString() { PruneStaleTag enabled = new PruneStaleTag(true); assertThat(enabled.toString(), is("PruneStaleTag { true }")); } @Test - public void testToStringDisabled() { + void testToStringDisabled() { PruneStaleTag disabled = new PruneStaleTag(false); assertThat(disabled.toString(), is("PruneStaleTag { false }")); } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathTest.java b/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathTest.java index 7a18475882..03601eb2e0 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathTest.java @@ -1,12 +1,12 @@ package hudson.plugins.git.extensions.impl; import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SparseCheckoutPathTest { +class SparseCheckoutPathTest { @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(SparseCheckoutPath.class) .usingGetClass() .verify(); diff --git a/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathsTest.java b/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathsTest.java index 5e8ca27aae..87a0e966a7 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathsTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SparseCheckoutPathsTest.java @@ -38,19 +38,19 @@ import org.jenkinsci.plugins.gitclient.GitClient; import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -public class SparseCheckoutPathsTest { +class SparseCheckoutPathsTest { - private final SparseCheckoutPaths emptySparseCheckoutPaths; - private final List emptySparseCheckoutPathList; + private SparseCheckoutPaths emptySparseCheckoutPaths; + private List emptySparseCheckoutPathList; - private final SparseCheckoutPaths sparseCheckoutPaths; - private final List sparseCheckoutPathList; + private SparseCheckoutPaths sparseCheckoutPaths; + private List sparseCheckoutPathList; private static final String SRC_DIR_NAME = "src"; private static final SparseCheckoutPath SRC_SPARSE_CHECKOUT_PATH = new SparseCheckoutPath(SRC_DIR_NAME); @@ -59,7 +59,9 @@ public class SparseCheckoutPathsTest { private LogHandler handler; private int logCount = 0; - public SparseCheckoutPathsTest() { + + @BeforeEach + void beforeEach() { emptySparseCheckoutPathList = new ArrayList<>(); emptySparseCheckoutPaths = new SparseCheckoutPaths(emptySparseCheckoutPathList); @@ -69,10 +71,7 @@ public SparseCheckoutPathsTest() { listener = null; handler = null; - } - @Before - public void createLogger() { Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++); handler = new LogHandler(); handler.setLevel(Level.ALL); @@ -83,17 +82,17 @@ public void createLogger() { } @Test - public void testGetSparseCheckoutPaths() { + void testGetSparseCheckoutPaths() { assertThat(sparseCheckoutPaths.getSparseCheckoutPaths(), hasItem(SRC_SPARSE_CHECKOUT_PATH)); } @Test - public void testGetSparseCheckoutPathsEmpty() { + void testGetSparseCheckoutPathsEmpty() { assertThat(emptySparseCheckoutPaths.getSparseCheckoutPaths(), is(empty())); } @Test - public void testDecorateCloneCommand() throws Exception { + void testDecorateCloneCommand() throws Exception { GitSCM scm = null; Run build = null; GitClient git = null; @@ -103,7 +102,7 @@ public void testDecorateCloneCommand() throws Exception { } @Test - public void testDecorateCloneCommandEmpty() throws Exception { + void testDecorateCloneCommandEmpty() throws Exception { GitSCM scm = null; Run build = null; GitClient git = null; @@ -113,7 +112,7 @@ public void testDecorateCloneCommandEmpty() throws Exception { } @Test - public void testDecorateCheckoutCommand() throws Exception { + void testDecorateCheckoutCommand() throws Exception { GitSCM scm = null; Run build = null; GitClient git = null; @@ -123,23 +122,23 @@ public void testDecorateCheckoutCommand() throws Exception { } @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(SparseCheckoutPaths.class).usingGetClass().verify(); } @Test - public void testHashCode() { + void testHashCode() { SparseCheckoutPaths emptySparseCheckoutPathsCopy = new SparseCheckoutPaths(emptySparseCheckoutPathList); assertThat(emptySparseCheckoutPaths.hashCode(), is(emptySparseCheckoutPathsCopy.hashCode())); assertThat(emptySparseCheckoutPaths, is(emptySparseCheckoutPathsCopy)); } @Test - public void testToString() { + void testToString() { assertThat(emptySparseCheckoutPaths.toString(), is("SparseCheckoutPaths{sparseCheckoutPaths=[]}")); } - private class MyCheckoutCommand implements CheckoutCommand { + private static class MyCheckoutCommand implements CheckoutCommand { private List sparsePathNames; diff --git a/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionDepthTest.java b/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionDepthTest.java index 42b2ae9906..05415a90c0 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionDepthTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionDepthTest.java @@ -12,17 +12,19 @@ import hudson.plugins.git.GitSCM; import hudson.plugins.git.util.Build; import hudson.plugins.git.util.BuildData; +import org.junit.jupiter.api.BeforeEach; + import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.SubmoduleUpdateCommand; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; import org.mockito.Mockito; -@RunWith(Parameterized.class) -public class SubmoduleOptionDepthTest { +@ParameterizedClass(name = "depth: configured={0}, used={1}") +@MethodSource("depthCombinations") +class SubmoduleOptionDepthTest { private GitSCM scm; private Run build; @@ -37,13 +39,12 @@ public SubmoduleOptionDepthTest(int configuredDepth, int usedDepth) { this.usedDepth = usedDepth; } - @Parameterized.Parameters(name = "depth: configured={0}, used={1}") - public static Object[][] depthCombinations() { + static Object[][] depthCombinations() { return new Object[][] { { 0, 1 }, { 1, 1 }, { 2, 2 } }; } - @Before - public void mockDependencies() throws Exception { + @BeforeEach + void beforeEach() throws Exception { scm = mock(GitSCM.class); build = mock(Run.class); git = mock(GitClient.class); @@ -57,7 +58,7 @@ public void mockDependencies() throws Exception { @Issue("JENKINS-53050") @Test - public void submoduleUpdateShouldUseValidShallowDepth() throws Exception { + void submoduleUpdateShouldUseValidShallowDepth() throws Exception { SubmoduleUpdateCommand submoduleUpdate = mock(SubmoduleUpdateCommand.class, Mockito.RETURNS_SELF); when(git.hasGitModules()).thenReturn(true); when(git.submoduleUpdate()).thenReturn(submoduleUpdate); diff --git a/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionTest.java index 32042c1c5a..a5e7d12758 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/SubmoduleOptionTest.java @@ -11,21 +11,20 @@ import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; +import org.junit.jupiter.api.BeforeEach; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.UnsupportedCommand; -import org.junit.Before; -import org.junit.Test; - +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.mockito.Mockito; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class SubmoduleOptionTest { +class SubmoduleOptionTest { private SubmoduleOption submoduleOption; @@ -45,14 +44,14 @@ private SubmoduleOption newSubmoduleOption() { USE_PARENT_CREDENTIALS_FALSE); } - @Before - public void setUp() throws Exception { + @BeforeEach + void beforeEach() throws Exception { submoduleOption = newSubmoduleOption(); } @Issue("JENKINS-31934") @Test - public void testSubmoduleUpdateThrowsIOException() throws Exception { + void testSubmoduleUpdateThrowsIOException() throws Exception { // In order to verify that the submodule option correctly converts // GitExceptions into IOExceptions, setup a SubmoduleOption, and run // it's onCheckoutCompleted extension point with a mocked git client @@ -73,12 +72,12 @@ public void testSubmoduleUpdateThrowsIOException() throws Exception { } @Test - public void testOnCheckoutCompleted() throws Exception { + void testOnCheckoutCompleted() throws Exception { /* See testSubmoduleUpdateThrowsIOException */ } @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(SubmoduleOption.class) .usingGetClass() .suppress(Warning.NONFINAL_FIELDS) @@ -86,12 +85,12 @@ public void equalsContract() { } @Test - public void testIsDisableSubmodules() { + void testIsDisableSubmodules() { assertThat(submoduleOption.isDisableSubmodules(), is(false)); } @Test - public void testIsDisableSubmodulesTrue() { + void testIsDisableSubmodulesTrue() { submoduleOption = new SubmoduleOption(true, RECURSIVE_SUBMODULES_FALSE, TRACKING_SUBMODULES_FALSE, @@ -102,12 +101,12 @@ public void testIsDisableSubmodulesTrue() { } @Test - public void testIsRecursiveSubmodules() { + void testIsRecursiveSubmodules() { assertThat(submoduleOption.isRecursiveSubmodules(), is(false)); } @Test - public void testIsRecursiveSubmodulesTrue() { + void testIsRecursiveSubmodulesTrue() { submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, true, TRACKING_SUBMODULES_FALSE, @@ -118,12 +117,12 @@ public void testIsRecursiveSubmodulesTrue() { } @Test - public void testIsTrackingSubmodules() { + void testIsTrackingSubmodules() { assertThat(submoduleOption.isTrackingSubmodules(), is(false)); } @Test - public void testIsTrackingSubmodulesTrue() { + void testIsTrackingSubmodulesTrue() { submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, RECURSIVE_SUBMODULES_FALSE, true, @@ -134,12 +133,12 @@ public void testIsTrackingSubmodulesTrue() { } @Test - public void testIsParentCredentials() { + void testIsParentCredentials() { assertThat(submoduleOption.isParentCredentials(), is(false)); } @Test - public void testIsParentCredentialsTrue() { + void testIsParentCredentialsTrue() { submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, RECURSIVE_SUBMODULES_FALSE, TRACKING_SUBMODULES_FALSE, @@ -150,12 +149,12 @@ public void testIsParentCredentialsTrue() { } @Test - public void testGetReference() { + void testGetReference() { assertThat(submoduleOption.getReference(), is(nullValue())); } @Test - public void testGetReferenceNotNull() { + void testGetReferenceNotNull() { final String referenceRepoDirName = "/repo.git"; submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, RECURSIVE_SUBMODULES_FALSE, @@ -167,12 +166,12 @@ public void testGetReferenceNotNull() { } @Test - public void testGetTimeout() { + void testGetTimeout() { assertThat(submoduleOption.getTimeout(), is(nullValue())); } @Test - public void testGetTimeoutNotNull() { + void testGetTimeoutNotNull() { Integer timeout = 3; submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, RECURSIVE_SUBMODULES_FALSE, @@ -184,13 +183,13 @@ public void testGetTimeoutNotNull() { } @Test - public void testSetShallow() { + void testSetShallow() { submoduleOption.setShallow(true); assertThat(submoduleOption.getShallow(), is(true)); } @Test - public void testGetShallow() { + void testGetShallow() { assertThat(submoduleOption.getShallow(), is(false)); } @@ -204,31 +203,31 @@ private Integer randomSmallNonNegativeIntegerOrNull() { } @Test - public void testSetDepth() { + void testSetDepth() { Integer depthValue = randomSmallNonNegativeIntegerOrNull(); submoduleOption.setDepth(depthValue); assertThat(submoduleOption.getDepth(), is(depthValue)); } @Test - public void testGetDepth() { + void testGetDepth() { assertThat(submoduleOption.getDepth(), is(nullValue())); } @Test - public void testGetThreads() { + void testGetThreads() { assertThat(submoduleOption.getThreads(), is(nullValue())); } @Test - public void testSetThreads() { + void testSetThreads() { Integer threads = randomSmallNonNegativeIntegerOrNull(); submoduleOption.setThreads(threads); assertThat(submoduleOption.getThreads(), is(threads)); } @Test - public void testToString() { + void testToString() { assertThat(submoduleOption.toString(), is("SubmoduleOption{" + "disableSubmodules=false" + ", recursiveSubmodules=false" @@ -243,7 +242,7 @@ public void testToString() { } @Test - public void testToStringDataBoundConstructor() { + void testToStringDataBoundConstructor() { submoduleOption = new SubmoduleOption(); assertThat(submoduleOption.toString(), is("SubmoduleOption{" + "disableSubmodules=false" @@ -260,7 +259,7 @@ public void testToStringDataBoundConstructor() { @Test @Issue("JENKINS-64382") - public void testDetermineSupportForJGit() throws Exception { + void testDetermineSupportForJGit() throws Exception { /* JGit was incorrectly used when submodule option was added with no items checked. */ GitSCM scm = new GitSCM("https://github.com/jenkinsci/git-plugin"); scm.getExtensions().add(submoduleOption); @@ -271,7 +270,7 @@ public void testDetermineSupportForJGit() throws Exception { @Test @Issue("JENKINS-64382") - public void testDetermineSupportForJGitRecursiveSubmodules() throws Exception { + void testDetermineSupportForJGitRecursiveSubmodules() throws Exception { /* JGit was incorrectly used when submodule option was added with only recursive submodule checked. */ GitSCM scm = new GitSCM("https://github.com/jenkinsci/git-plugin"); submoduleOption = new SubmoduleOption(DISABLE_SUBMODULES_FALSE, @@ -287,7 +286,7 @@ public void testDetermineSupportForJGitRecursiveSubmodules() throws Exception { } @Test - public void testDetermineSupportForJGitThreads() throws Exception { + void testDetermineSupportForJGitThreads() throws Exception { GitSCM scm = new GitSCM("https://github.com/jenkinsci/git-plugin"); Integer threads = randomSmallNonNegativeIntegerOrNull(); submoduleOption.setThreads(threads); diff --git a/src/test/java/hudson/plugins/git/extensions/impl/UserExclusionTest.java b/src/test/java/hudson/plugins/git/extensions/impl/UserExclusionTest.java index d0c1dda03b..4924d5f31f 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/UserExclusionTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/UserExclusionTest.java @@ -5,22 +5,25 @@ import hudson.plugins.git.TestGitRepo; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import java.io.File; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Kanstantsin Shautsou */ -public class UserExclusionTest extends GitSCMExtensionTest{ +class UserExclusionTest extends GitSCMExtensionTest{ - FreeStyleProject project; - TestGitRepo repo; + private FreeStyleProject project; + private TestGitRepo repo; @Override - public void before() throws Exception { - repo = new TestGitRepo("repo", tmp.newFolder(), listener); + protected void before() throws Exception { + repo = new TestGitRepo("repo", newFolder(tmp, "junit"), listener); project = setupBasicProject(repo); } @@ -29,26 +32,35 @@ protected GitSCMExtension getExtension() { return new UserExclusion("Jane Doe"); } - @Test - public void test() throws Exception { + @Test + void test() throws Exception { repo.commit("repo-init", repo.johnDoe, "repo0 initial commit"); - assertTrue("scm polling should detect a change after initial commit", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "scm polling should detect a change after initial commit"); build(project, Result.SUCCESS); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); repo.commit("repo-init", repo.janeDoe, "excluded user commit"); - assertFalse("scm polling should ignore excluded user", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should ignore excluded user"); // should be enough, but let's test more build(project, Result.SUCCESS); - assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "scm polling should not detect any more changes after build"); } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/UserIdentityTest.java b/src/test/java/hudson/plugins/git/extensions/impl/UserIdentityTest.java index f702cb0874..07ff5d4d1c 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/UserIdentityTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/UserIdentityTest.java @@ -9,21 +9,25 @@ import hudson.plugins.git.extensions.GitSCMExtensionTest; import hudson.plugins.git.util.GitUtilsTest; import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.Test; import org.jvnet.hudson.test.WithoutJenkins; +import java.io.File; +import java.io.IOException; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -public class UserIdentityTest extends GitSCMExtensionTest { +class UserIdentityTest extends GitSCMExtensionTest { - TestGitRepo repo; - GitClient git; + private TestGitRepo repo; + private GitClient git; @Override - public void before() { + protected void before() { // do nothing } @@ -33,8 +37,8 @@ protected GitSCMExtension getExtension() { } @Test - public void testUserIdentity() throws Exception { - repo = new TestGitRepo("repo", tmp.newFolder(), listener); + void testUserIdentity() throws Exception { + repo = new TestGitRepo("repo", newFolder(tmp, "junit"), listener); git = Git.with(listener, GitUtilsTest.getConfigNoSystemEnvsVars()).in(repo.gitDir).getClient(); FreeStyleProject projectWithMaster = setupBasicProject(repo); @@ -48,7 +52,7 @@ public void testUserIdentity() throws Exception { @Test @WithoutJenkins - public void testGetNameAndEmail(){ + void testGetNameAndEmail(){ UserIdentity userIdentity = new UserIdentity("Jane Doe", "janeDoe@xyz.com"); assertThat("Jane Doe", is(userIdentity.getName())); @@ -57,9 +61,18 @@ public void testGetNameAndEmail(){ @Test @WithoutJenkins - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(UserIdentity.class) .usingGetClass() .verify(); } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java b/src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java index 6c18dfdc9a..86ea69f9f9 100644 --- a/src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java +++ b/src/test/java/hudson/plugins/git/extensions/impl/WipeWorkspaceTest.java @@ -7,23 +7,27 @@ import hudson.plugins.git.TestGitRepo; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionTest; + +import java.io.File; +import java.io.IOException; import java.util.List; import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.Test; import org.jvnet.hudson.test.WithoutJenkins; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; -public class WipeWorkspaceTest extends GitSCMExtensionTest { +class WipeWorkspaceTest extends GitSCMExtensionTest { - TestGitRepo repo; - GitClient git; + private TestGitRepo repo; + private GitClient git; @Override - public void before() throws Exception { + protected void before() throws Exception { // do nothing } @@ -36,8 +40,8 @@ protected GitSCMExtension getExtension() { * Test to confirm the behavior of forcing re-clone before checkout by cleaning the workspace first. **/ @Test - public void testWipeWorkspace() throws Exception { - repo = new TestGitRepo("repo", tmp.newFolder(), listener); + void testWipeWorkspace() throws Exception { + repo = new TestGitRepo("repo", newFolder(tmp, "junit"), listener); git = Git.with(listener, new EnvVars()).in(repo.gitDir).getClient(); FreeStyleProject projectWithMaster = setupBasicProject(repo); @@ -50,9 +54,18 @@ public void testWipeWorkspace() throws Exception { @Test @WithoutJenkins - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(WipeWorkspace.class) .usingGetClass() .verify(); } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/git/opt/PreBuildMergeOptionsTest.java b/src/test/java/hudson/plugins/git/opt/PreBuildMergeOptionsTest.java index 459b468860..bfceb13a82 100644 --- a/src/test/java/hudson/plugins/git/opt/PreBuildMergeOptionsTest.java +++ b/src/test/java/hudson/plugins/git/opt/PreBuildMergeOptionsTest.java @@ -31,17 +31,25 @@ import hudson.plugins.git.extensions.impl.PreBuildMerge; import java.util.Collections; import org.jenkinsci.plugins.gitclient.MergeCommand; -import org.junit.Test; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class PreBuildMergeOptionsTest { +@WithJenkins +class PreBuildMergeOptionsTest { - @Rule public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } @Issue("JENKINS-9843") - @Test public void exporting() throws Exception { + @Test + void exporting() throws Exception { FreeStyleProject p = r.createFreeStyleProject(); p.setScm(new GitSCM(Collections.singletonList(new UserRemoteConfig("http://wherever/thing.git", "repo", null, null)), null, null, null, null, null, Collections.singletonList(new PreBuildMerge(new UserMergeOptions("repo", "master", MergeCommand.Strategy.DEFAULT.name(), MergeCommand.GitPluginFastForwardMode.FF))))); r.createWebClient().goToXml(p.getUrl() + "api/xml?depth=2"); diff --git a/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java b/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java index 9197f6bb8d..a7d5cb5f72 100644 --- a/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java +++ b/src/test/java/hudson/plugins/git/security/ApiTokenPropertyConfigurationTest.java @@ -7,27 +7,29 @@ import hudson.plugins.git.ApiTokenPropertyConfiguration; import jenkins.model.Jenkins; import net.sf.json.JSONObject; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.util.Collection; import java.util.Collections; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ApiTokenPropertyConfigurationTest { +@WithJenkins +class ApiTokenPropertyConfigurationTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; - @Before - public void init() { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); MockAuthorizationStrategy authorizationStrategy = new MockAuthorizationStrategy(); authorizationStrategy.grant(Jenkins.ADMINISTER).everywhere().to("alice"); @@ -36,7 +38,7 @@ public void init() { } @Test - public void testAdminPermissionRequiredToGenerateNewApiTokens() throws Exception { + void testAdminPermissionRequiredToGenerateNewApiTokens() throws Exception { try (JenkinsRule.WebClient wc = r.createWebClient()) { wc.login("bob"); WebRequest req = new WebRequest( @@ -52,7 +54,7 @@ public void testAdminPermissionRequiredToGenerateNewApiTokens() throws Exception } @Test - public void adminPermissionsRequiredToRevokeApiTokens() throws Exception { + void adminPermissionsRequiredToRevokeApiTokens() throws Exception { try (JenkinsRule.WebClient wc = r.createWebClient()) { wc.login("bob"); WebRequest req = new WebRequest(wc.createCrumbedUrl(ApiTokenPropertyConfiguration.get().getDescriptorUrl() + "/revoke"), HttpMethod.POST); @@ -66,7 +68,7 @@ public void adminPermissionsRequiredToRevokeApiTokens() throws Exception { } @Test - public void testBasicGenerationAndRevocation() throws Exception { + void testBasicGenerationAndRevocation() throws Exception { try (JenkinsRule.WebClient wc = r.createWebClient()) { wc.login("alice"); WebRequest generateReq = new WebRequest( @@ -113,7 +115,7 @@ public void testBasicGenerationAndRevocation() throws Exception { } @Test - public void isValidApiTokenReturnsTrueIfGivenApiTokenExists() { + void isValidApiTokenReturnsTrueIfGivenApiTokenExists() { JSONObject json = ApiTokenPropertyConfiguration.get().generateApiToken("test"); assertTrue(ApiTokenPropertyConfiguration.get().isValidApiToken(json.getString("value"))); diff --git a/src/test/java/hudson/plugins/git/util/AncestryBuildChooserTest.java b/src/test/java/hudson/plugins/git/util/AncestryBuildChooserTest.java index 4c948eba76..1bc546b9a3 100644 --- a/src/test/java/hudson/plugins/git/util/AncestryBuildChooserTest.java +++ b/src/test/java/hudson/plugins/git/util/AncestryBuildChooserTest.java @@ -8,6 +8,7 @@ import hudson.plugins.git.GitSCM; import hudson.plugins.git.Revision; import hudson.plugins.git.extensions.impl.BuildChooserSetting; +import org.junit.jupiter.api.BeforeEach; import java.util.Collection; import java.util.HashSet; @@ -25,13 +26,12 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.junit.Assert.*; -import org.junit.Before; +import static org.junit.jupiter.api.Assertions.*; -public class AncestryBuildChooserTest extends AbstractGitRepository { +class AncestryBuildChooserTest extends AbstractGitRepository { private String rootCommit = null; private String ancestorCommit = null; @@ -54,8 +54,8 @@ public class AncestryBuildChooserTest extends AbstractGitRepository { * * Creates a small repository of 5 commits with different branches and ages. */ - @Before - public void setUp() throws Exception { + @BeforeEach + void beforeEach() throws Exception { Set prevBranches = stringifyBranches(testGitClient.getBranches()); testGitClient.commit("Root Commit"); @@ -157,9 +157,9 @@ private List getFilteredTestCandidates(Integer maxAgeInDays, String ance return candidateSha1s; } - + @Test - public void testFilterRevisionsNoRestriction() throws Exception { + void testFilterRevisionsNoRestriction() throws Exception { final Integer maxAgeInDays = null; final String ancestorCommitSha1 = null; @@ -170,9 +170,9 @@ public void testFilterRevisionsNoRestriction() throws Exception { assertTrue(candidateSha1s.contains(tenDaysAgoCommit)); assertTrue(candidateSha1s.contains(twentyDaysAgoCommit)); } - + @Test - public void testFilterRevisionsZeroDate() throws Exception { + void testFilterRevisionsZeroDate() throws Exception { final Integer maxAgeInDays = 0; final String ancestorCommitSha1 = null; @@ -180,9 +180,9 @@ public void testFilterRevisionsZeroDate() throws Exception { assertEquals(0, candidateSha1s.size()); } - + @Test - public void testFilterRevisionsTenDays() throws Exception { + void testFilterRevisionsTenDays() throws Exception { final Integer maxAgeInDays = 10; final String ancestorCommitSha1 = null; @@ -191,9 +191,9 @@ public void testFilterRevisionsTenDays() throws Exception { assertEquals(1, candidateSha1s.size()); assertTrue(candidateSha1s.contains(fiveDaysAgoCommit)); } - + @Test - public void testFilterRevisionsThirtyDays() throws Exception { + void testFilterRevisionsThirtyDays() throws Exception { final Integer maxAgeInDays = 30; final String ancestorCommitSha1 = null; @@ -204,9 +204,9 @@ public void testFilterRevisionsThirtyDays() throws Exception { assertTrue(candidateSha1s.contains(tenDaysAgoCommit)); assertTrue(candidateSha1s.contains(twentyDaysAgoCommit)); } - + @Test - public void testFilterRevisionsBlankAncestor() throws Exception { + void testFilterRevisionsBlankAncestor() throws Exception { final Integer maxAgeInDays = null; final String ancestorCommitSha1 = ""; @@ -217,18 +217,18 @@ public void testFilterRevisionsBlankAncestor() throws Exception { assertTrue(candidateSha1s.contains(tenDaysAgoCommit)); assertTrue(candidateSha1s.contains(twentyDaysAgoCommit)); } - + @Test - public void testFilterRevisionsNonExistingAncestor() throws Exception { + void testFilterRevisionsNonExistingAncestor() throws Exception { final Integer maxAgeInDays = null; final String ancestorCommitSha1 = "This commit sha1 does not exist."; - assertThrows("Invalid sha1 should throw GitException.", GitException.class, - () -> getFilteredTestCandidates(maxAgeInDays, ancestorCommitSha1)); + assertThrows(GitException.class, () -> getFilteredTestCandidates(maxAgeInDays, ancestorCommitSha1), + "Invalid sha1 should throw GitException."); } - + @Test - public void testFilterRevisionsExistingAncestor() throws Exception { + void testFilterRevisionsExistingAncestor() throws Exception { final Integer maxAgeInDays = null; final String ancestorCommitSha1 = ancestorCommit; diff --git a/src/test/java/hudson/plugins/git/util/BuildDataLoggingTest.java b/src/test/java/hudson/plugins/git/util/BuildDataLoggingTest.java index bff6e26a87..c0af58e23f 100644 --- a/src/test/java/hudson/plugins/git/util/BuildDataLoggingTest.java +++ b/src/test/java/hudson/plugins/git/util/BuildDataLoggingTest.java @@ -6,15 +6,16 @@ import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author Mark Waite */ -public class BuildDataLoggingTest { +class BuildDataLoggingTest { private BuildData data; @@ -23,13 +24,10 @@ public class BuildDataLoggingTest { private LogHandler handler = null; - @Before - public void createTestData() throws Exception { + @BeforeEach + void beforeEach() { data = new BuildData(); - } - @Before - public void reconfigureLogging() throws Exception { handler = new LogHandler(); handler.setLevel(Level.ALL); BuildData.LOGGER.setUseParentHandlers(false); @@ -37,8 +35,8 @@ public void reconfigureLogging() throws Exception { BuildData.LOGGER.setLevel(Level.ALL); } - @After - public void restoreLogging() throws Exception { + @AfterEach + void afterEach() throws Exception { BuildData.LOGGER.removeHandler(handler); BuildData.LOGGER.setUseParentHandlers(ORIGINAL_USE_PARENT_HANDLERS); BuildData.LOGGER.setLevel(ORIGINAL_LEVEL); @@ -46,18 +44,18 @@ public void restoreLogging() throws Exception { /* Confirm URISyntaxException is logged at FINEST on invalid URL */ @Test - public void testSimilarToInvalidHttpsRemoteURL() { + void testSimilarToInvalidHttpsRemoteURL() { final String INVALID_URL = "https://github.com/jenkinsci/git-plugin?s=^IXIC"; BuildData invalid = new BuildData(); invalid.addRemoteUrl(INVALID_URL); - assertTrue("Invalid URL not similar to itself " + INVALID_URL, invalid.similarTo(invalid)); + assertTrue(invalid.similarTo(invalid), "Invalid URL not similar to itself " + INVALID_URL); String expectedMessage = "URI syntax exception on " + INVALID_URL; assertThat(handler.checkMessage(), is(expectedMessage)); assertThat(handler.checkLevel(), is(Level.FINEST)); } - class LogHandler extends Handler { + static class LogHandler extends Handler { private Level lastLevel = Level.INFO; private String lastMessage = ""; diff --git a/src/test/java/hudson/plugins/git/util/BuildDataTest.java b/src/test/java/hudson/plugins/git/util/BuildDataTest.java index fb47137281..1938a2600f 100644 --- a/src/test/java/hudson/plugins/git/util/BuildDataTest.java +++ b/src/test/java/hudson/plugins/git/util/BuildDataTest.java @@ -12,70 +12,68 @@ import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; +import org.junit.jupiter.api.BeforeEach; + import org.eclipse.jgit.lib.ObjectId; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; /** * @author Mark Waite */ -public class BuildDataTest { +class BuildDataTest { private BuildData data; private final ObjectId sha1 = ObjectId.fromString("929e92e3adaff2e6e1d752a8168c1598890fe84c"); private final String remoteUrl = "https://github.com/jenkinsci/git-plugin"; - @Before - public void setUp() throws Exception { + @BeforeEach + void beforeEach() throws Exception { data = new BuildData(); } @Test - public void testGetDisplayName() throws Exception { + void testGetDisplayName() throws Exception { assertThat(data.getDisplayName(), is("Git Build Data")); } @Test - public void testGetDisplayNameEmptyString() throws Exception { + void testGetDisplayNameEmptyString() throws Exception { String scmName = ""; BuildData dataWithSCM = new BuildData(scmName); assertThat(dataWithSCM.getDisplayName(), is("Git Build Data")); } @Test - public void testGetDisplayNameNullSCMName() throws Exception { + void testGetDisplayNameNullSCMName() throws Exception { BuildData dataWithNullSCM = new BuildData(null); assertThat(dataWithNullSCM.getDisplayName(), is("Git Build Data")); } @Test - public void testGetDisplayNameWithSCM() throws Exception { + void testGetDisplayNameWithSCM() throws Exception { final String scmName = "testSCM"; final BuildData dataWithSCM = new BuildData(scmName); assertThat("Git Build Data:" + scmName, is(dataWithSCM.getDisplayName())); } @Test - public void testGetIconFileName() { + void testGetIconFileName() { assertEquals("symbol-git-icon plugin-git", data.getIconFileName()); } @Test - public void testGetUrlName() { + void testGetUrlName() { assertThat(data.getUrlName(), is("git")); } @Test - public void testGetUrlNameMultipleEntries() { + void testGetUrlNameMultipleEntries() { Random random = new Random(); int randomIndex = random.nextInt(1234) + 1; data.setIndex(randomIndex); @@ -83,17 +81,17 @@ public void testGetUrlNameMultipleEntries() { } @Test - public void testHasBeenBuilt() { + void testHasBeenBuilt() { assertFalse(data.hasBeenBuilt(sha1)); } @Test - public void testGetLastBuild() { + void testGetLastBuild() { assertNull(data.getLastBuild(sha1)); } @Test - public void testGetLastBuildSingleBranch() { + void testGetLastBuildSingleBranch() { String branchName = "origin/master"; Collection branches = new ArrayList<>(); Branch branch = new Branch(branchName, sha1); @@ -117,7 +115,7 @@ public void testGetLastBuildSingleBranch() { } @Test - public void testGetLastBuildMultipleBranches() { + void testGetLastBuildMultipleBranches() { String branchName = "origin/master"; Collection branches = new ArrayList<>(); @@ -144,7 +142,7 @@ public void testGetLastBuildMultipleBranches() { } @Test - public void testGetLastBuildWithNullSha1() { + void testGetLastBuildWithNullSha1() { assertThat(data.getLastBuild(null), is(nullValue())); String branchName = "origin/master"; @@ -161,7 +159,7 @@ public void testGetLastBuildWithNullSha1() { } @Test - public void testSaveBuild() { + void testSaveBuild() { Revision revision = new Revision(sha1); Build build = new Build(revision, 1, Result.SUCCESS); data.saveBuild(build); @@ -178,7 +176,7 @@ public void testSaveBuild() { } @Test - public void testGetLastBuildOfBranch() { + void testGetLastBuildOfBranch() { String branchName = "origin/master"; assertNull(data.getLastBuildOfBranch(branchName)); @@ -192,7 +190,7 @@ public void testGetLastBuildOfBranch() { } @Test - public void testGetLastBuiltRevision() { + void testGetLastBuiltRevision() { Revision revision = new Revision(sha1); Build build = new Build(revision, 1, Result.SUCCESS); data.saveBuild(build); @@ -200,36 +198,36 @@ public void testGetLastBuiltRevision() { } @Test - public void testGetBuildsByBranchName() { + void testGetBuildsByBranchName() { assertTrue(data.getBuildsByBranchName().isEmpty()); } @Test - public void testGetScmName() { + void testGetScmName() { assertThat(data.getScmName(), is("")); } @Test - public void testSetScmName() { + void testSetScmName() { final String scmName = "Some SCM name"; data.setScmName(scmName); assertThat(data.getScmName(), is(scmName)); } @Test - public void testAddRemoteUrl() { + void testAddRemoteUrl() { data.addRemoteUrl(remoteUrl); assertEquals(1, data.getRemoteUrls().size()); String remoteUrl2 = "https://github.com/jenkinsci/git-plugin.git/"; data.addRemoteUrl(remoteUrl2); assertFalse(data.getRemoteUrls().isEmpty()); - assertTrue("Second URL not found in remote URLs", data.getRemoteUrls().contains(remoteUrl2)); + assertTrue(data.getRemoteUrls().contains(remoteUrl2), "Second URL not found in remote URLs"); assertEquals(2, data.getRemoteUrls().size()); } @Test - public void testHasBeenReferenced() { + void testHasBeenReferenced() { assertFalse(data.hasBeenReferenced(remoteUrl)); data.addRemoteUrl(remoteUrl); assertTrue(data.hasBeenReferenced(remoteUrl)); @@ -237,7 +235,7 @@ public void testHasBeenReferenced() { } @Test - public void testGetApi() { + void testGetApi() { Api api = data.getApi(); Api apiClone = data.clone().getApi(); assertEquals(api, api); @@ -245,71 +243,71 @@ public void testGetApi() { } @Test - public void testToString() { + void testToString() { assertEquals(data.toString(), data.clone().toString()); } @Test - public void testToStringEmptyBuildData() { + void testToStringEmptyBuildData() { BuildData empty = new BuildData(); assertThat(empty.toString(), endsWith("[scmName=,remoteUrls=[],buildsByBranchName={},lastBuild=null]")); } @Test - public void testToStringNullSCMBuildData() { + void testToStringNullSCMBuildData() { BuildData nullSCM = new BuildData(null); assertThat(nullSCM.toString(), endsWith("[scmName=,remoteUrls=[],buildsByBranchName={},lastBuild=null]")); } @Test - public void testToStringNonNullSCMBuildData() { + void testToStringNonNullSCMBuildData() { BuildData nonNullSCM = new BuildData("gitless"); assertThat(nonNullSCM.toString(), endsWith("[scmName=gitless,remoteUrls=[],buildsByBranchName={},lastBuild=null]")); } @Test - public void testEquals() { + void testEquals() { // Null object not equal non-null BuildData nullData = null; - assertNotEquals("Null object not equal non-null", data, nullData); + assertNotEquals(nullData, data, "Null object not equal non-null"); // Object should equal itself - assertEquals("Object not equal itself", data, data); - assertEquals("Object not equal itself", data, data); - assertEquals("Object hashCode not equal itself", data.hashCode(), data.hashCode()); + assertEquals(data, data, "Object not equal itself"); + assertEquals(data, data, "Object not equal itself"); + assertEquals(data.hashCode(), data.hashCode(), "Object hashCode not equal itself"); // Cloned object equals original object BuildData data1 = data.clone(); - assertEquals("Cloned objects not equal", data1, data); - assertEquals("Cloned objects not equal", data1, data); - assertEquals("Cloned objects not equal", data, data1); - assertEquals("Cloned object hashCodes not equal", data.hashCode(), data1.hashCode()); + assertEquals(data1, data, "Cloned objects not equal"); + assertEquals(data1, data, "Cloned objects not equal"); + assertEquals(data, data1, "Cloned objects not equal"); + assertEquals(data.hashCode(), data1.hashCode(), "Cloned object hashCodes not equal"); // Saved build makes object unequal Revision revision1 = new Revision(sha1); Build build1 = new Build(revision1, 1, Result.SUCCESS); data1.saveBuild(build1); - assertNotEquals("Distinct objects shouldn't be equal", data, data1); - assertNotEquals("Distinct objects shouldn't be equal", data1, data); + assertNotEquals(data, data1, "Distinct objects shouldn't be equal"); + assertNotEquals(data1, data, "Distinct objects shouldn't be equal"); // Same saved build makes objects equal BuildData data2 = data.clone(); data2.saveBuild(build1); - assertEquals("Objects with same saved build not equal", data2, data1); - assertEquals("Objects with same saved build not equal", data1, data2); - assertEquals("Objects with same saved build not equal hashCodes", data2.hashCode(), data1.hashCode()); + assertEquals(data2, data1, "Objects with same saved build not equal"); + assertEquals(data1, data2, "Objects with same saved build not equal"); + assertEquals(data2.hashCode(), data1.hashCode(), "Objects with same saved build not equal hashCodes"); // Add remote URL makes objects unequal final String remoteUrl2 = "git@github.com:jenkinsci/git-plugin.git"; data1.addRemoteUrl(remoteUrl2); - assertNotEquals("Distinct objects shouldn't be equal", data, data1); - assertNotEquals("Distinct objects shouldn't be equal", data1, data); + assertNotEquals(data, data1, "Distinct objects shouldn't be equal"); + assertNotEquals(data1, data, "Distinct objects shouldn't be equal"); // Add same remote URL makes objects equal data2.addRemoteUrl(remoteUrl2); - assertEquals("Objects with same remote URL not equal", data2, data1); - assertEquals("Objects with same remote URL not equal", data1, data2); - assertEquals("Objects with same remote URL not equal hashCodes", data2.hashCode(), data1.hashCode()); + assertEquals(data2, data1, "Objects with same remote URL not equal"); + assertEquals(data1, data2, "Objects with same remote URL not equal"); + assertEquals(data2.hashCode(), data1.hashCode(), "Objects with same remote URL not equal hashCodes"); // Another saved build still keeps objects equal String branchName = "origin/master"; @@ -341,12 +339,12 @@ public void testEquals() { BuildData emptyData = new BuildData(); emptyData.remoteUrls = null; - assertNotEquals("Non-empty object equal empty", data, emptyData); - assertNotEquals("Empty object similar to non-empty", emptyData, data); + assertNotEquals(data, emptyData, "Non-empty object equal empty"); + assertNotEquals(emptyData, data, "Empty object similar to non-empty"); } @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(BuildData.class) .usingGetClass() .suppress(Warning.NONFINAL_FIELDS) @@ -355,7 +353,7 @@ public void equalsContract() { } @Test - public void testSetIndex() { + void testSetIndex() { data.setIndex(null); assertNull(data.getIndex()); data.setIndex(-1); @@ -369,7 +367,7 @@ public void testSetIndex() { } @Test - public void testSimilarToHttpsRemoteURL() { + void testSimilarToHttpsRemoteURL() { final String SIMPLE_URL = "https://github.com/jenkinsci/git-plugin"; BuildData simple = new BuildData("git-" + SIMPLE_URL); simple.addRemoteUrl(SIMPLE_URL); @@ -377,7 +375,7 @@ public void testSimilarToHttpsRemoteURL() { } @Test - public void testSimilarToScpRemoteURL() { + void testSimilarToScpRemoteURL() { final String SIMPLE_URL = "git@github.com:jenkinsci/git-plugin"; BuildData simple = new BuildData("git-" + SIMPLE_URL); simple.addRemoteUrl(SIMPLE_URL); @@ -385,7 +383,7 @@ public void testSimilarToScpRemoteURL() { } @Test - public void testSimilarToSshRemoteURL() { + void testSimilarToSshRemoteURL() { final String SIMPLE_URL = "ssh://git@github.com/jenkinsci/git-plugin"; BuildData simple = new BuildData("git-" + SIMPLE_URL); simple.addRemoteUrl(SIMPLE_URL); @@ -396,37 +394,37 @@ private void permuteBaseURL(String simpleURL, BuildData simple) { final String TRAILING_SLASH_URL = simpleURL + "/"; BuildData trailingSlash = new BuildData("git-" + TRAILING_SLASH_URL); trailingSlash.addRemoteUrl(TRAILING_SLASH_URL); - assertTrue("Trailing slash not similar to simple URL " + TRAILING_SLASH_URL, - trailingSlash.similarTo(simple)); + assertTrue(trailingSlash.similarTo(simple), + "Trailing slash not similar to simple URL " + TRAILING_SLASH_URL); final String TRAILING_SLASHES_URL = TRAILING_SLASH_URL + "//"; BuildData trailingSlashes = new BuildData("git-" + TRAILING_SLASHES_URL); trailingSlashes.addRemoteUrl(TRAILING_SLASHES_URL); - assertTrue("Trailing slashes not similar to simple URL " + TRAILING_SLASHES_URL, - trailingSlashes.similarTo(simple)); + assertTrue(trailingSlashes.similarTo(simple), + "Trailing slashes not similar to simple URL " + TRAILING_SLASHES_URL); final String DOT_GIT_URL = simpleURL + ".git"; BuildData dotGit = new BuildData("git-" + DOT_GIT_URL); dotGit.addRemoteUrl(DOT_GIT_URL); - assertTrue("Dot git not similar to simple URL " + DOT_GIT_URL, - dotGit.similarTo(simple)); + assertTrue(dotGit.similarTo(simple), + "Dot git not similar to simple URL " + DOT_GIT_URL); final String DOT_GIT_TRAILING_SLASH_URL = DOT_GIT_URL + "/"; BuildData dotGitTrailingSlash = new BuildData("git-" + DOT_GIT_TRAILING_SLASH_URL); dotGitTrailingSlash.addRemoteUrl(DOT_GIT_TRAILING_SLASH_URL); - assertTrue("Dot git trailing slash not similar to dot git URL " + DOT_GIT_TRAILING_SLASH_URL, - dotGitTrailingSlash.similarTo(dotGit)); + assertTrue(dotGitTrailingSlash.similarTo(dotGit), + "Dot git trailing slash not similar to dot git URL " + DOT_GIT_TRAILING_SLASH_URL); final String DOT_GIT_TRAILING_SLASHES_URL = DOT_GIT_TRAILING_SLASH_URL + "///"; BuildData dotGitTrailingSlashes = new BuildData("git-" + DOT_GIT_TRAILING_SLASHES_URL); dotGitTrailingSlashes.addRemoteUrl(DOT_GIT_TRAILING_SLASHES_URL); - assertTrue("Dot git trailing slashes not similar to dot git URL " + DOT_GIT_TRAILING_SLASHES_URL, - dotGitTrailingSlashes.similarTo(dotGit)); + assertTrue(dotGitTrailingSlashes.similarTo(dotGit), + "Dot git trailing slashes not similar to dot git URL " + DOT_GIT_TRAILING_SLASHES_URL); } @Test @Issue("JENKINS-43630") - public void testSimilarToContainsNullURL() { + void testSimilarToContainsNullURL() { final String SIMPLE_URL = "ssh://git@github.com/jenkinsci/git-plugin"; BuildData simple = new BuildData("git-" + SIMPLE_URL); simple.addRemoteUrl(SIMPLE_URL); @@ -444,98 +442,98 @@ public void testSimilarToContainsNullURL() { } @Test - public void testGetIndex() { + void testGetIndex() { assertNull(data.getIndex()); } @Test - public void testGetRemoteUrls() { + void testGetRemoteUrls() { assertTrue(data.getRemoteUrls().isEmpty()); } @Test - public void testClone() { + void testClone() { // Tested in testSimilarTo and testEquals } @Test - public void testSimilarTo() { + void testSimilarTo() { data.addRemoteUrl(remoteUrl); // Null object not similar to non-null BuildData dataNull = null; - assertFalse("Null object similar to non-null", data.similarTo(dataNull)); + assertFalse(data.similarTo(dataNull), "Null object similar to non-null"); BuildData emptyData = new BuildData(); - assertFalse("Non-empty object similar to empty", data.similarTo(emptyData)); - assertFalse("Empty object similar to non-empty", emptyData.similarTo(data)); + assertFalse(data.similarTo(emptyData), "Non-empty object similar to empty"); + assertFalse(emptyData.similarTo(data), "Empty object similar to non-empty"); emptyData.remoteUrls = null; - assertFalse("Non-empty object similar to empty", data.similarTo(emptyData)); - assertFalse("Empty object similar to non-empty", emptyData.similarTo(data)); + assertFalse(data.similarTo(emptyData), "Non-empty object similar to empty"); + assertFalse(emptyData.similarTo(data), "Empty object similar to non-empty"); // Object should be similar to itself - assertTrue("Object not similar to itself", data.similarTo(data)); + assertTrue(data.similarTo(data), "Object not similar to itself"); // Object should not be similar to constructed variants Collection emptyList = new ArrayList<>(); - assertFalse("Object similar to data with SCM name", data.similarTo(new BuildData("abc"))); - assertFalse("Object similar to data with SCM name & empty", data.similarTo(new BuildData("abc", emptyList))); + assertFalse(data.similarTo(new BuildData("abc")), "Object similar to data with SCM name"); + assertFalse(data.similarTo(new BuildData("abc", emptyList)), "Object similar to data with SCM name & empty"); BuildData dataSCM = new BuildData("scm"); - assertFalse("Object similar to data with SCM name", dataSCM.similarTo(data)); - assertTrue("Object with SCM name not similar to data with SCM name", dataSCM.similarTo(new BuildData("abc"))); - assertTrue("Object with SCM name not similar to data with SCM name & empty", dataSCM.similarTo(new BuildData("abc", emptyList))); + assertFalse(dataSCM.similarTo(data), "Object similar to data with SCM name"); + assertTrue(dataSCM.similarTo(new BuildData("abc")), "Object with SCM name not similar to data with SCM name"); + assertTrue(dataSCM.similarTo(new BuildData("abc", emptyList)), "Object with SCM name not similar to data with SCM name & empty"); // Cloned object equals original object BuildData dataClone = data.clone(); - assertTrue("Clone not similar to origin", dataClone.similarTo(data)); - assertTrue("Origin not similar to clone", data.similarTo(dataClone)); + assertTrue(dataClone.similarTo(data), "Clone not similar to origin"); + assertTrue(data.similarTo(dataClone), "Origin not similar to clone"); // Saved build makes objects dissimilar Revision revision1 = new Revision(sha1); Build build1 = new Build(revision1, 1, Result.SUCCESS); dataClone.saveBuild(build1); - assertFalse("Unmodified origin similar to modified clone", data.similarTo(dataClone)); - assertFalse("Modified clone similar to unmodified origin", dataClone.similarTo(data)); - assertTrue("Modified clone not similar to itself", dataClone.similarTo(dataClone)); + assertFalse(data.similarTo(dataClone), "Unmodified origin similar to modified clone"); + assertFalse(dataClone.similarTo(data), "Modified clone similar to unmodified origin"); + assertTrue(dataClone.similarTo(dataClone), "Modified clone not similar to itself"); // Same saved build makes objects similar BuildData data2 = data.clone(); data2.saveBuild(build1); - assertFalse("Unmodified origin similar to modified clone", data.similarTo(data2)); - assertTrue("Objects with same saved build not similar (1)", data2.similarTo(dataClone)); - assertTrue("Objects with same saved build not similar (2)", dataClone.similarTo(data2)); + assertFalse(data.similarTo(data2), "Unmodified origin similar to modified clone"); + assertTrue(data2.similarTo(dataClone), "Objects with same saved build not similar (1)"); + assertTrue(dataClone.similarTo(data2), "Objects with same saved build not similar (2)"); // Add remote URL makes objects dissimilar final String remoteUrl = "https://github.com/jenkinsci/git-client-plugin.git"; dataClone.addRemoteUrl(remoteUrl); - assertFalse("Distinct objects shouldn't be similar (1)", data.similarTo(dataClone)); - assertFalse("Distinct objects shouldn't be similar (2)", dataClone.similarTo(data)); + assertFalse(data.similarTo(dataClone), "Distinct objects shouldn't be similar (1)"); + assertFalse(dataClone.similarTo(data), "Distinct objects shouldn't be similar (2)"); // Add same remote URL makes objects similar data2.addRemoteUrl(remoteUrl); - assertTrue("Objects with same remote URL dissimilar", data2.similarTo(dataClone)); - assertTrue("Objects with same remote URL dissimilar", dataClone.similarTo(data2)); + assertTrue(data2.similarTo(dataClone), "Objects with same remote URL dissimilar"); + assertTrue(dataClone.similarTo(data2), "Objects with same remote URL dissimilar"); // Add different remote URL objects similar final String trailingSlash = "git-client-plugin.git/"; // Unlikely as remote URL dataClone.addRemoteUrl(trailingSlash); - assertFalse("Distinct objects shouldn't be similar", data.similarTo(dataClone)); - assertFalse("Distinct objects shouldn't be similar", dataClone.similarTo(data)); + assertFalse(data.similarTo(dataClone), "Distinct objects shouldn't be similar"); + assertFalse(dataClone.similarTo(data), "Distinct objects shouldn't be similar"); data2.addRemoteUrl(trailingSlash); - assertTrue("Objects with same remote URL dissimilar", data2.similarTo(dataClone)); - assertTrue("Objects with same remote URL dissimilar", dataClone.similarTo(data2)); + assertTrue(data2.similarTo(dataClone), "Objects with same remote URL dissimilar"); + assertTrue(dataClone.similarTo(data2), "Objects with same remote URL dissimilar"); // Add different remote URL objects final String noSlash = "git-client-plugin"; // Unlikely as remote URL dataClone.addRemoteUrl(noSlash); - assertFalse("Distinct objects shouldn't be similar", data.similarTo(dataClone)); - assertFalse("Distinct objects shouldn't be similar", dataClone.similarTo(data)); + assertFalse(data.similarTo(dataClone), "Distinct objects shouldn't be similar"); + assertFalse(dataClone.similarTo(data), "Distinct objects shouldn't be similar"); data2.addRemoteUrl(noSlash); - assertTrue("Objects with same remote URL dissimilar", data2.similarTo(dataClone)); - assertTrue("Objects with same remote URL dissimilar", dataClone.similarTo(data2)); + assertTrue(data2.similarTo(dataClone), "Objects with same remote URL dissimilar"); + assertTrue(dataClone.similarTo(data2), "Objects with same remote URL dissimilar"); // Another saved build still keeps objects similar String branchName = "origin/master"; @@ -545,19 +543,19 @@ public void testSimilarTo() { Revision revision2 = new Revision(sha1, branches); Build build2 = new Build(revision2, 1, Result.FAILURE); dataClone.saveBuild(build2); - assertTrue("Another saved build, still similar (1)", dataClone.similarTo(data2)); - assertTrue("Another saved build, still similar (2)", data2.similarTo(dataClone)); + assertTrue(dataClone.similarTo(data2), "Another saved build, still similar (1)"); + assertTrue(data2.similarTo(dataClone), "Another saved build, still similar (2)"); data2.saveBuild(build2); - assertTrue("Another saved build, still similar (3)", dataClone.similarTo(data2)); - assertTrue("Another saved build, still similar (4)", data2.similarTo(dataClone)); + assertTrue(dataClone.similarTo(data2), "Another saved build, still similar (3)"); + assertTrue(data2.similarTo(dataClone), "Another saved build, still similar (4)"); // Saving different build results still similar BuildData dataClone.saveBuild(build1); - assertTrue("Saved build with different results, similar (5)", dataClone.similarTo(data2)); - assertTrue("Saved build with different results, similar (6)", data2.similarTo(dataClone)); + assertTrue(dataClone.similarTo(data2), "Saved build with different results, similar (5)"); + assertTrue(data2.similarTo(dataClone), "Saved build with different results, similar (6)"); data2.saveBuild(build2); - assertTrue("Saved build with different results, similar (7)", dataClone.similarTo(data2)); - assertTrue("Saved build with different results, similar (8)", data2.similarTo(dataClone)); + assertTrue(dataClone.similarTo(data2), "Saved build with different results, similar (7)"); + assertTrue(data2.similarTo(dataClone), "Saved build with different results, similar (8)"); // Set SCM name doesn't change similarity dataClone.setScmName("scm 1"); @@ -567,12 +565,12 @@ public void testSimilarTo() { } @Test - public void testHashCode() { + void testHashCode() { // Tested in testEquals } @Test - public void testHashCodeEmptyData() { + void testHashCodeEmptyData() { BuildData emptyData = new BuildData(); assertEquals(emptyData.hashCode(), emptyData.hashCode()); emptyData.remoteUrls = null; diff --git a/src/test/java/hudson/plugins/git/util/BuildTest.java b/src/test/java/hudson/plugins/git/util/BuildTest.java index 73c580da96..2b23270d68 100644 --- a/src/test/java/hudson/plugins/git/util/BuildTest.java +++ b/src/test/java/hudson/plugins/git/util/BuildTest.java @@ -4,13 +4,14 @@ import hudson.plugins.git.Revision; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; +import org.junit.jupiter.api.Test; + import org.eclipse.jgit.lib.ObjectId; -import org.junit.Test; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -public class BuildTest { +class BuildTest { private final int BUILD_NUMBER = 1; private final Result BUILD_RESULT = Result.NOT_BUILT; @@ -29,75 +30,75 @@ public class BuildTest { private final Build markedBuild = new Build(markedRevision, revision, BUILD_NUMBER, BUILD_RESULT); @Test - public void testGetSHA1() { + void testGetSHA1() { assertThat(build.getSHA1(), is(revision.getSha1())); } @Test - public void testGetRevision() { + void testGetRevision() { assertThat(build.getRevision(), is(revision)); } @Test - public void testGetMarked() { + void testGetMarked() { assertThat(build.getMarked(), is(revision)); } @Test - public void testGetMarkedDifferentRevision() { + void testGetMarkedDifferentRevision() { assertThat(markedBuild.getMarked(), is(markedRevision)); } @Test - public void testGetBuildNumber() { + void testGetBuildNumber() { assertThat(build.getBuildNumber(), is(BUILD_NUMBER)); } @Test - public void testGetBuildResult() { + void testGetBuildResult() { assertThat(build.getBuildResult(), is(BUILD_RESULT)); } @Test - public void testToString() { + void testToString() { assertThat(build.toString(), is("Build #" + BUILD_NUMBER + " of Revision " + revision.getSha1String() + " ()")); } @Test - public void testClone() { + void testClone() { Build clonedBuild = build.clone(); assertThat(clonedBuild.getSHA1(), is(build.getSHA1())); } @Test - public void testCloneNullRevision() { + void testCloneNullRevision() { Build clonedBuild = nullRevisionBuild.clone(); assertThat(clonedBuild.getRevision(), is(nullValue())); } @Test - public void testIsFor() { + void testIsFor() { assertThat(build.isFor(revision.getSha1String()), is(true)); } @Test - public void testIsForMarkedRevision() { + void testIsForMarkedRevision() { assertThat(markedBuild.isFor(revision.getSha1String()), is(true)); assertThat(markedBuild.isFor(markedRevision.getSha1String()), is(false)); } @Test - public void testIsForNullRevision() { + void testIsForNullRevision() { assertThat(nullRevisionBuild.isFor(revision.getSha1String()), is(false)); } @Test - public void testReadResolve() throws Exception { + void testReadResolve() throws Exception { assertThat(build.readResolve(), is(instanceOf(build.getClass()))); } @Test - public void testReadResolveNullRevision() throws Exception { + void testReadResolveNullRevision() throws Exception { Object readObject = nullRevisionBuild.readResolve(); assertThat(readObject, is(instanceOf(build.getClass()))); Build readBuild = (Build) readObject; @@ -106,7 +107,7 @@ public void testReadResolveNullRevision() throws Exception { } @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(Build.class) .usingGetClass() .suppress(Warning.NONFINAL_FIELDS) diff --git a/src/test/java/hudson/plugins/git/util/CandidateRevisionsTest.java b/src/test/java/hudson/plugins/git/util/CandidateRevisionsTest.java index fa66a703ce..f807b8f975 100644 --- a/src/test/java/hudson/plugins/git/util/CandidateRevisionsTest.java +++ b/src/test/java/hudson/plugins/git/util/CandidateRevisionsTest.java @@ -10,27 +10,31 @@ import java.util.Collection; import java.util.Collections; import java.util.Random; + +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.transport.RefSpec; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import jenkins.plugins.git.GitSampleRepoRule; import org.mockito.Mockito; -public class CandidateRevisionsTest extends AbstractGitRepository { +@WithGitSampleRepo +class CandidateRevisionsTest extends AbstractGitRepository { private File testGitDir2; private GitClient testGitClient2; - @Rule - public GitSampleRepoRule testGitRepo2 = new GitSampleRepoRule(); + private GitSampleRepoRule testGitRepo2; - @Before - public void createSecondGitRepository() throws Exception { + @BeforeEach + void setUp(GitSampleRepoRule repo) throws Exception { + testGitRepo2 = repo; testGitRepo2.init(); testGitDir2 = testGitRepo2.getRoot(); TaskListener listener = StreamTaskListener.fromStderr(); @@ -62,7 +66,7 @@ public void createSecondGitRepository() throws Exception { * revisions would also include the master branch. */ @Test - public void testChooseWithMultipleTag() throws Exception { + void testChooseWithMultipleTag() throws Exception { commitNewFile("file-1-in-repo-1"); ObjectId commit1 = testGitClient.revParse("HEAD"); assertEquals(commit1, testGitClient.revParse("master")); @@ -111,14 +115,6 @@ public void testChooseWithMultipleTag() throws Exception { Collection candidateRevisions = buildChooser.getCandidateRevisions(false, "tag/*", testGitClient2, null, buildData, context); assertEquals(1, candidateRevisions.size()); String name = candidateRevisions.iterator().next().getBranches().iterator().next().getName(); - assertTrue("Expected .*/tags/b or .*/tags/c, was '" + name + "'", name.matches("(origin|refs)/tags/tag/[bc]")); - } - - /** - * Inline ${@link hudson.Functions#isWindows()} to prevent a transient - * remote classloader issue. - */ - private boolean isWindows() { - return File.pathSeparatorChar == ';'; + assertTrue(name.matches("(origin|refs)/tags/tag/[bc]"), "Expected .*/tags/b or .*/tags/c, was '" + name + "'"); } } diff --git a/src/test/java/hudson/plugins/git/util/CommitTimeComparatorTest.java b/src/test/java/hudson/plugins/git/util/CommitTimeComparatorTest.java index 1f421cb89e..38c66e71f7 100644 --- a/src/test/java/hudson/plugins/git/util/CommitTimeComparatorTest.java +++ b/src/test/java/hudson/plugins/git/util/CommitTimeComparatorTest.java @@ -3,22 +3,22 @@ import hudson.plugins.git.AbstractGitRepository; import hudson.plugins.git.Branch; import hudson.plugins.git.Revision; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Kohsuke Kawaguchi */ -public class CommitTimeComparatorTest extends AbstractGitRepository { +class CommitTimeComparatorTest extends AbstractGitRepository { @Test - public void testSort_OrderIsOldToNew() throws Exception { + void testSort_OrderIsOldToNew() throws Exception { boolean first = true; // create repository with three commits for (int i=0; i<3; i++) { diff --git a/src/test/java/hudson/plugins/git/util/DefaultBuildChooserTest.java b/src/test/java/hudson/plugins/git/util/DefaultBuildChooserTest.java index a1bbf8d65a..53c7c07cde 100644 --- a/src/test/java/hudson/plugins/git/util/DefaultBuildChooserTest.java +++ b/src/test/java/hudson/plugins/git/util/DefaultBuildChooserTest.java @@ -7,20 +7,23 @@ import hudson.plugins.git.GitSCM; import hudson.plugins.git.Revision; +import org.junit.jupiter.api.Test; + import org.eclipse.jgit.lib.ObjectId; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.jvnet.hudson.test.Issue; /** * @author Arnout Engelen */ -public class DefaultBuildChooserTest extends AbstractGitRepository { +class DefaultBuildChooserTest extends AbstractGitRepository { + @Test - public void testChooseGitRevisionToBuildByShaHash() throws Exception { + void testChooseGitRevisionToBuildByShaHash() throws Exception { testGitClient.commit("Commit 1"); String shaHashCommit1 = testGitClient.getBranches().iterator().next().getSHA1String(); testGitClient.commit("Commit 2"); @@ -40,7 +43,7 @@ public void testChooseGitRevisionToBuildByShaHash() throws Exception { /* RegExp patterns prefixed with : should pass through to DefaultBuildChooser.getAdvancedCandidateRevisions */ @Test - public void testIsAdvancedSpec() throws Exception { + void testIsAdvancedSpec() throws Exception { DefaultBuildChooser buildChooser = (DefaultBuildChooser) new GitSCM("foo").getBuildChooser(); assertFalse(buildChooser.isAdvancedSpec("origin/master")); @@ -54,7 +57,7 @@ public void testIsAdvancedSpec() throws Exception { /* always failed before fix */ @Issue("JENKINS-37263") @Test - public void testPreferRemoteBranchInCandidateRevisionsWithWrongOrderInHashSet() throws Exception { + void testPreferRemoteBranchInCandidateRevisionsWithWrongOrderInHashSet() throws Exception { String branchName = "feature/42"; String localRef = "refs/heads/" + branchName; String remoteRef = "refs/remotes/origin/" + branchName; @@ -73,7 +76,7 @@ public void testPreferRemoteBranchInCandidateRevisionsWithWrongOrderInHashSet() /* was successful also before fix */ @Issue("JENKINS-37263") @Test - public void testPreferRemoteBranchInCandidateRevisionsWithCorrectOrderInHashSet() throws Exception { + void testPreferRemoteBranchInCandidateRevisionsWithCorrectOrderInHashSet() throws Exception { String branchName = "feature/42"; String localRef = "refs/heads/" + branchName; String remoteRef = "refs/remotes/origin/" + branchName; @@ -92,7 +95,7 @@ public void testPreferRemoteBranchInCandidateRevisionsWithCorrectOrderInHashSet( /* was successful also before fix */ @Issue("JENKINS-37263") @Test - public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommit() throws Exception { + void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommit() throws Exception { String branchName = "feature/42"; String localRef = "refs/heads/" + branchName; String remoteRef = "refs/remotes/origin/" + branchName; @@ -109,7 +112,7 @@ public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommit() thro /* was successful also before fix */ @Issue("JENKINS-37263") @Test - public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithOriginPrefix() throws Exception { + void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithOriginPrefix() throws Exception { String baseBranchName = "feature/42"; String branchName = "origin/" + baseBranchName; String localRef = "refs/heads/" + baseBranchName; @@ -126,7 +129,7 @@ public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithOri /* was successful also before fix */ @Issue("JENKINS-37263") @Test - public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithRemotesOriginPrefix() throws Exception { + void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithRemotesOriginPrefix() throws Exception { String baseBranchName = "feature/42"; String branchName = "remotes/origin/" + baseBranchName; String localRef = "refs/heads/" + baseBranchName; @@ -143,7 +146,7 @@ public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithRem /* was successful also before fix */ @Issue("JENKINS-37263") @Test - public void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithRefsHeadsPrefix() throws Exception { + void testSingleCandidateRevisionWithLocalAndRemoteRefsOnSameCommitWithRefsHeadsPrefix() throws Exception { String baseBranchName = "feature/42"; String branchName = "refs/heads/" + baseBranchName; String localRef = "refs/heads/" + baseBranchName; diff --git a/src/test/java/hudson/plugins/git/util/GitUtilsJenkinsRuleTest.java b/src/test/java/hudson/plugins/git/util/GitUtilsJenkinsRuleTest.java index e58b3b031a..6ff7adac1a 100644 --- a/src/test/java/hudson/plugins/git/util/GitUtilsJenkinsRuleTest.java +++ b/src/test/java/hudson/plugins/git/util/GitUtilsJenkinsRuleTest.java @@ -36,17 +36,24 @@ import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import org.junit.ClassRule; -import org.junit.Test; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +@WithJenkins +class GitUtilsJenkinsRuleTest { -public class GitUtilsJenkinsRuleTest { + private static JenkinsRule r; - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; + } @Test - public void testWorkspaceToNode() throws Exception { + void testWorkspaceToNode() throws Exception { String labelString = "label-" + UUID.randomUUID(); Label label = new LabelAtom(labelString); DumbSlave agent = r.createOnlineSlave(label); @@ -58,17 +65,17 @@ public void testWorkspaceToNode() throws Exception { } @Test - public void testWorkspaceToNodeRootPath() { + void testWorkspaceToNodeRootPath() { assertThat(GitUtils.workspaceToNode(r.getInstance().getRootPath()), is(r.getInstance())); } @Test - public void testWorkspaceToNodeNullWorkspace() { + void testWorkspaceToNodeNullWorkspace() { assertThat(GitUtils.workspaceToNode(null), is(r.getInstance())); } @Test - public void testResolveGitTool() { + void testResolveGitTool() { TaskListener listener = StreamTaskListener.NULL; String gitTool = "Default"; GitTool tool = GitUtils.resolveGitTool(gitTool, listener); @@ -76,7 +83,7 @@ public void testResolveGitTool() { } @Test - public void testResolveGitToolNull() { + void testResolveGitToolNull() { TaskListener listener = StreamTaskListener.NULL; String gitTool = null; GitTool tool = GitUtils.resolveGitTool(gitTool, listener); @@ -84,7 +91,7 @@ public void testResolveGitToolNull() { } @Test - public void testResolveGitToolNonExistentTool() { + void testResolveGitToolNonExistentTool() { TaskListener listener = StreamTaskListener.NULL; String gitTool = "non-existent-tool"; GitTool tool = GitUtils.resolveGitTool(gitTool, listener); @@ -92,7 +99,7 @@ public void testResolveGitToolNonExistentTool() { } @Test - public void testResolveGitToolBuiltOnNull() { + void testResolveGitToolBuiltOnNull() { TaskListener listener = StreamTaskListener.NULL; String gitTool = null; Node builtOn = null; @@ -102,7 +109,7 @@ public void testResolveGitToolBuiltOnNull() { } @Test - public void testResolveGitToolBuiltOnAgent() throws Exception { + void testResolveGitToolBuiltOnAgent() throws Exception { TaskListener listener = StreamTaskListener.NULL; String gitTool = "/opt/my-non-existing-git/bin/git"; String labelString = "label-" + UUID.randomUUID(); diff --git a/src/test/java/hudson/plugins/git/util/GitUtilsTest.java b/src/test/java/hudson/plugins/git/util/GitUtilsTest.java index 5e793eeb13..11371db9f5 100644 --- a/src/test/java/hudson/plugins/git/util/GitUtilsTest.java +++ b/src/test/java/hudson/plugins/git/util/GitUtilsTest.java @@ -31,6 +31,7 @@ import hudson.plugins.git.Revision; import hudson.util.StreamTaskListener; import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -38,6 +39,7 @@ import java.util.Random; import java.util.Set; import jenkins.plugins.git.GitSampleRepoRule; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.eclipse.jgit.lib.ObjectId; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; @@ -45,19 +47,19 @@ import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import static org.hamcrest.MatcherAssert.assertThat; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +@WithGitSampleRepo public class GitUtilsTest { - @ClassRule - public static GitSampleRepoRule originRepo = new GitSampleRepoRule(); + private static GitSampleRepoRule originRepo; - @ClassRule - public static TemporaryFolder repoParentFolder = new TemporaryFolder(); + @TempDir + private static File repoParentFolder; private static final String[] HEAD_BRANCH_NAMES = { "master", @@ -100,8 +102,10 @@ public class GitUtilsTest { private static final Random RANDOM = new Random(); - @BeforeClass - public static void createSampleOriginRepo() throws Exception { + @BeforeAll + static void beforeAll(GitSampleRepoRule repo) throws Exception { + originRepo = repo; + String fileName = "README"; originRepo.init(); originRepo.git("config", "user.name", "Author User Name"); @@ -154,62 +158,62 @@ public static void createSampleOriginRepo() throws Exception { originRepo.git("checkout", "master"); // Master branch as current branch in origin repo headRevision = new Revision(headId, branchList); - File gitDir = repoParentFolder.newFolder("test-repo"); + File gitDir = newFolder(repoParentFolder, "test-repo"); gitClient = Git.with(NULL_LISTENER, ENV).in(gitDir).using("git").getClient(); gitClient.init(); gitClient.clone_().url(originRepo.fileUrl()).repositoryName("origin").execute(); gitClient.checkout("origin/master", "master"); } - @Before - public void createGitUtils() throws Exception { + @BeforeEach + void beforeEach() throws Exception { gitUtils = new GitUtils(NULL_LISTENER, gitClient); } @Test - public void testSortBranchesForRevision_Revision_List() { + void testSortBranchesForRevision_Revision_List() { Revision result = gitUtils.sortBranchesForRevision(headRevision, branchSpecList); assertThat(result, is(headRevision)); } @Test - public void testSortBranchesForRevision_Revision_List_Prior() { + void testSortBranchesForRevision_Revision_List_Prior() { Revision result = gitUtils.sortBranchesForRevision(priorRevision, priorBranchSpecList); assertThat(result, is(priorRevision)); } @Test - public void testSortBranchesForRevision_Revision_List_Mix_1() { + void testSortBranchesForRevision_Revision_List_Mix_1() { Revision result = gitUtils.sortBranchesForRevision(headRevision, priorBranchSpecList); assertThat(result, is(headRevision)); } @Test - public void testSortBranchesForRevision_Revision_List_Mix_2() { + void testSortBranchesForRevision_Revision_List_Mix_2() { Revision result = gitUtils.sortBranchesForRevision(priorRevision, branchSpecList); assertThat(result, is(priorRevision)); } @Test - public void testSortBranchesForRevision_Revision_List_Prior_3_args() { + void testSortBranchesForRevision_Revision_List_Prior_3_args() { Revision result = gitUtils.sortBranchesForRevision(headRevision, branchSpecList, ENV); assertThat(result, is(headRevision)); } @Test - public void testSortBranchesForRevision_3args() { + void testSortBranchesForRevision_3args() { Revision result = gitUtils.sortBranchesForRevision(headRevision, branchSpecList, ENV); assertThat(result, is(headRevision)); } @Test - public void testSortBranchesForRevision_3args_Prior() { + void testSortBranchesForRevision_3args_Prior() { Revision result = gitUtils.sortBranchesForRevision(priorRevision, branchSpecList, ENV); assertThat(result, is(priorRevision)); } @Test - public void testGetRevisionContainingBranch() throws Exception { + void testGetRevisionContainingBranch() throws Exception { for (String branchName : HEAD_BRANCH_NAMES) { Revision revision = gitUtils.getRevisionContainingBranch("origin/" + branchName); assertThat(revision, is(headRevision)); @@ -217,72 +221,72 @@ public void testGetRevisionContainingBranch() throws Exception { } @Test - public void testGetRevisionContainingBranch_OlderName() throws Exception { + void testGetRevisionContainingBranch_OlderName() throws Exception { Revision revision = gitUtils.getRevisionContainingBranch("origin/" + OLDER_BRANCH_NAME); assertThat(revision, is(priorRevision)); } /* Tags are searched in getRevisionContainingBranch beginning with 3.2.0 */ @Test - public void testGetRevisionContainingBranch_UseTagNameHead0() throws Exception { + void testGetRevisionContainingBranch_UseTagNameHead0() throws Exception { Revision revision = gitUtils.getRevisionContainingBranch("refs/tags/" + HEAD_TAG_NAME_0); assertThat(revision, is(headTag0Revision)); } /* Tags are searched in getRevisionContainingBranch beginning with 3.2.0 */ @Test - public void testGetRevisionContainingBranch_UseTagNameHead1() throws Exception { + void testGetRevisionContainingBranch_UseTagNameHead1() throws Exception { Revision revision = gitUtils.getRevisionContainingBranch("refs/tags/" + HEAD_TAG_NAME_1); assertThat(revision, is(headRevision)); } /* Tags are searched in getRevisionContainingBranch beginning with 3.2.0 */ @Test - public void testGetRevisionContainingBranch_UseTagNameHead2() throws Exception { + void testGetRevisionContainingBranch_UseTagNameHead2() throws Exception { Revision revision = gitUtils.getRevisionContainingBranch("refs/tags/" + HEAD_TAG_NAME_2); assertThat(revision, is(headRevision)); } /* Tags are searched in getRevisionContainingBranch beginning with 3.2.0 */ @Test - public void testGetRevisionContainingBranch_UseTagNamePrior1() throws Exception { + void testGetRevisionContainingBranch_UseTagNamePrior1() throws Exception { Revision revision = gitUtils.getRevisionContainingBranch("refs/tags/" + PRIOR_TAG_NAME_1); assertThat(revision, is(priorRevision)); } /* Tags are searched in getRevisionContainingBranch beginning with 3.2.0 */ @Test - public void testGetRevisionContainingBranch_UseTagNamePrior2() throws Exception { + void testGetRevisionContainingBranch_UseTagNamePrior2() throws Exception { Revision revision = gitUtils.getRevisionContainingBranch("refs/tags/" + PRIOR_TAG_NAME_2); assertThat(revision, is(priorRevision)); } @Test - public void testGetRevisionContainingBranch_InvalidBranchName() throws Exception { + void testGetRevisionContainingBranch_InvalidBranchName() throws Exception { Revision revision = gitUtils.getRevisionContainingBranch("origin/not-a-valid-branch-name"); assertThat(revision, is(nullValue(Revision.class))); } @Test - public void testGetRevisionContainingBranch_InvalidTagName() throws Exception { + void testGetRevisionContainingBranch_InvalidTagName() throws Exception { Revision revision = gitUtils.getRevisionContainingBranch("ref/tags/not-a-valid-tag-name"); assertThat(revision, is(nullValue(Revision.class))); } @Test - public void testGetRevisionForSHA1() throws Exception { + void testGetRevisionForSHA1() throws Exception { Revision revision = gitUtils.getRevisionForSHA1(headId); assertThat(revision, is(headRevision)); } @Test - public void testGetRevisionForSHA1PriorRevision() throws Exception { + void testGetRevisionForSHA1PriorRevision() throws Exception { Revision revision = gitUtils.getRevisionForSHA1(priorHeadId); assertThat(revision, is(priorRevision)); } @Test - public void testGetRevisionForSHA1UnknownRevision() throws Exception { + void testGetRevisionForSHA1UnknownRevision() throws Exception { ObjectId unknown = ObjectId.fromString("a422d10c6dc4262effb12f9e7a64911111000000"); Revision unknownRevision = new Revision(unknown); Revision revision = gitUtils.getRevisionForSHA1(unknown); @@ -290,7 +294,7 @@ public void testGetRevisionForSHA1UnknownRevision() throws Exception { } @Test - public void testFilterTipBranches() throws Exception { + void testFilterTipBranches() throws Exception { Collection multiRevisionList = new ArrayList<>(); multiRevisionList.add(priorRevision); multiRevisionList.add(headRevision); @@ -301,7 +305,7 @@ public void testFilterTipBranches() throws Exception { } @Test - public void testFilterTipBranchesNoRemovals() throws Exception { + void testFilterTipBranchesNoRemovals() throws Exception { Collection headRevisionList = new ArrayList<>(); headRevisionList.add(headRevision); List result = gitUtils.filterTipBranches(headRevisionList); @@ -309,7 +313,7 @@ public void testFilterTipBranchesNoRemovals() throws Exception { } @Test - public void testFilterTipBranchesNoRemovalsNonTip() throws Exception { + void testFilterTipBranchesNoRemovalsNonTip() throws Exception { Collection priorRevisionList = new ArrayList<>(); priorRevisionList.add(priorRevision); List result = gitUtils.filterTipBranches(priorRevisionList); @@ -317,7 +321,7 @@ public void testFilterTipBranchesNoRemovalsNonTip() throws Exception { } @Test - public void testFixupNames() { + void testFixupNames() { String[] names = {"origin", "origin2", null, "", null}; String[] urls = { "git://example.com/jenkinsci/git-plugin.git", @@ -354,7 +358,7 @@ private Set getActualNames(@NonNull Collection revisions) { } @Test - public void testGetAllBranchRevisions() throws Exception { + void testGetAllBranchRevisions() throws Exception { Collection allRevisions = gitUtils.getAllBranchRevisions(); assertThat(allRevisions, hasItem(headRevision)); Set expectedNames = getExpectedNames(); @@ -371,4 +375,13 @@ public static EnvVars getConfigNoSystemEnvsVars() { envVars.put("GIT_CONFIG_NOSYSTEM", "1"); return envVars; } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java index 64a05d5917..1524ebab11 100644 --- a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java +++ b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java @@ -26,6 +26,8 @@ import hudson.util.StreamTaskListener; import java.io.File; import java.io.IOException; +import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -34,6 +36,8 @@ import java.util.Set; import java.util.TreeMap; import java.util.UUID; + +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import jenkins.plugins.git.traits.BranchDiscoveryTrait; import jenkins.plugins.git.traits.DiscoverOtherRefsTrait; import jenkins.plugins.git.traits.IgnoreOnPushNotificationTrait; @@ -45,7 +49,7 @@ import jenkins.scm.api.SCMRevision; import jenkins.scm.api.SCMSource; -import static java.util.concurrent.TimeUnit.SECONDS; +import static hudson.Functions.isWindows; import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.collection.IsEmptyCollection.empty; @@ -63,26 +67,20 @@ import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.TestJGitAPIImpl; import org.jenkinsci.plugins.workflow.job.WorkflowJob; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Stopwatch; -import org.junit.rules.TestName; -import org.junit.runner.OrderWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.MockedStatic; import org.mockito.Mockito; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.atLeastOnce; @@ -97,41 +95,46 @@ /** * Tests for {@link AbstractGitSCMSource} */ -@OrderWith(RandomOrder.class) -public class AbstractGitSCMSourceTest { +@TestMethodOrder(MethodOrderer.Random.class) +@WithJenkins +@WithGitSampleRepo +class AbstractGitSCMSourceTest { + + private static final String GIT_BRANCH_SCM_HEAD_DEV_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; + private static final String GIT_BRANCH_SCM_HEAD_DEV_DEV_2_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; - static final String GitBranchSCMHead_DEV_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; - static final String GitBranchSCMHead_DEV_DEV2_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; + private JenkinsRule r; - @Rule - public JenkinsRule r = new JenkinsRule(); - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); - @Rule - public GitSampleRepoRule sampleRepo2 = new GitSampleRepoRule(); + private GitSampleRepoRule sampleRepo; + private GitSampleRepoRule sampleRepo2; - @ClassRule - public static Stopwatch stopwatch = new Stopwatch(); - @Rule - public TestName testName = new TestName(); + private static final Instant START_TIME = Instant.now(); private static final int MAX_SECONDS_FOR_THESE_TESTS = 210; + @BeforeEach + void beforeEach(JenkinsRule rule, GitSampleRepoRule repo1, GitSampleRepoRule repo2) { + r = rule; + sampleRepo = repo1; + sampleRepo2 = repo2; + } + private boolean isTimeAvailable() { String env = System.getenv("CI"); - if (env == null || !Boolean.parseBoolean(env)) { + if (!Boolean.parseBoolean(env)) { // Run all tests when not in CI environment return true; } - return stopwatch.runtime(SECONDS) <= MAX_SECONDS_FOR_THESE_TESTS; + return Duration.between(START_TIME, Instant.now()).toSeconds() <= MAX_SECONDS_FOR_THESE_TESTS; } // TODO AbstractGitSCMSourceRetrieveHeadsTest *sounds* like it would be the right place, but it does not in fact retrieve any heads! + // Tests deprecated GitSCMSource constructor @Issue("JENKINS-37482") @Test - @Deprecated // Tests deprecated GitSCMSource constructor - public void retrieveHeads() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + @Deprecated + void retrieveHeads() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.write("file", "modified"); @@ -139,19 +142,19 @@ public void retrieveHeads() throws Exception { SCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "*", "", true); TaskListener listener = StreamTaskListener.fromStderr(); // SCMHeadObserver.Collector.result is a TreeMap so order is predictable: - assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_MASTER, source.fetch(listener).toString()); // And reuse cache: - assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_MASTER, source.fetch(listener).toString()); sampleRepo.git("checkout", "-b", "dev2"); sampleRepo.write("file", "modified again"); sampleRepo.git("commit", "--all", "--message=dev2"); // After changing data: - assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_DEV_2_MASTER, source.fetch(listener).toString()); } @Test - public void retrieveHeadsRequiresBranchDiscovery() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveHeadsRequiresBranchDiscovery() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.write("file", "modified"); @@ -161,20 +164,20 @@ public void retrieveHeadsRequiresBranchDiscovery() throws Exception { // SCMHeadObserver.Collector.result is a TreeMap so order is predictable: assertEquals("[]", source.fetch(listener).toString()); source.setTraits(Collections.singletonList(new BranchDiscoveryTrait())); - assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_MASTER, source.fetch(listener).toString()); // And reuse cache: - assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_MASTER, source.fetch(listener).toString()); sampleRepo.git("checkout", "-b", "dev2"); sampleRepo.write("file", "modified again"); sampleRepo.git("commit", "--all", "--message=dev2"); // After changing data: - assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_DEV_2_MASTER, source.fetch(listener).toString()); } @Issue("JENKINS-46207") @Test - public void retrieveHeadsSupportsTagDiscovery_ignoreTagsWithoutTagDiscoveryTrait() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveHeadsSupportsTagDiscovery_ignoreTagsWithoutTagDiscoveryTrait() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.write("file", "modified"); @@ -190,20 +193,20 @@ public void retrieveHeadsSupportsTagDiscovery_ignoreTagsWithoutTagDiscoveryTrait // SCMHeadObserver.Collector.result is a TreeMap so order is predictable: assertEquals("[]", source.fetch(listener).toString()); source.setTraits(Collections.singletonList(new BranchDiscoveryTrait())); - assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_MASTER, source.fetch(listener).toString()); // And reuse cache: - assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_MASTER, source.fetch(listener).toString()); sampleRepo.git("checkout", "-b", "dev2"); sampleRepo.write("file", "modified again"); sampleRepo.git("commit", "--all", "--message=dev2"); // After changing data: - assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_DEV_2_MASTER, source.fetch(listener).toString()); } @Issue("JENKINS-46207") @Test - public void retrieveHeadsSupportsTagDiscovery_findTagsWithTagDiscoveryTrait() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveHeadsSupportsTagDiscovery_findTagsWithTagDiscoveryTrait() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.write("file", "modified"); @@ -265,8 +268,8 @@ public void retrieveHeadsSupportsTagDiscovery_findTagsWithTagDiscoveryTrait() th @Issue("JENKINS-46207") @Test - public void retrieveHeadsSupportsTagDiscovery_onlyTagsWithoutBranchDiscoveryTrait() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveHeadsSupportsTagDiscovery_onlyTagsWithoutBranchDiscoveryTrait() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.write("file", "modified"); @@ -290,8 +293,8 @@ public void retrieveHeadsSupportsTagDiscovery_onlyTagsWithoutBranchDiscoveryTrai @Issue("JENKINS-45953") @Test - public void retrieveRevisions() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveRevisions() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.write("file", "modified"); @@ -316,8 +319,8 @@ public void retrieveRevisions() throws Exception { @Issue("JENKINS-64803") @Test - public void retrieveTags_folderScopedCredentials() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveTags_folderScopedCredentials() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.write("file", "modified"); @@ -372,8 +375,8 @@ public void retrieveTags_folderScopedCredentials() throws Exception { @Issue("JENKINS-47824") @Test - public void retrieveByName() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveByName() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); String masterHash = sampleRepo.head(); sampleRepo.git("checkout", "-b", "dev"); @@ -468,15 +471,15 @@ public static abstract class ActionableSCMSourceOwner extends Actionable impleme @Test @Deprecated - public void retrievePrimaryHead_NotDuplicated() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrievePrimaryHead_NotDuplicated() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); retrievePrimaryHead(false); } @Test @Deprecated - public void retrievePrimaryHead_Duplicated() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrievePrimaryHead_Duplicated() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); retrievePrimaryHead(true); } @@ -542,8 +545,8 @@ private void retrievePrimaryHead(boolean duplicatePrimary) throws Exception { @Issue("JENKINS-31155") @Test - public void retrieveRevision() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveRevision() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=v1"); @@ -578,8 +581,8 @@ public void retrieveRevision() throws Exception { @Issue("JENKINS-48061") @Test - public void retrieveRevision_nonHead() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveRevision_nonHead() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=v1"); @@ -602,11 +605,11 @@ public void retrieveRevision_nonHead() throws Exception { assertEquals("v3", fileAt(v3, run, source, listener)); } + // @Ignore("At least file:// protocol doesn't allow fetching unannounced commits") @Issue("JENKINS-48061") @Test - // @Ignore("At least file:// protocol doesn't allow fetching unannounced commits") - public void retrieveRevision_nonAdvertised() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveRevision_nonAdvertised() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=v1"); @@ -634,8 +637,8 @@ public void retrieveRevision_nonAdvertised() throws Exception { @Issue("JENKINS-48061") @Test - public void retrieveRevision_customRef() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveRevision_customRef() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=v1"); @@ -665,8 +668,8 @@ public void retrieveRevision_customRef() throws Exception { @Issue("JENKINS-48061") @Test - public void retrieveRevision_customRef_descendant() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveRevision_customRef_descendant() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=v1"); @@ -701,8 +704,8 @@ public void retrieveRevision_customRef_descendant() throws Exception { @Issue("JENKINS-48061") @Test - public void retrieveRevision_customRef_abbrev_sha1() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveRevision_customRef_abbrev_sha1() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=v1"); @@ -732,8 +735,8 @@ public void retrieveRevision_customRef_abbrev_sha1() throws Exception { @Issue("JENKINS-48061") @Test - public void retrieveRevision_pr_refspec() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveRevision_pr_refspec() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=v1"); @@ -760,8 +763,8 @@ public void retrieveRevision_pr_refspec() throws Exception { @Issue("JENKINS-48061") @Test - public void retrieveRevision_pr_local_refspec() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void retrieveRevision_pr_local_refspec() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=v1"); @@ -802,8 +805,8 @@ private String fileAt(String revision, Run run, SCMSource source, TaskListe @Issue("JENKINS-48061") @Test - public void fetchOtherRef() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void fetchOtherRef() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=v1"); @@ -838,8 +841,8 @@ public void fetchOtherRef() throws Exception { @Issue("JENKINS-48061") @Test - public void fetchOtherRevisions() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void fetchOtherRevisions() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.write("file", "v1"); sampleRepo.git("commit", "--all", "--message=v1"); @@ -872,11 +875,12 @@ public void fetchOtherRevisions() throws Exception { )); } + // Check GitSCMSource deprecated constructor @Issue("JENKINS-37727") @Test - @Deprecated // Check GitSCMSource deprecated constructor - public void pruneRemovesDeletedBranches() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + @Deprecated + void pruneRemovesDeletedBranches() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); /* Write a file to the master branch */ @@ -894,9 +898,9 @@ public void pruneRemovesDeletedBranches() throws Exception { GitSCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "*", "", true); TaskListener listener = StreamTaskListener.fromStderr(); // SCMHeadObserver.Collector.result is a TreeMap so order is predictable: - assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_MASTER, source.fetch(listener).toString()); // And reuse cache: - assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_MASTER, source.fetch(listener).toString()); /* Create dev2 branch and write a file to it */ sampleRepo.git("checkout", "-b", "dev2", "master"); @@ -905,7 +909,7 @@ public void pruneRemovesDeletedBranches() throws Exception { sampleRepo.git("commit", "--message=dev2-branch-commit-message"); // Verify new branch is visible - assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_DEV_2_MASTER, source.fetch(listener).toString()); /* Delete the dev branch */ sampleRepo.git("branch", "-D", "dev"); @@ -914,10 +918,11 @@ public void pruneRemovesDeletedBranches() throws Exception { assertEquals("[GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]", source.fetch(listener).toString()); } + // Tests deprecated getExtensions() and setExtensions() @Test - @Deprecated // Tests deprecated getExtensions() and setExtensions() - public void testSpecificRevisionBuildChooser() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + @Deprecated + void testSpecificRevisionBuildChooser() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); /* Write a file to the master branch */ @@ -975,10 +980,11 @@ public void testSpecificRevisionBuildChooser() throws Exception { } + // Tests deprecated GitSCMSource constructor @Test - @Deprecated // Tests deprecated GitSCMSource constructor - public void testCustomRemoteName() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + @Deprecated + void testCustomRemoteName() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); GitSCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "upstream", null, "*", "", true); @@ -991,10 +997,11 @@ public void testCustomRemoteName() throws Exception { assertEquals("+refs/heads/*:refs/remotes/upstream/*", config.getRefspec()); } + // Tests deprecated GitSCMSource constructor @Test - @Deprecated // Tests deprecated GitSCMSource constructor - public void testCustomRefSpecs() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + @Deprecated + void testCustomRefSpecs() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); GitSCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", null, "+refs/heads/*:refs/remotes/origin/* +refs/merge-requests/*/head:refs/remotes/origin/merge-requests/*", "*", "", true); @@ -1014,12 +1021,12 @@ private boolean isPruneOnFetchEnabled() throws Exception { CliGitCommand gitCmd = new CliGitCommand(null); boolean checkForErrors = false; // Treat failure of `git config --get fetch.prune` as false String[] pruneOnFetch = gitCmd.run(checkForErrors, "config", "--get", "fetch.prune"); - return pruneOnFetch.length > 0 && Boolean.valueOf(pruneOnFetch[0]); + return pruneOnFetch.length > 0 && Boolean.parseBoolean(pruneOnFetch[0]); } @Test - public void refLockEncounteredIfPruneTraitNotPresentOnNotFoundRetrieval() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void refLockEncounteredIfPruneTraitNotPresentOnNotFoundRetrieval() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); if (isPruneOnFetchEnabled()) { // Command line git won't throw expected exception if it is pruning @@ -1039,8 +1046,8 @@ public void refLockEncounteredIfPruneTraitNotPresentOnNotFoundRetrieval() throws } @Test - public void refLockEncounteredIfPruneTraitNotPresentOnTagRetrieval() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void refLockEncounteredIfPruneTraitNotPresentOnTagRetrieval() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); if (isPruneOnFetchEnabled()) { // Command line git won't throw expected exception if it is pruning @@ -1060,8 +1067,8 @@ public void refLockEncounteredIfPruneTraitNotPresentOnTagRetrieval() throws Exce } @Test - public void refLockAvoidedIfPruneTraitPresentOnNotFoundRetrieval() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void refLockAvoidedIfPruneTraitPresentOnNotFoundRetrieval() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); TaskListener listener = StreamTaskListener.fromStderr(); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); source.setTraits((Arrays.asList(new TagDiscoveryTrait(), new PruneStaleBranchTrait()))); @@ -1074,8 +1081,8 @@ public void refLockAvoidedIfPruneTraitPresentOnNotFoundRetrieval() throws Except } @Test - public void refLockAvoidedIfPruneTraitPresentOnTagRetrieval() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void refLockAvoidedIfPruneTraitPresentOnTagRetrieval() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); TaskListener listener = StreamTaskListener.fromStderr(); GitSCMSource source = new GitSCMSource(sampleRepo.toString()); source.setTraits((Arrays.asList(new TagDiscoveryTrait(), new PruneStaleBranchTrait()))); @@ -1112,9 +1119,10 @@ private void createRefLockEnvironment(TaskListener listener, GitSCMSource source sampleRepo.git("push", source.getRemote(), "v1.2"); } - @Test @Issue("JENKINS-50394") - public void when_commits_added_during_discovery_we_do_not_crash() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + @Test + @Issue("JENKINS-50394") + void when_commits_added_during_discovery_we_do_not_crash() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.write("file", "modified"); @@ -1228,8 +1236,4 @@ public void execute() throws GitException, InterruptedException { }; } } - - private boolean isWindows() { - return File.pathSeparatorChar == ';'; - } } diff --git a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTrivialTest.java b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTrivialTest.java index 6500a699d8..a26bdd216e 100644 --- a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTrivialTest.java +++ b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTrivialTest.java @@ -10,15 +10,17 @@ import jenkins.scm.api.SCMHead; import jenkins.scm.api.SCMRevision; import nl.jqno.equalsverifier.EqualsVerifier; +import org.junit.jupiter.api.BeforeEach; + import org.eclipse.jgit.transport.RefSpec; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Before; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.mockito.Mockito.*; -public class AbstractGitSCMSourceTrivialTest { +class AbstractGitSCMSourceTrivialTest { private AbstractGitSCMSource gitSCMSource = null; @@ -32,8 +34,8 @@ public class AbstractGitSCMSourceTrivialTest { private final String expectedRefSpec = "+refs/heads/*:refs/remotes/origin/*"; private final List expectedRefSpecs = new ArrayList<>(); - @Before - public void setUp() throws Exception { + @BeforeEach + void beforeEach() throws Exception { if (expectedRefSpecs.isEmpty()) { expectedRefSpecs.add(new RefSpec(expectedRefSpec)); } @@ -42,7 +44,7 @@ public void setUp() throws Exception { @Test @Deprecated - public void basicTestIsExcluded() { + void basicTestIsExcluded() { AbstractGitSCMSource abstractGitSCMSource = mock(AbstractGitSCMSource.class); when(abstractGitSCMSource.getIncludes()).thenReturn("*master release* fe?ture"); @@ -69,42 +71,42 @@ public void basicTestIsExcluded() { } @Test - public void testGetCredentialsId() { + void testGetCredentialsId() { assertEquals(expectedCredentialsId, gitSCMSource.getCredentialsId()); } @Test - public void testGetRemote() { + void testGetRemote() { assertEquals(expectedRemote, gitSCMSource.getRemote()); } @Test @Deprecated - public void testGetIncludes() { + void testGetIncludes() { assertEquals(expectedIncludes, gitSCMSource.getIncludes()); } @Test @Deprecated - public void testGetExcludes() { + void testGetExcludes() { assertEquals(expectedExcludes, gitSCMSource.getExcludes()); } @Test @Deprecated - public void testGetRemoteName() { + void testGetRemoteName() { assertEquals(expectedRemote, gitSCMSource.getRemoteName()); } @Test @Deprecated - public void testGetRefSpecs() { + void testGetRefSpecs() { assertEquals(expectedRefSpecs, gitSCMSource.getRefSpecs()); } @Test @Deprecated - public void testIsExcluded() { + void testIsExcluded() { assertFalse(gitSCMSource.isExcluded("master")); assertFalse(gitSCMSource.isExcluded("remote/master")); assertFalse(gitSCMSource.isExcluded("release/X.Y")); @@ -129,15 +131,15 @@ public void testIsExcluded() { @Test @Deprecated - public void testGetRemoteConfigs() { + void testGetRemoteConfigs() { List remoteConfigs = gitSCMSource.getRemoteConfigs(); assertEquals(expectedRemote, remoteConfigs.get(0).getName()); assertEquals(expectedRefSpec, remoteConfigs.get(0).getRefspec()); - assertEquals("Wrong number of entries in remoteConfigs", 1, remoteConfigs.size()); + assertEquals(1, remoteConfigs.size(), "Wrong number of entries in remoteConfigs"); } @Test - public void testBuild() { + void testBuild() { final String expectedBranchName = "origin/master"; SCMHead head = new SCMHead(expectedBranchName); SCMRevision revision = new SCMRevisionImpl(head); @@ -146,15 +148,15 @@ public void testBuild() { List remoteConfigs = gitSCM.getUserRemoteConfigs(); assertEquals(expectedRemote, remoteConfigs.get(0).getName()); assertEquals(expectedRefSpec, remoteConfigs.get(0).getRefspec()); - assertEquals("Wrong number of entries in remoteConfigs", 1, remoteConfigs.size()); + assertEquals(1, remoteConfigs.size(), "Wrong number of entries in remoteConfigs"); List branches = gitSCM.getBranches(); assertEquals(expectedBranchName, branches.get(0).getName()); - assertEquals("Wrong number of branches", 1, branches.size()); + assertEquals(1, branches.size(), "Wrong number of branches"); } @Test - public void equalsContractSCMRevisionImpl() { + void equalsContractSCMRevisionImpl() { EqualsVerifier.forClass(AbstractGitSCMSource.SCMRevisionImpl.class) .usingGetClass() .verify(); @@ -193,7 +195,7 @@ public List getRefSpecs() { } } - private class SCMRevisionImpl extends SCMRevision { + private static class SCMRevisionImpl extends SCMRevision { protected SCMRevisionImpl(@NonNull SCMHead scmh) { super(scmh); diff --git a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceWantTagsTest.java b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceWantTagsTest.java index df45f3a43d..2a7b87ca76 100644 --- a/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceWantTagsTest.java +++ b/src/test/java/jenkins/plugins/git/AbstractGitSCMSourceWantTagsTest.java @@ -4,8 +4,8 @@ import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import hudson.EnvVars; import hudson.model.TaskListener; @@ -16,6 +16,8 @@ import java.util.List; import java.util.Set; import java.util.stream.Collectors; + +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import jenkins.plugins.git.traits.BranchDiscoveryTrait; import jenkins.plugins.git.traits.TagDiscoveryTrait; import jenkins.scm.api.SCMHead; @@ -24,24 +26,23 @@ import org.jenkinsci.plugins.gitclient.FetchCommand; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.TestJGitAPIImpl; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Tests for {@link AbstractGitSCMSource} and the wantTags change. */ -public class AbstractGitSCMSourceWantTagsTest { +@WithJenkins +@WithGitSampleRepo +class AbstractGitSCMSourceWantTagsTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; - @ClassRule - public static GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + private static GitSampleRepoRule sampleRepo; private GitSCMSource source; private final TaskListener LISTENER = StreamTaskListener.fromStderr(); @@ -50,8 +51,12 @@ public class AbstractGitSCMSourceWantTagsTest { private static final String ANNOTATED_TAG_NAME = "annotated-tag"; private static final String BRANCH_NAME = "dev"; - @BeforeClass - public static void fillSampleRepo() throws Exception { + private static final boolean ORIGINAL_IGNORE_TAG_DISCOVERY_TRAIT = GitSCMSource.IGNORE_TAG_DISCOVERY_TRAIT; + + @BeforeAll + static void beforeAll(GitSampleRepoRule repo) throws Exception { + sampleRepo = repo; + sampleRepo.init(); sampleRepo.git("checkout", "-b", BRANCH_NAME); sampleRepo.write("file", "modified"); @@ -64,30 +69,22 @@ public static void fillSampleRepo() throws Exception { sampleRepo.git("commit", "--all", "--message=" + BRANCH_NAME + "-commit-3"); } - @Before - public void setGitSCMSource() { - source = new GitSCMSource(sampleRepo.toString()); - } + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; - @Before - public void setMockGitClient() { + source = new GitSCMSource(sampleRepo.toString()); System.setProperty(Git.class.getName() + ".mockClient", MockGitClientForTags.class.getName()); } - @After - public void clearMockGitClient() { + @AfterEach + void afterEach() { System.clearProperty(Git.class.getName() + ".mockClient"); - } - - private static final boolean ORIGINAL_IGNORE_TAG_DISCOVERY_TRAIT = GitSCMSource.IGNORE_TAG_DISCOVERY_TRAIT; - - @After - public void resetIgnoreTagDiscoveryTrait() { GitSCMSource.IGNORE_TAG_DISCOVERY_TRAIT = ORIGINAL_IGNORE_TAG_DISCOVERY_TRAIT; } @Test - public void indexingHasNoTrait() throws Exception { + void indexingHasNoTrait() throws Exception { // The source has no traits - empty result and no tags fetched Set noHeads = source.fetch(LISTENER); assertThat(noHeads, is(empty())); @@ -95,7 +92,7 @@ public void indexingHasNoTrait() throws Exception { } @Test - public void indexingHasNoTraitIgnoreTagDiscoveryTrait() throws Exception { + void indexingHasNoTraitIgnoreTagDiscoveryTrait() throws Exception { // The source has no traits - empty result and no tags fetched GitSCMSource.IGNORE_TAG_DISCOVERY_TRAIT = true; Set noHeads = source.fetch(LISTENER); @@ -104,70 +101,70 @@ public void indexingHasNoTraitIgnoreTagDiscoveryTrait() throws Exception { } @Test - public void indexingHasTagDiscoveryTrait() throws Exception { + void indexingHasTagDiscoveryTrait() throws Exception { // The source has the tag discovery trait - only tags fetched source.setTraits(Collections.singletonList(new TagDiscoveryTrait())); Set taggedHeads = source.fetch(LISTENER); assertThat( - taggedHeads.stream().map(p -> p.getName()).collect(Collectors.toList()), + taggedHeads.stream().map(SCMHead::getName).collect(Collectors.toList()), containsInAnyOrder(LIGHTWEIGHT_TAG_NAME, ANNOTATED_TAG_NAME)); assertTrue(tagsFetched); } @Test - public void indexingHasTagDiscoveryTraitIgnoreTagDiscoveryTrait() throws Exception { + void indexingHasTagDiscoveryTraitIgnoreTagDiscoveryTrait() throws Exception { GitSCMSource.IGNORE_TAG_DISCOVERY_TRAIT = true; // The source has the tag discovery trait - only tags fetched source.setTraits(Collections.singletonList(new TagDiscoveryTrait())); Set taggedHeads = source.fetch(LISTENER); assertThat( - taggedHeads.stream().map(p -> p.getName()).collect(Collectors.toList()), + taggedHeads.stream().map(SCMHead::getName).collect(Collectors.toList()), containsInAnyOrder(LIGHTWEIGHT_TAG_NAME, ANNOTATED_TAG_NAME)); assertTrue(tagsFetched); } @Test - public void indexingHasBranchDiscoveryTrait() throws Exception { + void indexingHasBranchDiscoveryTrait() throws Exception { // The source has the branch discovery trait - only branches fetched source.setTraits(Collections.singletonList(new BranchDiscoveryTrait())); Set branchHeads = source.fetch(LISTENER); assertThat( - branchHeads.stream().map(p -> p.getName()).collect(Collectors.toList()), + branchHeads.stream().map(SCMHead::getName).collect(Collectors.toList()), containsInAnyOrder(BRANCH_NAME, "master")); assertFalse(tagsFetched); } @Test - public void indexingHasBranchDiscoveryTraitIgnoreTagDiscoveryTrait() throws Exception { + void indexingHasBranchDiscoveryTraitIgnoreTagDiscoveryTrait() throws Exception { GitSCMSource.IGNORE_TAG_DISCOVERY_TRAIT = true; // The source has the branch discovery trait - only branches fetched source.setTraits(Collections.singletonList(new BranchDiscoveryTrait())); Set branchHeads = source.fetch(LISTENER); assertThat( - branchHeads.stream().map(p -> p.getName()).collect(Collectors.toList()), + branchHeads.stream().map(SCMHead::getName).collect(Collectors.toList()), containsInAnyOrder(BRANCH_NAME, "master")); assertTrue(tagsFetched); // tags fetched but returned heads is only branches } @Test - public void indexingHasBranchAndTagDiscoveryTrait() throws Exception { + void indexingHasBranchAndTagDiscoveryTrait() throws Exception { // The source has the branch discovery and tag discovery trait - branches and tags fetched source.setTraits(List.of(new BranchDiscoveryTrait(), new TagDiscoveryTrait())); Set heads = source.fetch(LISTENER); assertThat( - heads.stream().map(p -> p.getName()).collect(Collectors.toList()), + heads.stream().map(SCMHead::getName).collect(Collectors.toList()), containsInAnyOrder(BRANCH_NAME, "master", LIGHTWEIGHT_TAG_NAME, ANNOTATED_TAG_NAME)); assertTrue(tagsFetched); } @Test - public void indexingHasBranchAndTagDiscoveryTraitIgnoreTagDiscoveryTrait() throws Exception { + void indexingHasBranchAndTagDiscoveryTraitIgnoreTagDiscoveryTrait() throws Exception { GitSCMSource.IGNORE_TAG_DISCOVERY_TRAIT = true; // The source has the branch discovery and tag discovery trait - branches and tags fetched source.setTraits(List.of(new BranchDiscoveryTrait(), new TagDiscoveryTrait())); Set heads = source.fetch(LISTENER); assertThat( - heads.stream().map(p -> p.getName()).collect(Collectors.toList()), + heads.stream().map(SCMHead::getName).collect(Collectors.toList()), containsInAnyOrder(BRANCH_NAME, "master", LIGHTWEIGHT_TAG_NAME, ANNOTATED_TAG_NAME)); assertTrue(tagsFetched); } diff --git a/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java index 84ef955eb7..41140534c3 100644 --- a/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/BrowsersJCasCCompatibilityTest.java @@ -23,12 +23,13 @@ import hudson.plugins.git.browser.TFS2013GitRepositoryBrowser; import hudson.plugins.git.browser.ViewGitWeb; import hudson.scm.SCM; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; +import io.jenkins.plugins.casc.misc.junit.jupiter.AbstractRoundTripTest; import org.jenkinsci.plugins.workflow.libs.GlobalLibraries; import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration; import org.jenkinsci.plugins.workflow.libs.LibraryRetriever; import org.jenkinsci.plugins.workflow.libs.SCMRetriever; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.util.ArrayList; import java.util.List; @@ -38,13 +39,15 @@ import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.hamcrest.MatcherAssert.assertThat; -public class BrowsersJCasCCompatibilityTest extends RoundTripAbstractTest { +@WithJenkins +class BrowsersJCasCCompatibilityTest extends AbstractRoundTripTest { + @Override - protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { + protected void assertConfiguredAsExpected(JenkinsRule rule, String s) { final List libraries = GlobalLibraries.get().getLibraries(); assertThat(libraries, containsInAnyOrder( allOf( @@ -137,7 +140,7 @@ protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenk final SCM scm = ((SCMRetriever) retriever).getScm(); assertThat(errorMessage, scm, instanceOf(GitSCM.class)); final GitSCM gitSCM = (GitSCM)scm; - assertNotNull(errorMessage, gitSCM.getBrowser()); + assertNotNull(gitSCM.getBrowser(), errorMessage); browsers.add(gitSCM.getBrowser()); } diff --git a/src/test/java/jenkins/plugins/git/CliGitCommand.java b/src/test/java/jenkins/plugins/git/CliGitCommand.java index f22e91718b..29752b653e 100644 --- a/src/test/java/jenkins/plugins/git/CliGitCommand.java +++ b/src/test/java/jenkins/plugins/git/CliGitCommand.java @@ -41,8 +41,10 @@ import java.util.concurrent.TimeUnit; import org.eclipse.jgit.lib.Repository; import static org.hamcrest.Matchers.hasItems; +import static org.junit.jupiter.api.Assertions.*; + import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.Assert; + import static org.hamcrest.MatcherAssert.assertThat; /** @@ -105,7 +107,7 @@ private String[] run(boolean assertProcessStatus) throws IOException, Interrupte } output = result.split("[\\n\\r]"); if (assertProcessStatus) { - Assert.assertEquals(args.toString() + " command failed and reported '" + Arrays.toString(output) + "'", 0, status); + assertEquals(0, status, args.toString() + " command failed and reported '" + Arrays.toString(output) + "'"); } return output; } @@ -113,12 +115,12 @@ private String[] run(boolean assertProcessStatus) throws IOException, Interrupte public void assertOutputContains(String... expectedRegExes) { List notFound = new ArrayList<>(); boolean modified = notFound.addAll(Arrays.asList(expectedRegExes)); - Assert.assertTrue("Missing regular expressions in assertion", modified); + assertTrue(modified, "Missing regular expressions in assertion"); for (String line : output) { notFound.removeIf(line::matches); } if (!notFound.isEmpty()) { - Assert.fail(Arrays.toString(output) + " did not match all strings in notFound: " + Arrays.toString(expectedRegExes)); + fail(Arrays.toString(output) + " did not match all strings in notFound: " + Arrays.toString(expectedRegExes)); } } diff --git a/src/test/java/jenkins/plugins/git/FIPSModeSCMSourceTest.java b/src/test/java/jenkins/plugins/git/FIPSModeSCMSourceTest.java index 8855101f3a..3c7cf6f9b7 100644 --- a/src/test/java/jenkins/plugins/git/FIPSModeSCMSourceTest.java +++ b/src/test/java/jenkins/plugins/git/FIPSModeSCMSourceTest.java @@ -4,9 +4,10 @@ import hudson.model.TaskListener; import hudson.util.StreamTaskListener; import java.io.IOException; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.RealJenkinsRule; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.jvnet.hudson.test.junit.jupiter.RealJenkinsExtension; import java.util.List; import java.util.logging.Level; @@ -15,21 +16,22 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class FIPSModeSCMSourceTest { +class FIPSModeSCMSourceTest { - @Rule public RealJenkinsRule rule = new RealJenkinsRule().omitPlugins("eddsa-api", "trilead-api", "git-tag-message") + @RegisterExtension + private final RealJenkinsExtension extension = new RealJenkinsExtension().omitPlugins("eddsa-api", "trilead-api", "git-tag-message") .javaOptions("-Djenkins.security.FIPS140.COMPLIANCE=true") .withLogger(AbstractGitSCMSource.class, Level.SEVERE); @Test @SuppressWarnings("deprecation") - public void remotesAreNotFetchedTest() throws Throwable { - rule.then( r -> { + void remotesAreNotFetchedTest() throws Throwable { + extension.then(r -> { GitSCMSource source = new GitSCMSource("http://insecure-repo"); TaskListener listener = StreamTaskListener.fromStderr(); - assertThrows("expected exception as repo doesn't exist", IOException.class, () -> source.fetch(listener)); + assertThrows(IOException.class, () -> source.fetch(listener), "expected exception as repo doesn't exist"); LogRecorder logRecorder = new LogRecorder(AbstractGitSCMSource.class.getName()); LogRecorder.Target target = new LogRecorder.Target(AbstractGitSCMSource.class.getName(), Level.SEVERE); @@ -38,14 +40,14 @@ public void remotesAreNotFetchedTest() throws Throwable { assertThat("We should no see the error in the logs", logRecorder.getLogRecords().size(), is(0)); // Using creds we should be getting an exception - Throwable exception = assertThrows("We're not saving creds", IllegalArgumentException.class, () -> source.setCredentialsId("cred-id")); + Throwable exception = assertThrows(IllegalArgumentException.class, () -> source.setCredentialsId("cred-id"), "We're not saving creds"); assertThat(exception.getMessage(), containsString("FIPS requires a secure channel")); assertThat("credentials are not saved", source.getCredentialsId(), nullValue()); // Using old constructor (restricted since 3.4.0) to simulate credentials are being set with unsecure connection // This would be equivalent to a user manually adding credentials to config.xml GitSCMSource anotherSource = new GitSCMSource("fake", "http://insecure", "credentialsId", "", "", true); - exception = assertThrows("fetch was interrupted so no credential was leaked", IllegalArgumentException.class, () -> anotherSource.fetch(listener)); + exception = assertThrows(IllegalArgumentException.class, () -> anotherSource.fetch(listener), "fetch was interrupted so no credential was leaked"); assertThat("We should have a severe log indicating the error", logRecorder.getLogRecords().size(), is(1)); assertThat("Exception indicates problem", exception.getMessage(), containsString("FIPS requires a secure channel")); }); diff --git a/src/test/java/jenkins/plugins/git/GitBranchSCMHeadTest.java b/src/test/java/jenkins/plugins/git/GitBranchSCMHeadTest.java index 0a24cbaffa..5aeb6413cf 100644 --- a/src/test/java/jenkins/plugins/git/GitBranchSCMHeadTest.java +++ b/src/test/java/jenkins/plugins/git/GitBranchSCMHeadTest.java @@ -5,61 +5,63 @@ import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; import java.io.File; import java.io.IOException; import java.net.URL; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static hudson.Functions.isWindows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -public class GitBranchSCMHeadTest { +@WithJenkins +class GitBranchSCMHeadTest { - @Rule - public JenkinsRule r = new JenkinsRule() { - @Override - public void before() throws Throwable { - if (!isWindows() && "testMigrationNoBuildStorm".equals(this.getTestDescription().getMethodName())) { - URL res = getClass().getResource("/jenkins/plugins/git/GitBranchSCMHeadTest/testMigrationNoBuildStorm_repositories.zip"); - final File path = new File("/tmp/JENKINS-48061"); - if (path.exists()) { - if (path.isDirectory()) { - FileUtils.deleteDirectory(path); - } else { - path.delete(); - } - } + private JenkinsRule r; - new FilePath(new File(res.toURI())).unzip(new FilePath(path.getParentFile())); - } - super.before(); - } - }; + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } - @After - public void removeRepos() throws IOException { + @AfterEach + void afterEach() throws IOException { final File path = new File("/tmp/JENKINS-48061"); if (path.exists() && path.isDirectory()) { FileUtils.deleteDirectory(path); } } - + // getBuilds.size() @Issue("JENKINS-48061") @Test @LocalData - @Deprecated // getBuilds.size() - public void testMigrationNoBuildStorm() throws Exception { + @Deprecated + void testMigrationNoBuildStorm() throws Exception { if (isWindows()) { // Test is unreliable on Windows, too low value to investigate further /* Do not distract warnings system by using assumeThat to skip tests */ return; } + + URL res = getClass().getResource("/jenkins/plugins/git/GitBranchSCMHeadTest/testMigrationNoBuildStorm_repositories.zip"); + final File path = new File("/tmp/JENKINS-48061"); + if (path.exists()) { + if (path.isDirectory()) { + FileUtils.deleteDirectory(path); + } else { + path.delete(); + } + } + + new FilePath(new File(res.toURI())).unzip(new FilePath(path.getParentFile())); + final WorkflowMultiBranchProject job = r.jenkins.getItemByFullName("job", WorkflowMultiBranchProject.class); assertEquals(4, job.getItems().size()); WorkflowJob master = job.getItem("master"); @@ -82,9 +84,4 @@ public void testMigrationNoBuildStorm() throws Exception { v4 = job.getItem("v4"); assertEquals(0, v4.getBuilds().size()); } - - /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ - private boolean isWindows() { - return File.pathSeparatorChar==';'; - } } diff --git a/src/test/java/jenkins/plugins/git/GitHooksConfigurationTest.java b/src/test/java/jenkins/plugins/git/GitHooksConfigurationTest.java index 65cb5f6a7b..9d12b22c01 100644 --- a/src/test/java/jenkins/plugins/git/GitHooksConfigurationTest.java +++ b/src/test/java/jenkins/plugins/git/GitHooksConfigurationTest.java @@ -25,27 +25,28 @@ import hudson.EnvVars; import hudson.model.TaskListener; -import java.io.File; + import java.util.Random; import org.eclipse.jgit.lib.StoredConfig; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +import static hudson.Functions.isWindows; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class GitHooksConfigurationTest { +@WithJenkins +class GitHooksConfigurationTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; private GitHooksConfiguration configuration; private GitClient client; @@ -53,18 +54,17 @@ public class GitHooksConfigurationTest { private final Random random = new Random(); private static final String NULL_HOOKS_PATH = isWindows() ? "NUL:" : "/dev/null"; - public GitHooksConfigurationTest() { - } + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + r = rule; - @Before - public void setUp() throws Exception { configuration = GitHooksConfiguration.get(); Git git = Git.with(TaskListener.NULL, new EnvVars()); client = git.getClient(); } - @After - public void resetHooksPath() throws Exception { + @AfterEach + void afterEach() throws Exception { client.withRepository((repo, channel) -> { final StoredConfig repoConfig = repo.getConfig(); repoConfig.unset("core", null, "hooksPath"); @@ -74,46 +74,46 @@ public void resetHooksPath() throws Exception { } @Test - public void testGet() { + void testGet() { assertThat(GitHooksConfiguration.get(), is(configuration)); } @Test - public void testIsAllowedOnController() { + void testIsAllowedOnController() { assertFalse(configuration.isAllowedOnController()); } @Test - public void testSetAllowedOnController() { + void testSetAllowedOnController() { configuration.setAllowedOnController(true); assertTrue(configuration.isAllowedOnController()); } @Test - public void testSetAllowedOnControllerFalse() { + void testSetAllowedOnControllerFalse() { configuration.setAllowedOnController(false); assertFalse(configuration.isAllowedOnController()); } @Test - public void testIsAllowedOnAgents() { + void testIsAllowedOnAgents() { assertFalse(configuration.isAllowedOnAgents()); } @Test - public void testSetAllowedOnAgents() { + void testSetAllowedOnAgents() { configuration.setAllowedOnAgents(true); assertTrue(configuration.isAllowedOnAgents()); } @Test - public void testSetAllowedOnAgentsFalse() { + void testSetAllowedOnAgentsFalse() { configuration.setAllowedOnAgents(false); assertFalse(configuration.isAllowedOnAgents()); } @Test - public void testGetCategory() { + void testGetCategory() { assertThat(GitHooksConfiguration.get().getCategory(), is(configuration.getCategory())); } @@ -136,7 +136,7 @@ private String getCoreHooksPath() throws Exception { } @Test - public void testConfigure_GitClient() throws Exception { + void testConfigure_GitClient() throws Exception { GitHooksConfiguration.configure(client); /* Check configured value from repository */ @@ -145,7 +145,7 @@ public void testConfigure_GitClient() throws Exception { } @Test - public void testConfigure_GitClient_boolean() throws Exception { + void testConfigure_GitClient_boolean() throws Exception { boolean allowed = true; GitHooksConfiguration.configure(client, allowed); @@ -155,7 +155,7 @@ public void testConfigure_GitClient_boolean() throws Exception { } @Test - public void testConfigure_GitClient_booleanFalse() throws Exception { + void testConfigure_GitClient_booleanFalse() throws Exception { boolean allowed = false; GitHooksConfiguration.configure(client, allowed); @@ -181,7 +181,7 @@ private void configure_3args(boolean allowedOnController) throws Exception { } @Test - public void testConfigure_3args() throws Exception { + void testConfigure_3args() throws Exception { boolean allowedOnController = true; /* Change the hooksPath in repository */ @@ -193,7 +193,7 @@ public void testConfigure_3args() throws Exception { } @Test - public void testConfigure_3argsFalse() throws Exception { + void testConfigure_3argsFalse() throws Exception { boolean allowedOnController = false; /* Change the hooksPath in repository */ @@ -203,8 +203,4 @@ public void testConfigure_3argsFalse() throws Exception { String hooksPath = getCoreHooksPath(); assertThat(hooksPath, is(NULL_HOOKS_PATH)); } - - private static boolean isWindows() { - return File.pathSeparatorChar == ';'; - } } diff --git a/src/test/java/jenkins/plugins/git/GitJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/GitJCasCCompatibilityTest.java index d5733251bf..302ce9a7d4 100644 --- a/src/test/java/jenkins/plugins/git/GitJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GitJCasCCompatibilityTest.java @@ -2,19 +2,22 @@ import hudson.plugins.git.GitSCM; import hudson.scm.SCM; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; +import io.jenkins.plugins.casc.misc.junit.jupiter.AbstractRoundTripTest; import org.hamcrest.CoreMatchers; import org.jenkinsci.plugins.workflow.libs.GlobalLibraries; import org.jenkinsci.plugins.workflow.libs.LibraryRetriever; import org.jenkinsci.plugins.workflow.libs.SCMRetriever; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.MatcherAssert.assertThat; -public class GitJCasCCompatibilityTest extends RoundTripAbstractTest { +@WithJenkins +class GitJCasCCompatibilityTest extends AbstractRoundTripTest { + @Override - protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { + protected void assertConfiguredAsExpected(JenkinsRule rule, String s) { LibraryRetriever retriever = GlobalLibraries.get().getLibraries().get(0).getRetriever(); assertThat(retriever, CoreMatchers.instanceOf(SCMRetriever.class)); SCM scm = ((SCMRetriever) retriever).getScm(); diff --git a/src/test/java/jenkins/plugins/git/GitRemoteHeadRefActionTest.java b/src/test/java/jenkins/plugins/git/GitRemoteHeadRefActionTest.java index f9f1f4c1c8..a40cd1179a 100644 --- a/src/test/java/jenkins/plugins/git/GitRemoteHeadRefActionTest.java +++ b/src/test/java/jenkins/plugins/git/GitRemoteHeadRefActionTest.java @@ -1,12 +1,12 @@ package jenkins.plugins.git; import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GitRemoteHeadRefActionTest { +class GitRemoteHeadRefActionTest { @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(GitRemoteHeadRefAction.class) .usingGetClass() .verify(); diff --git a/src/test/java/jenkins/plugins/git/GitSCMBuilderTest.java b/src/test/java/jenkins/plugins/git/GitSCMBuilderTest.java index 11016cdf19..673f16764b 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMBuilderTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMBuilderTest.java @@ -11,8 +11,9 @@ import hudson.plugins.git.util.InverseBuildChooser; import java.util.Collections; import jenkins.scm.api.SCMHead; +import org.junit.jupiter.api.Test; + import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.Test; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; @@ -24,7 +25,7 @@ import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; -public class GitSCMBuilderTest { +class GitSCMBuilderTest { private GitSCMBuilder instance = new GitSCMBuilder<>( new SCMHead("master"), @@ -33,7 +34,7 @@ public class GitSCMBuilderTest { null); @Test - public void build() throws Exception { + void build() throws Exception { GitSCM scm = instance.build(); assertThat(scm.getBrowser(), is(nullValue())); assertThat(scm.getUserRemoteConfigs(), contains(allOf( @@ -50,7 +51,7 @@ public void build() throws Exception { } @Test - public void withRevision() throws Exception { + void withRevision() throws Exception { instance.withExtension(new BuildChooserSetting(new InverseBuildChooser())); GitSCM scm = instance.build(); assertThat(scm.getExtensions().get(BuildChooserSetting.class), notNullValue()); @@ -77,7 +78,7 @@ public void withRevision() throws Exception { } @Test - public void withBrowser() throws Exception { + void withBrowser() throws Exception { instance.withBrowser(new GithubWeb("http://git.test/repo.git")); assertThat(instance.browser(), is(instanceOf(GithubWeb.class))); GitSCM scm = instance.build(); @@ -96,7 +97,7 @@ public void withBrowser() throws Exception { } @Test - public void withCredentials() throws Exception { + void withCredentials() throws Exception { instance.withCredentials("example-id"); assertThat(instance.credentialsId(), is("example-id")); GitSCM scm = instance.build(); @@ -115,7 +116,7 @@ public void withCredentials() throws Exception { } @Test - public void withExtension() throws Exception { + void withExtension() throws Exception { instance.withExtension(new AuthorInChangelog()); assertThat(instance.extensions(), contains(instanceOf(AuthorInChangelog.class))); GitSCM scm = instance.build(); @@ -179,7 +180,7 @@ public void withExtension() throws Exception { } @Test - public void withExtensions() throws Exception { + void withExtensions() throws Exception { instance.withExtensions(new AuthorInChangelog()); assertThat(instance.extensions(), contains(instanceOf(AuthorInChangelog.class))); GitSCM scm = instance.build(); @@ -268,7 +269,7 @@ public void withExtensions() throws Exception { } @Test - public void withGitTool() throws Exception { + void withGitTool() throws Exception { instance.withGitTool("git"); assertThat(instance.gitTool(), is("git")); GitSCM scm = instance.build(); @@ -287,7 +288,7 @@ public void withGitTool() throws Exception { } @Test - public void withRefSpecAndCloneOption() throws Exception { + void withRefSpecAndCloneOption() throws Exception { instance.withRefSpec("+refs/heads/master:refs/remotes/@{remote}/master"); instance.withExtension(new CloneOption(false, false, null, null)); assertThat(instance.refSpecs(), contains("+refs/heads/master:refs/remotes/@{remote}/master")); @@ -307,7 +308,7 @@ public void withRefSpecAndCloneOption() throws Exception { } @Test - public void withRefSpec() throws Exception { + void withRefSpec() throws Exception { instance.withRefSpec("+refs/heads/master:refs/remotes/@{remote}/master"); assertThat(instance.refSpecs(), contains("+refs/heads/master:refs/remotes/@{remote}/master")); GitSCM scm = instance.build(); @@ -398,7 +399,7 @@ public void withRefSpec() throws Exception { } @Test - public void withRefSpecs() throws Exception { + void withRefSpecs() throws Exception { instance.withRefSpecs(Collections.singletonList("+refs/heads/master:refs/remotes/@{remote}/master")); assertThat(instance.refSpecs(), contains("+refs/heads/master:refs/remotes/@{remote}/master")); GitSCM scm = instance.build(); @@ -463,7 +464,7 @@ public void withRefSpecs() throws Exception { } @Test - public void withoutRefSpecs() throws Exception { + void withoutRefSpecs() throws Exception { instance.withRefSpecs(Collections.singletonList("+refs/heads/feature:refs/remotes/@{remote}/feature")); if (instance.refSpecs().contains("+refs/heads/*:refs/remotes/@{remote}/*")) { return; @@ -487,7 +488,7 @@ public void withoutRefSpecs() throws Exception { } @Test - public void withRemote() throws Exception { + void withRemote() throws Exception { instance.withRemote("http://git.test/my-repo.git"); assertThat(instance.remote(), is("http://git.test/my-repo.git")); GitSCM scm = instance.build(); @@ -506,7 +507,7 @@ public void withRemote() throws Exception { } @Test - public void withRemoteName() throws Exception { + void withRemoteName() throws Exception { instance.withRemoteName("my-remote"); assertThat(instance.remoteName(), is("my-remote")); GitSCM scm = instance.build(); @@ -525,7 +526,7 @@ public void withRemoteName() throws Exception { } @Test - public void withAdditionalRemote() throws Exception { + void withAdditionalRemote() throws Exception { instance.withAdditionalRemote("upstream", "http://git.test/upstream.git", "+refs/heads/master:refs/remotes/@{remote}/master"); assertThat(instance.additionalRemoteNames(), contains("upstream")); diff --git a/src/test/java/jenkins/plugins/git/GitSCMFileSystemTest.java b/src/test/java/jenkins/plugins/git/GitSCMFileSystemTest.java index 64eb3718d5..f9665b9f36 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMFileSystemTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMFileSystemTest.java @@ -36,6 +36,8 @@ import java.util.Iterator; import java.util.Set; import java.util.TreeSet; + +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import jenkins.scm.api.SCMFile; import jenkins.scm.api.SCMFileSystem; import jenkins.scm.api.SCMHead; @@ -47,13 +49,14 @@ import org.eclipse.jgit.lib.ObjectId; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +import static hudson.Functions.isWindows; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThanOrEqualTo; @@ -62,24 +65,22 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.*; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; /** * Tests for {@link AbstractGitSCMSource} */ -public class GitSCMFileSystemTest { +@WithJenkins +@WithGitSampleRepo +class GitSCMFileSystemTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + private GitSampleRepoRule sampleRepo; - private final static String GIT_2_6_0_TAG = "git-2.6.0"; - private final static String GIT_2_6_1_TAG = "git-2.6.1"; + private static final String GIT_2_6_0_TAG = "git-2.6.0"; + private static final String GIT_2_6_1_TAG = "git-2.6.1"; /* This test requires the tag git-2.6.1 and git-2.6.0. If you're working from a * forked copy of the repository and your fork was created before the @@ -90,8 +91,10 @@ public class GitSCMFileSystemTest { * $ git fetch --tags https://github.com/jenkinsci/git-plugin * $ git push --tags origin */ - @BeforeClass - public static void confirmTagsAvailable() throws Exception { + @BeforeAll + static void beforeAll(JenkinsRule rule) throws Exception { + r = rule; + File gitDir = new File("."); GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("jgit").getClient(); @@ -108,9 +111,15 @@ public static void confirmTagsAvailable() throws Exception { } } + @BeforeEach + void beforeEach(GitSampleRepoRule repo) { + sampleRepo = repo; + } + + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void ofSource_Smokes() throws Exception { + @Deprecated + void ofSource_Smokes() throws Exception { sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.write("file", "modified"); @@ -133,9 +142,10 @@ public void ofSource_Smokes() throws Exception { assertThat(file.contentAsString(), is("modified")); } + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void ofSourceRevision() throws Exception { + @Deprecated + void ofSourceRevision() throws Exception { sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); SCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "*", "", true); @@ -154,9 +164,10 @@ public void ofSourceRevision() throws Exception { assertThat(file.contentAsString(), is("")); } + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void ofSourceRevision_GitBranchSCMHead() throws Exception { + @Deprecated + void ofSourceRevision_GitBranchSCMHead() throws Exception { sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); SCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "*", "", true); @@ -177,7 +188,7 @@ public void ofSourceRevision_GitBranchSCMHead() throws Exception { @Issue("JENKINS-42817") @Test - public void slashyBranches() throws Exception { + void slashyBranches() throws Exception { sampleRepo.init(); sampleRepo.git("checkout", "-b", "bug/JENKINS-42817"); sampleRepo.write("file", "modified"); @@ -198,7 +209,7 @@ public void slashyBranches() throws Exception { @Issue("JENKINS-57587") @Test - public void wildcardBranchNameCausesNPE() throws Exception { + void wildcardBranchNameCausesNPE() throws Exception { sampleRepo.init(); sampleRepo.write("file", "contents-for-npe-when-branch-name-is-asterisk"); sampleRepo.git("commit", "--all", "--message=npe-when-branch-name-is-asterisk"); @@ -217,9 +228,10 @@ public void wildcardBranchNameCausesNPE() throws Exception { assertThat("Wildcard branch name '*' resolved to a specific checkout unexpectedly", fs, is(nullValue())); } + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void lastModified_Smokes() throws Exception { + @Deprecated + void lastModified_Smokes() throws Exception { if (isWindows()) { // Windows file system last modify dates not trustworthy /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -246,9 +258,10 @@ public void lastModified_Smokes() throws Exception { assertThat(lastModified / 1000L, lessThanOrEqualTo((currentTime + fileSystemAllowedOffset) / 1000L)); } + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void directoryTraversal() throws Exception { + @Deprecated + void directoryTraversal() throws Exception { sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.mkdirs("dir/subdir"); @@ -282,9 +295,10 @@ public void directoryTraversal() throws Exception { assertThat(file.contentAsString(), is("modified")); } + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void mixedContent() throws Exception { + @Deprecated + void mixedContent() throws Exception { sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.write("file", "modified"); @@ -327,7 +341,7 @@ public void mixedContent() throws Exception { } @Test - public void given_filesystem_when_askingChangesSinceSameRevision_then_changesAreEmpty() throws Exception { + void given_filesystem_when_askingChangesSinceSameRevision_then_changesAreEmpty() throws Exception { File gitDir = new File("."); GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("git").getClient(); @@ -342,7 +356,7 @@ public void given_filesystem_when_askingChangesSinceSameRevision_then_changesAre } @Test - public void given_filesystem_when_askingChangesSinceOldRevision_then_changesArePopulated() throws Exception { + void given_filesystem_when_askingChangesSinceOldRevision_then_changesArePopulated() throws Exception { File gitDir = new File("."); GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("git").getClient(); @@ -363,7 +377,7 @@ public void given_filesystem_when_askingChangesSinceOldRevision_then_changesAreP } @Test - public void given_filesystem_when_askingChangesSinceNewRevision_then_changesArePopulatedButEmpty() throws Exception { + void given_filesystem_when_askingChangesSinceNewRevision_then_changesArePopulatedButEmpty() throws Exception { File gitDir = new File("."); GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("git").getClient(); @@ -387,7 +401,7 @@ public void given_filesystem_when_askingChangesSinceNewRevision_then_changesAreP } @Test - public void create_SCMFileSystem_from_tag() throws Exception { + void create_SCMFileSystem_from_tag() throws Exception { sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.mkdirs("dir/subdir"); @@ -423,14 +437,14 @@ public void create_SCMFileSystem_from_tag() throws Exception { @Issue("JENKINS-52964") @Test - public void filesystem_supports_descriptor() throws Exception { + void filesystem_supports_descriptor() throws Exception { SCMSourceDescriptor descriptor = r.jenkins.getDescriptorByType(GitSCMSource.DescriptorImpl.class); assertTrue(SCMFileSystem.supports(descriptor)); } @Issue("JENKINS-42971") @Test - public void calculate_head_name_with_env() throws Exception { + void calculate_head_name_with_env() throws Exception { GitSCMFileSystem.BuilderImpl.HeadNameResult result1 = GitSCMFileSystem.BuilderImpl.HeadNameResult.calculate(new BranchSpec("${BRANCH}"), null, new EnvVars("BRANCH", "master-a")); assertEquals("master-a", result1.headName); @@ -466,7 +480,7 @@ public void calculate_head_name_with_env() throws Exception { * exception when the rev was non-null and the env was null. */ @Issue("JENKINS-70158") @Test - public void null_pointer_exception() throws Exception { + void null_pointer_exception() throws Exception { File gitDir = new File("."); GitClient client = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using("git").getClient(); ObjectId git260 = client.revParse(GIT_2_6_0_TAG); @@ -476,9 +490,4 @@ public void null_pointer_exception() throws Exception { assertEquals("master-f", result1.headName); assertEquals(Constants.R_HEADS, result1.prefix); } - - /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ - private boolean isWindows() { - return java.io.File.pathSeparatorChar==';'; - } } diff --git a/src/test/java/jenkins/plugins/git/GitSCMJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/GitSCMJCasCCompatibilityTest.java index 1b84d2f82a..55d157c182 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMJCasCCompatibilityTest.java @@ -1,25 +1,26 @@ package jenkins.plugins.git; import hudson.plugins.git.GitSCM; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import io.jenkins.plugins.casc.misc.junit.jupiter.AbstractRoundTripTest; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; + +@WithJenkins +class GitSCMJCasCCompatibilityTest extends AbstractRoundTripTest { -public class GitSCMJCasCCompatibilityTest extends RoundTripAbstractTest { @Override - protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { - GitSCM.DescriptorImpl gitSCM = (GitSCM.DescriptorImpl) restartableJenkinsRule.j.jenkins.getScm(GitSCM.class.getSimpleName()); + protected void assertConfiguredAsExpected(JenkinsRule rule, String s) { + GitSCM.DescriptorImpl gitSCM = (GitSCM.DescriptorImpl) rule.jenkins.getScm(GitSCM.class.getSimpleName()); assertEquals("user_name", gitSCM.getGlobalConfigName()); assertEquals("me@mail.com", gitSCM.getGlobalConfigEmail()); - assertTrue("Allow second fetch setting not honored", gitSCM.isAllowSecondFetch()); - assertTrue("Show entire commit summary setting not honored", gitSCM.isShowEntireCommitSummaryInChanges()); - assertTrue("Hide credentials setting not honored", gitSCM.isHideCredentials()); - assertFalse("Use existing account setting not honored", gitSCM.isUseExistingAccountWithSameEmail()); - assertTrue("Create account based on email setting not honored", gitSCM.isCreateAccountBasedOnEmail()); - assertTrue("Add git tag action setting not honored", gitSCM.isAddGitTagAction()); + assertTrue(gitSCM.isAllowSecondFetch(), "Allow second fetch setting not honored"); + assertTrue(gitSCM.isShowEntireCommitSummaryInChanges(), "Show entire commit summary setting not honored"); + assertTrue(gitSCM.isHideCredentials(), "Hide credentials setting not honored"); + assertFalse(gitSCM.isUseExistingAccountWithSameEmail(), "Use existing account setting not honored"); + assertTrue(gitSCM.isCreateAccountBasedOnEmail(), "Create account based on email setting not honored"); + assertTrue(gitSCM.isAddGitTagAction(), "Add git tag action setting not honored"); } @Override diff --git a/src/test/java/jenkins/plugins/git/GitSCMSourceContextTest.java b/src/test/java/jenkins/plugins/git/GitSCMSourceContextTest.java index 5625009b93..75f4d7d77a 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMSourceContextTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMSourceContextTest.java @@ -1,12 +1,12 @@ package jenkins.plugins.git; import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GitSCMSourceContextTest { +class GitSCMSourceContextTest { @Test - public void equalsContract_RefNameMapping() { + void equalsContract_RefNameMapping() { EqualsVerifier.forClass(GitSCMSourceContext.RefNameMapping.class) .usingGetClass() .verify(); diff --git a/src/test/java/jenkins/plugins/git/GitSCMSourceDefaultsTest.java b/src/test/java/jenkins/plugins/git/GitSCMSourceDefaultsTest.java index d61ec5d72f..2f0d3d096c 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMSourceDefaultsTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMSourceDefaultsTest.java @@ -1,12 +1,12 @@ package jenkins.plugins.git; import nl.jqno.equalsverifier.EqualsVerifier; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GitSCMSourceDefaultsTest { +class GitSCMSourceDefaultsTest { @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(GitSCMSourceDefaults.class) .usingGetClass() .verify(); diff --git a/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java b/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java index 2aead56e05..2e012cafef 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMSourceTest.java @@ -17,7 +17,6 @@ import hudson.tools.InstallSourceProperty; import hudson.tools.ToolInstallation; import java.io.ByteArrayInputStream; -import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.nio.charset.StandardCharsets; @@ -43,9 +42,8 @@ import jenkins.scm.api.SCMSourceOwner; import jenkins.scm.api.metadata.PrimaryInstanceMetadataAction; import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; @@ -53,8 +51,10 @@ import java.io.IOException; import java.util.Collections; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mockito; +import static hudson.Functions.isWindows; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -64,8 +64,8 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -74,23 +74,24 @@ /** * @author Robin Müller */ -public class GitSCMSourceTest { +@WithJenkins +class GitSCMSourceTest { - public static final String REMOTE = "git@remote:test/project.git"; + private static final String REMOTE = "git@remote:test/project.git"; - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; private GitStatus gitStatus; - @Before - public void setup() { + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; gitStatus = new GitStatus(); } @Test @Deprecated - public void testSourceOwnerTriggeredByDoNotifyCommit() throws Exception { + void testSourceOwnerTriggeredByDoNotifyCommit() throws Exception { String notifyCommitApiToken = ApiTokenPropertyConfiguration.get().generateApiToken("test").getString("value"); GitSCMSource gitSCMSource = new GitSCMSource("id", REMOTE, "", "*", "", false); GitSCMSourceOwner scmSourceOwner = setupGitSCMSourceOwner(gitSCMSource); @@ -164,7 +165,7 @@ public SCMHeadEvent waitSCMHeadEvent(long timeout, TimeUnit units) @Issue("JENKINS-47526") @Test - public void telescopeFetch() throws Exception { + void telescopeFetch() throws Exception { GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git"); assertThat(GitSCMTelescope.of(instance), nullValue()); @@ -210,7 +211,7 @@ public void telescopeFetch() throws Exception { @Issue("JENKINS-47526") @Test - public void telescopeFetchWithCriteria() throws Exception { + void telescopeFetchWithCriteria() throws Exception { GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git"); assertThat(GitSCMTelescope.of(instance), nullValue()); @@ -260,7 +261,7 @@ public void telescopeFetchWithCriteria() throws Exception { @Issue("JENKINS-47526") @Test - public void telescopeFetchRevisions() throws Exception { + void telescopeFetchRevisions() throws Exception { GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git"); assertThat(GitSCMTelescope.of(instance), nullValue()); @@ -282,7 +283,7 @@ public void telescopeFetchRevisions() throws Exception { @Issue("JENKINS-47526") @Test - public void telescopeFetchRevision() throws Exception { + void telescopeFetchRevision() throws Exception { GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git"); assertThat(GitSCMTelescope.of(instance), nullValue()); @@ -304,7 +305,7 @@ public void telescopeFetchRevision() throws Exception { @Issue("JENKINS-47526") @Test - public void telescopeFetchRevisionByName() throws Exception { + void telescopeFetchRevisionByName() throws Exception { GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git"); assertThat(GitSCMTelescope.of(instance), nullValue()); @@ -324,7 +325,7 @@ public void telescopeFetchRevisionByName() throws Exception { @Issue("JENKINS-47526") @Test - public void telescopeFetchActions() throws Exception { + void telescopeFetchActions() throws Exception { GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git"); assertThat(GitSCMTelescope.of(instance), nullValue()); @@ -358,7 +359,7 @@ public void telescopeFetchActions() throws Exception { @Issue("JENKINS-52754") @Test - public void gitSCMSourceShouldResolveToolsForMaster() throws Exception { + void gitSCMSourceShouldResolveToolsForMaster() throws Exception { if (isWindows()) { // Runs on Unix only /* Do not distract warnings system by using assumeThat to skip tests */ return; @@ -375,7 +376,7 @@ public void gitSCMSourceShouldResolveToolsForMaster() throws Exception { GitSCMSource instance = new GitSCMSource("http://git.test/telescope.git"); instance.fetchRevisions(log, null); - assertTrue("Installer should be invoked", inst.isInvoked()); + assertTrue(inst.isInvoked(), "Installer should be invoked"); } private static class HelloToolInstaller extends CommandInstaller { @@ -448,17 +449,13 @@ protected SCMFileSystem build(@NonNull String remote, StandardCredentials creden return new SCMFileSystem(rev) { @Override public long lastModified() throws IOException, InterruptedException { - switch (hash) { - case "6769413a79793e242c73d7377f0006c6aea95480": - return 15086163840000L; - case "3f0b897057d8b43d3b9ff55e3fdefbb021493470": - return 15086173840000L; - case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc": - return 15086183840000L; - case "315fd8b5cae3363b29050f1aabfc27c985e22f7e": - return 15086193840000L; - } - return 0L; + return switch (hash) { + case "6769413a79793e242c73d7377f0006c6aea95480" -> 15086163840000L; + case "3f0b897057d8b43d3b9ff55e3fdefbb021493470" -> 15086173840000L; + case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc" -> 15086183840000L; + case "315fd8b5cae3363b29050f1aabfc27c985e22f7e" -> 15086193840000L; + default -> 0L; + }; } @NonNull @@ -486,43 +483,35 @@ public long getTimestamp(@NonNull String remote, StandardCredentials credentials refOrHash = "315fd8b5cae3363b29050f1aabfc27c985e22f7e"; break; } - switch (refOrHash) { - case "6769413a79793e242c73d7377f0006c6aea95480": - return 15086163840000L; - case "3f0b897057d8b43d3b9ff55e3fdefbb021493470": - return 15086173840000L; - case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc": - return 15086183840000L; - case "315fd8b5cae3363b29050f1aabfc27c985e22f7e": - return 15086193840000L; - } - return 0L; + return switch (refOrHash) { + case "6769413a79793e242c73d7377f0006c6aea95480" -> 15086163840000L; + case "3f0b897057d8b43d3b9ff55e3fdefbb021493470" -> 15086173840000L; + case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc" -> 15086183840000L; + case "315fd8b5cae3363b29050f1aabfc27c985e22f7e" -> 15086193840000L; + default -> 0L; + }; } @Override public SCMRevision getRevision(@NonNull String remote, StandardCredentials credentials, @NonNull String refOrHash) throws IOException, InterruptedException { - switch (refOrHash) { - case "refs/heads/foo": - return new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480" - ); - case "refs/heads/bar": - return new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470" - ); - case "refs/heads/manchu": - return new AbstractGitSCMSource.SCMRevisionImpl( - new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc" - ); - case "refs/tags/v1.0.0": - return new GitTagSCMRevision( - new GitTagSCMHead("v1.0.0", 15086193840000L), - "315fd8b5cae3363b29050f1aabfc27c985e22f7e" - ); - } - return null; + return switch (refOrHash) { + case "refs/heads/foo" -> new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("foo"), "6769413a79793e242c73d7377f0006c6aea95480" + ); + case "refs/heads/bar" -> new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("bar"), "3f0b897057d8b43d3b9ff55e3fdefbb021493470" + ); + case "refs/heads/manchu" -> new AbstractGitSCMSource.SCMRevisionImpl( + new SCMHead("manchu"), "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc" + ); + case "refs/tags/v1.0.0" -> new GitTagSCMRevision( + new GitTagSCMHead("v1.0.0", 15086193840000L), + "315fd8b5cae3363b29050f1aabfc27c985e22f7e" + ); + default -> null; + }; } @Override @@ -593,17 +582,13 @@ public Iterable children() throws IOException, InterruptedException { @Override public long lastModified() throws IOException, InterruptedException { - switch (hash) { - case "6769413a79793e242c73d7377f0006c6aea95480": - return 15086163840000L; - case "3f0b897057d8b43d3b9ff55e3fdefbb021493470": - return 15086173840000L; - case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc": - return 15086183840000L; - case "315fd8b5cae3363b29050f1aabfc27c985e22f7e": - return 15086193840000L; - } - return 0L; + return switch (hash) { + case "6769413a79793e242c73d7377f0006c6aea95480" -> 15086163840000L; + case "3f0b897057d8b43d3b9ff55e3fdefbb021493470" -> 15086173840000L; + case "a94782d8d90b56b7e0d277c04589bd2e6f70d2cc" -> 15086183840000L; + case "315fd8b5cae3363b29050f1aabfc27c985e22f7e" -> 15086193840000L; + default -> 0L; + }; } @NonNull @@ -689,9 +674,4 @@ public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) thro return SCMFile.Type.REGULAR_FILE.equals(probe.stat(path).getType()); } } - - /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ - private boolean isWindows() { - return File.pathSeparatorChar==';'; - } } diff --git a/src/test/java/jenkins/plugins/git/GitSCMSourceTraitsTest.java b/src/test/java/jenkins/plugins/git/GitSCMSourceTraitsTest.java index e3db3797b8..58e452e28b 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMSourceTraitsTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMSourceTraitsTest.java @@ -37,11 +37,12 @@ import jenkins.scm.api.trait.SCMSourceTrait; import jenkins.scm.impl.trait.WildcardSCMHeadFilterTrait; import org.hamcrest.Matchers; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; @@ -55,18 +56,17 @@ import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; -public class GitSCMSourceTraitsTest { +@WithJenkins +class GitSCMSourceTraitsTest { /** * All tests in this class only use Jenkins for the extensions */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; - @Rule - public TestName currentTestName = new TestName(); + private String currentTestName; private GitSCMSource load() { - return load(currentTestName.getMethodName()); + return load(currentTestName); } private GitSCMSource load(String dataSet) { @@ -74,8 +74,18 @@ private GitSCMSource load(String dataSet) { getClass().getResource(getClass().getSimpleName() + "/" + dataSet + ".xml")); } + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; + } + + @BeforeEach + void beforeEach(TestInfo info) { + currentTestName = info.getTestMethod().orElseThrow().getName(); + } + @Test - public void modern() throws Exception { + void modern() throws Exception { GitSCMSource instance = load(); assertThat(instance.getId(), is("5b061c87-da5c-4d69-b9d5-b041d065c945")); assertThat(instance.getRemote(), is("git://git.test/example.git")); @@ -84,22 +94,22 @@ public void modern() throws Exception { } @Test - public void cleancheckout_v1_extension() { + void cleancheckout_v1_extension() { verifyCleanCheckoutTraits(false); } @Test - public void cleancheckout_v1_trait() { + void cleancheckout_v1_trait() { verifyCleanCheckoutTraits(false); } @Test - public void cleancheckout_v2_extension() { + void cleancheckout_v2_extension() { verifyCleanCheckoutTraits(true); } @Test - public void cleancheckout_v2_trait() { + void cleancheckout_v2_trait() { verifyCleanCheckoutTraits(true); } @@ -133,9 +143,10 @@ private void verifyCleanCheckoutTraits(boolean deleteUntrackedNestedRepositories ); } + // Includes tests of deprecated methods getIncludes, getExcludes, & getRawRefSpecs @Test - @Deprecated // Includes tests of deprecated methods getIncludes, getExcludes, & getRawRefSpecs - public void pimpped_out() throws Exception { + @Deprecated + void pimpped_out() throws Exception { GitSCMSource instance = load(); assertThat(instance.getId(), is("fd2380f8-d34f-48d5-8006-c34542bc4a89")); assertThat(instance.getRemote(), is("git://git.test/example.git")); @@ -292,13 +303,14 @@ public void pimpped_out() throws Exception { } @Test - public void given__modernCode__when__constructor__then__traitsEmpty() throws Exception { + void given__modernCode__when__constructor__then__traitsEmpty() throws Exception { assertThat(new GitSCMSource("git://git.test/example.git").getTraits(), is(empty())); } + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults1() throws Exception { + @Deprecated + void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults1() throws Exception { GitSCMSource instance = new GitSCMSource("id", "git://git.test/example.git", null, "*", "", false); assertThat(instance.getTraits(), contains( instanceOf(BranchDiscoveryTrait.class) @@ -310,9 +322,10 @@ public void given__legacyCode__when__constructor__then__traitsContainLegacyDefau assertThat(instance.getRawRefSpecs(), is("+refs/heads/*:refs/remotes/origin/*")); } + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults2() throws Exception { + @Deprecated + void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults2() throws Exception { GitSCMSource instance = new GitSCMSource("id", "git://git.test/example.git", null, "*", "", true); assertThat(instance.getTraits(), containsInAnyOrder( instanceOf(BranchDiscoveryTrait.class), @@ -321,9 +334,10 @@ public void given__legacyCode__when__constructor__then__traitsContainLegacyDefau assertThat(instance.isIgnoreOnPushNotifications(), is(true)); } + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults3() throws Exception { + @Deprecated + void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults3() throws Exception { GitSCMSource instance = new GitSCMSource("id", "git://git.test/example.git", null, "foo/*", "", false); assertThat(instance.getTraits(), contains( instanceOf(BranchDiscoveryTrait.class), @@ -337,9 +351,10 @@ public void given__legacyCode__when__constructor__then__traitsContainLegacyDefau assertThat(instance.getExcludes(), is("")); } + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults4() throws Exception { + @Deprecated + void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults4() throws Exception { GitSCMSource instance = new GitSCMSource("id", "git://git.test/example.git", null, "", "foo/*", false); assertThat(instance.getTraits(), contains( instanceOf(BranchDiscoveryTrait.class), @@ -353,9 +368,10 @@ public void given__legacyCode__when__constructor__then__traitsContainLegacyDefau assertThat(instance.getExcludes(), is("foo/*")); } + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults5() throws Exception { + @Deprecated + void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults5() throws Exception { GitSCMSource instance = new GitSCMSource("id", "git://git.test/example.git", null, "upstream", null, "*", "", false); assertThat(instance.getTraits(), contains( @@ -368,9 +384,10 @@ public void given__legacyCode__when__constructor__then__traitsContainLegacyDefau assertThat(instance.getRemoteName(), is("upstream")); } + // Testing deprecated GitSCMSource constructor @Test - @Deprecated // Testing deprecated GitSCMSource constructor - public void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults6() throws Exception { + @Deprecated + void given__legacyCode__when__constructor__then__traitsContainLegacyDefaults6() throws Exception { GitSCMSource instance = new GitSCMSource("id", "git://git.test/example.git", null, null, "refs/pulls/*:refs/upstream/*", "*", "", false); diff --git a/src/test/java/jenkins/plugins/git/GitSCMTelescopeTest.java b/src/test/java/jenkins/plugins/git/GitSCMTelescopeTest.java index c2da45a352..d3696ef355 100644 --- a/src/test/java/jenkins/plugins/git/GitSCMTelescopeTest.java +++ b/src/test/java/jenkins/plugins/git/GitSCMTelescopeTest.java @@ -51,6 +51,8 @@ import java.util.Iterator; import java.util.List; import java.util.Set; + +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import jenkins.plugins.git.traits.GitBrowserSCMSourceTrait; import jenkins.plugins.git.traits.GitToolSCMSourceTrait; import jenkins.scm.api.SCMFileSystem; @@ -65,37 +67,40 @@ import jenkins.scm.api.trait.SCMSourceTrait; import jenkins.scm.api.trait.SCMSourceTraitDescriptor; import org.acegisecurity.AccessDeniedException; -import org.junit.Test; import static org.hamcrest.Matchers.*; import org.jenkinsci.plugins.gitclient.GitClient; import static org.hamcrest.MatcherAssert.*; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Before; -import org.junit.ClassRule; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class GitSCMTelescopeTest /* extends AbstractGitRepository */ { +@WithGitSampleRepo +class GitSCMTelescopeTest /* extends AbstractGitRepository */ { private final StandardCredentials credentials = null; /* REPO can be allocated once for the whole test suite so long as nothing changes it */ - @ClassRule - static public final GitSampleRepoRule READ_ONLY_REPO = new GitSampleRepoRule(); + private static GitSampleRepoRule readOnlyRepo; - private final String remote; + private static String remote; private GitSCMTelescope telescope; - public GitSCMTelescopeTest() { - remote = READ_ONLY_REPO.fileUrl(); + @BeforeAll + static void beforeAll(GitSampleRepoRule repo) { + readOnlyRepo = repo; + remote = readOnlyRepo.fileUrl(); } - @Before - public void createTelescopeForRemote() { + @BeforeEach + void beforeEach() { telescope = new GitSCMTelescopeImpl(remote); } @Test - public void testOf_GitSCM() throws Exception { + void testOf_GitSCM() throws Exception { /* Testing GitSCMTelescope.of() for non null return needs JenkinsRule */ GitSCM multiBranchSource = new GitSCM(remote); GitSCMTelescope telescopeOfMultiBranchSource = GitSCMTelescope.of(multiBranchSource); @@ -103,25 +108,25 @@ public void testOf_GitSCM() throws Exception { } @Test - public void testOf_AbstractGitSCMSource() { + void testOf_AbstractGitSCMSource() { AbstractGitSCMSource source = new AbstractGitSCMSourceImpl(); GitSCMTelescope telescopeOfAbstractGitSCMSource = GitSCMTelescope.of(source); assertThat(telescopeOfAbstractGitSCMSource, is(nullValue())); } @Test - public void testSupports_StringFalse() { + void testSupports_StringFalse() { GitSCMTelescope telescopeWithoutRemote = new GitSCMTelescopeImpl(); assertFalse(telescopeWithoutRemote.supports(remote)); } @Test - public void testSupports_String() { + void testSupports_String() { assertTrue(telescope.supports(remote)); } @Test - public void testValidate() throws Exception { + void testValidate() throws Exception { telescope.validate(remote, credentials); } @@ -156,28 +161,28 @@ private GitSCM getSingleBranchSource(String repoUrl) throws Exception { } @Test - public void testSupports_SCM() throws Exception { + void testSupports_SCM() throws Exception { GitSCM singleBranchSource = getSingleBranchSource(remote); // single branch source is supported by telescope assertTrue(telescope.supports(singleBranchSource)); } @Test - public void testSupports_SCMNullSCM() throws Exception { + void testSupports_SCMNullSCM() throws Exception { NullSCM nullSCM = new NullSCM(); // NullSCM is not supported by telescope assertFalse(telescope.supports(nullSCM)); } @Test - public void testSupports_SCMMultiBranchSource() throws Exception { + void testSupports_SCMMultiBranchSource() throws Exception { GitSCM multiBranchSource = new GitSCM(remote); // Multi-branch source is not supported by telescope assertFalse(telescope.supports(multiBranchSource)); } @Test - public void testSupports_SCMSource() { + void testSupports_SCMSource() { SCMSource source = new GitSCMSource(remote); SCMSourceOwner sourceOwner = new SCMSourceOwnerImpl(); source.setOwner(sourceOwner); @@ -185,44 +190,44 @@ public void testSupports_SCMSource() { } @Test - public void testSupports_SCMSourceNoOwner() { + void testSupports_SCMSourceNoOwner() { SCMSource source = new GitSCMSource(remote); // SCMSource without an owner not supported by telescope assertFalse(telescope.supports(source)); } @Test - public void testSupports_SCMSourceNullSource() { + void testSupports_SCMSourceNullSource() { SCMSource source = new SCMSourceImpl(); // Non AbstractGitSCMSource is not supported by telescope assertFalse(telescope.supports(source)); } @Test - public void testGetTimestamp_3args_1() throws Exception { + void testGetTimestamp_3args_1() throws Exception { String refOrHash = "master"; assertThat(telescope.getTimestamp(remote, credentials, refOrHash), is(12345L)); } @Test - public void testGetTimestamp_3args_2Tag() throws Exception { + void testGetTimestamp_3args_2Tag() throws Exception { SCMHead head = new GitTagSCMHead("git-tag-name", 56789L); assertThat(telescope.getTimestamp(remote, credentials, head), is(12345L)); } @Test - public void testGetTimestamp_3args_2() throws Exception { + void testGetTimestamp_3args_2() throws Exception { SCMHead head = new SCMHead("git-tag-name"); assertThat(telescope.getTimestamp(remote, credentials, head), is(12345L)); } @Test - public void testGetDefaultTarget() throws Exception { + void testGetDefaultTarget() throws Exception { assertThat(telescope.getDefaultTarget(remote, null), is("")); } @Test - public void testBuild_3args_1() throws Exception { + void testBuild_3args_1() throws Exception { SCMSource source = new GitSCMSource(remote); SCMSourceOwner sourceOwner = new SCMSourceOwnerImpl(); source.setOwner(sourceOwner); @@ -235,7 +240,7 @@ public void testBuild_3args_1() throws Exception { } @Test - public void testBuild_3args_1NoOwner() throws Exception { + void testBuild_3args_1NoOwner() throws Exception { SCMSource source = new GitSCMSource(remote); SCMHead head = new SCMHead("some-name"); SCMRevision rev = null; @@ -244,7 +249,7 @@ public void testBuild_3args_1NoOwner() throws Exception { } @Test - public void testBuild_3args_2() throws Exception { + void testBuild_3args_2() throws Exception { Item owner = new ItemImpl(); SCM scm = getSingleBranchSource(remote); SCMHead head = new SCMHead("some-name"); @@ -256,7 +261,7 @@ public void testBuild_3args_2() throws Exception { } @Test - public void testBuild_4args() throws Exception { + void testBuild_4args() throws Exception { SCMHead head = new SCMHead("some-name"); String SHA1 = "0123456789abcdef0123456789abcdef01234567"; SCMRevision rev = new AbstractGitSCMSource.SCMRevisionImpl(head, SHA1); @@ -267,7 +272,7 @@ public void testBuild_4args() throws Exception { } @Test - public void testGetRevision_3args_1() throws Exception { + void testGetRevision_3args_1() throws Exception { SCMHead head = new SCMHead("some-name"); String SHA1 = "0123456789abcdef0123456789abcdef01234567"; SCMRevision rev = new AbstractGitSCMSource.SCMRevisionImpl(head, SHA1); @@ -277,7 +282,7 @@ public void testGetRevision_3args_1() throws Exception { } @Test - public void testGetRevision_3args_2() throws Exception { + void testGetRevision_3args_2() throws Exception { SCMHead head = new GitTagSCMHead("git-tag-name", 56789L); String SHA1 = "0123456789abcdef0123456789abcdef01234567"; SCMRevision rev = new AbstractGitSCMSource.SCMRevisionImpl(head, SHA1); @@ -286,7 +291,7 @@ public void testGetRevision_3args_2() throws Exception { } @Test - public void testGetRevisions_3args() throws Exception { + void testGetRevisions_3args() throws Exception { Set referenceTypes = new HashSet<>(); Iterable revisions = telescope.getRevisions(remote, credentials, referenceTypes); assertThat(revisions, is(notNullValue())); @@ -294,7 +299,7 @@ public void testGetRevisions_3args() throws Exception { } @Test - public void testGetRevisions_3argsWithRev() throws Exception { + void testGetRevisions_3argsWithRev() throws Exception { Set referenceTypes = new HashSet<>(); SCMHead head = new GitTagSCMHead("git-tag-name", 56789L); String SHA1 = "0123456789abcdef0123456789abcdef01234567"; @@ -308,7 +313,7 @@ public void testGetRevisions_3argsWithRev() throws Exception { } @Test - public void testGetRevisions_String_StandardCredentials() throws Exception { + void testGetRevisions_String_StandardCredentials() throws Exception { String SHA1 = "0123456789abcdef0123456789abcdef01234567"; SCMHead head = new GitTagSCMHead("git-tag-name", 56789L); SCMRevision rev = new AbstractGitSCMSource.SCMRevisionImpl(head, SHA1); diff --git a/src/test/java/jenkins/plugins/git/GitToolChooserTest.java b/src/test/java/jenkins/plugins/git/GitToolChooserTest.java index 8d9e950bd5..e9ecdaf3e6 100644 --- a/src/test/java/jenkins/plugins/git/GitToolChooserTest.java +++ b/src/test/java/jenkins/plugins/git/GitToolChooserTest.java @@ -13,6 +13,7 @@ import hudson.tools.*; import hudson.util.StreamTaskListener; import jenkins.model.Jenkins; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import jenkins.plugins.git.traits.BranchDiscoveryTrait; import org.jenkinsci.plugins.gitclient.JGitApacheTool; @@ -20,53 +21,56 @@ import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Stopwatch; -import org.junit.rules.TestName; -import org.junit.runner.OrderWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mockito; import java.io.File; import java.io.IOException; +import java.time.Duration; +import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Set; -import static java.util.concurrent.TimeUnit.SECONDS; +import static hudson.Functions.isWindows; import static org.hamcrest.io.FileMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * The test aims to functionally validate "estimation of size" and "git implementation recommendation" from a * cached directory and from plugin extensions. */ -@OrderWith(RandomOrder.class) -public class GitToolChooserTest { +@TestMethodOrder(MethodOrderer.Random.class) +@WithJenkins +@WithGitSampleRepo +class GitToolChooserTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + private GitSampleRepoRule sampleRepo; - static final String GitBranchSCMHead_DEV_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; + static final String GIT_BRANCH_SCM_HEAD_DEV_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]"; private CredentialsStore store = null; private static Random random = new Random(); - @Before - public void enableSystemCredentialsProvider() { + @BeforeEach + void beforeEach(JenkinsRule rule, GitSampleRepoRule repo) { + r = rule; + sampleRepo = repo; + SystemCredentialsProvider.getInstance().setDomainCredentialsMap( Collections.singletonMap(Domain.global(), Collections.emptyList())); for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.get())) { @@ -78,25 +82,22 @@ public void enableSystemCredentialsProvider() { assertThat("The system credentials provider is enabled", store, notNullValue()); } - @Before - public void resetRepositorySizeCache() { + @BeforeEach + void beforeEach() { GitToolChooser.clearRepositorySizeCache(); } - @ClassRule - public static Stopwatch stopwatch = new Stopwatch(); - @Rule - public TestName testName = new TestName(); + private static final Instant START_TIME = Instant.now(); private static final int MAX_SECONDS_FOR_THESE_TESTS = 150; private boolean isTimeAvailable() { String env = System.getenv("CI"); - if (env == null || !Boolean.parseBoolean(env)) { + if (!Boolean.parseBoolean(env)) { // Run all tests when not in CI environment return true; } - return stopwatch.runtime(SECONDS) <= MAX_SECONDS_FOR_THESE_TESTS; + return Duration.between(START_TIME, Instant.now()).toSeconds() <= MAX_SECONDS_FOR_THESE_TESTS; } /* @@ -105,8 +106,8 @@ private boolean isTimeAvailable() { */ @Issue("JENKINS-63519") @Test - public void testResolveGitTool() throws IOException, InterruptedException { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testResolveGitTool() throws IOException, InterruptedException { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git"; Item context = Mockito.mock(Item.class); String credentialsId = null; @@ -128,12 +129,12 @@ There is no specific agent(node=null). In this case agent = Jenkins.get(). */ @Issue("JENKINS-63519") @Test - public void testResolveGitToolWithJenkins() throws IOException, InterruptedException { + void testResolveGitToolWithJenkins() throws IOException, InterruptedException { if (isWindows()) { // Runs on Unix only /* Do not distract warnings system by using assumeThat to skip tests */ return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git"; Item context = Mockito.mock(Item.class); String credentialsId = null; @@ -159,12 +160,12 @@ public void testResolveGitToolWithJenkins() throws IOException, InterruptedExcep */ @Issue("JENKINS-63519") @Test - public void testResolutionGitToolOnAgent() throws Exception { + void testResolutionGitToolOnAgent() throws Exception { if (isWindows()) { // Runs on Unix only /* Do not distract warnings system by using assumeThat to skip tests */ return; } - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git"; Item context = Mockito.mock(Item.class); String credentialsId = null; @@ -203,8 +204,8 @@ public void testResolutionGitToolOnAgent() throws Exception { instead of recommending no git implementation. */ @Test - public void testSizeEstimationWithNoGitCache() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testSizeEstimationWithNoGitCache() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); GitSCMSource instance = new GitSCMSource("https://github.com/rishabhBudhouliya/git-plugin.git"); @@ -234,8 +235,8 @@ public void testSizeEstimationWithNoGitCache() throws Exception { out repository and ultimately provide a suggestion on the base of decided heuristic. */ @Test - public void testSizeEstimationWithGitCache() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testSizeEstimationWithGitCache() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); sampleRepo.git("checkout", "-b", "dev"); sampleRepo.write("file", "modified"); @@ -251,7 +252,7 @@ public void testSizeEstimationWithGitCache() throws Exception { // SCMHeadObserver.Collector.result is a TreeMap so order is predictable: assertEquals("[]", source.fetch(listener).toString()); source.setTraits(Collections.singletonList(new BranchDiscoveryTrait())); - assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString()); + assertEquals(GIT_BRANCH_SCM_HEAD_DEV_MASTER, source.fetch(listener).toString()); // With JGit, we don't ask the name and home of the tool GitTool tool = new JGitTool(Collections.emptyList()); @@ -288,8 +289,8 @@ public void testSizeEstimationWithGitCache() throws Exception { /* Test the remoteAlternatives permutation of git repo URLs */ @Test @Issue("JENKINS-63539") - public void testRemoteAlternatives() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testRemoteAlternatives() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); GitTool tool = new JGitTool(Collections.emptyList()); GitToolChooser nullRemoteSizeEstimator = new GitToolChooser("git://example.com/git/git.git", null, null, tool, null, TaskListener.NULL, true); @@ -331,8 +332,8 @@ public void testRemoteAlternatives() throws Exception { /* Test conversion of any remote alternative of git repo URLs to a standard URL */ @Test - public void testConvertToCanonicalURL() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testConvertToCanonicalURL() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); GitTool tool = new JGitTool(Collections.emptyList()); String[] remoteAlternatives = { @@ -365,8 +366,8 @@ public void testConvertToCanonicalURL() throws Exception { recommend "git" as the optimal implementation from the heuristics */ @Test - public void testSizeEstimationWithAPIForGit() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testSizeEstimationWithAPIForGit() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git"; sampleRepo.init(); store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github")); @@ -388,8 +389,8 @@ public void testSizeEstimationWithAPIForGit() throws Exception { recommend "jgit" as the optimal implementation from the heuristics */ @Test - public void testSizeEstimationWithAPIForJGit() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testSizeEstimationWithAPIForJGit() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://github.com/rishabhBudhouliya/git-plugin.git"; sampleRepo.init(); store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github")); @@ -412,8 +413,8 @@ public void testSizeEstimationWithAPIForJGit() throws Exception { the estimator recommends no git implementation */ @Test - public void testSizeEstimationWithBitbucketAPIs() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testSizeEstimationWithBitbucketAPIs() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://bitbucket.com/rishabhBudhouliya/git-plugin.git"; sampleRepo.init(); store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github")); @@ -434,8 +435,8 @@ public void testSizeEstimationWithBitbucketAPIs() throws Exception { "INFO" message and returns no recommendation. */ @Test - public void testSizeEstimationWithException() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testSizeEstimationWithException() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://bitbucket.com/rishabhBudhouliya/git-plugin.git"; sampleRepo.init(); store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github")); @@ -456,8 +457,8 @@ public void testSizeEstimationWithException() throws Exception { and try querying for size of repo, if it throws an exception we catch it and recommend "NONE", i.e, no recommendation. */ @Test - public void testSizeEstimationWithNoCredentials() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testSizeEstimationWithNoCredentials() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); buildAProject(sampleRepo, true); @@ -476,8 +477,8 @@ public void testSizeEstimationWithNoCredentials() throws Exception { Scenario 1: Size of repo is < 5 MiB, "jgit" should be recommended */ @Test - public void testGitToolChooserWithCustomGitTool() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testGitToolChooserWithCustomGitTool() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://github.com/rishabhBudhouliya/git-plugin.git"; Item context = Mockito.mock(Item.class); String credentialsId = null; @@ -495,8 +496,8 @@ public void testGitToolChooserWithCustomGitTool() throws Exception { } @Test - public void testGitToolChooserWithBothGitAndJGit() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testGitToolChooserWithBothGitAndJGit() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://github.com/rishabhBudhouliya/git-plugin.git"; Item context = Mockito.mock(Item.class); String credentialsId = null; @@ -514,8 +515,8 @@ public void testGitToolChooserWithBothGitAndJGit() throws Exception { According to the size of repo, GitToolChooser will recommend "jgit" even if "jgitapache" is present */ @Test - public void testGitToolChooserWithAllTools() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testGitToolChooserWithAllTools() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://github.com/rishabhBudhouliya/git-plugin.git"; Item context = Mockito.mock(Item.class); String credentialsId = null; @@ -535,8 +536,8 @@ public void testGitToolChooserWithAllTools() throws Exception { recommend `jgitapache` */ @Test - public void testGitToolChooserWithJGitApache() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testGitToolChooserWithJGitApache() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://github.com/rishabhBudhouliya/git-plugin.git"; Item context = Mockito.mock(Item.class); String credentialsId = null; @@ -554,8 +555,8 @@ public void testGitToolChooserWithJGitApache() throws Exception { According to the size of repo, GitToolChooser will recommend "jgitapache" since that is user's configured choice */ @Test - public void testGitToolChooserWithJGitApacheAndGit() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testGitToolChooserWithJGitApacheAndGit() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://github.com/rishabhBudhouliya/git-plugin.git"; Item context = Mockito.mock(Item.class); String credentialsId = null; @@ -573,8 +574,8 @@ public void testGitToolChooserWithJGitApacheAndGit() throws Exception { Scenario 2: Size of repo is > 5 MiB, "git" should be recommended */ @Test - public void testGitToolChooserWithDefaultTool() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testGitToolChooserWithDefaultTool() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git"; sampleRepo.init(); store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github")); @@ -591,8 +592,8 @@ public void testGitToolChooserWithDefaultTool() throws Exception { } @Test - public void testGitToolChooserWithOnlyJGit() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testGitToolChooserWithOnlyJGit() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git"; sampleRepo.init(); store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github")); @@ -614,8 +615,8 @@ public void testGitToolChooserWithOnlyJGit() throws Exception { } @Test - public void testGitToolChooserWithCustomGitTool_2() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testGitToolChooserWithCustomGitTool_2() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git"; sampleRepo.init(); store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github")); @@ -637,8 +638,8 @@ public void testGitToolChooserWithCustomGitTool_2() throws Exception { } @Test - public void testGitToolChooserWithAllTools_2() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testGitToolChooserWithAllTools_2() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git"; sampleRepo.init(); store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github")); @@ -663,8 +664,8 @@ public void testGitToolChooserWithAllTools_2() throws Exception { @Test @Issue("JENKINS-63541") - public void getCacheDirCreatesNoDirectory() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void getCacheDirCreatesNoDirectory() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); // Generate a unique repository name and compute expected cache directory String remoteName = "https://github.com/jenkinsci/git-plugin-" + java.util.UUID.randomUUID() + ".git"; String cacheEntry = AbstractGitSCMSource.getCacheEntry(remoteName); @@ -687,8 +688,8 @@ public void getCacheDirCreatesNoDirectory() throws Exception { /* Do not throw null pointer excception if remote configuration is empty. */ @Test @Issue("JENKINS-63572") - public void testSizeEstimationWithNoRemoteConfig() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void testSizeEstimationWithNoRemoteConfig() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); sampleRepo.init(); failAProject(sampleRepo); @@ -815,9 +816,4 @@ private void failAProject(GitSampleRepoRule sampleRepo) throws Exception { private StandardCredentials createCredential(CredentialsScope scope, String id) throws FormException { return new UsernamePasswordCredentialsImpl(scope, id, "desc: " + id, "username", "password-longer-than-14"); } - - /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ - private boolean isWindows() { - return File.pathSeparatorChar==';'; - } } diff --git a/src/test/java/jenkins/plugins/git/GitToolJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/GitToolJCasCCompatibilityTest.java index 18891a961c..90a6cf244b 100644 --- a/src/test/java/jenkins/plugins/git/GitToolJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GitToolJCasCCompatibilityTest.java @@ -10,8 +10,9 @@ import hudson.tools.ToolPropertyDescriptor; import hudson.tools.ZipExtractionInstaller; import hudson.util.DescribableList; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import io.jenkins.plugins.casc.misc.junit.jupiter.AbstractRoundTripTest; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; @@ -20,13 +21,15 @@ import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.hamcrest.MatcherAssert.assertThat; -public class GitToolJCasCCompatibilityTest extends RoundTripAbstractTest { +@WithJenkins +class GitToolJCasCCompatibilityTest extends AbstractRoundTripTest { + @Override - protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { - final ToolDescriptor descriptor = (ToolDescriptor) restartableJenkinsRule.j.jenkins.getDescriptor(GitTool.class); + protected void assertConfiguredAsExpected(JenkinsRule rule, String s) { + final ToolDescriptor descriptor = (ToolDescriptor) rule.jenkins.getDescriptor(GitTool.class); final ToolInstallation[] installations = descriptor.getInstallations(); assertThat(installations, arrayWithSize(1)); assertEquals("Default", installations[0].getName()); diff --git a/src/test/java/jenkins/plugins/git/GitUsernamePasswordBindingTest.java b/src/test/java/jenkins/plugins/git/GitUsernamePasswordBindingTest.java index e2490e0476..4ac92ba7d4 100644 --- a/src/test/java/jenkins/plugins/git/GitUsernamePasswordBindingTest.java +++ b/src/test/java/jenkins/plugins/git/GitUsernamePasswordBindingTest.java @@ -8,7 +8,6 @@ import hudson.EnvVars; import hudson.FilePath; -import hudson.model.Descriptor.FormException; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Item; @@ -17,6 +16,7 @@ import hudson.tasks.BatchFile; import hudson.tasks.Shell; import jenkins.model.Jenkins; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FilenameUtils; import org.jenkinsci.plugins.credentialsbinding.MultiBinding; @@ -27,68 +27,67 @@ import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Stopwatch; -import org.junit.rules.TemporaryFolder; -import org.junit.rules.TestName; -import org.junit.runner.OrderWith; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.jvnet.hudson.test.BuildWatcher; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.BuildWatcherExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Collection; import java.util.Random; -import static org.junit.Assume.assumeTrue; +import static hudson.Functions.isWindows; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static java.util.concurrent.TimeUnit.SECONDS; -@OrderWith(RandomOrder.class) -@RunWith(Parameterized.class) -public class GitUsernamePasswordBindingTest { +@TestMethodOrder(MethodOrderer.Random.class) +@ParameterizedClass(name = "User {0}: Password {1}: GitToolInstance {2}") +@MethodSource("data") +@WithJenkins +@WithGitSampleRepo +class GitUsernamePasswordBindingTest { - @ClassRule - public static BuildWatcher bw = new BuildWatcher(); + @SuppressWarnings("unused") + @RegisterExtension + private static final BuildWatcherExtension BUILD_WATCHER = new BuildWatcherExtension(); - @Parameterized.Parameters(name = "User {0}: Password {1}: GitToolInstance {2}") - public static Collection data() { + static Collection data() { return Arrays.asList(testData); } - @Rule - public final TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; - @Rule - public GitSampleRepoRule g = new GitSampleRepoRule(); + private GitSampleRepoRule g; - @ClassRule - public static Stopwatch stopwatch = new Stopwatch(); - @Rule - public TestName testName = new TestName(); + private static final Instant START_TIME = Instant.now(); private static final int MAX_SECONDS_FOR_THESE_TESTS = 200; private boolean isTimeAvailable() { String env = System.getenv("CI"); - if (env == null || !Boolean.parseBoolean(env)) { + if (!Boolean.parseBoolean(env)) { // Run all tests when not in CI environment return true; } - return stopwatch.runtime(SECONDS) <= MAX_SECONDS_FOR_THESE_TESTS; + return Duration.between(START_TIME, Instant.now()).toSeconds() <= MAX_SECONDS_FOR_THESE_TESTS; } private final String username; @@ -100,10 +99,10 @@ private boolean isTimeAvailable() { private final String credentialID = DigestUtils.sha256Hex(("Git Usernanme and Password Binding").getBytes(StandardCharsets.UTF_8)); private File rootDir = null; + private FilePath rootFilePath = null; private UsernamePasswordCredentialsImpl credentials = null; private GitUsernamePasswordBinding gitCredBind = null; - private static final Random random = new Random(); private static String[] userNames = { @@ -113,6 +112,7 @@ private boolean isTimeAvailable() { "r-Name", "randomName", }; + private static String[] passwords = { "&Ampersand-long-enough&", "He said \"Hello\", then left.", @@ -128,8 +128,8 @@ private boolean isTimeAvailable() { new JGitApacheTool(), new JGitTool(), }; - /* Create three test data items using random selections from the larger set of data */ + private static Object[][] testData = new Object[][]{ {userNames[random.nextInt(userNames.length)], passwords[random.nextInt(passwords.length)], gitTools[random.nextInt(gitTools.length)]}, {userNames[random.nextInt(userNames.length)], passwords[random.nextInt(passwords.length)], gitTools[random.nextInt(gitTools.length)]}, @@ -142,10 +142,13 @@ public GitUsernamePasswordBindingTest(String username, String password, GitTool this.gitToolInstance = gitToolInstance; } - @Before - public void basicSetup() throws FormException, IOException { + @BeforeEach + void beforeEach(JenkinsRule rule, GitSampleRepoRule repo) throws Exception { + r = rule; + g = repo; + //File init - rootDir = tempFolder.getRoot(); + rootDir = tempFolder; rootFilePath = new FilePath(rootDir.getAbsoluteFile()); //Credential init @@ -172,8 +175,8 @@ private String shellCheck() { } @Test - public void test_EnvironmentVariables_FreeStyleProject() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void test_EnvironmentVariables_FreeStyleProject() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject prj = r.createFreeStyleProject(); prj.getBuildWrappersList().add(new SecretBuildWrapper(Collections.> singletonList(new GitUsernamePasswordBinding(gitToolInstance.getName(), credentialID)))); @@ -221,8 +224,8 @@ public void test_EnvironmentVariables_FreeStyleProject() throws Exception { } @Test - public void test_EnvironmentVariables_PipelineJob() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void test_EnvironmentVariables_PipelineJob() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); WorkflowJob project = r.createProject(WorkflowJob.class); // JENKINS-66214 - allow either gitUsernamePassword or GitUsernamePassword as keyword @@ -270,14 +273,14 @@ public void test_EnvironmentVariables_PipelineJob() throws Exception { } @Test - public void test_isCurrentNodeOSUnix(){ - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void test_isCurrentNodeOSUnix(){ + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); assertThat(gitCredBind.isCurrentNodeOSUnix(r.createLocalLauncher()), not(equalTo(isWindows()))); } @Test - public void test_getCliGitTool_using_FreeStyleProject() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void test_getCliGitTool_using_FreeStyleProject() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); FreeStyleProject prj = r.createFreeStyleProject(); prj.getBuildWrappersList().add(new SecretBuildWrapper(Collections.> singletonList(new GitUsernamePasswordBinding(gitToolInstance.getName(), credentialID)))); @@ -301,8 +304,8 @@ public void test_getCliGitTool_using_FreeStyleProject() throws Exception { } @Test - public void test_getGitClientInstance() throws IOException, InterruptedException { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void test_getGitClientInstance() throws IOException, InterruptedException { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); if (isCliGitTool()) { assertThat(gitCredBind.getGitClientInstance(gitToolInstance.getGitExe(), rootFilePath, new EnvVars(), TaskListener.NULL), instanceOf(CliGitAPIImpl.class)); @@ -313,8 +316,8 @@ public void test_getGitClientInstance() throws IOException, InterruptedException } @Test - public void test_GenerateGitScript_write() throws Exception { - assumeTrue("Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded", isTimeAvailable()); + void test_GenerateGitScript_write() throws Exception { + assumeTrue(isTimeAvailable(), "Test class max time " + MAX_SECONDS_FOR_THESE_TESTS + " exceeded"); GitUsernamePasswordBinding.GenerateGitScript tempGenScript = new GitUsernamePasswordBinding.GenerateGitScript(this.username, this.password, credentials.getId(), !isWindows()); assertThat(tempGenScript.type(), is(StandardUsernamePasswordCredentials.class)); FilePath tempScriptFile = tempGenScript.write(credentials, rootFilePath); @@ -330,14 +333,6 @@ public void test_GenerateGitScript_write() throws Exception { } } - /** - * inline ${@link hudson.Functions#isWindows()} to prevent a transient - * remote classloader issue - */ - private static boolean isWindows() { - return File.pathSeparatorChar == ';'; - } - private boolean isCliGitTool() { return gitToolInstance.getClass().equals(GitTool.class); } diff --git a/src/test/java/jenkins/plugins/git/GlobalLibraryWithLegacyJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/GlobalLibraryWithLegacyJCasCCompatibilityTest.java index 3b04744c94..2e68284446 100644 --- a/src/test/java/jenkins/plugins/git/GlobalLibraryWithLegacyJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GlobalLibraryWithLegacyJCasCCompatibilityTest.java @@ -31,13 +31,14 @@ import hudson.plugins.git.extensions.impl.UserIdentity; import hudson.plugins.git.extensions.impl.WipeWorkspace; import hudson.scm.SCM; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; +import io.jenkins.plugins.casc.misc.junit.jupiter.AbstractRoundTripTest; import org.jenkinsci.plugins.gitclient.MergeCommand; import org.jenkinsci.plugins.workflow.libs.GlobalLibraries; import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration; import org.jenkinsci.plugins.workflow.libs.LibraryRetriever; import org.jenkinsci.plugins.workflow.libs.SCMRetriever; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.util.List; @@ -47,14 +48,14 @@ import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; + +@WithJenkins +class GlobalLibraryWithLegacyJCasCCompatibilityTest extends AbstractRoundTripTest { -public class GlobalLibraryWithLegacyJCasCCompatibilityTest extends RoundTripAbstractTest { @Override - protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { + protected void assertConfiguredAsExpected(JenkinsRule rule, String s) { final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0); assertEquals("My Git Lib", library.getName()); assertEquals("1.2.3", library.getDefaultVersion()); diff --git a/src/test/java/jenkins/plugins/git/GlobalLibraryWithModernJCasCCompatibilityTest.java b/src/test/java/jenkins/plugins/git/GlobalLibraryWithModernJCasCCompatibilityTest.java index d2ba122324..a669228d0a 100644 --- a/src/test/java/jenkins/plugins/git/GlobalLibraryWithModernJCasCCompatibilityTest.java +++ b/src/test/java/jenkins/plugins/git/GlobalLibraryWithModernJCasCCompatibilityTest.java @@ -5,7 +5,7 @@ import hudson.plugins.git.extensions.impl.CloneOption; import hudson.plugins.git.extensions.impl.SubmoduleOption; import hudson.plugins.git.extensions.impl.UserIdentity; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; +import io.jenkins.plugins.casc.misc.junit.jupiter.AbstractRoundTripTest; import jenkins.plugins.git.traits.AuthorInChangelogTrait; import jenkins.plugins.git.traits.CheckoutOptionTrait; import jenkins.plugins.git.traits.CleanAfterCheckoutTrait; @@ -31,7 +31,8 @@ import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration; import org.jenkinsci.plugins.workflow.libs.LibraryRetriever; import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; @@ -39,13 +40,15 @@ import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@WithJenkins +class GlobalLibraryWithModernJCasCCompatibilityTest extends AbstractRoundTripTest { -public class GlobalLibraryWithModernJCasCCompatibilityTest extends RoundTripAbstractTest { @Override - protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { + protected void assertConfiguredAsExpected(JenkinsRule rule, String s) { final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0); assertEquals("My Git Lib", library.getName()); assertEquals("1.2.3", library.getDefaultVersion()); diff --git a/src/test/java/jenkins/plugins/git/MergeWithGitSCMExtensionTest.java b/src/test/java/jenkins/plugins/git/MergeWithGitSCMExtensionTest.java index a060442df9..a1c54f29b7 100644 --- a/src/test/java/jenkins/plugins/git/MergeWithGitSCMExtensionTest.java +++ b/src/test/java/jenkins/plugins/git/MergeWithGitSCMExtensionTest.java @@ -9,12 +9,16 @@ import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionTest; import hudson.plugins.git.util.BuildData; +import org.junit.jupiter.api.Test; + import org.eclipse.jgit.lib.Constants; -import org.junit.Test; -import static org.junit.Assert.*; +import java.io.File; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; -public class MergeWithGitSCMExtensionTest extends GitSCMExtensionTest { +class MergeWithGitSCMExtensionTest extends GitSCMExtensionTest { private FreeStyleProject project; @@ -23,8 +27,9 @@ public class MergeWithGitSCMExtensionTest extends GitSCMExtensionTest { private String baseHash; private String MASTER_FILE = "commitFileBase"; - public void before() throws Exception { - repo = new TestGitRepo("repo", tmp.newFolder(), listener); + @Override + protected void before() throws Exception { + repo = new TestGitRepo("repo", newFolder(tmp, "junit"), listener); // make an initial commit to master and get hash this.baseHash = repo.commit(MASTER_FILE, repo.johnDoe, "Initial Commit"); // set the base name as HEAD @@ -34,18 +39,19 @@ public void before() throws Exception { repo.git.branch("integration"); } + @Test - public void testBasicMergeWithSCMExtension() throws Exception { + void testBasicMergeWithSCMExtension() throws Exception { FreeStyleBuild baseBuild = build(project, Result.SUCCESS); } @Test - public void testFailedMergeWithSCMExtension() throws Exception { + void testFailedMergeWithSCMExtension() throws Exception { FreeStyleBuild firstBuild = build(project, Result.SUCCESS); assertEquals(GitSCM.class, project.getScm().getClass()); GitSCM gitSCM = (GitSCM)project.getScm(); BuildData buildData = gitSCM.getBuildData(firstBuild); - assertNotNull("Build data not found", buildData); + assertNotNull(buildData, "Build data not found"); assertEquals(firstBuild.getNumber(), buildData.lastBuild.getBuildNumber()); Revision firstMarked = buildData.lastBuild.getMarked(); Revision firstRevision = buildData.lastBuild.getRevision(); @@ -61,9 +67,9 @@ public void testFailedMergeWithSCMExtension() throws Exception { repo.git.checkout().ref("master").execute(); // as baseName and baseHash don't change in master branch, this commit should merge ! - assertFalse("SCM polling should not detect any more changes after build", project.poll(listener).hasChanges()); + assertFalse(project.poll(listener).hasChanges(), "SCM polling should not detect any more changes after build"); String conflictSha1= repo.commit(MASTER_FILE, "new John Doe content will conflict", repo.johnDoe, repo.johnDoe, "Commit success!"); - assertTrue("SCM polling should detect changes", project.poll(listener).hasChanges()); + assertTrue(project.poll(listener).hasChanges(), "SCM polling should detect changes"); FreeStyleBuild secondBuild = build(project, Result.SUCCESS); @@ -83,4 +89,13 @@ protected GitSCMExtension getExtension() { return new MergeWithGitSCMExtension(baseName,baseHash); } + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } + } diff --git a/src/test/java/jenkins/plugins/git/ModernScmTest.java b/src/test/java/jenkins/plugins/git/ModernScmTest.java index 69f7ee8e48..d07227a144 100644 --- a/src/test/java/jenkins/plugins/git/ModernScmTest.java +++ b/src/test/java/jenkins/plugins/git/ModernScmTest.java @@ -26,23 +26,29 @@ import hudson.ExtensionList; import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; -public class ModernScmTest { +@WithJenkins +class ModernScmTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } @Test @Issue("JENKINS-58964") - public void gitIsModernScm() { + void gitIsModernScm() { SCMSourceRetriever.DescriptorImpl descriptor = ExtensionList.lookupSingleton(SCMSourceRetriever.DescriptorImpl.class); assertThat(descriptor.getSCMDescriptors(), hasItem(instanceOf(GitSCMSource.DescriptorImpl.class))); } diff --git a/src/test/java/jenkins/plugins/git/RandomOrder.java b/src/test/java/jenkins/plugins/git/RandomOrder.java deleted file mode 100644 index a293f783bf..0000000000 --- a/src/test/java/jenkins/plugins/git/RandomOrder.java +++ /dev/null @@ -1,13 +0,0 @@ -package jenkins.plugins.git; - -import org.junit.runner.manipulation.Ordering; - -import java.util.Random; - -public class RandomOrder implements Ordering.Factory { - private static final long SEED = new Random().nextLong(); - @Override - public Ordering create(Ordering.Context context) { - return Ordering.shuffledBy(new Random(SEED)); - } -} diff --git a/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtension.java b/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtension.java index 8276c1c011..60eed0b7bb 100644 --- a/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtension.java +++ b/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtension.java @@ -1,5 +1,6 @@ package jenkins.plugins.git.junit.jupiter; +import edu.umd.cs.findbugs.annotations.NonNull; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterContext; @@ -14,25 +15,29 @@ */ public class GitSampleRepoExtension implements ParameterResolver, AfterEachCallback { - private static final String KEY = "git-sample-repo"; + private static final String KEY = "git-sample-repo-"; private static final ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace.create(GitSampleRepoExtension.class); + private static int counter = 0; @Override - public void afterEach(ExtensionContext context) { - var rule = context.getStore(NAMESPACE).remove(KEY, GitSampleRepoRule.class); - if (rule != null) { - rule.after(); + public void afterEach(@NonNull ExtensionContext context) { + for (int i = counter; i >= 0; i--) { + var rule = context.getStore(NAMESPACE).remove(KEY + i, GitSampleRepoRule.class); + if (rule != null) { + rule.after(); + } } } @Override - public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + public boolean supportsParameter(@NonNull ParameterContext parameterContext, @NonNull ExtensionContext extensionContext) throws ParameterResolutionException { return parameterContext.getParameter().getType().equals(GitSampleRepoRule.class); } @Override - public GitSampleRepoRule resolveParameter(ParameterContext parameterContext, ExtensionContext context) { - var rule = context.getStore(NAMESPACE).getOrComputeIfAbsent(KEY, key -> new GitSampleRepoRule(), GitSampleRepoRule.class); + public GitSampleRepoRule resolveParameter(@NonNull ParameterContext parameterContext, @NonNull ExtensionContext context) { + // TODO: Replace with non-deprecated method once consumers upgraded to JUnit 6.x + var rule = context.getStore(NAMESPACE).getOrComputeIfAbsent(KEY + counter++, key -> new GitSampleRepoRule(), GitSampleRepoRule.class); if (rule != null) { try { rule.before(); diff --git a/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtensionClassTest.java b/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtensionClassTest.java index 5f3bbe3a09..3a2e9c3678 100644 --- a/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtensionClassTest.java +++ b/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtensionClassTest.java @@ -1,20 +1,27 @@ package jenkins.plugins.git.junit.jupiter; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import jenkins.plugins.git.GitSampleRepoRule; +import static org.junit.jupiter.api.Assertions.assertNotNull; + @WithGitSampleRepo class GitSampleRepoExtensionClassTest { @Test void gitSampleRepoIsInjected(GitSampleRepoRule rule) throws Exception { - Assertions.assertNotNull(rule); + assertNotNull(rule); // somehow testing initialization var root = rule.getRoot(); - Assertions.assertNotNull(root); + assertNotNull(root); rule.init(); - Assertions.assertNotNull(rule.head()); + assertNotNull(rule.head()); + } + + @Test + void multipleGitSampleReposInjected(GitSampleRepoRule rule1, GitSampleRepoRule rule2) throws Exception { + gitSampleRepoIsInjected(rule1); + gitSampleRepoIsInjected(rule2); } } diff --git a/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtensionMethodTest.java b/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtensionMethodTest.java index 2cbded222b..f98dae8d30 100644 --- a/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtensionMethodTest.java +++ b/src/test/java/jenkins/plugins/git/junit/jupiter/GitSampleRepoExtensionMethodTest.java @@ -1,20 +1,28 @@ package jenkins.plugins.git.junit.jupiter; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import jenkins.plugins.git.GitSampleRepoRule; +import static org.junit.jupiter.api.Assertions.assertNotNull; + class GitSampleRepoExtensionMethodTest { @WithGitSampleRepo @Test void gitSampleRepoIsInjected(GitSampleRepoRule rule) throws Exception { - Assertions.assertNotNull(rule); + assertNotNull(rule); // somehow testing initialization var root = rule.getRoot(); - Assertions.assertNotNull(root); + assertNotNull(root); rule.init(); - Assertions.assertNotNull(rule.head()); + assertNotNull(rule.head()); + } + + @WithGitSampleRepo + @Test + void multipleGitSampleReposInjected(GitSampleRepoRule rule1, GitSampleRepoRule rule2) throws Exception { + gitSampleRepoIsInjected(rule1); + gitSampleRepoIsInjected(rule2); } } diff --git a/src/test/java/jenkins/plugins/git/traits/DiscoverOtherRefsTraitTest.java b/src/test/java/jenkins/plugins/git/traits/DiscoverOtherRefsTraitTest.java index 611e4ba8ce..116ef74be1 100644 --- a/src/test/java/jenkins/plugins/git/traits/DiscoverOtherRefsTraitTest.java +++ b/src/test/java/jenkins/plugins/git/traits/DiscoverOtherRefsTraitTest.java @@ -23,20 +23,20 @@ */ package jenkins.plugins.git.traits; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class DiscoverOtherRefsTraitTest { +class DiscoverOtherRefsTraitTest { @Test - public void getFullRefSpec() throws Exception { + void getFullRefSpec() throws Exception { DiscoverOtherRefsTrait t = new DiscoverOtherRefsTrait("refs/custom/*"); assertEquals("+refs/custom/*:refs/remotes/@{remote}/custom/*", t.getFullRefSpec()); } @Test - public void getNameMapping() throws Exception { + void getNameMapping() throws Exception { DiscoverOtherRefsTrait t = new DiscoverOtherRefsTrait("refs/bobby/*"); assertEquals("bobby-@{1}", t.getNameMapping()); t = new DiscoverOtherRefsTrait("refs/bobby/*/merge"); diff --git a/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java b/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java index 9402b2d644..15755487e6 100644 --- a/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java +++ b/src/test/java/jenkins/plugins/git/traits/GitSCMExtensionTraitTest.java @@ -6,16 +6,23 @@ import java.util.ArrayList; import java.util.List; import jenkins.scm.api.trait.SCMSourceTrait; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; -public class GitSCMExtensionTraitTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); +@WithJenkins +class GitSCMExtensionTraitTest { + + private static JenkinsRule r; + + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; + } public List descriptors() { List list = new ArrayList<>(); @@ -28,7 +35,7 @@ public List descriptors() { } @Test - public void extensionClassesOverrideEquals() { + void extensionClassesOverrideEquals() { for (GitSCMExtensionTraitDescriptor d : descriptors()) { assertThat(d.getExtensionClass().getName() + " overrides equals(Object)", Util.isOverridden(GitSCMExtension.class, d.getExtensionClass(), "equals", Object.class), @@ -37,7 +44,7 @@ public void extensionClassesOverrideEquals() { } @Test - public void extensionClassesOverrideHashCode() { + void extensionClassesOverrideHashCode() { for (GitSCMExtensionTraitDescriptor d : descriptors()) { assertThat(d.getExtensionClass().getName() + " overrides hashCode()", Util.isOverridden(GitSCMExtension.class, d.getExtensionClass(), "hashCode"), @@ -46,7 +53,7 @@ public void extensionClassesOverrideHashCode() { } @Test - public void extensionClassesOverrideToString() { + void extensionClassesOverrideToString() { for (GitSCMExtensionTraitDescriptor d : descriptors()) { assertThat(d.getExtensionClass().getName() + " overrides toString()", Util.isOverridden(GitSCMExtension.class, d.getExtensionClass(), "toString"), diff --git a/src/test/java/jenkins/plugins/git/traits/MultibranchProjectTraitsTest.java b/src/test/java/jenkins/plugins/git/traits/MultibranchProjectTraitsTest.java index fb5310375f..4b3a5817e6 100644 --- a/src/test/java/jenkins/plugins/git/traits/MultibranchProjectTraitsTest.java +++ b/src/test/java/jenkins/plugins/git/traits/MultibranchProjectTraitsTest.java @@ -2,30 +2,35 @@ import jenkins.plugins.git.GitSampleRepoRule; import jenkins.plugins.git.GitSCMSource; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.libs.GlobalLibraries; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration; import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension; import java.util.Collections; import java.util.Random; -public class MultibranchProjectTraitsTest { - @Rule - public RestartableJenkinsRule story = new RestartableJenkinsRule(); - @Rule - public GitSampleRepoRule sharedLibrarySampleRepo = new GitSampleRepoRule(); +@WithGitSampleRepo +class MultibranchProjectTraitsTest { + + @RegisterExtension + private final JenkinsSessionExtension story = new JenkinsSessionExtension(); + + private GitSampleRepoRule sharedLibrarySampleRepo; private Random random = new Random(); - @Before - public void setUpTestRepositories() throws Exception { + @BeforeEach + void beforeEach(GitSampleRepoRule repo) throws Exception { + sharedLibrarySampleRepo = repo; + // Initialize our repository and put shared library code in the branch `libraryBranch` sharedLibrarySampleRepo.init(); sharedLibrarySampleRepo.write("vars/book.groovy", "def call() {echo 'Greetings from the library'}"); @@ -38,11 +43,11 @@ public void setUpTestRepositories() throws Exception { Tests a checkout step in a pipeline using Symbol names instead of $class */ @Test - public void basicSharedLibrarySymbolsTest() throws Exception { + void basicSharedLibrarySymbolsTest() throws Throwable { story.then( r -> { GlobalLibraries.get().setLibraries(Collections.singletonList( // TODO: Something more interesting with traits, maybe gitBranchDiscovery - new LibraryConfiguration("thelibrary", new SCMSourceRetriever(new GitSCMSource(sharedLibrarySampleRepo.toString())))));; - WorkflowJob job = story.j.jenkins.createProject(WorkflowJob.class, "test-pipeline-job"); + new LibraryConfiguration("thelibrary", new SCMSourceRetriever(new GitSCMSource(sharedLibrarySampleRepo.toString()))))); + WorkflowJob job = r.jenkins.createProject(WorkflowJob.class, "test-pipeline-job"); job.setDefinition(new CpsFlowDefinition( "library 'thelibrary@libraryBranch'\n" + "node() {\n" @@ -53,10 +58,10 @@ public void basicSharedLibrarySymbolsTest() throws Exception { + " )" + "}" , true)); - WorkflowRun run = story.j.waitForCompletion(job.scheduleBuild2(0).waitForStart()); - story.j.waitForCompletion(run); - story.j.waitForMessage("Finished: SUCCESS", run); - story.j.assertLogContains("Greetings from the library", run); + WorkflowRun run = r.waitForCompletion(job.scheduleBuild2(0).waitForStart()); + r.waitForCompletion(run); + r.waitForMessage("Finished: SUCCESS", run); + r.assertLogContains("Greetings from the library", run); }); } @@ -64,10 +69,10 @@ public void basicSharedLibrarySymbolsTest() throws Exception { Tests a checkout step in a pipeline using $class for backward compatibility */ @Test - public void basicSharedLibraryClassTest() throws Exception { + void basicSharedLibraryClassTest() throws Throwable { story.then( r -> { GlobalLibraries.get().setLibraries(Collections.singletonList(new LibraryConfiguration("thelibrary", new SCMSourceRetriever(new GitSCMSource(sharedLibrarySampleRepo.toString()))))); - WorkflowJob job = story.j.jenkins.createProject(WorkflowJob.class, "test-pipeline-job"); + WorkflowJob job = r.jenkins.createProject(WorkflowJob.class, "test-pipeline-job"); job.setDefinition(new CpsFlowDefinition( "library 'thelibrary@libraryBranch'\n" + "node {\n" @@ -78,10 +83,10 @@ public void basicSharedLibraryClassTest() throws Exception { + " userRemoteConfigs: [[url: $/" + sharedLibrarySampleRepo + "/$]]]\n" + " )" + "}", true)); - WorkflowRun run = story.j.waitForCompletion(job.scheduleBuild2(0).waitForStart()); - story.j.waitForCompletion(run); - story.j.waitForMessage("Finished: SUCCESS", run); - story.j.assertLogContains("Greetings from the library", run); + WorkflowRun run = r.waitForCompletion(job.scheduleBuild2(0).waitForStart()); + r.waitForCompletion(run); + r.waitForMessage("Finished: SUCCESS", run); + r.assertLogContains("Greetings from the library", run); }); } diff --git a/src/test/java/jenkins/plugins/git/traits/PruneStaleBranchTraitTest.java b/src/test/java/jenkins/plugins/git/traits/PruneStaleBranchTraitTest.java index 1b6f0abc2e..453fc33437 100644 --- a/src/test/java/jenkins/plugins/git/traits/PruneStaleBranchTraitTest.java +++ b/src/test/java/jenkins/plugins/git/traits/PruneStaleBranchTraitTest.java @@ -7,10 +7,10 @@ import jenkins.scm.api.SCMSourceCriteria; import jenkins.scm.api.trait.SCMSourceContext; import jenkins.scm.api.trait.SCMSourceRequest; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; -import org.junit.Test; import org.jvnet.hudson.test.Issue; /** @@ -19,13 +19,10 @@ * * @author Mark Waite */ -public class PruneStaleBranchTraitTest { - - public PruneStaleBranchTraitTest() { - } +class PruneStaleBranchTraitTest { @Test - public void testDecorateContextWithGitSCMSourceContent() { + void testDecorateContextWithGitSCMSourceContent() { GitSCMSourceContext context = new GitSCMSourceContext(null, null); assertThat(context.pruneRefs(), is(false)); PruneStaleBranchTrait pruneStaleBranchTrait = new PruneStaleBranchTrait(); @@ -35,7 +32,7 @@ public void testDecorateContextWithGitSCMSourceContent() { @Test @Issue("JENKINS-57683") - public void testDecorateContextWithNonGitSCMSourceContent() { + void testDecorateContextWithNonGitSCMSourceContent() { SCMSourceContext context = new FakeSCMSourceContext(null, null); PruneStaleBranchTrait pruneStaleBranchTrait = new PruneStaleBranchTrait(); pruneStaleBranchTrait.decorateContext(context); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/TestJGitAPIImpl.java b/src/test/java/org/jenkinsci/plugins/gitclient/TestJGitAPIImpl.java index 3dddfcc599..ff86057590 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/TestJGitAPIImpl.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/TestJGitAPIImpl.java @@ -1,14 +1,13 @@ package org.jenkinsci.plugins.gitclient; import hudson.model.TaskListener; -import jenkins.plugins.git.AbstractGitSCMSourceTest; import org.jenkinsci.plugins.gitclient.jgit.PreemptiveAuthHttpClientConnectionFactory; import java.io.File; /** * This is just here to make the constructors public - * @see AbstractGitSCMSourceTest#when_commits_added_during_discovery_we_do_not_crash() + * AbstractGitSCMSourceTest#when_commits_added_during_discovery_we_do_not_crash() */ public class TestJGitAPIImpl extends JGitAPIImpl { public TestJGitAPIImpl(File workspace, TaskListener listener) { diff --git a/src/test/java/org/jenkinsci/plugins/gittagmessage/AbstractGitTagMessageExtensionTest.java b/src/test/java/org/jenkinsci/plugins/gittagmessage/AbstractGitTagMessageExtensionTest.java index f84dcbba05..0250904b0b 100644 --- a/src/test/java/org/jenkinsci/plugins/gittagmessage/AbstractGitTagMessageExtensionTest.java +++ b/src/test/java/org/jenkinsci/plugins/gittagmessage/AbstractGitTagMessageExtensionTest.java @@ -10,23 +10,26 @@ import org.eclipse.jgit.util.SystemReader; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.jvnet.hudson.test.JenkinsRule; +import java.io.File; +import org.junit.jupiter.api.AfterEach; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +@WithJenkins public abstract class AbstractGitTagMessageExtensionTest & ParameterizedJobMixIn.ParameterizedJob, R extends Run & Queue.Executable> { - @Rule public final JenkinsRule r = new JenkinsRule(); + protected JenkinsRule r; - @Rule public final TemporaryFolder repoDir = new TemporaryFolder(); + @TempDir + protected File repoDir; - private GitClient repo; + protected GitClient repo; /** * @param refSpec The refspec to check out. @@ -44,26 +47,24 @@ private J configureGitTagMessageJob() throws Exception { /** Asserts that the given build exported tag information, or not, if {@code null}. */ protected abstract void assertBuildEnvironment(R run, String expectedName, String expectedMessage) throws Exception; - @Before - public void setUp() throws Exception { + @BeforeEach + protected void beforeEach(JenkinsRule rule) throws Exception { + r = rule; SystemReader.getInstance().getUserConfig().clear(); // Set up a temporary git repository for each test case - repo = Git.with(r.createTaskListener(), GitUtilsTest.getConfigNoSystemEnvsVars()).in(repoDir.getRoot()).getClient(); + repo = Git.with(r.createTaskListener(), GitUtilsTest.getConfigNoSystemEnvsVars()).in(repoDir).getClient(); repo.init(); - } - @Before - public void allowNonRemoteCheckout() { GitSCM.ALLOW_LOCAL_CHECKOUT = true; } - @After - public void disallowNonRemoteCheckout() { + @AfterEach + protected void afterEach() { GitSCM.ALLOW_LOCAL_CHECKOUT = false; } @Test - public void commitWithoutTagShouldNotExportMessage() throws Exception { + void commitWithoutTagShouldNotExportMessage() throws Exception { // Given a git repo without any tags repo.commit("commit 1"); @@ -76,7 +77,7 @@ public void commitWithoutTagShouldNotExportMessage() throws Exception { } @Test - public void commitWithEmptyTagMessageShouldNotExportMessage() throws Exception { + void commitWithEmptyTagMessageShouldNotExportMessage() throws Exception { // Given a git repo which has been tagged, but without a message repo.commit("commit 1"); repo.tag("release-1.0", null); @@ -90,7 +91,7 @@ public void commitWithEmptyTagMessageShouldNotExportMessage() throws Exception { } @Test - public void commitWithTagShouldExportMessage() throws Exception { + void commitWithTagShouldExportMessage() throws Exception { // Given a git repo which has been tagged repo.commit("commit 1"); repo.tag("release-1.0", "This is the first release. "); @@ -104,7 +105,7 @@ public void commitWithTagShouldExportMessage() throws Exception { } @Test - public void commitWithMultipleTagsShouldExportMessage() throws Exception { + void commitWithMultipleTagsShouldExportMessage() throws Exception { // Given a commit with multiple tags pointing to it repo.commit("commit 1"); repo.tag("release-candidate-1.0", "This is the first release candidate."); @@ -120,7 +121,7 @@ public void commitWithMultipleTagsShouldExportMessage() throws Exception { } @Test - public void jobWithMatchingTagShouldExportThatTagMessage() throws Exception { + void jobWithMatchingTagShouldExportThatTagMessage() throws Exception { // Given a commit with multiple tags pointing to it repo.commit("commit 1"); repo.tag("alpha/1", "Alpha #1"); @@ -137,7 +138,7 @@ public void jobWithMatchingTagShouldExportThatTagMessage() throws Exception { } @Test - public void commitWithTagOnPreviousCommitWithConfigurationOptInShouldExportThatTagMessage() throws Exception { + void commitWithTagOnPreviousCommitWithConfigurationOptInShouldExportThatTagMessage() throws Exception { // Given a git repo which has been tagged on a previous commit repo.commit("commit 1"); repo.tag("release-1.0", "This is the first release"); @@ -152,7 +153,7 @@ public void commitWithTagOnPreviousCommitWithConfigurationOptInShouldExportThatT } @Test - public void commitWithMultipleTagsOnPreviousCommitWithConfigurationOptInShouldExportThatTagMessage() throws Exception { + void commitWithMultipleTagsOnPreviousCommitWithConfigurationOptInShouldExportThatTagMessage() throws Exception { // Given a git repo which has been tagged on a previous commit with multiple tags repo.commit("commit 1"); repo.tag("release-candidate-1.0", "This is the first release candidate."); diff --git a/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java b/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java index 78de12bc6d..6b6cfc7302 100644 --- a/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java +++ b/src/test/java/org/jenkinsci/plugins/gittagmessage/GitTagMessageExtensionTest.java @@ -1,6 +1,5 @@ package org.jenkinsci.plugins.gittagmessage; -import hudson.Functions; import hudson.Util; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; @@ -13,6 +12,7 @@ import java.util.Collections; +import static hudson.Functions.isWindows; import static org.jenkinsci.plugins.gittagmessage.GitTagMessageAction.ENV_VAR_NAME_MESSAGE; import static org.jenkinsci.plugins.gittagmessage.GitTagMessageAction.ENV_VAR_NAME_TAG; @@ -27,7 +27,7 @@ public class GitTagMessageExtensionTest extends AbstractGitTagMessageExtensionTe protected FreeStyleProject configureGitTagMessageJob(String refSpec, String branchSpec, boolean useMostRecentTag) throws Exception { GitTagMessageExtension extension = new GitTagMessageExtension(); extension.setUseMostRecentTag(useMostRecentTag); - UserRemoteConfig remote = new UserRemoteConfig(repoDir.getRoot().getAbsolutePath(), "origin", refSpec, null); + UserRemoteConfig remote = new UserRemoteConfig(repoDir.getAbsolutePath(), "origin", refSpec, null); GitSCM scm = new GitSCM( Collections.singletonList(remote), Collections.singletonList(new BranchSpec(branchSpec)), @@ -50,7 +50,7 @@ protected void assertBuildEnvironment(FreeStyleBuild build, String expectedName, } private static Builder createEnvEchoBuilder(String key, String envVarName) { - if (Functions.isWindows()) { + if (isWindows()) { return new BatchFile("echo %s='%%%s%%'".formatted(key, envVarName)); } return new Shell("echo \"%s='${%s}'\"".formatted(key, envVarName));