diff --git a/.gitignore b/.gitignore index 13a344f89a..279ad586c7 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,6 @@ target/ work/ -.@tmp/ .vs/ .vscode/ diff --git a/pom.xml b/pom.xml index a092b0496b..2a7c677b21 100644 --- a/pom.xml +++ b/pom.xml @@ -46,6 +46,7 @@ Max Low false + false @@ -206,11 +207,6 @@ test-harness test - - junit - junit - test - nl.jqno.equalsverifier equalsverifier @@ -238,7 +234,7 @@ org.mockito - mockito-core + mockito-junit-jupiter test @@ -247,12 +243,6 @@ 3.4 test - - org.testcontainers - testcontainers - 1.21.3 - test - diff --git a/src/test/java/hudson/plugins/git/BranchTest.java b/src/test/java/hudson/plugins/git/BranchTest.java index febb240d2e..5851ee3236 100644 --- a/src/test/java/hudson/plugins/git/BranchTest.java +++ b/src/test/java/hudson/plugins/git/BranchTest.java @@ -7,56 +7,45 @@ import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectIdRef; import org.eclipse.jgit.lib.Ref; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class BranchTest { +class BranchTest { - private final String branchSHA1; - private final String branchName; - private final ObjectId branchHead; - private final Branch branch; - private final String refPrefix; - private final Ref branchRef; - private final Branch branchFromRef; - - private static final String REMOTE_BRANCH_NAME = "origin/master"; - - public BranchTest() { - this.branchSHA1 = "fa71f704f9b90fa1f857d1623f3fe33fa2277ca9"; - this.branchName = REMOTE_BRANCH_NAME; - this.branchHead = ObjectId.fromString(branchSHA1); - this.refPrefix = "refs/remotes/"; - this.branchRef = new ObjectIdRef.PeeledNonTag(Ref.Storage.NEW, refPrefix + branchName, branchHead); - this.branch = new Branch(branchName, branchHead); - this.branchFromRef = new Branch(branchRef); - } + private static final String BRANCH_SHA_1 = "fa71f704f9b90fa1f857d1623f3fe33fa2277ca9"; + private static final String BRANCH_NAME = "origin/master"; + private static final ObjectId BRANCH_HEAD = ObjectId.fromString(BRANCH_SHA_1); + private static final Branch BRANCH = new Branch(BRANCH_NAME, BRANCH_HEAD); + private static final String REF_PREFIX = "refs/remotes/"; + private static final Ref BRANCH_REF = + new ObjectIdRef.PeeledNonTag(Ref.Storage.NEW, REF_PREFIX + BRANCH_NAME, BRANCH_HEAD); + private static final Branch BRANCH_FROM_REF = new Branch(BRANCH_REF); @Test - public void testToString() { - assertThat(branch.toString(), is(branchFromRef.toString())); + void testToString() { + assertThat(BRANCH.toString(), is(BRANCH_FROM_REF.toString())); } @Test - public void testToString_Contents() { - String expected = "Branch " + branchName + "(" + branchSHA1 + ")"; - assertThat(branch.toString(), is(expected)); + void testToString_Contents() { + String expected = "Branch " + BRANCH_NAME + "(" + BRANCH_SHA_1 + ")"; + assertThat(BRANCH.toString(), is(expected)); } @Test - public void hashCodeContract() { - assertThat(branch, is(branchFromRef)); - assertThat(branch.hashCode(), is(branchFromRef.hashCode())); + void hashCodeContract() { + assertThat(BRANCH, is(BRANCH_FROM_REF)); + assertThat(BRANCH.hashCode(), is(BRANCH_FROM_REF.hashCode())); } @Test - public void constructorRefArgStripped() { - Ref ref = new ObjectIdRef.PeeledNonTag(Ref.Storage.LOOSE, refPrefix + branchName, branchHead); + void constructorRefArgStripped() { + Ref ref = new ObjectIdRef.PeeledNonTag(Ref.Storage.LOOSE, REF_PREFIX + BRANCH_NAME, BRANCH_HEAD); Branch strippedBranch = new Branch(ref); - assertThat(strippedBranch.getName(), is(branchName)); + assertThat(strippedBranch.getName(), is(BRANCH_NAME)); } @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(Branch.class) .usingGetClass() .withRedefinedSuperclass() diff --git a/src/test/java/hudson/plugins/git/GitAPIBadInitTest.java b/src/test/java/hudson/plugins/git/GitAPIBadInitTest.java index f3fb672e68..07bc91fe3c 100644 --- a/src/test/java/hudson/plugins/git/GitAPIBadInitTest.java +++ b/src/test/java/hudson/plugins/git/GitAPIBadInitTest.java @@ -2,8 +2,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import hudson.EnvVars; import hudson.model.TaskListener; @@ -13,46 +13,50 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import org.jenkinsci.plugins.gitclient.GitClient; -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; -public class GitAPIBadInitTest { +class GitAPIBadInitTest { - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; - private final EnvVars env; - - public GitAPIBadInitTest() { - env = new EnvVars(); - } + private final EnvVars env = new EnvVars(); private File tempDir; private TaskListener listener; - @Before - public void setUp() throws IOException, InterruptedException { - tempDir = tempFolder.newFolder(); + @BeforeEach + void setUp() throws Exception { + tempDir = newFolder(tempFolder, "junit"); listener = StreamTaskListener.fromStderr(); } @Test - public void testInitExistingDirectory() throws Exception { + void testInitExistingDirectory() throws Exception { GitClient git = new GitAPI("git", tempDir, listener, env); git.init(); File gitDir = new File(tempDir, ".git"); - assertTrue(gitDir + " not created", gitDir.exists()); - assertTrue(gitDir + " not a directory", gitDir.isDirectory()); + assertTrue(gitDir.exists(), gitDir + " not created"); + assertTrue(gitDir.isDirectory(), gitDir + " not a directory"); } @Test - public void testInitExistingFile() throws Exception { + void testInitExistingFile() throws Exception { File existingFile = new File(tempDir, "file-exists"); Files.writeString(existingFile.toPath(), "git init should fail due to this file", StandardCharsets.UTF_8); GitClient git = new GitAPI("git", existingFile, listener, env); GitException e = assertThrows(GitException.class, git::init); assertThat(e.getMessage(), is("Could not init " + existingFile.getAbsolutePath())); } + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/git/GitExceptionTest.java b/src/test/java/hudson/plugins/git/GitExceptionTest.java index cebdd5d28f..7cf328d059 100644 --- a/src/test/java/hudson/plugins/git/GitExceptionTest.java +++ b/src/test/java/hudson/plugins/git/GitExceptionTest.java @@ -5,29 +5,27 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isA; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import hudson.EnvVars; import hudson.model.TaskListener; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import org.eclipse.jgit.api.errors.JGitInternalException; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -public class GitExceptionTest { +class GitExceptionTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + private File folder; @Test - public void throwsGitException() { + void throwsGitException() { GitException e = assertThrows(GitException.class, () -> { throw new GitException(); }); @@ -35,7 +33,7 @@ public void throwsGitException() { } @Test - public void throwsGitExceptionExpectedMessage() { + void throwsGitExceptionExpectedMessage() { String message = "My custom git exception message"; GitException e = assertThrows(GitException.class, () -> { throw new GitException(message); @@ -44,7 +42,7 @@ public void throwsGitExceptionExpectedMessage() { } @Test - public void throwsGitExceptionExpectedMessageWithCause() { + void throwsGitExceptionExpectedMessageWithCause() { String message = "My custom git exception message"; GitException e = assertThrows(GitException.class, () -> { throw new GitException(message, new IOException("Custom IOException message")); @@ -54,7 +52,7 @@ public void throwsGitExceptionExpectedMessageWithCause() { } @Test - public void initCliImplThrowsGitException() throws IOException, InterruptedException { + void initCliImplThrowsGitException() throws Exception { if (new File("/").canWrite()) { // running as root? return; } @@ -72,7 +70,7 @@ public void initCliImplThrowsGitException() throws IOException, InterruptedExcep } @Test - public void initJGitImplThrowsGitException() throws IOException, InterruptedException { + void initJGitImplThrowsGitException() throws Exception { if (new File("/").canWrite()) { // running as root? return; } @@ -91,10 +89,10 @@ public void initJGitImplThrowsGitException() throws IOException, InterruptedExce } @Test - public void initCliImplCollisionThrowsGitException() throws IOException, InterruptedException { - File dir = folder.getRoot(); - File dotGit = folder.newFile(".git"); - Files.write(dotGit.toPath(), "file named .git".getBytes(StandardCharsets.UTF_8), APPEND); + void initCliImplCollisionThrowsGitException() throws Exception { + File dir = folder; + File dotGit = newFile(folder, ".git"); + Files.writeString(dotGit.toPath(), "file named .git", APPEND); GitClient defaultClient = Git.with(TaskListener.NULL, new EnvVars()).in(dir).using("git").getClient(); assertThrows( @@ -103,10 +101,10 @@ public void initCliImplCollisionThrowsGitException() throws IOException, Interru } @Test - public void initJGitImplCollisionThrowsGitException() throws IOException, InterruptedException { - File dir = folder.getRoot(); - File dotGit = folder.newFile(".git"); - Files.write(dotGit.toPath(), "file named .git".getBytes(StandardCharsets.UTF_8), APPEND); + void initJGitImplCollisionThrowsGitException() throws Exception { + File dir = folder; + File dotGit = newFile(folder, ".git"); + Files.writeString(dotGit.toPath(), "file named .git", APPEND); GitClient defaultClient = Git.with(TaskListener.NULL, new EnvVars()).in(dir).using("jgit").getClient(); JGitInternalException e = assertThrows( @@ -122,4 +120,12 @@ public void initJGitImplCollisionThrowsGitException() throws IOException, Interr private static boolean isWindows() { return File.pathSeparatorChar == ';'; } + + private static File newFile(File parent, String child) throws Exception { + File result = new File(parent, child); + if (!result.createNewFile()) { + throw new IOException("Couldn't create file " + result); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/git/GitLockFailedExceptionTest.java b/src/test/java/hudson/plugins/git/GitLockFailedExceptionTest.java index ba01459319..e53ba8089e 100644 --- a/src/test/java/hudson/plugins/git/GitLockFailedExceptionTest.java +++ b/src/test/java/hudson/plugins/git/GitLockFailedExceptionTest.java @@ -3,14 +3,14 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GitLockFailedExceptionTest { +class GitLockFailedExceptionTest { @Test - public void throwsGitLockFailedException() { + void throwsGitLockFailedException() { GitLockFailedException lockFailed = assertThrows(GitLockFailedException.class, () -> { throw new GitLockFailedException(); }); @@ -18,7 +18,7 @@ public void throwsGitLockFailedException() { } @Test - public void throwsGitLockFailedExceptionWithMessage() { + void throwsGitLockFailedExceptionWithMessage() { String message = "My local exception message"; GitLockFailedException lockFailed = assertThrows(GitLockFailedException.class, () -> { throw new GitLockFailedException(message); @@ -27,7 +27,7 @@ public void throwsGitLockFailedExceptionWithMessage() { } @Test - public void throwsGitLockFailedExceptionWithCause() { + void throwsGitLockFailedExceptionWithCause() { String message = "My git exception message"; GitException e = new GitException(message); GitLockFailedException lockFailed = assertThrows(GitLockFailedException.class, () -> { @@ -37,7 +37,7 @@ public void throwsGitLockFailedExceptionWithCause() { } @Test - public void throwsGitLockFailedExceptionWithCauseAndMessage() { + void throwsGitLockFailedExceptionWithCauseAndMessage() { String message = "My git exception message"; GitException e = new GitException(message); String lockMessage = "My lock message that is not part of the GitException"; diff --git a/src/test/java/hudson/plugins/git/GitObjectTest.java b/src/test/java/hudson/plugins/git/GitObjectTest.java index d3087f4e4a..e6ea4d48aa 100644 --- a/src/test/java/hudson/plugins/git/GitObjectTest.java +++ b/src/test/java/hudson/plugins/git/GitObjectTest.java @@ -1,65 +1,66 @@ package hudson.plugins.git; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import nl.jqno.equalsverifier.EqualsVerifier; import org.eclipse.jgit.lib.ObjectId; -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.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -public class GitObjectTest { +@ParameterizedClass(name = "{0}-{1}") +@MethodSource("gitObjects") +class GitObjectTest { - private final String sha1String; - private final String name; - private final ObjectId sha1; + @Parameter(0) + private String name; - private final GitObject gitObject; + @Parameter(1) + private String sha1String; - public GitObjectTest(String name, String sha1String) { - this.name = name; - this.sha1String = sha1String; - this.sha1 = sha1String != null ? ObjectId.fromString(sha1String) : null; - gitObject = new GitObject(name, sha1); - } + @Parameter(2) + private ObjectId sha1; + + @Parameter(3) + private GitObject gitObject; - @Parameterized.Parameters(name = "{0}-{1}") - public static Collection gitObjects() { - List arguments = new ArrayList<>(); + static List gitObjects() { + List arguments = new ArrayList<>(); String tagStr = "git-client-1.16.0"; String tagSHA1 = "b24875cb995865a9e3a802dc0e9c8041640df0a7"; String[] names = {tagStr, ObjectId.zeroId().getName(), "", null}; String[] hashes = {tagSHA1, ObjectId.zeroId().name(), null}; for (String name : names) { - for (String sha1 : hashes) { - Object[] item = {name, sha1}; - arguments.add(item); + for (String sha1String : hashes) { + ObjectId sha1 = sha1String != null ? ObjectId.fromString(sha1String) : null; + GitObject gitObject = new GitObject(name, sha1); + arguments.add(Arguments.of(name, sha1String, sha1, gitObject)); } } return arguments; } @Test - public void testGetSHA1() { + void testGetSHA1() { assertEquals(sha1, gitObject.getSHA1()); } @Test - public void testGetName() { + void testGetName() { assertEquals(name, gitObject.getName()); } @Test - public void testGetSHA1String() { + void testGetSHA1String() { assertEquals(sha1String, gitObject.getSHA1String()); } @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(GitObject.class) .usingGetClass() .withRedefinedSubclass(Tag.class) diff --git a/src/test/java/hudson/plugins/git/GitToolResolverTest.java b/src/test/java/hudson/plugins/git/GitToolResolverTest.java index daf0ab475c..4163748859 100644 --- a/src/test/java/hudson/plugins/git/GitToolResolverTest.java +++ b/src/test/java/hudson/plugins/git/GitToolResolverTest.java @@ -10,28 +10,28 @@ import hudson.tools.CommandInstaller; import hudson.tools.InstallSourceProperty; import java.io.File; -import java.io.IOException; import java.util.Collections; -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.junit.jupiter.WithJenkins; -public class GitToolResolverTest { +@WithJenkins +class GitToolResolverTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; private GitTool gitTool; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp(JenkinsRule rule) { + r = rule; GitTool.onLoaded(); gitTool = GitTool.getDefaultInstallation(); } @Test - public void shouldResolveToolsOnMaster() throws Exception { + void shouldResolveToolsOnMaster() throws Exception { // Jenkins 2.307+ uses "built-in" for the label on the controller node // Before 2.307, used the deprecated term "master" final String label = r.jenkins.getSelfLabel().getName(); diff --git a/src/test/java/hudson/plugins/git/GitToolTest.java b/src/test/java/hudson/plugins/git/GitToolTest.java index a2654eb0f2..8c561dbce0 100644 --- a/src/test/java/hudson/plugins/git/GitToolTest.java +++ b/src/test/java/hudson/plugins/git/GitToolTest.java @@ -2,8 +2,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; -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; import hudson.EnvVars; import hudson.model.Node; @@ -11,36 +11,41 @@ import hudson.slaves.DumbSlave; import hudson.tools.ToolDescriptor; import hudson.util.StreamTaskListener; -import java.io.IOException; import java.util.List; import org.apache.commons.lang3.SystemUtils; import org.jenkinsci.plugins.gitclient.JGitApacheTool; import org.jenkinsci.plugins.gitclient.JGitTool; -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; -public class GitToolTest { +@WithJenkins +class GitToolTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; private GitTool gitTool; - @Before - public void setUp() throws IOException { + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } + + @BeforeEach + void setUp() { GitTool.onLoaded(); gitTool = GitTool.getDefaultInstallation(); } @Test - public void testGetGitExe() { + void testGetGitExe() { assertEquals(SystemUtils.IS_OS_WINDOWS ? "git.exe" : "git", gitTool.getGitExe()); } @Test - public void testForNode() throws Exception { + void testForNode() throws Exception { DumbSlave agent = r.createSlave(); agent.setMode(Node.Mode.EXCLUSIVE); TaskListener log = StreamTaskListener.fromStdout(); @@ -49,27 +54,27 @@ public void testForNode() throws Exception { } @Test - public void testForEnvironment() { + void testForEnvironment() { EnvVars environment = new EnvVars(); GitTool newTool = gitTool.forEnvironment(environment); assertEquals(gitTool.getGitExe(), newTool.getGitExe()); } @Test - public void testGetDescriptor() { + void testGetDescriptor() { GitTool.DescriptorImpl descriptor = gitTool.getDescriptor(); assertEquals("Git", descriptor.getDisplayName()); } @Test - public void testGetInstallationFromDescriptor() { + void testGetInstallationFromDescriptor() { GitTool.DescriptorImpl descriptor = gitTool.getDescriptor(); assertNull(descriptor.getInstallation("")); assertNull(descriptor.getInstallation("not-a-valid-git-install")); } @Test - public void testGetApplicableFromDescriptor() { + void testGetApplicableFromDescriptor() { GitTool.DescriptorImpl gitDescriptor = gitTool.getDescriptor(); GitTool.DescriptorImpl jgitDescriptor = (new JGitTool()).getDescriptor(); GitTool.DescriptorImpl jgitApacheDescriptor = (new JGitApacheTool()).getDescriptor(); diff --git a/src/test/java/hudson/plugins/git/IndexEntryTest.java b/src/test/java/hudson/plugins/git/IndexEntryTest.java index 3245c038c0..cd18cbc308 100644 --- a/src/test/java/hudson/plugins/git/IndexEntryTest.java +++ b/src/test/java/hudson/plugins/git/IndexEntryTest.java @@ -1,80 +1,81 @@ package hudson.plugins.git; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.io.File; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class IndexEntryTest { +class IndexEntryTest { - private final String mode = "160000"; - private final String type = "commit"; - private final String object = "index-entry-object"; - private final String file = ".git" + File.separator + "index-entry-file"; + private static final String MODE = "160000"; + private static final String TYPE = "commit"; + private static final String OBJECT = "index-entry-object"; + private static final String FILE = ".git" + File.separator + "index-entry-file"; private IndexEntry entry; - @Before - public void setUp() { - entry = new IndexEntry(mode, type, object, file); + @BeforeEach + void setUp() { + entry = new IndexEntry(MODE, TYPE, OBJECT, FILE); } @Test - public void testGetMode() { - assertEquals(mode, entry.getMode()); + void testGetMode() { + assertEquals(MODE, entry.getMode()); } @Test - public void testSetMode() { + void testSetMode() { String myMode = "100777"; entry.setMode(myMode); assertEquals(myMode, entry.getMode()); } @Test - public void testGetType() { - assertEquals(type, entry.getType()); + void testGetType() { + assertEquals(TYPE, entry.getType()); } @Test - public void testSetType() { + void testSetType() { String myType = "tag"; entry.setType(myType); assertEquals(myType, entry.getType()); } @Test - public void testGetObject() { - assertEquals(object, entry.getObject()); + void testGetObject() { + assertEquals(OBJECT, entry.getObject()); } @Test - public void testSetObject() { + void testSetObject() { String myObject = "my-object"; entry.setObject(myObject); assertEquals(myObject, entry.getObject()); } @Test - public void testGetFile() { - assertEquals(file, entry.getFile()); + void testGetFile() { + assertEquals(FILE, entry.getFile()); } @Test - public void testSetFile() { + void testSetFile() { String myFile = "my-file"; entry.setFile(myFile); assertEquals(myFile, entry.getFile()); } @Test - public void testToString() { - String expected = "IndexEntry[mode=" + mode + ",type=" + type + ",file=" + file + ",object=" + object + "]"; + void testToString() { + String expected = "IndexEntry[mode=" + MODE + ",type=" + TYPE + ",file=" + FILE + ",object=" + OBJECT + "]"; assertEquals(expected, entry.toString()); } @Test - public void testHashCode() { + void testHashCode() { assertEquals(entry.hashCode(), entry.hashCode()); IndexEntry entryClone = new IndexEntry(entry.getMode(), entry.getType(), entry.getObject(), entry.getFile()); @@ -92,7 +93,7 @@ public void testHashCode() { } @Test - public void testEquals() { + void testEquals() { assertEquals(entry, entry); IndexEntry entryClone = new IndexEntry(entry.getMode(), entry.getType(), entry.getObject(), entry.getFile()); diff --git a/src/test/java/hudson/plugins/git/RevisionTest.java b/src/test/java/hudson/plugins/git/RevisionTest.java index 2bba2b7908..b6dcc18f0f 100644 --- a/src/test/java/hudson/plugins/git/RevisionTest.java +++ b/src/test/java/hudson/plugins/git/RevisionTest.java @@ -1,45 +1,30 @@ package hudson.plugins.git; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Collection; +import java.util.List; import org.eclipse.jgit.lib.ObjectId; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class RevisionTest { +class RevisionTest { - private final String sha1; - private final ObjectId objectId; - private final Revision revision1; + private final String sha1 = "3725b67f3daa6621dd01356c96c08a1f85b90c61"; + private final ObjectId objectId = ObjectId.fromString(sha1); + private final Revision revision1 = new Revision(objectId); - private final Collection emptyCollection; - private final Revision revision2; + private final Collection emptyCollection = new ArrayList<>(); + private final Revision revision2 = new Revision(objectId, emptyCollection); - private final String branchName; - private final String sha1a; - private final Branch branch; - private final Collection branchCollection; - private final Revision revisionWithBranches; - - public RevisionTest() { - sha1 = "3725b67f3daa6621dd01356c96c08a1f85b90c61"; - objectId = ObjectId.fromString(sha1); - revision1 = new Revision(objectId); - - emptyCollection = new ArrayList<>(); - revision2 = new Revision(objectId, emptyCollection); - - branchName = "origin/tests/getSubmodules"; - sha1a = "9ac446c472a6433fe503d294ebb7d5691b590269"; - branch = new Branch(branchName, ObjectId.fromString(sha1a)); - branchCollection = new ArrayList<>(); - branchCollection.add(branch); - revisionWithBranches = new Revision(ObjectId.fromString(sha1a), branchCollection); - } + private final String branchName = "origin/tests/getSubmodules"; + private final String sha1a = "9ac446c472a6433fe503d294ebb7d5691b590269"; + private final Branch branch = new Branch(branchName, ObjectId.fromString(sha1a)); + private final Collection branchCollection = List.of(branch); + private final Revision revisionWithBranches = new Revision(ObjectId.fromString(sha1a), branchCollection); @Test - public void testEquals() { + void testEquals() { assertEquals(revision1, revision1); assertNotEquals(revision1, null); assertNotEquals(null, revision1); @@ -53,19 +38,19 @@ public void testEquals() { } @Test - public void testGetSha1() { + void testGetSha1() { assertEquals(objectId, revision1.getSha1()); assertEquals(objectId, revision2.getSha1()); } @Test - public void testGetSha1String() { + void testGetSha1String() { assertEquals(sha1, revision1.getSha1String()); assertEquals(sha1, revision2.getSha1String()); } @Test - public void testSetSha1() { + void testSetSha1() { String newSha1 = "b397392d6d00af263583edeaf8f7773a619d1cf8"; ObjectId newObjectId = ObjectId.fromString(newSha1); Revision rev = new Revision(objectId); @@ -81,9 +66,8 @@ public void testSetSha1() { } @Test - public void testGetBranches() { + void testGetBranches() { assertEquals(0, revision1.getBranches().size()); - assertEquals(0, revision2.getBranches().size()); Collection branches = revisionWithBranches.getBranches(); @@ -92,7 +76,7 @@ public void testGetBranches() { } @Test - public void testSetBranches() { + void testSetBranches() { Revision rev = new Revision(objectId); rev.setBranches(emptyCollection); @@ -106,7 +90,7 @@ public void testSetBranches() { } @Test - public void testContainsBranchName() { + void testContainsBranchName() { assertFalse(revision1.containsBranchName(branchName)); assertFalse(revision2.containsBranchName(branchName)); @@ -132,26 +116,26 @@ public void testContainsBranchName() { } @Test - public void testToString() { + void testToString() { assertEquals("Revision " + sha1 + " ()", revision1.toString()); assertEquals("Revision " + sha1 + " ()", revision2.toString()); assertEquals("Revision " + sha1a + " (" + branchName + ")", revisionWithBranches.toString()); } @Test - public void testToStringNullOneArgument() { + void testToStringNullOneArgument() { Revision nullRevision = new Revision(null); assertEquals("Revision null ()", nullRevision.toString()); } @Test - public void testToStringNullTwoArguments() { + void testToStringNullTwoArguments() { Revision nullRevision = new Revision(null, null); assertEquals("Revision null ()", nullRevision.toString()); } @Test - public void testClone() { + void testClone() { Revision revision1Clone = revision1.clone(); assertEquals(objectId, revision1Clone.getSha1()); @@ -167,7 +151,7 @@ public void testClone() { } @Test - public void testHashCode() { + void testHashCode() { assertEquals(revision1, revision2); assertEquals(revision1.hashCode(), revision2.hashCode()); diff --git a/src/test/java/hudson/plugins/git/TagTest.java b/src/test/java/hudson/plugins/git/TagTest.java index 891ba229ff..4e069ad8a7 100644 --- a/src/test/java/hudson/plugins/git/TagTest.java +++ b/src/test/java/hudson/plugins/git/TagTest.java @@ -1,49 +1,50 @@ package hudson.plugins.git; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import nl.jqno.equalsverifier.EqualsVerifier; 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; -public class TagTest { +class TagTest { private Tag tag; - @Before - public void assignTag() { + @BeforeEach + void assignTag() { String tagName = "git-client-1.8.1"; ObjectId tagSHA1 = ObjectId.fromString("3725b67f3daa6621dd01356c96c08a1f85b90c61"); tag = new Tag(tagName, tagSHA1); } @Test - public void testGetCommitMessage() { + void testGetCommitMessage() { assertNull(tag.getCommitMessage()); } @Test - public void testSetCommitMessage() { + void testSetCommitMessage() { String tagMessage = "My commit message"; tag.setCommitMessage(tagMessage); assertEquals(tagMessage, tag.getCommitMessage()); } @Test - public void testGetCommitSHA1() { + void testGetCommitSHA1() { assertNull(tag.getCommitSHA1()); } @Test - public void testSetCommitSHA1() { + void testSetCommitSHA1() { String mySHA1 = "7d34e076db3364912ec35f1ef06a3d638e6ab075"; tag.setCommitSHA1(mySHA1); assertEquals(mySHA1, tag.getCommitSHA1()); } @Test - public void equalsContract() { + void equalsContract() { EqualsVerifier.forClass(Tag.class) .withIgnoredFields("commitSHA1", "commitMessage") .usingGetClass() diff --git a/src/test/java/jmh/benchmark/BenchmarkRunner.java b/src/test/java/jmh/benchmark/BenchmarkRunner.java index e62ae62938..76ddb27616 100644 --- a/src/test/java/jmh/benchmark/BenchmarkRunner.java +++ b/src/test/java/jmh/benchmark/BenchmarkRunner.java @@ -1,11 +1,10 @@ package jmh.benchmark; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.concurrent.TimeUnit; import jenkins.benchmark.jmh.BenchmarkFinder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.results.format.ResultFormatType; import org.openjdk.jmh.runner.Runner; @@ -16,20 +15,20 @@ * A runner class which finds benchmark tests annotated with @JmhBenchmark and launches them with the selected options * provided by JMH */ -public class BenchmarkRunner { +class BenchmarkRunner { /** * Returns true if property benchmark.run is set. * @return true if benchmarks should be run */ - private boolean shouldRunBenchmarks() throws Exception { + private boolean shouldRunBenchmarks() { return Boolean.parseBoolean(System.getProperty("benchmark.run", "false")); } @Test - public void runJmhBenchmarks() throws Exception { + void runJmhBenchmarks() throws Exception { if (!shouldRunBenchmarks()) { String msg = "{\"benchmark.run\": false, \"reason\": \"Benchmark not run because benchmark.run is false\"}"; - Files.write(Path.of("jmh-report.json"), msg.getBytes(StandardCharsets.UTF_8)); + Files.writeString(Path.of("jmh-report.json"), msg); return; } ChainedOptionsBuilder options = new OptionsBuilder() diff --git a/src/test/java/jmh/benchmark/FolderForBenchmark.java b/src/test/java/jmh/benchmark/FolderForBenchmark.java index 1be0073931..2d20c55cd7 100644 --- a/src/test/java/jmh/benchmark/FolderForBenchmark.java +++ b/src/test/java/jmh/benchmark/FolderForBenchmark.java @@ -4,10 +4,9 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; -import org.junit.Rule; /** - * Similar to a TemporaryFolder JUnit Rule, it provides a local git repository for the lifetime of a benchmark test. + * Provides a local git repository for a benchmark test. * @author RishabhBudhouliya **/ public class FolderForBenchmark { @@ -134,8 +133,7 @@ public File getRoot() { } /** - * Delete all files and folders under the temporary folder. Usually not - * called directly, since it is automatically applied by the {@link Rule} + * Delete all files and folders under the temporary folder. */ public void delete() { if (folder != null) { diff --git a/src/test/java/jmh/benchmark/GitClientFetchBenchmark.java b/src/test/java/jmh/benchmark/GitClientFetchBenchmark.java index 93830f32de..76b9687860 100644 --- a/src/test/java/jmh/benchmark/GitClientFetchBenchmark.java +++ b/src/test/java/jmh/benchmark/GitClientFetchBenchmark.java @@ -78,17 +78,21 @@ public static class CloneRepoState { File remoteRepoDir; URIish urIish; /** - * We test the performance of git fetch on four repositories, varying them on the basis of their + * We test the performance of git fetch on multiple repositories, varying them on the basis of their * commit history size, number of branches and ultimately their overall size. - * Java-logging-benchmarks: (0.034 MiB) https://github.com/stephenc/java-logging-benchmarks.git - * Coreutils: (4.58 MiB) https://github.com/uutils/coreutils.git - * Cairo: (93.54 MiB) https://github.com/cairoshell/cairoshell.git - * Samba: (324.26 MiB) https://github.com/samba-team/samba.git + * Java-logging-benchmarks: (0.14 MiB) https://github.com/stephenc/java-logging-benchmarks.git + * Implied labels plugin: (0.54 MiB) https://github.com/jenkinsci/implied-labels-plugin.git + * Git client plugin: (8.5 MiB) https://github.com/jenkinsci/git-client-plugin.git + * Git plugin: (11 MiB) https://github.com/jenkinsci/git-plugin.git + * Coreutils: (35 MiB) https://github.com/uutils/coreutils.git + * Samba: (450 MiB) https://github.com/samba-team/samba.git */ @Param({ "https://github.com/stephenc/java-logging-benchmarks.git", + "https://github.com/jenkinsci/implied-labels-plugin.git", + "https://github.com/jenkinsci/git-client-plugin.git", + "https://github.com/jenkinsci/git-plugin.git", "https://github.com/uutils/coreutils.git", - "https://github.com/freedesktop/cairo.git", "https://github.com/samba-team/samba.git" }) String repoUrl; diff --git a/src/test/java/jmh/benchmark/GitClientFetchVanillaBenchmark.java b/src/test/java/jmh/benchmark/GitClientFetchVanillaBenchmark.java deleted file mode 100644 index b001b589ab..0000000000 --- a/src/test/java/jmh/benchmark/GitClientFetchVanillaBenchmark.java +++ /dev/null @@ -1,146 +0,0 @@ -// package jmh.benchmark; -// -// import hudson.EnvVars; -// import hudson.model.TaskListener; -// import org.eclipse.jgit.transport.RefSpec; -// import org.eclipse.jgit.transport.URIish; -// import org.jenkinsci.plugins.gitclient.FetchCommand; -// import org.jenkinsci.plugins.gitclient.Git; -// import org.jenkinsci.plugins.gitclient.GitClient; -// import org.junit.After; -// import org.junit.Before; -// import org.junit.Test; -// import org.junit.runner.RunWith; -// import org.junit.runners.Parameterized; -// -// import java.io.File; -// import java.nio.file.Files; -// import java.util.ArrayList; -// import java.util.Collection; -// import java.util.List; -// -// import static org.junit.Assert.assertFalse; -// import static org.junit.Assert.assertTrue; -// -/// ** -// * A vanilla benchmark is basically a performance test without JMH, it uses System.nanoTime() to measure the execution -// * time. This test was created for the sole purpose to "sanity check" the JMH benchmark results. -// */ -// @RunWith(Parameterized.class) -// public class GitClientFetchVanillaBenchmark { -// -// String gitExe; -// -// public GitClientFetchVanillaBenchmark(final String gitImplName) { -// this.gitExe = gitImplName; -// } -// -// @Parameterized.Parameters(name = "{0}") -// public static Collection gitObjects() { -// List arguments = new ArrayList<>(); -// String[] gitImplNames = {"git", "jgit"}; -// for (String gitImplName : gitImplNames) { -// Object[] item = {gitImplName}; -// arguments.add(item); -// } -// return arguments; -// } -// -// final FolderForBenchmark tmp = new FolderForBenchmark(); -// File gitDir; -// File parentDir; -// GitClient gitClient; -// List refSpecs = new ArrayList<>(); -// URIish urIish; -// String urlOne = "https://github.com/stephenc/java-logging-benchmarks.git"; -// String urlTwo = "https://github.com/uutils/coreutils.git"; -// String urlThree = "https://github.com/freedesktop/cairo.git"; -// String urlFour = "https://github.com/samba-team/samba.git"; -// File repoOneDir; -// File repoTwoDir; -// File repoThreeDir; -// File repoFourDir; -// -// private File cloneUpstreamRepositoryLocally(File parentDir, String repoUrl) throws Exception { -// String repoName = repoUrl.split("/")[repoUrl.split("/").length - 1]; -// File gitRepoDir = new File(parentDir, repoName); -// gitRepoDir.mkdir(); -// GitClient cloningGitClient = Git.with(TaskListener.NULL, new -// EnvVars()).in(gitRepoDir).using(gitExe).getClient(); -// cloningGitClient.clone_().url(repoUrl).execute(); -// assertTrue("Unable to create git repo", gitRepoDir.exists()); -// return gitRepoDir; -// } -// -// @Before -// public void setupEnv() throws Exception { -// tmp.before(); -// gitDir = tmp.newFolder(); // local test git repository -// parentDir = tmp.newFolder(); // local copy of upstream git repository -// repoOneDir = cloneUpstreamRepositoryLocally(parentDir, urlOne); -// repoTwoDir = cloneUpstreamRepositoryLocally(parentDir, urlTwo); -// repoThreeDir = cloneUpstreamRepositoryLocally(parentDir, urlThree); -// repoFourDir = cloneUpstreamRepositoryLocally(parentDir, urlFour); -// -// gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using(gitExe).getClient(); -// -// // fetching all branches branch -// refSpecs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); -// -// // initialize the test folder for git fetch -// gitClient.init(); -// System.out.println("Do Setup"); -// } -// -// @After -// public void tearDown() { -// try { -// File gitDir = gitClient.withRepository((repo, channel) -> repo.getDirectory()); -// System.out.println(gitDir.isDirectory()); -// } catch (Exception e) { -// e.getMessage(); -// } -// tmp.after(); -// System.out.println("Do TearDown"); -// } -// -// @Test -// public void gitFetchBenchmark1() throws Exception { -// urIish = new URIish("file://" + repoOneDir.getAbsolutePath()); -// FetchCommand fetch = gitClient.fetch_().from(urIish, refSpecs); -// long begin = System.nanoTime(); -// fetch.execute(); -// long end = System.nanoTime(); -// System.out.println("The execution time is" + " " + (end - begin)); -// } -// -// @Test -// public void gitFetchBenchmark2() throws Exception { -// urIish = new URIish("file://" + repoTwoDir.getAbsolutePath()); -// FetchCommand fetch = gitClient.fetch_().from(urIish, refSpecs); -// long begin = System.nanoTime(); -// fetch.execute(); -// long end = System.nanoTime(); -// System.out.println("The execution time is" + " " + (end - begin)); -// } -// -// @Test -// public void gitFetchBenchmark3() throws Exception { -// urIish = new URIish("file://" + repoThreeDir.getAbsolutePath()); -// FetchCommand fetch = gitClient.fetch_().from(urIish, refSpecs); -// long begin = System.nanoTime(); -// fetch.execute(); -// long end = System.nanoTime(); -// System.out.println("The execution time is" + " " + (end - begin)); -// } -// -// @Test -// public void gitFetchBenchmark4() throws Exception { -// urIish = new URIish("file://" + repoFourDir.getAbsolutePath()); -// FetchCommand fetch = gitClient.fetch_().from(urIish, refSpecs); -// long begin = System.nanoTime(); -// fetch.execute(); -// long end = System.nanoTime(); -// System.out.println("The execution time is" + " " + (end - begin)); -// } -// } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPIImplTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPIImplTest.java index 084c281540..43f71662dc 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPIImplTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPIImplTest.java @@ -1,7 +1,7 @@ package org.jenkinsci.plugins.gitclient; -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; @@ -16,43 +16,27 @@ protected GitClient setupGitAPI(File ws) throws Exception { return Git.with(listener, env).in(ws).using("git").getClient(); } - public static class VersionTest { - - private boolean expectedIsAtLeastVersion; - private int major; - private int minor; - private int rev; - private int bugfix; - - public VersionTest(boolean assertTrueOrFalse, int major, int minor, int rev, int bugfix) { - this.expectedIsAtLeastVersion = assertTrueOrFalse; - this.major = major; - this.minor = minor; - this.rev = rev; - this.bugfix = bugfix; - } - } + public record VersionTest(boolean expectedIsAtLeastVersion, int major, int minor, int rev, int bugfix) {} public void assertVersionOutput(String versionOutput, VersionTest[] versions) { - setTimeoutVisibleInCurrentTest(false); /* No timeout for git --version command */ CliGitAPIImpl git = new CliGitAPIImpl("git", new File("."), listener, env); git.computeGitVersion(versionOutput); for (VersionTest version : versions) { String msg = versionOutput + " for " + version.major + version.minor + version.rev + version.bugfix; if (version.expectedIsAtLeastVersion) { assertTrue( - "Failed " + msg, - git.isAtLeastVersion(version.major, version.minor, version.rev, version.bugfix)); + git.isAtLeastVersion(version.major, version.minor, version.rev, version.bugfix), + "Failed " + msg); assertTrue( - "Failed " + msg, - git.isCliGitVerAtLeast(version.major, version.minor, version.rev, version.bugfix)); + git.isCliGitVerAtLeast(version.major, version.minor, version.rev, version.bugfix), + "Failed " + msg); } else { assertFalse( - "Passed " + msg, - git.isAtLeastVersion(version.major, version.minor, version.rev, version.bugfix)); + git.isAtLeastVersion(version.major, version.minor, version.rev, version.bugfix), + "Passed " + msg); assertFalse( - "Passed " + msg, - git.isCliGitVerAtLeast(version.major, version.minor, version.rev, version.bugfix)); + git.isCliGitVerAtLeast(version.major, version.minor, version.rev, version.bugfix), + "Passed " + msg); } } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPITempFileTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPITempFileTest.java index 2b2ad38fcc..80a508b45b 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPITempFileTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPITempFileTest.java @@ -4,7 +4,7 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import hudson.EnvVars; import hudson.model.TaskListener; @@ -12,15 +12,15 @@ import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.Random; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; /** @@ -29,71 +29,69 @@ * * @author Mark Waite */ -@RunWith(Parameterized.class) -public class CliGitAPITempFileTest { +@ParameterizedClass(name = "{0}") +@MethodSource("workspaceDirNames") +class CliGitAPITempFileTest { - private final String workspaceDirName; - private final boolean mustUseSystemTempDir; - private final String filenamePrefix; - private final String filenameSuffix; - /* Should temp folder be in same parent dir as workspace? */ + @Parameter(0) + private String workspaceDirName; + + @Parameter(1) + private boolean mustUseSystemTempDir; + + @Parameter(2) + private String filenamePrefix; + + @Parameter(3) + private String filenameSuffix; private static final String INVALID_CHARACTERS = "%" + (isWindows() ? " ()" : "`"); - @Rule - public TemporaryFolder workspaceParentFolder = new TemporaryFolder(); + /* Should temp folder be in same parent dir as workspace? */ + @TempDir + private File workspaceParentFolder; - public CliGitAPITempFileTest( - String workspaceDirName, boolean mustUseSystemTempDir, String filenamePrefix, String filenameSuffix) { - this.workspaceDirName = workspaceDirName; - this.mustUseSystemTempDir = mustUseSystemTempDir; - this.filenamePrefix = filenamePrefix; - this.filenameSuffix = filenameSuffix; - } + private File workspace; - @Parameterized.Parameters(name = "{0}") - public static Collection workspaceDirNames() { + static List workspaceDirNames() { Random random = new Random(); - List workspaceNames = new ArrayList<>(); + List workspaceNames = new ArrayList<>(); for (int charIndex = 0; charIndex < INVALID_CHARACTERS.length(); charIndex++) { - Object[] oneWorkspace = { - "use " + INVALID_CHARACTERS.charAt(charIndex) + " dir", - true, - random.nextBoolean() ? "pre" : null, - random.nextBoolean() ? ".suff" : null - }; + Arguments oneWorkspace = Arguments.of( + "use " + INVALID_CHARACTERS.charAt(charIndex) + " dir", + true, + random.nextBoolean() ? "pre" : null, + random.nextBoolean() ? ".suff" : null); workspaceNames.add(oneWorkspace); } String[] goodNames = {"$5.00", "b&d", "f[x]", "mark@home"}; for (String goodName : goodNames) { - Object[] oneWorkspace = { - goodName, false, random.nextBoolean() ? "pre" : null, random.nextBoolean() ? ".suff" : null - }; + Arguments oneWorkspace = Arguments.of( + goodName, false, random.nextBoolean() ? "pre" : null, random.nextBoolean() ? ".suff" : null); workspaceNames.add(oneWorkspace); } String[] badNames = {"50%off"}; for (String badName : badNames) { - Object[] oneWorkspace = { - badName, true, random.nextBoolean() ? "pre" : null, random.nextBoolean() ? ".suff" : null - }; + Arguments oneWorkspace = Arguments.of( + badName, true, random.nextBoolean() ? "pre" : null, random.nextBoolean() ? ".suff" : null); workspaceNames.add(oneWorkspace); } String[] platformNames = {"(abc)", "abs(x)", "shame's own"}; for (String platformName : platformNames) { - Object[] oneWorkspace = { - platformName, isWindows(), random.nextBoolean() ? "pre" : null, random.nextBoolean() ? ".suff" : null - }; + Arguments oneWorkspace = Arguments.of( + platformName, + isWindows(), + random.nextBoolean() ? "pre" : null, + random.nextBoolean() ? ".suff" : null); workspaceNames.add(oneWorkspace); } return workspaceNames; } - private File workspace; - - @Before - public void createWorkspace() throws Exception { - workspace = workspaceParentFolder.newFolder(workspaceDirName); - assertTrue("'" + workspace.getAbsolutePath() + "' not a directory", workspace.isDirectory()); + @BeforeEach + void createWorkspace() throws Exception { + workspace = newFolder(workspaceParentFolder, workspaceDirName); + assertTrue(workspace.isDirectory(), "'" + workspace.getAbsolutePath() + "' not a directory"); assertThat(workspace.getAbsolutePath(), containsString(workspaceDirName)); } @@ -102,9 +100,10 @@ public void createWorkspace() throws Exception { * contains no characters that are invalid for CLI git authentication. * */ + // and ... @Test - @Issue({"JENKINS-44301", "JENKINS-43931"}) // and ... - public void testTempFilePathCharactersValid() throws IOException { + @Issue({"JENKINS-44301", "JENKINS-43931"}) + void testTempFilePathCharactersValid() throws Exception { CliGitAPIImplExtension cliGit = new CliGitAPIImplExtension("git", workspace, null, null); for (int charIndex = 0; charIndex < INVALID_CHARACTERS.length(); charIndex++) { Path tempFile = cliGit.createTempFile(filenamePrefix, filenameSuffix); @@ -137,4 +136,13 @@ private CliGitAPIImplExtension(String gitExe, File workspace, TaskListener liste super(gitExe, workspace, listener, environment); } } + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPIWindowsFilePermissionsTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPIWindowsFilePermissionsTest.java index 8d68898f00..e2da81fc5a 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPIWindowsFilePermissionsTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/CliGitAPIWindowsFilePermissionsTest.java @@ -1,9 +1,7 @@ package org.jenkinsci.plugins.gitclient; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.File; import java.nio.file.Files; @@ -12,22 +10,25 @@ import java.nio.file.attribute.AclEntryType; import java.nio.file.attribute.AclFileAttributeView; import java.nio.file.attribute.UserPrincipal; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -public class CliGitAPIWindowsFilePermissionsTest { +class CliGitAPIWindowsFilePermissionsTest { private CliGitAPIImpl cliGit; private Path file; private AclFileAttributeView fileAttributeView; private UserPrincipal userPrincipal; - @Before - public void beforeEach() throws Exception { - if (!isWindows()) { - return; - } - cliGit = new CliGitAPIImpl("git", new File("."), null, null); + @TempDir + private static File tempDir; + + @BeforeEach + void beforeEach() throws Exception { + assumeTrue(isWindows()); + + cliGit = new CliGitAPIImpl("git", tempDir, null, null); file = cliGit.createTempFile("permission", ".suff"); fileAttributeView = Files.getFileAttributeView(file, AclFileAttributeView.class); assertNotNull(fileAttributeView); @@ -36,10 +37,7 @@ public void beforeEach() throws Exception { } @Test - public void test_windows_file_permission_is_set_correctly() throws Exception { - if (!isWindows()) { - return; - } + void test_windows_file_permission_is_set_correctly() throws Exception { cliGit.fixSshKeyOnWindows(file); assertEquals(1, fileAttributeView.getAcl().size()); AclEntry aclEntry = fileAttributeView.getAcl().get(0); @@ -50,10 +48,7 @@ public void test_windows_file_permission_is_set_correctly() throws Exception { } @Test - public void test_windows_file_permission_are_incorrect() throws Exception { - if (!isWindows()) { - return; - } + void test_windows_file_permission_are_incorrect() throws Exception { // By default files include System and builtin administrators assertNotSame(1, fileAttributeView.getAcl().size()); for (AclEntry entry : fileAttributeView.getAcl()) { diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/CliGitCommand.java b/src/test/java/org/jenkinsci/plugins/gitclient/CliGitCommand.java index 28f8fe306f..095a8ad8cd 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/CliGitCommand.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/CliGitCommand.java @@ -1,6 +1,6 @@ package org.jenkinsci.plugins.gitclient; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import hudson.EnvVars; import hudson.Launcher; @@ -55,18 +55,11 @@ class CliGitCommand { args = null; } - CliGitCommand(GitClient client, String... arguments) throws GitException { - this(client); - args = new ArgumentListBuilder("git"); - args.add(arguments); - } - - void initializeRepository() throws GitException, IOException, InterruptedException { + void initializeRepository() throws GitException, InterruptedException { initializeRepository("git-client-user", "git-client-user@example.com"); } - void initializeRepository(String userName, String userEmail) - throws GitException, IOException, InterruptedException { + void initializeRepository(String userName, String userEmail) throws GitException, InterruptedException { gitClient.config(GitClient.ConfigLevel.LOCAL, "user.name", userName); gitClient.config(GitClient.ConfigLevel.LOCAL, "user.email", userEmail); gitClient.config(GitClient.ConfigLevel.LOCAL, "commit.gpgsign", "false"); @@ -77,7 +70,7 @@ void initializeRepository(String userName, String userEmail) gitClient.config(GitClient.ConfigLevel.LOCAL, "gpg.format", "openpgp"); } - void removeRepositorySettings() throws GitException, IOException, InterruptedException { + void removeRepositorySettings() throws GitException, InterruptedException { gitClient.config(GitClient.ConfigLevel.LOCAL, "user.name", null); gitClient.config(GitClient.ConfigLevel.LOCAL, "user.email", null); gitClient.config(GitClient.ConfigLevel.LOCAL, "commit.gpgsign", null); @@ -85,17 +78,13 @@ void removeRepositorySettings() throws GitException, IOException, InterruptedExc gitClient.config(GitClient.ConfigLevel.LOCAL, "gpg.format", null); } - String[] run(String... arguments) throws IOException, InterruptedException { + String[] run(String... arguments) throws Exception { args = new ArgumentListBuilder("git"); args.add(arguments); return run(true); } - String[] run() throws IOException, InterruptedException { - return run(true); - } - - private String[] run(boolean assertProcessStatus) throws IOException, InterruptedException { + private String[] run(boolean assertProcessStatus) throws Exception { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ByteArrayOutputStream bytesErr = new ByteArrayOutputStream(); Launcher.ProcStarter p = launcher.launch() @@ -111,7 +100,7 @@ private String[] run(boolean assertProcessStatus) throws IOException, Interrupte } output = result.split("[\\n\\r]"); if (assertProcessStatus) { - 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; } @@ -119,7 +108,7 @@ private String[] run(boolean assertProcessStatus) throws IOException, Interrupte void assertOutputContains(String... expectedRegExes) { List notFound = new ArrayList<>(); boolean modified = notFound.addAll(Arrays.asList(expectedRegExes)); - assertTrue("Missing regular expressions in assertion", modified); + assertTrue(modified, "Missing regular expressions in assertion"); for (String line : output) { notFound.removeIf(line::matches); } @@ -129,7 +118,7 @@ void assertOutputContains(String... expectedRegExes) { } } - String[] runWithoutAssert(String... arguments) throws IOException, InterruptedException { + String[] runWithoutAssert(String... arguments) throws Exception { args = new ArgumentListBuilder("git"); args.add(arguments); return run(false); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/CredentialsTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/CredentialsTest.java index dfee573df5..07b65878ad 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/CredentialsTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/CredentialsTest.java @@ -4,9 +4,7 @@ import static org.hamcrest.Matchers.hasItems; 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.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey; import com.cloudbees.plugins.credentials.CredentialsProvider; @@ -14,7 +12,6 @@ import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; -import hudson.model.Descriptor.FormException; import hudson.model.Fingerprint; import hudson.util.LogTaskListener; import java.io.File; @@ -23,7 +20,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; @@ -39,42 +35,66 @@ import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +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.io.TempDir; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +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; /** * Test authenticated operations with the git implementations. * Uses contents of ~/.ssh/auth-data for parameterized tests. * @author Mark Waite */ -@RunWith(Parameterized.class) -public class CredentialsTest { +@ParameterizedClass(name = "Impl:{0} User:{2} Pass:{3} Embed:{9} Phrase:{5} URL:{1}", allowZeroInvocations = true) +@MethodSource("gitRepoUrls") +@WithJenkins +class CredentialsTest { // Required for credentials use - @ClassRule - public static final JenkinsRule r = new JenkinsRule(); - - private final String gitImpl; - private final String gitRepoURL; - private final String username; - private final String password; - private final File privateKey; - private final String passphrase; - private final String fileToCheck; - private final Boolean submodules; - private final Boolean useParentCreds; - private final Boolean lfsSpecificTest; - private final char specialCharacter; - private final Boolean credentialsEmbeddedInURL; + private static JenkinsRule r; + + @Parameter(0) + private String gitImpl; + + @Parameter(1) + private String gitRepoURL; + + @Parameter(2) + private String username; + + @Parameter(3) + private String password; + + @Parameter(4) + private File privateKey; + + @Parameter(5) + private String passphrase; + + @Parameter(6) + private String fileToCheck; + + @Parameter(7) + private Boolean submodules; + + @Parameter(8) + private Boolean useParentCreds; + + @Parameter(9) + private Boolean lfsSpecificTest; + + @Parameter(10) + private Boolean credentialsEmbeddedInURL; + + private char specialCharacter; private GitClient git; private File repo; @@ -82,8 +102,8 @@ public class CredentialsTest { private final Random random = new Random(); - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; private int logCount; private LogHandler handler; @@ -96,38 +116,20 @@ public class CredentialsTest { /* Directory containing local private keys for tests */ private static final File AUTH_DATA_DIR = new File(SSH_DIR, "auth-data"); - private static final File CURR_DIR = new File("."); - private static long firstTestStartTime = 0; /* Windows refuses directory names with '*', '<', '>', '|', '?', and ':' */ - private final String SPECIALS_TO_CHECK = "%()`$&{}[]" + (isWindows() ? "" : "*<>:|?"); + private static final String SPECIALS_TO_CHECK = "%()`$&{}[]" + (isWindows() ? "" : "*<>:|?"); private static int specialsIndex = 0; - public CredentialsTest( - String gitImpl, - String gitRepoUrl, - String username, - String password, - File privateKey, - String passphrase, - String fileToCheck, - Boolean submodules, - Boolean useParentCreds, - Boolean credentialsEmbeddedInURL, - Boolean lfsSpecificTest) { - this.gitImpl = gitImpl; - this.gitRepoURL = gitRepoUrl; - this.privateKey = privateKey; - this.passphrase = passphrase; - this.username = username; - this.password = password; - this.fileToCheck = fileToCheck; - this.submodules = submodules; - this.useParentCreds = useParentCreds; - this.lfsSpecificTest = lfsSpecificTest; - this.specialCharacter = SPECIALS_TO_CHECK.charAt(specialsIndex); - this.credentialsEmbeddedInURL = credentialsEmbeddedInURL; + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } + + @BeforeEach + void setUp() throws Exception { + specialCharacter = SPECIALS_TO_CHECK.charAt(specialsIndex); specialsIndex = specialsIndex + 1; if (specialsIndex >= SPECIALS_TO_CHECK.length()) { specialsIndex = 0; @@ -135,21 +137,18 @@ public CredentialsTest( if (firstTestStartTime == 0) { firstTestStartTime = System.currentTimeMillis(); } - } - @Before - public void setUp() throws FormException, IOException, InterruptedException { git = null; - repo = tempFolder.newFolder(); + repo = newFolder(tempFolder, "junit"); /* Use a repo with a special character in name - JENKINS-43931 */ String newDirName = "use " + specialCharacter + " dir"; File repoParent = repo; repo = new File(repoParent, newDirName); boolean dirCreated = repo.mkdirs(); - assertTrue("Failed to create " + repo.getAbsolutePath(), dirCreated); + assertTrue(dirCreated, "Failed to create " + repo.getAbsolutePath()); File repoTemp = new File(repoParent, newDirName + "@tmp"); // use adjacent temp directory dirCreated = repoTemp.mkdirs(); - assertTrue("Failed to create " + repoTemp.getAbsolutePath(), dirCreated); + assertTrue(dirCreated, "Failed to create " + repoTemp.getAbsolutePath()); Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++); handler = new LogHandler(); handler.setLevel(Level.ALL); @@ -160,8 +159,8 @@ public void setUp() throws FormException, IOException, InterruptedException { git = Git.with(listener, new hudson.EnvVars()).in(repo).using(gitImpl).getClient(); assertTrue( - "Bad username, password, privateKey combo: '" + username + "', '" + password + "'", - (password == null || password.isEmpty()) ^ (privateKey == null || !privateKey.exists())); + (password == null || password.isEmpty()) ^ (privateKey == null || !privateKey.exists()), + "Bad username, password, privateKey combo: '" + username + "', '" + password + "'"); if (password != null && !password.isEmpty()) { testedCredential = newUsernamePasswordCredential(username, password); } @@ -175,32 +174,32 @@ public void setUp() throws FormException, IOException, InterruptedException { } } - @Before - public void enableSETSID() { + @BeforeEach + void enableSETSID() { CliGitAPIImpl.CALL_SETSID = gitImpl.equals("git") && privateKey != null && passphrase != null; } - @After - public void checkFingerprintNotSet() throws Exception { + @AfterEach + void checkFingerprintNotSet() throws Exception { /* Since these are API level tests, they should not track credential usage */ /* Credential usage is tracked at the job / project level */ Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(testedCredential); assertThat("Fingerprint should not be set after API level use", fingerprint, nullValue()); } - @After - public void clearCredentials() { + @AfterEach + void clearCredentials() { if (git != null) { git.clearCredentials(); } } - @After - public void disableSETSID() { + @AfterEach + void disableSETSID() { org.jenkinsci.plugins.gitclient.CliGitAPIImpl.CALL_SETSID = false; } - private BasicSSHUserPrivateKey newPrivateKeyCredential(String username, File privateKey) throws IOException { + private BasicSSHUserPrivateKey newPrivateKeyCredential(String username, File privateKey) throws Exception { CredentialsScope scope = CredentialsScope.GLOBAL; String id = "private-key-" + privateKey.getPath() + random.nextInt(); String privateKeyData = Files.readString(privateKey.toPath(), StandardCharsets.UTF_8); @@ -214,23 +213,14 @@ private BasicSSHUserPrivateKey newPrivateKeyCredential(String username, File pri } private StandardUsernamePasswordCredentials newUsernamePasswordCredential(String username, String password) - throws FormException { + throws Exception { CredentialsScope scope = CredentialsScope.GLOBAL; String id = "username-" + username + "-password-" + password + random.nextInt(); return new UsernamePasswordCredentialsImpl(scope, id, "desc: " + id, username, password); } - private boolean isShallowCloneSupported(String implementation, GitClient gitClient) { - if (!(gitClient instanceof CliGitAPIImpl)) { - return true; - } - CliGitAPIImpl cli = (CliGitAPIImpl) gitClient; - return cli.isAtLeastVersion(1, 9, 0, 0); - } - - @Parameterized.Parameters(name = "Impl:{0} User:{2} Pass:{3} Embed:{9} Phrase:{5} URL:{1}") - public static Collection gitRepoUrls() throws IOException, InterruptedException, ParseException { - List repos = new ArrayList<>(); + static List gitRepoUrls() throws Exception { + List repos = new ArrayList<>(); String[] implementations = new String[] {"git", "jgit", "jgitapache"}; for (String implementation : implementations) { /* Add upstream repository as authentication test with private @@ -243,19 +233,18 @@ public static Collection gitRepoUrls() throws IOException, InterruptedException, String url = "https://github.com/jenkinsci/git-client-plugin.git"; /* Add URL if it matches the pattern */ if (URL_MUST_MATCH_PATTERN.matcher(url).matches()) { - Object[] masterRepo = { - implementation, - url, - username, - null, - DEFAULT_PRIVATE_KEY, - null, - "README.adoc", - false, - false, - false, - false - }; + Arguments masterRepo = Arguments.of( + implementation, + url, + username, + null, + DEFAULT_PRIVATE_KEY, + null, + "README.adoc", + false, + false, + false, + false); repos.add(masterRepo); } } @@ -332,19 +321,18 @@ public static Collection gitRepoUrls() throws IOException, InterruptedException, /* Add URL if it matches the pattern */ if (URL_MUST_MATCH_PATTERN.matcher(repoURL).matches()) { - Object[] repo = { - implementation, - repoURL, - username, - password, - privateKey, - passphrase, - fileToCheck, - submodules, - useParentCreds, - false, - lfsSpecificTest - }; + Arguments repo = Arguments.of( + implementation, + repoURL, + username, + password, + privateKey, + passphrase, + fileToCheck, + submodules, + useParentCreds, + false, + lfsSpecificTest); repos.add(repo); /* Add embedded credentials test case if valid username, valid password, CLI git, and http protocol */ if (username != null @@ -359,19 +347,18 @@ public static Collection gitRepoUrls() throws IOException, InterruptedException, /* Use existing username and password to create an embedded credentials test case */ String repoURLwithCredentials = repoURL.replaceAll( "(https?://)(.*@)?(.*)", "$1" + username + ":" + password + "@$3"); - Object[] repoWithCredentials = { - implementation, - repoURLwithCredentials, - username, - password, - privateKey, - passphrase, - fileToCheck, - submodules, - useParentCreds, - true, - lfsSpecificTest - }; + Arguments repoWithCredentials = Arguments.of( + implementation, + repoURLwithCredentials, + username, + password, + privateKey, + passphrase, + fileToCheck, + submodules, + useParentCreds, + true, + lfsSpecificTest); repos.add(0, repoWithCredentials); } } @@ -390,7 +377,7 @@ private void gitFetch(String source) throws Exception { private void gitFetch(String source, String branch, Boolean allowShallowClone) throws Exception { URIish sourceURI = new URIish(source); List refSpecs = new ArrayList<>(); - refSpecs.add(new RefSpec("+refs/heads/" + branch + ":refs/remotes/origin/" + branch + "")); + refSpecs.add(new RefSpec("+refs/heads/" + branch + ":refs/remotes/origin/" + branch)); FetchCommand cmd = git.fetch_().from(sourceURI, refSpecs).tags(false); // Reduce network transfer by using shallow clone cmd.shallow(true).depth(1); @@ -432,13 +419,13 @@ private boolean testPeriodExpired() { @Test @Issue("JENKINS-50573") - public void testFetchWithCredentials() throws Exception { + void testFetchWithCredentials() throws Exception { if (testPeriodExpired() || lfsSpecificTest) { return; } File clonedFile = new File(repo, fileToCheck); git.init_().workspace(repo.getAbsolutePath()).execute(); - assertFalse("file " + fileToCheck + " in " + repo + ", has " + listDir(repo), clonedFile.exists()); + assertFalse(clonedFile.exists(), "file " + fileToCheck + " in " + repo + ", has " + listDir(repo)); addCredential(); /* Fetch with remote URL */ gitFetch(gitRepoURL); @@ -456,56 +443,50 @@ public void testFetchWithCredentials() throws Exception { SubmoduleUpdateCommand subcmd = git.submoduleUpdate().parentCredentials(useParentCreds); subcmd.execute(); } - assertTrue("master: " + master + " not in repo", git.isCommitInRepo(master)); - assertEquals("Master != HEAD", master, git.withRepository((gitRepo, unusedChannel) -> gitRepo.findRef("master") - .getObjectId())); - assertEquals("Wrong branch", "master", git.withRepository((gitRepo, unusedChanel) -> gitRepo.getBranch())); - assertTrue("No file " + fileToCheck + ", has " + listDir(repo), clonedFile.exists()); + assertTrue(git.isCommitInRepo(master), "master: " + master + " not in repo"); + assertEquals( + master, + git.withRepository( + (gitRepo, unusedChannel) -> gitRepo.findRef("master").getObjectId()), + "Master != HEAD"); + assertEquals("master", git.withRepository((gitRepo, unusedChanel) -> gitRepo.getBranch()), "Wrong branch"); + assertTrue(clonedFile.exists(), "No file " + fileToCheck + ", has " + listDir(repo)); /* prune opens a remote connection to list remote branches */ git.prune(new RemoteConfig(git.withRepository((gitRepo, unusedChannel) -> gitRepo.getConfig()), "origin")); } @Test - public void testRemoteReferencesWithCredentials() throws Exception { + void testRemoteReferencesWithCredentials() throws Exception { if (testPeriodExpired()) { return; } addCredential(); - Map remoteReferences; - switch (random.nextInt(4)) { - default: - case 0: - remoteReferences = git.getRemoteReferences(gitRepoURL, null, true, false); - break; - case 1: - remoteReferences = git.getRemoteReferences(gitRepoURL, null, true, true); - break; - case 2: - remoteReferences = git.getRemoteReferences(gitRepoURL, "master", true, false); - break; - case 3: - remoteReferences = git.getRemoteReferences(gitRepoURL, "master", true, true); - break; - } + Map remoteReferences = + switch (random.nextInt(4)) { + case 1 -> git.getRemoteReferences(gitRepoURL, null, true, true); + case 2 -> git.getRemoteReferences(gitRepoURL, "master", true, false); + case 3 -> git.getRemoteReferences(gitRepoURL, "master", true, true); + default -> git.getRemoteReferences(gitRepoURL, null, true, false); + }; assertThat(remoteReferences.keySet(), hasItems("refs/heads/master")); } @Test @Issue("JENKINS-50573") - public void isURIishRemote() throws Exception { + void isURIishRemote() throws Exception { URIish uri = new URIish(gitRepoURL); - assertTrue("Should be remote but isn't: " + uri, uri.isRemote()); + assertTrue(uri.isRemote(), "Should be remote but isn't: " + uri); } @Test @Issue("JENKINS-45228") - public void testLfsMergeWithCredentials() throws Exception { + void testLfsMergeWithCredentials() throws Exception { if (testPeriodExpired() || !lfsSpecificTest) { return; } File clonedFile = new File(repo, fileToCheck); git.init_().workspace(repo.getAbsolutePath()).execute(); - assertFalse("file " + fileToCheck + " in " + repo + ", has " + listDir(repo), clonedFile.exists()); + assertFalse(clonedFile.exists(), "file " + fileToCheck + " in " + repo + ", has " + listDir(repo)); addCredential(); /* Fetch with remote name "origin" instead of remote URL */ @@ -518,11 +499,10 @@ public void testLfsMergeWithCredentials() throws Exception { .lfsRemote("origin") .deleteBranchIfExist(true) .execute(); - assertTrue("master: " + master + " not in repo", git.isCommitInRepo(master)); - assertEquals( - "Master != HEAD", master, git.getRepository().findRef("master").getObjectId()); - assertEquals("Wrong branch", "master", git.getRepository().getBranch()); - assertTrue("No file " + fileToCheck + ", has " + listDir(repo), clonedFile.exists()); + assertTrue(git.isCommitInRepo(master), "master: " + master + " not in repo"); + assertEquals(master, git.getRepository().findRef("master").getObjectId(), "Master != HEAD"); + assertEquals("master", git.getRepository().getBranch(), "Wrong branch"); + assertTrue(clonedFile.exists(), "No file " + fileToCheck + ", has " + listDir(repo)); ObjectId modified_lfs = git.getHeadRev(gitRepoURL, "modified_lfs"); git.merge() @@ -531,12 +511,12 @@ public void testLfsMergeWithCredentials() throws Exception { .setRevisionToMerge(modified_lfs) .execute(); assertEquals( - "Fast-forward merge failed. master and modified_lfs should be the same.", git.revParse("HEAD"), - modified_lfs); + modified_lfs, + "Fast-forward merge failed. master and modified_lfs should be the same."); } - private boolean isWindows() { + private static boolean isWindows() { return File.pathSeparatorChar == ';'; } @@ -552,4 +532,13 @@ private boolean isWindows() { Boolean.parseBoolean(System.getProperty("TEST_ALL_CREDENTIALS", NOT_JENKINS)); private static final Pattern URL_MUST_MATCH_PATTERN = Pattern.compile(System.getProperty("URL_MUST_MATCH_PATTERN", ".*")); + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/FilePermissionsTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/FilePermissionsTest.java index 71c1d3d23b..e58f3d7faa 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/FilePermissionsTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/FilePermissionsTest.java @@ -1,13 +1,11 @@ package org.jenkinsci.plugins.gitclient; import static org.jenkinsci.plugins.gitclient.GitAPITest.getConfigNoSystemEnvVars; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import hudson.model.TaskListener; -import hudson.plugins.git.GitException; import hudson.util.StreamTaskListener; import java.io.File; -import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.Files; @@ -22,33 +20,32 @@ import java.util.UUID; import org.apache.commons.io.FileUtils; import org.eclipse.jgit.util.SystemReader; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) -public class FilePermissionsTest { - - private final int permission; - - /** - * Test that command line git preserves execute permission across clone. Git - * does not preserve all file permission bits, only the execute bit for the - * owner. - */ - public FilePermissionsTest(Integer filePermission) { - this.permission = filePermission; - } +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Test that command line git preserves execute permission across clone. Git + * does not preserve all file permission bits, only the execute bit for the + * owner. + */ +@ParameterizedClass +@MethodSource("permissionBits") +class FilePermissionsTest { + + @Parameter(0) + private int permission; private static final TaskListener listener = StreamTaskListener.fromStdout(); private static File repo; - @BeforeClass - public static void createTestRepo() throws Exception { + @BeforeAll + static void createTestRepo() throws Exception { if (isWindows()) { return; } @@ -68,8 +65,8 @@ public static void createTestRepo() throws Exception { * Git 2.32.0 honors the configuration variable `init.defaultBranch` and uses it for the name of the initial branch. * This method reads the global configuration and uses it to set the value of `defaultBranchName`. */ - @BeforeClass - public static void computeDefaultBranchName() throws Exception { + @BeforeAll + static void computeDefaultBranchName() throws Exception { File configDir = Files.createTempDirectory("readGitConfig").toFile(); CliGitCommand getDefaultBranchNameCmd = new CliGitCommand(Git.with(TaskListener.NULL, getConfigNoSystemEnvVars()) @@ -83,11 +80,11 @@ public static void computeDefaultBranchName() throws Exception { defaultBranchName = result; } } - assertTrue("Failed to delete temporary readGitConfig directory", configDir.delete()); + assertTrue(configDir.delete(), "Failed to delete temporary readGitConfig directory"); } - @AfterClass - public static void verifyTestRepo() throws Exception { + @AfterAll + static void verifyTestRepo() throws Exception { if (isWindows()) { return; } @@ -120,31 +117,30 @@ private static File cloneTestRepo(File repo) throws Exception { return newRepo; } - private static void verifyFile(File repo, int staticPerm) throws IOException { + private static void verifyFile(File repo, int staticPerm) throws Exception { String fileName = "git-%03o.txt".formatted(staticPerm); File file = new File(repo, fileName); - assertTrue("Missing " + file.getAbsolutePath(), file.exists()); + assertTrue(file.exists(), "Missing " + file.getAbsolutePath()); String content = Files.readString(file.toPath(), StandardCharsets.UTF_8); - assertTrue(fileName + " wrong content: '" + content + "'", content.contains(fileName)); + assertTrue(content.contains(fileName), fileName + " wrong content: '" + content + "'"); String rwx = permString(staticPerm); Set expected = PosixFilePermissions.fromString(rwx); Path path = FileSystems.getDefault().getPath(file.getPath()); PosixFileAttributes attrs = Files.getFileAttributeView(path, PosixFileAttributeView.class).readAttributes(); assertEquals( - fileName + " OWNER_EXECUTE (execute) perm mismatch, expected: " + expected + ", was actually: " - + attrs.permissions(), expected.contains(PosixFilePermission.OWNER_EXECUTE), - attrs.permissions().contains(PosixFilePermission.OWNER_EXECUTE)); + attrs.permissions().contains(PosixFilePermission.OWNER_EXECUTE), + fileName + " OWNER_EXECUTE (execute) perm mismatch, expected: " + expected + ", was actually: " + + attrs.permissions()); } - @After - public void checkListenerLoggedNoErrors() { - assertFalse("Error logged by listener", listener.getLogger().checkError()); + @AfterEach + void checkListenerLoggedNoErrors() { + assertFalse(listener.getLogger().checkError(), "Error logged by listener"); } - @Parameterized.Parameters - public static List permissionBits() { + static List permissionBits() { List permissions = new ArrayList<>(); /* 0640 and 0740 are the only permissions to be tested */ Integer[] permissionArray0640 = {0640}; @@ -158,7 +154,7 @@ public static List permissionBits() { } @Test - public void posixPermissionTest() throws IOException, GitException, InterruptedException { + void posixPermissionTest() throws Exception { if (isWindows()) { return; } @@ -170,13 +166,13 @@ private String getFileName() { return "git-%03o.txt".formatted(permission); } - private void addFile() throws IOException, GitException, InterruptedException { + private void addFile() throws Exception { String fileName = getFileName(); String content = fileName + " and UUID " + UUID.randomUUID(); File added = new File(repo, fileName); - assertFalse(fileName + " already exists", added.exists()); + assertFalse(added.exists(), fileName + " already exists"); Files.writeString(added.toPath(), content, StandardCharsets.UTF_8); - assertTrue(fileName + " doesn't exist", added.exists()); + assertTrue(added.exists(), fileName + " doesn't exist"); GitClient git = Git.with(listener, getConfigNoSystemEnvVars()).in(repo).getClient(); git.add(fileName); @@ -187,17 +183,17 @@ private void addFile() throws IOException, GitException, InterruptedException { git.commit("Perms %03o %s".formatted(permission, fileName)); } - private void modifyFile() throws IOException, GitException, InterruptedException { + private void modifyFile() throws Exception { String fileName = getFileName(); String content = fileName + " chg UUID " + UUID.randomUUID(); File modified = new File(repo, fileName); - assertTrue(fileName + " doesn't exist", modified.exists()); + assertTrue(modified.exists(), fileName + " doesn't exist"); Files.writeString(modified.toPath(), content, StandardCharsets.UTF_8); GitClient git = Git.with(listener, getConfigNoSystemEnvVars()).in(repo).getClient(); git.add(fileName); git.commit("Modified " + fileName); - assertTrue(fileName + " doesn't exist", modified.exists()); + assertTrue(modified.exists(), fileName + " doesn't exist"); } private static String permString(int filePermission) { diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPICliGitNotIntializedTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPICliGitNotInitializedTest.java similarity index 77% rename from src/test/java/org/jenkinsci/plugins/gitclient/GitAPICliGitNotIntializedTest.java rename to src/test/java/org/jenkinsci/plugins/gitclient/GitAPICliGitNotInitializedTest.java index 4023fb3b85..278a7bc552 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPICliGitNotIntializedTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPICliGitNotInitializedTest.java @@ -1,8 +1,6 @@ package org.jenkinsci.plugins.gitclient; -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.*; import hudson.EnvVars; import hudson.Util; @@ -10,63 +8,62 @@ import hudson.remoting.VirtualChannel; import hudson.util.StreamTaskListener; import java.io.File; -import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.lib.Repository; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +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.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Git API Test which are solely for CLI git, * but doesn't need an initialized working repo. * These tests are not implemented for JGit. */ -@RunWith(Parameterized.class) -public class GitAPICliGitNotIntializedTest { - @Rule - public GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); +@ParameterizedClass(name = "{0}") +@MethodSource("gitObjects") +class GitAPICliGitNotInitializedTest { + + @RegisterExtension + private final GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); private int logCount = 0; private static final String LOGGING_STARTED = "Logging started"; private LogHandler handler = null; private TaskListener listener; - private final String gitImplName; - WorkspaceWithRepo workspace; + @Parameter(0) + private String gitImplName; + + private WorkspaceWithRepo workspace; private GitClient testGitClient; private File testGitDir; - public GitAPICliGitNotIntializedTest(final String gitImplName) { - this.gitImplName = gitImplName; - } - - @Parameterized.Parameters(name = "{0}") - public static Collection gitObjects() { - List arguments = new ArrayList<>(); + static List gitObjects() { + List arguments = new ArrayList<>(); String[] gitImplNames = {"git"}; for (String gitImplName : gitImplNames) { - Object[] item = {gitImplName}; + Arguments item = Arguments.of(gitImplName); arguments.add(item); } return arguments; } - @BeforeClass - public static void loadLocalMirror() throws Exception { + @BeforeAll + static void loadLocalMirror() throws Exception { /* Prime the local mirror cache before other tests run */ /* Allow 2-6 second delay before priming the cache */ /* Allow other tests a better chance to prime the cache */ @@ -81,8 +78,8 @@ public static void loadLocalMirror() throws Exception { Util.deleteRecursive(tempDir); } - @Before - public void setUpRepositories() throws Exception { + @BeforeEach + void setUpRepositories() throws Exception { Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++); handler = new LogHandler(); handler.setLevel(Level.ALL); @@ -98,11 +95,11 @@ public void setUpRepositories() throws Exception { testGitDir = workspace.getGitFileDir(); } - @After - public void afterTearDown() { + @AfterEach + void afterTearDown() { try { String messages = StringUtils.join(handler.getMessages(), ";"); - assertTrue("Logging not started: " + messages, handler.containsMessageSubstring(LOGGING_STARTED)); + assertTrue(handler.containsMessageSubstring(LOGGING_STARTED), "Logging not started: " + messages); } finally { handler.close(); } @@ -113,7 +110,7 @@ public void afterTearDown() { * is not run with JGit. */ @Test - public void testSubmoduleCheckoutSimple() throws Exception { + void testSubmoduleCheckoutSimple() throws Exception { workspace.cloneRepo(workspace, workspace.localMirror()); assertSubmoduleDirs(testGitDir, false, false); @@ -139,28 +136,16 @@ private void assertSubmoduleRepository(File submoduleDir) throws Exception { * functioning repository object */ submoduleClient.withRepository((final Repository repo, VirtualChannel channel) -> { - assertTrue( - repo.getDirectory() + " is not a valid repository", - repo.getObjectDatabase().exists()); + assertTrue(repo.getObjectDatabase().exists(), repo.getDirectory() + " is not a valid repository"); return null; }); } protected GitClient setupGitAPI(File ws) throws Exception { - setCliGitDefaults(); return Git.with(listener, new EnvVars()).in(ws).using(gitImplName).getClient(); } - private static boolean cliGitDefaultsSet = false; - - private void setCliGitDefaults() throws Exception { - if (!cliGitDefaultsSet) { - CliGitCommand gitCmd = new CliGitCommand(null); - } - cliGitDefaultsSet = true; - } - - private void assertSubmoduleContents(File repo) throws IOException { + private void assertSubmoduleContents(File repo) throws Exception { final File modulesDir = new File(repo, "modules"); final File sshkeysDir = new File(modulesDir, "sshkeys"); @@ -179,17 +164,17 @@ private void assertSubmoduleContents(File repo) throws IOException { assertFileContains(ntpContributingFile, ntpContributingContent); /* Check substring in file */ } - private void assertFileContains(File file, String expectedContent) throws IOException { + private void assertFileContains(File file, String expectedContent) throws Exception { assertFileExists(file); final String fileContent = Files.readString(file.toPath(), StandardCharsets.UTF_8); final String message = file + " does not contain '" + expectedContent + "', contains '" + fileContent + "'"; - assertTrue(message, fileContent.contains(expectedContent)); + assertTrue(fileContent.contains(expectedContent), message); } - private void assertFileContents(File file, String expectedContent) throws IOException { + private void assertFileContents(File file, String expectedContent) throws Exception { assertFileExists(file); final String fileContent = Files.readString(file.toPath(), StandardCharsets.UTF_8); - assertEquals(file + " wrong content", expectedContent, fileContent); + assertEquals(expectedContent, fileContent, file + " wrong content"); } private void assertSubmoduleDirs(File repo, boolean dirsShouldExist, boolean filesShouldExist) { @@ -229,16 +214,16 @@ private void assertDirNotFound(File dir) { } private void assertFileNotFound(File file) { - assertFalse(file + " found, peer files: " + listDir(file.getParentFile()), file.exists()); + assertFalse(file.exists(), file + " found, peer files: " + listDir(file.getParentFile())); } private void assertDirExists(File dir) { assertFileExists(dir); - assertTrue(dir + " is not a directory", dir.isDirectory()); + assertTrue(dir.isDirectory(), dir + " is not a directory"); } private void assertFileExists(File file) { - assertTrue(file + " not found, peer files: " + listDir(file.getParentFile()), file.exists()); + assertTrue(file.exists(), file + " not found, peer files: " + listDir(file.getParentFile())); } private String listDir(File dir) { @@ -254,7 +239,7 @@ private String listDir(File dir) { fileList.append(file.getName()); fileList.append(','); } - if (fileList.length() > 0) { + if (!fileList.isEmpty()) { fileList.deleteCharAt(fileList.length() - 1); } return fileList.toString(); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPIForCliGitTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPIForCliGitTest.java index 93e6b23f00..87ecfd4820 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPIForCliGitTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPIForCliGitTest.java @@ -1,50 +1,53 @@ package org.jenkinsci.plugins.gitclient; -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.Util; import hudson.model.TaskListener; -import hudson.plugins.git.GitException; import hudson.util.StreamTaskListener; import java.io.File; import java.nio.file.Files; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.lib.ObjectId; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +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.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Git API Test which are solely for CLI git, * These tests are not implemented for JGit. */ -@RunWith(Parameterized.class) +@ParameterizedClass(name = "{0}") +@MethodSource("gitObjects") public class GitAPIForCliGitTest { - @Rule - public GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); - @Rule - public GitClientSampleRepoRule secondRepo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule secondRepo = new GitClientSampleRepoRule(); private int logCount = 0; private static final String LOGGING_STARTED = "Logging started"; private LogHandler handler = null; private TaskListener listener; - private final String gitImplName; - WorkspaceWithRepo workspace; + @Parameter(0) + private String gitImplName; + + private WorkspaceWithRepo workspace; private GitClient testGitClient; private File testGitDir; @@ -54,23 +57,18 @@ public class GitAPIForCliGitTest { */ private static String defaultBranchName = "mast" + "er"; // Intentionally split string - public GitAPIForCliGitTest(final String gitImplName) { - this.gitImplName = gitImplName; - } - - @Parameterized.Parameters(name = "{0}") - public static Collection gitObjects() { - List arguments = new ArrayList<>(); + static List gitObjects() { + List arguments = new ArrayList<>(); String[] gitImplNames = {"git"}; for (String gitImplName : gitImplNames) { - Object[] item = {gitImplName}; + Arguments item = Arguments.of(gitImplName); arguments.add(item); } return arguments; } - @BeforeClass - public static void loadLocalMirror() throws Exception { + @BeforeAll + static void loadLocalMirror() throws Exception { /* Prime the local mirror cache before other tests run */ /* Allow 2-6 second delay before priming the cache */ /* Allow other tests a better chance to prime the cache */ @@ -90,8 +88,8 @@ public static void loadLocalMirror() throws Exception { * Git 2.32.0 honors the configuration variable `init.defaultBranch` and uses it for the name of the initial branch. * This method reads the global configuration and uses it to set the value of `defaultBranchName`. */ - @BeforeClass - public static void computeDefaultBranchName() throws Exception { + @BeforeAll + static void computeDefaultBranchName() throws Exception { File configDir = Files.createTempDirectory("readGitConfig").toFile(); CliGitCommand getDefaultBranchNameCmd = new CliGitCommand(Git.with(TaskListener.NULL, new hudson.EnvVars()) .in(configDir) @@ -104,11 +102,11 @@ public static void computeDefaultBranchName() throws Exception { defaultBranchName = result; } } - assertTrue("Failed to delete temporary readGitConfig directory", configDir.delete()); + assertTrue(configDir.delete(), "Failed to delete temporary readGitConfig directory"); } - @Before - public void setUpRepositories() throws Exception { + @BeforeEach + void setUpRepositories() throws Exception { Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++); handler = new LogHandler(); handler.setLevel(Level.ALL); @@ -125,11 +123,11 @@ public void setUpRepositories() throws Exception { workspace.initializeWorkspace(); } - @After - public void afterTearDown() { + @AfterEach + void afterTearDown() { try { String messages = StringUtils.join(handler.getMessages(), ";"); - assertTrue("Logging not started: " + messages, handler.containsMessageSubstring(LOGGING_STARTED)); + assertTrue(handler.containsMessageSubstring(LOGGING_STARTED), "Logging not started: " + messages); } finally { handler.close(); } @@ -137,7 +135,7 @@ public void afterTearDown() { /* Test should move to a class that will also test JGit */ @Test - public void testPushFromShallowClone() throws Exception { + void testPushFromShallowClone() throws Exception { WorkspaceWithRepo remote = new WorkspaceWithRepo(secondRepo.getRoot(), gitImplName, TaskListener.NULL); remote.initializeWorkspace(); remote.commitEmpty("init"); @@ -160,11 +158,4 @@ public void testPushFromShallowClone() throws Exception { remote.launchCommand("git", "rev-parse", defaultBranchName).substring(0, 40); assertEquals(sha1.name(), remoteSha1); } - - private void assertExceptionMessageContains(GitException ge, String expectedSubstring) { - String actual = ge.getMessage().toLowerCase(); - assertTrue( - "Expected '" + expectedSubstring + "' exception message, but was: " + actual, - actual.contains(expectedSubstring)); - } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPIJGitNotInitializedTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPIJGitNotInitializedTest.java index 7a02c81b9f..4598715711 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPIJGitNotInitializedTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPIJGitNotInitializedTest.java @@ -2,9 +2,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import hudson.Util; import hudson.model.TaskListener; @@ -14,53 +12,52 @@ import java.io.File; import java.nio.file.Files; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) -public class GitAPIJGitNotInitializedTest { - - @Rule - public GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); +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.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@ParameterizedClass(name = "{0}") +@MethodSource("gitObjects") +class GitAPIJGitNotInitializedTest { + + @RegisterExtension + private final GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); private int logCount = 0; private static final String LOGGING_STARTED = "Logging started"; private LogHandler handler = null; private TaskListener listener; - private final String gitImplName; + + @Parameter(0) + private String gitImplName; WorkspaceWithRepo workspace; private GitClient testGitClient; - public GitAPIJGitNotInitializedTest(final String gitImplName) { - this.gitImplName = gitImplName; - } - - @Parameterized.Parameters(name = "{0}") - public static Collection gitObjects() { - List arguments = new ArrayList<>(); + static List gitObjects() { + List arguments = new ArrayList<>(); String[] gitImplNames = {"jgit", "jgitapache"}; for (String gitImplName : gitImplNames) { - Object[] item = {gitImplName}; + Arguments item = Arguments.of(gitImplName); arguments.add(item); } return arguments; } - @BeforeClass - public static void loadLocalMirror() throws Exception { + @BeforeAll + static void loadLocalMirror() throws Exception { /* Prime the local mirror cache before other tests run * Allow 2-5 second delay before priming the cache * Allow other tests a better chance to prime the cache @@ -76,8 +73,8 @@ public static void loadLocalMirror() throws Exception { Util.deleteRecursive(tempDir); } - @Before - public void setUpRepositories() throws Exception { + @BeforeEach + void setUpRepositories() throws Exception { Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++); handler = new LogHandler(); handler.setLevel(Level.ALL); @@ -92,18 +89,18 @@ public void setUpRepositories() throws Exception { testGitClient = workspace.getGitClient(); } - @After - public void afterTearDown() { + @AfterEach + void afterTearDown() { try { String messages = StringUtils.join(handler.getMessages(), ";"); - assertTrue("Logging not started: " + messages, handler.containsMessageSubstring(LOGGING_STARTED)); + assertTrue(handler.containsMessageSubstring(LOGGING_STARTED), "Logging not started: " + messages); } finally { handler.close(); } } @Test - public void testGetSubmoduleUrl() throws Exception { + void testGetSubmoduleUrl() throws Exception { workspace.cloneRepo(workspace, workspace.localMirror()); workspace.launchCommand("git", "checkout", "tests/getSubmodules"); testGitClient.submoduleInit(); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPINotIntializedTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPINotInitializedTest.java similarity index 66% rename from src/test/java/org/jenkinsci/plugins/gitclient/GitAPINotIntializedTest.java rename to src/test/java/org/jenkinsci/plugins/gitclient/GitAPINotInitializedTest.java index cbb053f4a5..0184e8c231 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPINotIntializedTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPINotInitializedTest.java @@ -1,8 +1,6 @@ package org.jenkinsci.plugins.gitclient; -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.*; import hudson.EnvVars; import hudson.Util; @@ -11,11 +9,8 @@ import hudson.remoting.VirtualChannel; import hudson.util.StreamTaskListener; import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Random; @@ -23,53 +18,52 @@ import java.util.logging.Logger; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -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.api.extension.RegisterExtension; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; /** * Git API Tests which doesn't need a working initialized git repo. - * Implemented in JUnit 4 + * Implemented in JUnit 5 */ -@RunWith(Parameterized.class) -public class GitAPINotIntializedTest { +@ParameterizedClass(name = "{0}") +@MethodSource("gitObjects") +class GitAPINotInitializedTest { - @Rule - public GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); private int logCount = 0; private static final String LOGGING_STARTED = "Logging started"; private LogHandler handler = null; private TaskListener listener; - private final String gitImplName; - WorkspaceWithRepo workspace; + @Parameter(0) + private String gitImplName; + + private WorkspaceWithRepo workspace; private GitClient testGitClient; private File testGitDir; - private CliGitCommand cliGitCommand; - - public GitAPINotIntializedTest(final String gitImplName) { - this.gitImplName = gitImplName; - } - @Parameterized.Parameters(name = "{0}") - public static Collection gitObjects() { - List arguments = new ArrayList<>(); + static List gitObjects() { + List arguments = new ArrayList<>(); String[] gitImplNames = {"git", "jgit", "jgitapache"}; for (String gitImplName : gitImplNames) { - Object[] item = {gitImplName}; + Arguments item = Arguments.of(gitImplName); arguments.add(item); } return arguments; } - @BeforeClass - public static void loadLocalMirror() throws Exception { + @BeforeAll + static void loadLocalMirror() throws Exception { /* Prime the local mirror cache before other tests run */ /* Allow 2-6 second delay before priming the cache */ /* Allow other tests a better chance to prime the cache */ @@ -84,8 +78,8 @@ public static void loadLocalMirror() throws Exception { Util.deleteRecursive(tempDir); } - @Before - public void setUpRepositories() throws Exception { + @BeforeEach + void setUpRepositories() throws Exception { Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++); handler = new LogHandler(); handler.setLevel(Level.ALL); @@ -99,14 +93,13 @@ public void setUpRepositories() throws Exception { testGitClient = workspace.getGitClient(); testGitDir = workspace.getGitFileDir(); - cliGitCommand = workspace.getCliGitCommand(); } @Test - public void testHasGitRepoWithInvalidGitRepo() throws Exception { + void testHasGitRepoWithInvalidGitRepo() throws Exception { // Create an empty directory named .git - "corrupt" git repo File emptyDotGitDir = workspace.file(".git"); - assertTrue("mkdir .git failed", emptyDotGitDir.mkdir()); + assertTrue(emptyDotGitDir.mkdir(), "mkdir .git failed"); boolean hasGitRepo = testGitClient.hasGitRepo(); // Don't assert condition if the temp directory is inside the dev dir. // CLI git searches up the directory tree seeking a '.git' directory. @@ -115,11 +108,11 @@ public void testHasGitRepoWithInvalidGitRepo() throws Exception { && emptyDotGitDir.getAbsolutePath().contains("tmp")) { return; } - assertFalse("Invalid Git repo reported as valid in " + emptyDotGitDir.getAbsolutePath(), hasGitRepo); + assertFalse(hasGitRepo, "Invalid Git repo reported as valid in " + emptyDotGitDir.getAbsolutePath()); } @Test - public void testSetSubmoduleUrl() throws Exception { + void testSetSubmoduleUrl() throws Exception { workspace.cloneRepo(workspace, workspace.localMirror()); workspace.launchCommand("git", "checkout", "tests/getSubmodules"); testGitClient.submoduleInit(); @@ -138,15 +131,15 @@ public void testSetSubmoduleUrl() throws Exception { @Issue("JENKINS-23299") @Test - public void testGetHeadRev() throws Exception { + void testGetHeadRev() throws Exception { Map heads = testGitClient.getHeadRev(remoteMirrorURL); ObjectId master = testGitClient.getHeadRev(remoteMirrorURL, "refs/heads/master"); - assertEquals("URL is " + remoteMirrorURL + ", heads is " + heads, master, heads.get("refs/heads/master")); + assertEquals(master, heads.get("refs/heads/master"), "URL is " + remoteMirrorURL + ", heads is " + heads); /* Test with a specific tag reference - JENKINS-23299 */ ObjectId knownTag = testGitClient.getHeadRev(remoteMirrorURL, "refs/tags/git-client-1.10.0"); ObjectId expectedTag = ObjectId.fromString("1fb23708d6b639c22383c8073d6e75051b2a63aa"); // commit SHA1 - assertEquals("Wrong SHA1 for git-client-1.10.0 tag", expectedTag, knownTag); + assertEquals(expectedTag, knownTag, "Wrong SHA1 for git-client-1.10.0 tag"); } /** @@ -162,27 +155,27 @@ public void testGetHeadRev() throws Exception { * occur earlier than the expected value. */ @Test - public void testGetHeadRevWildCards() throws Exception { + void testGetHeadRevWildCards() throws Exception { Map heads = testGitClient.getHeadRev(workspace.localMirror()); ObjectId master = testGitClient.getHeadRev(workspace.localMirror(), "refs/heads/master"); - assertEquals("heads is " + heads, heads.get("refs/heads/master"), master); + assertEquals(heads.get("refs/heads/master"), master, "heads is " + heads); ObjectId wildOrigin = testGitClient.getHeadRev(workspace.localMirror(), "*/master"); - assertEquals("heads is " + heads, heads.get("refs/heads/master"), wildOrigin); + assertEquals(heads.get("refs/heads/master"), wildOrigin, "heads is " + heads); ObjectId master1 = testGitClient.getHeadRev( workspace.localMirror(), "not-a-real-origin-but-allowed/m*ster"); // matches master - assertEquals("heads is " + heads, heads.get("refs/heads/master"), master1); + assertEquals(heads.get("refs/heads/master"), master1, "heads is " + heads); ObjectId getSubmodules1 = testGitClient.getHeadRev(workspace.localMirror(), "X/g*[b]m*dul*"); // matches tests/getSubmodules - assertEquals("heads is " + heads, heads.get("refs/heads/tests/getSubmodules"), getSubmodules1); + assertEquals(heads.get("refs/heads/tests/getSubmodules"), getSubmodules1, "heads is " + heads); ObjectId getSubmodules = testGitClient.getHeadRev(workspace.localMirror(), "N/*et*modul*"); - assertEquals("heads is " + heads, heads.get("refs/heads/tests/getSubmodules"), getSubmodules); + assertEquals(heads.get("refs/heads/tests/getSubmodules"), getSubmodules, "heads is " + heads); } /* Opening a git repository in a directory with a symbolic git file instead * of a git directory should function properly. */ @Test - public void testWithRepositoryWorksWithSubmodule() throws Exception { + void testWithRepositoryWorksWithSubmodule() throws Exception { workspace.cloneRepo(workspace, workspace.localMirror()); assertSubmoduleDirs(testGitDir, false, false); @@ -204,59 +197,15 @@ private void assertSubmoduleRepository(File submoduleDir) throws Exception { * functioning repository object */ submoduleClient.withRepository((final Repository repo, VirtualChannel channel) -> { - assertTrue( - repo.getDirectory() + " is not a valid repository", - repo.getObjectDatabase().exists()); + assertTrue(repo.getObjectDatabase().exists(), repo.getDirectory() + " is not a valid repository"); return null; }); } protected GitClient setupGitAPI(File ws) throws Exception { - setCliGitDefaults(); return Git.with(listener, new EnvVars()).in(ws).using(gitImplName).getClient(); } - private static boolean cliGitDefaultsSet = false; - - private void setCliGitDefaults() throws Exception { - if (!cliGitDefaultsSet) { - CliGitCommand gitCmd = new CliGitCommand(null); - } - cliGitDefaultsSet = true; - } - - private void assertSubmoduleContents(File repo) throws IOException { - final File modulesDir = new File(repo, "modules"); - - final File sshkeysDir = new File(modulesDir, "sshkeys"); - final File sshkeysModuleFile = new File(sshkeysDir, "Modulefile"); - assertFileExists(sshkeysModuleFile); - - final File keeperFile = new File(modulesDir, "keeper"); - final String keeperContent = ""; - assertFileExists(keeperFile); - assertFileContents(keeperFile, keeperContent); - - final File ntpDir = new File(modulesDir, "ntp"); - final File ntpContributingFile = new File(ntpDir, "CONTRIBUTING.md"); - final String ntpContributingContent = "Puppet Labs modules on the Puppet Forge are open projects"; - assertFileExists(ntpContributingFile); - assertFileContains(ntpContributingFile, ntpContributingContent); /* Check substring in file */ - } - - private void assertFileContains(File file, String expectedContent) throws IOException { - assertFileExists(file); - final String fileContent = Files.readString(file.toPath(), StandardCharsets.UTF_8); - final String message = file + " does not contain '" + expectedContent + "', contains '" + fileContent + "'"; - assertTrue(message, fileContent.contains(expectedContent)); - } - - private void assertFileContents(File file, String expectedContent) throws IOException { - assertFileExists(file); - final String fileContent = Files.readString(file.toPath(), StandardCharsets.UTF_8); - assertEquals(file + " wrong content", expectedContent, fileContent); - } - private void assertSubmoduleDirs(File repo, boolean dirsShouldExist, boolean filesShouldExist) { final File modulesDir = new File(repo, "modules"); final File ntpDir = new File(modulesDir, "ntp"); @@ -294,16 +243,16 @@ private void assertDirNotFound(File dir) { } private void assertFileNotFound(File file) { - assertFalse(file + " found, peer files: " + listDir(file.getParentFile()), file.exists()); + assertFalse(file.exists(), file + " found, peer files: " + listDir(file.getParentFile())); } private void assertDirExists(File dir) { assertFileExists(dir); - assertTrue(dir + " is not a directory", dir.isDirectory()); + assertTrue(dir.isDirectory(), dir + " is not a directory"); } private void assertFileExists(File file) { - assertTrue(file + " not found, peer files: " + listDir(file.getParentFile()), file.exists()); + assertTrue(file.exists(), file + " not found, peer files: " + listDir(file.getParentFile())); } private String listDir(File dir) { @@ -319,7 +268,7 @@ private String listDir(File dir) { fileList.append(file.getName()); fileList.append(','); } - if (fileList.length() > 0) { + if (!fileList.isEmpty()) { fileList.deleteCharAt(fileList.length() - 1); } return fileList.toString(); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITest.java index 9ac644a6c6..3a8a6b7c45 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITest.java @@ -1,6 +1,5 @@ package org.jenkinsci.plugins.gitclient; -import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.containsString; @@ -8,11 +7,7 @@ import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import hudson.EnvVars; import hudson.FilePath; @@ -44,29 +39,32 @@ import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; import org.eclipse.jgit.util.SystemReader; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +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.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; /** - * Git API tests implemented in JUnit 4. + * Git API tests implemented in JUnit 5. */ -@RunWith(Parameterized.class) -public class GitAPITest { +@ParameterizedClass(name = "{0}") +@MethodSource("gitObjects") +class GitAPITest { - @Rule - public GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); - @Rule - public GitClientSampleRepoRule secondRepo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule secondRepo = new GitClientSampleRepoRule(); - @Rule - public GitClientSampleRepoRule thirdRepo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule thirdRepo = new GitClientSampleRepoRule(); private int logCount = 0; private final Random random = new Random(); @@ -74,7 +72,9 @@ public class GitAPITest { private static final String DEFAULT_MIRROR_BRANCH_NAME = "mast" + "er"; private LogHandler handler = null; private TaskListener listener; - private final String gitImplName; + + @Parameter(0) + private String gitImplName; /** * Tests that need the default branch name can use this variable. @@ -83,34 +83,29 @@ public class GitAPITest { private int checkoutTimeout = -1; - WorkspaceWithRepo workspace; + private WorkspaceWithRepo workspace; private GitClient testGitClient; private File testGitDir; - public GitAPITest(final String gitImplName) { - this.gitImplName = gitImplName; - } - public static EnvVars getConfigNoSystemEnvVars() { EnvVars envVars = new EnvVars(); envVars.put("GIT_CONFIG_NOSYSTEM", "1"); return envVars; } - @Parameterized.Parameters(name = "{0}") - public static Collection gitObjects() { - List arguments = new ArrayList<>(); + static List gitObjects() { + List arguments = new ArrayList<>(); String[] gitImplNames = {"git", "jgit", "jgitapache"}; for (String gitImplName : gitImplNames) { - Object[] item = {gitImplName}; + Arguments item = Arguments.of(gitImplName); arguments.add(item); } return arguments; } - @BeforeClass - public static void loadLocalMirror() throws Exception { + @BeforeAll + static void loadLocalMirror() throws Exception { SystemReader.getInstance().getUserConfig().clear(); /* Prime the local mirror cache before other tests run */ /* Allow 2-6 second delay before priming the cache */ @@ -131,8 +126,8 @@ public static void loadLocalMirror() throws Exception { * Git 2.32.0 honors the configuration variable `init.defaultBranch` and uses it for the name of the initial branch. * This method reads the global configuration and uses it to set the value of `defaultBranchName`. */ - @BeforeClass - public static void computeDefaultBranchName() throws Exception { + @BeforeAll + static void computeDefaultBranchName() throws Exception { File configDir = Files.createTempDirectory("readGitConfig").toFile(); CliGitCommand getDefaultBranchNameCmd = new CliGitCommand(Git.with(TaskListener.NULL, getConfigNoSystemEnvVars()) @@ -146,11 +141,11 @@ public static void computeDefaultBranchName() throws Exception { defaultBranchName = result; } } - assertTrue("Failed to delete temporary readGitConfig directory", configDir.delete()); + assertTrue(configDir.delete(), "Failed to delete temporary readGitConfig directory"); } - @Before - public void setUpRepositories() throws Exception { + @BeforeEach + void setUpRepositories() throws Exception { checkoutTimeout = -1; Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++); @@ -169,11 +164,11 @@ public void setUpRepositories() throws Exception { workspace.initializeWorkspace(); } - @After - public void afterTearDown() { + @AfterEach + void afterTearDown() { try { String messages = StringUtils.join(handler.getMessages(), ";"); - assertTrue("Logging not started: " + messages, handler.containsMessageSubstring(LOGGING_STARTED)); + assertTrue(handler.containsMessageSubstring(LOGGING_STARTED), "Logging not started: " + messages); assertCheckoutTimeout(); } finally { handler.close(); @@ -210,7 +205,7 @@ private void assertSubstringTimeout(final String substring, int expectedTimeout) } private Collection getBranchNames(Collection branches) { - return branches.stream().map(Branch::getName).collect(toList()); + return branches.stream().map(Branch::getName).toList(); } private void assertBranchesExist(Set branches, String... names) { @@ -221,16 +216,16 @@ private void assertBranchesExist(Set branches, String... names) { } @Test - public void testGetRemoteUrl() throws Exception { + void testGetRemoteUrl() throws Exception { workspace.launchCommand("git", "remote", "add", "origin", "https://github.com/jenkinsci/git-client-plugin.git"); workspace.launchCommand("git", "remote", "add", "ndeloof", "git@github.com:ndeloof/git-client-plugin.git"); String remoteUrl = workspace.getGitClient().getRemoteUrl("origin"); assertEquals( - "unexpected remote URL " + remoteUrl, "https://github.com/jenkinsci/git-client-plugin.git", remoteUrl); + "https://github.com/jenkinsci/git-client-plugin.git", remoteUrl, "unexpected remote URL " + remoteUrl); } @Test - public void testEmptyComment() throws Exception { + void testEmptyComment() throws Exception { workspace.commitEmpty("init-empty-comment-to-tag-fails-on-windows"); if (isWindows()) { testGitClient.tag("non-empty-comment", "empty-tag-comment-fails-on-windows"); @@ -240,80 +235,76 @@ public void testEmptyComment() throws Exception { } @Test - public void testCreateBranch() throws Exception { + void testCreateBranch() throws Exception { workspace.commitEmpty("init"); testGitClient.branch("test"); String branches = workspace.launchCommand("git", "branch", "-l"); - assertTrue("default branch not listed", branches.contains(defaultBranchName)); - assertTrue("test branch not listed", branches.contains("test")); + assertTrue(branches.contains(defaultBranchName), "default branch not listed"); + assertTrue(branches.contains("test"), "test branch not listed"); } @Test - public void testDeleteBranch() throws Exception { + void testDeleteBranch() throws Exception { workspace.commitEmpty("init"); testGitClient.branch("test"); testGitClient.deleteBranch("test"); String branches = workspace.launchCommand("git", "branch", "-l"); - assertFalse("deleted test branch still present", branches.contains("test")); + assertFalse(branches.contains("test"), "deleted test branch still present"); if (testGitClient instanceof JGitAPIImpl) { // JGit does not throw an exception testGitClient.deleteBranch("test"); } else { - Exception exception = assertThrows(GitException.class, () -> { - testGitClient.deleteBranch("test"); - }); + Exception exception = assertThrows(GitException.class, () -> testGitClient.deleteBranch("test")); assertThat(exception.getMessage(), is("Could not delete branch test")); } } @Test - public void testDeleteTag() throws Exception { + void testDeleteTag() throws Exception { workspace.commitEmpty("init"); workspace.tag("test"); workspace.tag("another"); testGitClient.deleteTag("test"); String tags = workspace.launchCommand("git", "tag"); - assertFalse("deleted test tag still present", tags.contains("test")); - assertTrue("expected tag not listed", tags.contains("another")); + assertFalse(tags.contains("test"), "deleted test tag still present"); + assertTrue(tags.contains("another"), "expected tag not listed"); if (testGitClient instanceof JGitAPIImpl) { // JGit does not throw an exception testGitClient.deleteTag("test"); } else { - Exception exception = assertThrows(GitException.class, () -> { - testGitClient.deleteTag("test"); - }); + Exception exception = assertThrows(GitException.class, () -> testGitClient.deleteTag("test")); assertThat(exception.getMessage(), is("Could not delete tag test")); } } @Test - public void testListTagsWithFilter() throws Exception { + void testListTagsWithFilter() throws Exception { workspace.commitEmpty("init"); workspace.tag("test"); workspace.tag("another_test"); workspace.tag("yet_another"); Set tags = testGitClient.getTagNames("*test"); - assertTrue("expected tag test not listed", tags.contains("test")); - assertTrue("expected tag another_tag not listed", tags.contains("another_test")); - assertFalse("unexpected tag yet_another listed", tags.contains("yet_another")); + assertTrue(tags.contains("test"), "expected tag test not listed"); + assertTrue(tags.contains("another_test"), "expected tag another_tag not listed"); + assertFalse(tags.contains("yet_another"), "unexpected tag yet_another listed"); } @Test - public void testListTagsWithoutFilter() throws Exception { + void testListTagsWithoutFilter() throws Exception { workspace.commitEmpty("init"); workspace.tag("test"); workspace.tag("another_test"); workspace.tag("yet_another"); Set allTags = testGitClient.getTagNames(null); - assertTrue("tag 'test' not listed", allTags.contains("test")); - assertTrue("tag 'another_test' not listed", allTags.contains("another_test")); - assertTrue("tag 'yet_another' not listed", allTags.contains("yet_another")); + assertTrue(allTags.contains("test"), "tag 'test' not listed"); + assertTrue(allTags.contains("another_test"), "tag 'another_test' not listed"); + assertTrue(allTags.contains("yet_another"), "tag 'yet_another' not listed"); } @Issue("JENKINS-37794") @Test - public void testGetTagNamesSupportsSlashesInTagNames() throws Exception { + void testGetTagNamesSupportsSlashesInTagNames() throws Exception { workspace.commitEmpty("init-getTagNames-supports-slashes"); testGitClient.tag("no-slash", "Tag without a /"); Set tags = testGitClient.getTagNames(null); @@ -339,7 +330,7 @@ public void testGetTagNamesSupportsSlashesInTagNames() throws Exception { } @Test - public void testListBranchesContainingRef() throws Exception { + void testListBranchesContainingRef() throws Exception { workspace.commitEmpty("init"); testGitClient.branch("test"); testGitClient.branch("another"); @@ -349,19 +340,19 @@ public void testListBranchesContainingRef() throws Exception { } @Test - public void testListTagsStarFilter() throws Exception { + void testListTagsStarFilter() throws Exception { workspace.commitEmpty("init"); workspace.tag("test"); workspace.tag("another_test"); workspace.tag("yet_another"); Set allTags = testGitClient.getTagNames("*"); - assertTrue("tag 'test' not listed", allTags.contains("test")); - assertTrue("tag 'another_test' not listed", allTags.contains("another_test")); - assertTrue("tag 'yet_another' not listed", allTags.contains("yet_another")); + assertTrue(allTags.contains("test"), "tag 'test' not listed"); + assertTrue(allTags.contains("another_test"), "tag 'another_test' not listed"); + assertTrue(allTags.contains("yet_another"), "tag 'yet_another' not listed"); } @Test - public void testTagExists() throws Exception { + void testTagExists() throws Exception { workspace.commitEmpty("init"); workspace.tag("test"); assertTrue(testGitClient.tagExists("test")); @@ -369,14 +360,14 @@ public void testTagExists() throws Exception { } @Test - public void testGetTagMessage() throws Exception { + void testGetTagMessage() throws Exception { workspace.commitEmpty("init"); workspace.launchCommand("git", "tag", "test", "-m", "this-is-a-test"); assertEquals("this-is-a-test", testGitClient.getTagMessage("test")); } @Test - public void testGetTagMessageMultiLine() throws Exception { + void testGetTagMessageMultiLine() throws Exception { workspace.commitEmpty("init"); workspace.launchCommand("git", "tag", "test", "-m", "test 123!\n* multi-line tag message\n padded "); @@ -387,52 +378,50 @@ public void testGetTagMessageMultiLine() throws Exception { } @Test - public void testCreateRef() throws Exception { + void testCreateRef() throws Exception { workspace.commitEmpty("init"); testGitClient.ref("refs/testing/testref"); - assertTrue( - "test ref not created", - workspace.launchCommand("git", "show-ref").contains("refs/testing/testref")); + assertTrue(workspace.launchCommand("git", "show-ref").contains("refs/testing/testref"), "test ref not created"); } @Test - public void testDeleteRef() throws Exception { + void testDeleteRef() throws Exception { workspace.commitEmpty("init"); testGitClient.ref("refs/testing/testref"); testGitClient.ref("refs/testing/anotherref"); testGitClient.deleteRef("refs/testing/testref"); String refs = workspace.launchCommand("git", "show-ref"); - assertFalse("deleted test tag still present", refs.contains("refs/testing/testref")); - assertTrue("expected tag not listed", refs.contains("refs/testing/anotherref")); + assertFalse(refs.contains("refs/testing/testref"), "deleted test tag still present"); + assertTrue(refs.contains("refs/testing/anotherref"), "expected tag not listed"); testGitClient.deleteRef("refs/testing/testref"); // Double-deletes do nothing. } @Test - public void testListRefsWithPrefix() throws Exception { + void testListRefsWithPrefix() throws Exception { workspace.commitEmpty("init"); testGitClient.ref("refs/testing/testref"); testGitClient.ref("refs/testing/nested/anotherref"); testGitClient.ref("refs/testing/nested/yetanotherref"); Set refs = testGitClient.getRefNames("refs/testing/nested/"); - assertFalse("ref testref listed", refs.contains("refs/testing/testref")); - assertTrue("ref anotherref not listed", refs.contains("refs/testing/nested/anotherref")); - assertTrue("ref yetanotherref not listed", refs.contains("refs/testing/nested/yetanotherref")); + assertFalse(refs.contains("refs/testing/testref"), "ref testref listed"); + assertTrue(refs.contains("refs/testing/nested/anotherref"), "ref anotherref not listed"); + assertTrue(refs.contains("refs/testing/nested/yetanotherref"), "ref yetanotherref not listed"); } @Test - public void testListRefsWithoutPrefix() throws Exception { + void testListRefsWithoutPrefix() throws Exception { workspace.commitEmpty("init"); testGitClient.ref("refs/testing/testref"); testGitClient.ref("refs/testing/nested/anotherref"); testGitClient.ref("refs/testing/nested/yetanotherref"); Set allRefs = testGitClient.getRefNames(""); - assertTrue("ref testref not listed", allRefs.contains("refs/testing/testref")); - assertTrue("ref anotherref not listed", allRefs.contains("refs/testing/nested/anotherref")); - assertTrue("ref yetanotherref not listed", allRefs.contains("refs/testing/nested/yetanotherref")); + assertTrue(allRefs.contains("refs/testing/testref"), "ref testref not listed"); + assertTrue(allRefs.contains("refs/testing/nested/anotherref"), "ref anotherref not listed"); + assertTrue(allRefs.contains("refs/testing/nested/yetanotherref"), "ref yetanotherref not listed"); } @Test - public void testRefExists() throws Exception { + void testRefExists() throws Exception { workspace.commitEmpty("init"); testGitClient.ref("refs/testing/testref"); assertTrue(testGitClient.refExists("refs/testing/testref")); @@ -441,24 +430,24 @@ public void testRefExists() throws Exception { } @Test - public void testHasGitRepoWithValidGitRepo() throws Exception { - assertTrue("Valid Git repo reported as invalid", testGitClient.hasGitRepo()); + void testHasGitRepoWithValidGitRepo() throws Exception { + assertTrue(testGitClient.hasGitRepo(), "Valid Git repo reported as invalid"); } @Test - public void testCleanWithParameter() throws Exception { + void testCleanWithParameter() throws Exception { workspace.commitEmpty("init"); final String dirName1 = "dir1"; final String fileName1 = dirName1 + File.separator + "fileName1"; final String fileName2 = "fileName2"; - assertTrue("Did not create dir " + dirName1, workspace.file(dirName1).mkdir()); + assertTrue(workspace.file(dirName1).mkdir(), "Did not create dir " + dirName1); workspace.touch(workspace.getGitFileDir(), fileName1, ""); workspace.touch(workspace.getGitFileDir(), fileName2, ""); final String dirName3 = "dir-with-submodule"; File submodule = workspace.file(dirName3); - assertTrue("Did not create dir " + dirName3, submodule.mkdir()); + assertTrue(submodule.mkdir(), "Did not create dir " + dirName3); WorkspaceWithRepo workspace1 = new WorkspaceWithRepo(submodule, gitImplName, TaskListener.NULL); workspace1.initializeWorkspace(); workspace1.commitEmpty("init"); @@ -475,7 +464,7 @@ public void testCleanWithParameter() throws Exception { @Issue({"JENKINS-20410", "JENKINS-27910", "JENKINS-22434"}) @Test - public void testClean() throws Exception { + void testClean() throws Exception { workspace.commitEmpty("init"); /* String starts with a surrogate character, mathematical @@ -511,7 +500,7 @@ public void testClean() throws Exception { final String dirName1 = "\u5c4f\u5e55\u622a\u56fe-dir-not-added"; final String fileName1 = dirName1 + File.separator + "\u5c4f\u5e55\u622a\u56fe-fileName1-not-added.xml"; final String fileName2 = ".test-\u00f8\u00e4\u00fc\u00f6-fileName2-not-added"; - assertTrue("Did not create dir " + dirName1, workspace.file(dirName1).mkdir()); + assertTrue(workspace.file(dirName1).mkdir(), "Did not create dir " + dirName1); workspace.touch(testGitDir, fileName1, ""); workspace.touch(testGitDir, fileName2, ""); workspace.touch(testGitDir, fileName, "new content"); @@ -525,42 +514,41 @@ public void testClean() throws Exception { assertEquals("content " + fileNameSwim, workspace.contentOf(fileNameSwim)); String status = workspace.launchCommand("git", "status"); assertTrue( - "unexpected status " + status, - status.contains("working directory clean") || status.contains("working tree clean")); + status.contains("working directory clean") || status.contains("working tree clean"), + "unexpected status " + status); /* A few poorly placed tests of hudson.FilePath - testing JENKINS-22434 */ FilePath fp = new FilePath(workspace.file(fileName)); - assertTrue(fp + " missing", fp.exists()); + assertTrue(fp.exists(), fp + " missing"); - assertTrue("mkdir " + dirName1 + " failed", workspace.file(dirName1).mkdir()); - assertTrue("dir " + dirName1 + " missing", workspace.file(dirName1).isDirectory()); + assertTrue(workspace.file(dirName1).mkdir(), "mkdir " + dirName1 + " failed"); + assertTrue(workspace.file(dirName1).isDirectory(), "dir " + dirName1 + " missing"); FilePath dir1 = new FilePath(workspace.file(dirName1)); workspace.touch(testGitDir, fileName1, ""); - assertTrue("Did not create file " + fileName1, workspace.file(fileName1).exists()); + assertTrue(workspace.file(fileName1).exists(), "Did not create file " + fileName1); - assertTrue(dir1 + " missing", dir1.exists()); + assertTrue(dir1.exists(), dir1 + " missing"); dir1.deleteRecursive(); /* Fails on Linux JDK 7 with LANG=C, ok with LANG=en_US.UTF-8 */ /* Java reports "Malformed input or input contains unmappable characters" */ - assertFalse( - "Did not delete file " + fileName1, workspace.file(fileName1).exists()); - assertFalse(dir1 + " not deleted", dir1.exists()); + assertFalse(workspace.file(fileName1).exists(), "Did not delete file " + fileName1); + assertFalse(dir1.exists(), dir1 + " not deleted"); workspace.touch(testGitDir, fileName2, ""); FilePath fp2 = new FilePath(workspace.file(fileName2)); - assertTrue(fp2 + " missing", fp2.exists()); + assertTrue(fp2.exists(), fp2 + " missing"); fp2.delete(); - assertFalse(fp2 + " not deleted", fp2.exists()); + assertFalse(fp2.exists(), fp2 + " not deleted"); String dirContents = Arrays.toString((new File(testGitDir.getAbsolutePath())).listFiles()); String finalStatus = workspace.launchCommand("git", "status"); assertTrue( - "unexpected final status " + finalStatus + " dir contents: " + dirContents, - finalStatus.contains("working directory clean") || finalStatus.contains("working tree clean")); + finalStatus.contains("working directory clean") || finalStatus.contains("working tree clean"), + "unexpected final status " + finalStatus + " dir contents: " + dirContents); } @Test - public void testPushTags() throws Exception { + void testPushTags() throws Exception { /* Working Repo with commit */ final String fileName1 = "file1"; workspace.touch(testGitDir, fileName1, fileName1 + " content " + java.util.UUID.randomUUID()); @@ -578,7 +566,7 @@ public void testPushTags() throws Exception { testGitClient.push("origin", defaultBranchName); ObjectId bareCommit1 = bare.getGitClient().getHeadRev(bare.getGitFileDir().getAbsolutePath(), defaultBranchName); - assertEquals("bare != working", commit1, bareCommit1); + assertEquals(commit1, bareCommit1, "bare != working"); assertEquals( commit1, bare.getGitClient() @@ -586,15 +574,15 @@ public void testPushTags() throws Exception { /* Add tag1 to working repo without pushing it to bare repo */ workspace.tag("tag1"); - assertTrue("tag1 wasn't created", testGitClient.tagExists("tag1")); - assertEquals("tag1 points to wrong commit", commit1, testGitClient.revParse("tag1")); + assertTrue(testGitClient.tagExists("tag1"), "tag1 wasn't created"); + assertEquals(commit1, testGitClient.revParse("tag1"), "tag1 points to wrong commit"); testGitClient .push() .ref(defaultBranchName) .to(new URIish(bare.getGitFileDir().getAbsolutePath())) .tags(false) .execute(); - assertFalse("tag1 pushed unexpectedly", bare.launchCommand("git", "tag").contains("tag1")); + assertFalse(bare.launchCommand("git", "tag").contains("tag1"), "tag1 pushed unexpectedly"); /* Push tag1 to bare repo */ testGitClient @@ -603,7 +591,7 @@ public void testPushTags() throws Exception { .to(new URIish(bare.getGitFileDir().getAbsolutePath())) .tags(true) .execute(); - assertTrue("tag1 not pushed", bare.launchCommand("git", "tag").contains("tag1")); + assertTrue(bare.launchCommand("git", "tag").contains("tag1"), "tag1 not pushed"); /* Create a new commit, move tag1 to that commit, attempt push */ workspace.touch(testGitDir, fileName1, fileName1 + " content " + java.util.UUID.randomUUID()); @@ -611,18 +599,16 @@ public void testPushTags() throws Exception { testGitClient.commit("commit2"); ObjectId commit2 = workspace.head(); workspace.tag("tag1", true); /* Tag already exists, move from commit1 to commit2 */ - assertTrue("tag1 wasn't created", testGitClient.tagExists("tag1")); - assertEquals("tag1 points to wrong commit", commit2, testGitClient.revParse("tag1")); + assertTrue(testGitClient.tagExists("tag1"), "tag1 wasn't created"); + assertEquals(commit2, testGitClient.revParse("tag1"), "tag1 points to wrong commit"); if (testGitClient instanceof CliGitAPIImpl) { // Modern CLI git should throw exception pushing a change to existing tag - Exception exception = assertThrows(GitException.class, () -> { - testGitClient - .push() - .ref(defaultBranchName) - .to(new URIish(bare.getGitFileDir().getAbsolutePath())) - .tags(true) - .execute(); - }); + Exception exception = assertThrows(GitException.class, () -> testGitClient + .push() + .ref(defaultBranchName) + .to(new URIish(bare.getGitFileDir().getAbsolutePath())) + .tags(true) + .execute()); assertThat(exception.getMessage(), containsString("already exists")); } else { testGitClient @@ -635,15 +621,13 @@ public void testPushTags() throws Exception { if (testGitClient instanceof CliGitAPIImpl) { /* CliGit throws exception updating existing tag */ - Exception exception = assertThrows(GitException.class, () -> { - testGitClient - .push() - .ref(defaultBranchName) - .to(new URIish(bare.getGitFileDir().getAbsolutePath())) - .tags(true) - .force(false) - .execute(); - }); + Exception exception = assertThrows(GitException.class, () -> testGitClient + .push() + .ref(defaultBranchName) + .to(new URIish(bare.getGitFileDir().getAbsolutePath())) + .tags(true) + .force(false) + .execute()); assertThat(exception.getMessage(), containsString("already exists")); } else { /* JGit does not throw exception updating existing tag - ugh */ @@ -669,13 +653,13 @@ public void testPushTags() throws Exception { * to PushCommand. */ workspace.tag("tag3"); - assertTrue("tag3 wasn't created", testGitClient.tagExists("tag3")); + assertTrue(testGitClient.tagExists("tag3"), "tag3 wasn't created"); testGitClient .push() .ref(defaultBranchName) .to(new URIish(bare.getGitFileDir().getAbsolutePath())) .execute(); - assertFalse("tag3 was pushed", bare.launchCommand("git", "tag").contains("tag3")); + assertFalse(bare.launchCommand("git", "tag").contains("tag3"), "tag3 was pushed"); /* Add another tag to working repo and push tags to the bare repo */ final String fileName2 = "file2"; @@ -683,21 +667,21 @@ public void testPushTags() throws Exception { testGitClient.add(fileName2); testGitClient.commit("commit2"); workspace.tag("tag2"); - assertTrue("tag2 wasn't created", testGitClient.tagExists("tag2")); + assertTrue(testGitClient.tagExists("tag2"), "tag2 wasn't created"); testGitClient .push() .ref(defaultBranchName) .to(new URIish(bare.getGitFileDir().getAbsolutePath())) .tags(true) .execute(); - assertTrue("tag1 wasn't pushed", bare.launchCommand("git", "tag").contains("tag1")); - assertTrue("tag2 wasn't pushed", bare.launchCommand("git", "tag").contains("tag2")); - assertTrue("tag3 wasn't pushed", bare.launchCommand("git", "tag").contains("tag3")); + assertTrue(bare.launchCommand("git", "tag").contains("tag1"), "tag1 wasn't pushed"); + assertTrue(bare.launchCommand("git", "tag").contains("tag2"), "tag2 wasn't pushed"); + assertTrue(bare.launchCommand("git", "tag").contains("tag3"), "tag3 wasn't pushed"); } @Issue("JENKINS-34309") @Test - public void testListBranches() throws Exception { + void testListBranches() throws Exception { Set branches = testGitClient.getBranches(); assertEquals(0, branches.size()); // empty repo should have 0 branches workspace.commitEmpty("init"); @@ -721,32 +705,32 @@ public void testListBranches() throws Exception { assertEquals(3, branches.size()); String output = workspace.launchCommand("git", "branch", "-v", "--no-abbrev"); assertTrue( - "git branch -v --no-abbrev missing test commit msg: '" + output + "'", - output.contains(testBranchCommitMessage)); + output.contains(testBranchCommitMessage), + "git branch -v --no-abbrev missing test commit msg: '" + output + "'"); assertTrue( - "git branch -v --no-abbrev missing another commit msg: '" + output + "'", - output.contains(anotherBranchCommitMessage)); + output.contains(anotherBranchCommitMessage), + "git branch -v --no-abbrev missing another commit msg: '" + output + "'"); if (workspace.cgit().isAtLeastVersion(2, 13, 0, 0) && !workspace.cgit().isAtLeastVersion(2, 30, 0, 0)) { - assertTrue("git branch -v --no-abbrev missing Ctrl-M: '" + output + "'", output.contains("\r")); + assertTrue(output.contains("\r"), "git branch -v --no-abbrev missing Ctrl-M: '" + output + "'"); assertTrue( - "git branch -v --no-abbrev missing test commit msg Ctrl-M: '" + output + "'", - output.contains(testBranchCommitMessage + "\r")); + output.contains(testBranchCommitMessage + "\r"), + "git branch -v --no-abbrev missing test commit msg Ctrl-M: '" + output + "'"); assertTrue( - "git branch -v --no-abbrev missing another commit msg Ctrl-M: '" + output + "'", - output.contains(anotherBranchCommitMessage + "\r")); + output.contains(anotherBranchCommitMessage + "\r"), + "git branch -v --no-abbrev missing another commit msg Ctrl-M: '" + output + "'"); } else { - assertFalse("git branch -v --no-abbrev contains Ctrl-M: '" + output + "'", output.contains("\r")); + assertFalse(output.contains("\r"), "git branch -v --no-abbrev contains Ctrl-M: '" + output + "'"); assertFalse( - "git branch -v --no-abbrev contains test commit msg Ctrl-M: '" + output + "'", - output.contains(testBranchCommitMessage + "\r")); + output.contains(testBranchCommitMessage + "\r"), + "git branch -v --no-abbrev contains test commit msg Ctrl-M: '" + output + "'"); assertFalse( - "git branch -v --no-abbrev contains another commit msg Ctrl-M: '" + output + "'", - output.contains(anotherBranchCommitMessage + "\r")); + output.contains(anotherBranchCommitMessage + "\r"), + "git branch -v --no-abbrev contains another commit msg Ctrl-M: '" + output + "'"); } } @Test - public void testListRemoteBranches() throws Exception { + void testListRemoteBranches() throws Exception { WorkspaceWithRepo remote = new WorkspaceWithRepo(secondRepo.getRoot(), gitImplName, TaskListener.NULL); remote.initializeWorkspace(); remote.commitEmpty("init"); @@ -775,13 +759,13 @@ public void testListRemoteBranches() throws Exception { branchCount = 4; } assertEquals( - "Wrong branch count, found " + branches.size() + " branches: " + branches, branchCount, - branches.size()); + branches.size(), + "Wrong branch count, found " + branches.size() + " branches: " + branches); } @Test - public void testRemoteListTagsWithFilter() throws Exception { + void testRemoteListTagsWithFilter() throws Exception { WorkspaceWithRepo remote = new WorkspaceWithRepo(secondRepo.getRoot(), gitImplName, TaskListener.NULL); remote.initializeWorkspace(); remote.commitEmpty("init"); @@ -794,13 +778,13 @@ public void testRemoteListTagsWithFilter() throws Exception { workspace.launchCommand("git", "fetch", "origin"); Set local_tags = testGitClient.getTagNames("*test"); Set tags = testGitClient.getRemoteTagNames("*test"); - assertTrue("expected tag test not listed", tags.contains("test")); - assertTrue("expected tag another_test not listed", tags.contains("another_test")); - assertFalse("unexpected yet_another tag listed", tags.contains("yet_another")); + assertTrue(tags.contains("test"), "expected tag test not listed"); + assertTrue(tags.contains("another_test"), "expected tag another_test not listed"); + assertFalse(tags.contains("yet_another"), "unexpected yet_another tag listed"); } @Test - public void testRemoteListTagsWithoutFilter() throws Exception { + void testRemoteListTagsWithoutFilter() throws Exception { WorkspaceWithRepo remote = new WorkspaceWithRepo(secondRepo.getRoot(), gitImplName, TaskListener.NULL); remote.initializeWorkspace(); remote.commitEmpty("init"); @@ -812,14 +796,14 @@ public void testRemoteListTagsWithoutFilter() throws Exception { "git", "remote", "add", "origin", remote.getGitFileDir().getAbsolutePath()); workspace.launchCommand("git", "fetch", "origin"); Set allTags = workspace.getGitClient().getRemoteTagNames(null); - assertTrue("tag 'test' not listed", allTags.contains("test")); - assertTrue("tag 'another_test' not listed", allTags.contains("another_test")); - assertTrue("tag 'yet_another' not listed", allTags.contains("yet_another")); + assertTrue(allTags.contains("test"), "tag 'test' not listed"); + assertTrue(allTags.contains("another_test"), "tag 'another_test' not listed"); + assertTrue(allTags.contains("yet_another"), "tag 'yet_another' not listed"); } @Issue("JENKINS-23299") @Test - public void testCreateTag() throws Exception { + void testCreateTag() throws Exception { final String gitDir = testGitDir.getAbsolutePath() + File.separator + ".git"; workspace.commitEmpty("init"); ObjectId commitId = testGitClient.revParse("HEAD"); @@ -840,11 +824,11 @@ public void testCreateTag() throws Exception { final String shortTagRef = "test"; ObjectId tagHeadIdByShortRef = testGitClient.getHeadRev(gitDir, shortTagRef); if (testGitClient instanceof JGitAPIImpl) { - assertEquals("annotated tag does not match commit SHA1", commitId, tagHeadIdByShortRef); + assertEquals(commitId, tagHeadIdByShortRef, "annotated tag does not match commit SHA1"); } else { - assertNull("annotated tag unexpectedly not null", tagHeadIdByShortRef); + assertNull(tagHeadIdByShortRef, "annotated tag unexpectedly not null"); } - assertEquals("annotated tag does not match commit SHA1", commitId, testGitClient.revParse(shortTagRef)); + assertEquals(commitId, testGitClient.revParse(shortTagRef), "annotated tag does not match commit SHA1"); /* * Spec: "refs/tags/test" (more specific tag syntax) @@ -852,23 +836,23 @@ public void testCreateTag() throws Exception { */ final String longTagRef = "refs/tags/test"; assertEquals( - "annotated tag does not match commit SHA1", commitId, testGitClient.getHeadRev(gitDir, longTagRef)); - assertEquals("annotated tag does not match commit SHA1", commitId, testGitClient.revParse(longTagRef)); + commitId, testGitClient.getHeadRev(gitDir, longTagRef), "annotated tag does not match commit SHA1"); + assertEquals(commitId, testGitClient.revParse(longTagRef), "annotated tag does not match commit SHA1"); final String tagNames = workspace.launchCommand("git", "tag", "-l").trim(); - assertEquals("tag not created", "test", tagNames); + assertEquals("test", tagNames, "tag not created"); final String tagNamesWithMessages = workspace.launchCommand("git", "tag", "-l", "-n1"); assertTrue( - "unexpected tag message : " + tagNamesWithMessages, - tagNamesWithMessages.contains("this is an annotated tag")); + tagNamesWithMessages.contains("this is an annotated tag"), + "unexpected tag message : " + tagNamesWithMessages); ObjectId invalidTagId = testGitClient.getHeadRev(gitDir, "not-a-valid-tag"); - assertNull("did not expect reference for invalid tag but got : " + invalidTagId, invalidTagId); + assertNull(invalidTagId, "did not expect reference for invalid tag but got : " + invalidTagId); } @Test - public void testRevparseSHA1HEADorTag() throws Exception { + void testRevparseSHA1HEADorTag() throws Exception { workspace.commitEmpty("init"); workspace.touch(testGitDir, "file1", ""); testGitClient.add("file1"); @@ -881,14 +865,14 @@ public void testRevparseSHA1HEADorTag() throws Exception { } @Test - public void testRevparseThrowsExpectedException() throws Exception { + void testRevparseThrowsExpectedException() throws Exception { workspace.commitEmpty("init"); final GitException ex = assertThrows(GitException.class, () -> testGitClient.revParse("unknown-to-rev-parse")); assertThat(ex.getMessage(), containsString("unknown-to-rev-parse")); } @Test - public void testPush() throws Exception { + void testPush() throws Exception { workspace.commitEmpty("init"); workspace.touch(testGitDir, "file1", ""); workspace.tag("file1"); @@ -908,7 +892,7 @@ public void testPush() throws Exception { } @Test - public void testNotesAddFirstNote() throws Exception { + void testNotesAddFirstNote() throws Exception { workspace.touch(testGitDir, "file1", ""); testGitClient.add("file1"); workspace.commitEmpty("init"); @@ -923,7 +907,7 @@ public void testNotesAddFirstNote() throws Exception { } @Test - public void testNotesAppendFirstNote() throws Exception { + void testNotesAppendFirstNote() throws Exception { workspace.initializeWorkspace(); workspace.touch(testGitDir, "file1", ""); testGitClient.add("file1"); @@ -939,7 +923,7 @@ public void testNotesAppendFirstNote() throws Exception { } @Test - public void testPrune() throws Exception { + void testPrune() throws Exception { // pretend that 'teamWorkspace' is a team repository and workspace1 and workspace2 are team members WorkspaceWithRepo teamWorkspace = new WorkspaceWithRepo(secondRepo.getRoot(), gitImplName, TaskListener.NULL); teamWorkspace.initBareRepo(teamWorkspace.getGitClient(), true); @@ -973,7 +957,7 @@ public void testPrune() throws Exception { } @Test - public void testRevListAll() throws Exception { + void testRevListAll() throws Exception { workspace.launchCommand("git", "pull", workspace.localMirror()); final StringBuilder out = new StringBuilder(); @@ -985,7 +969,7 @@ public void testRevListAll() throws Exception { } @Test - public void testRevList_() throws Exception { + void testRevList_() throws Exception { List oidList = new ArrayList<>(); workspace.launchCommand("git", "pull", workspace.localMirror()); @@ -1003,7 +987,7 @@ public void testRevList_() throws Exception { } @Test - public void testRevListFirstParent() throws Exception { + void testRevListFirstParent() throws Exception { workspace.launchCommand("git", "pull", workspace.localMirror()); for (Branch b : testGitClient.getRemoteBranches()) { @@ -1026,7 +1010,7 @@ public void testRevListFirstParent() throws Exception { } @Test - public void testRevList() throws Exception { + void testRevList() throws Exception { workspace.launchCommand("git", "pull", workspace.localMirror()); for (Branch b : testGitClient.getRemoteBranches()) { @@ -1040,7 +1024,7 @@ public void testRevList() throws Exception { } @Test - public void testMergeStrategy() throws Exception { + void testMergeStrategy() throws Exception { workspace.commitEmpty("init"); testGitClient.branch("branch1"); testGitClient.checkout().ref("branch1").execute(); @@ -1060,11 +1044,11 @@ public void testMergeStrategy() throws Exception { .setRevisionToMerge(testGitClient.getHeadRev(testGitDir.getAbsolutePath(), "branch1")) .execute(); assertEquals( - "merge didn't selected OURS content", "content2", Files.readString(f.toPath(), StandardCharsets.UTF_8)); + "content2", Files.readString(f.toPath(), StandardCharsets.UTF_8), "merge didn't selected OURS content"); } @Test - public void testMergeStrategyCorrectFail() throws Exception { + void testMergeStrategyCorrectFail() throws Exception { workspace.commitEmpty("init"); testGitClient.branch("branch1"); testGitClient.checkout().ref("branch1").execute(); @@ -1087,7 +1071,7 @@ public void testMergeStrategyCorrectFail() throws Exception { @Issue("JENKINS-12402") @Test - public void testMergeFastForwardModeFF() throws Exception { + void testMergeFastForwardModeFF() throws Exception { workspace.commitEmpty("init"); testGitClient.branch("branch1"); testGitClient.checkout().ref("branch1").execute(); @@ -1113,7 +1097,7 @@ public void testMergeFastForwardModeFF() throws Exception { .setRevisionToMerge(testGitClient.getHeadRev(testGitDir.getAbsolutePath(), "branch1")) .execute(); assertEquals( - "Fast-forward merge failed. default branch and branch1 should be the same.", workspace.head(), branch1); + workspace.head(), branch1, "Fast-forward merge failed. default branch and branch1 should be the same."); // The second merge calls for fast-forward (FF), but a merge commit will result // This tests that calling for FF gracefully falls back to a commit merge @@ -1126,18 +1110,18 @@ public void testMergeFastForwardModeFF() throws Exception { // The merge commit (head) should have branch2 and branch1 as parents List revList = testGitClient.revList("HEAD^1"); assertEquals( - "Merge commit failed. branch1 should be a parent of HEAD but it isn't.", revList.get(0).name(), - branch1.name()); + branch1.name(), + "Merge commit failed. branch1 should be a parent of HEAD but it isn't."); revList = testGitClient.revList("HEAD^2"); assertEquals( - "Merge commit failed. branch2 should be a parent of HEAD but it isn't.", revList.get(0).name(), - branch2.name()); + branch2.name(), + "Merge commit failed. branch2 should be a parent of HEAD but it isn't."); } @Test - public void testMergeFastForwardModeFFOnly() throws Exception { + void testMergeFastForwardModeFFOnly() throws Exception { workspace.commitEmpty("init"); testGitClient.branch("branch1"); testGitClient.checkout().ref("branch1").execute(); @@ -1163,27 +1147,25 @@ public void testMergeFastForwardModeFFOnly() throws Exception { .setRevisionToMerge(testGitClient.getHeadRev(testGitDir.getAbsolutePath(), "branch1")) .execute(); assertEquals( - "Fast-forward merge failed. Default branch and branch1 should be the same but aren't.", workspace.head(), - branch1); + branch1, + "Fast-forward merge failed. Default branch and branch1 should be the same but aren't."); // The second merge calls for fast-forward only (FF_ONLY), but a merge commit is required, hence it is expected // to fail - assertThrows(GitException.class, () -> { - testGitClient - .merge() - .setGitPluginFastForwardMode(MergeCommand.GitPluginFastForwardMode.FF_ONLY) - .setRevisionToMerge(testGitClient.getHeadRev(testGitDir.getAbsolutePath(), "branch2")) - .execute(); - }); + assertThrows(GitException.class, () -> testGitClient + .merge() + .setGitPluginFastForwardMode(MergeCommand.GitPluginFastForwardMode.FF_ONLY) + .setRevisionToMerge(testGitClient.getHeadRev(testGitDir.getAbsolutePath(), "branch2")) + .execute()); assertEquals( - "Fast-forward merge abort failed. Default branch and branch1 should still be the same as the merge was aborted.", workspace.head(), - branch1); + branch1, + "Fast-forward merge abort failed. Default branch and branch1 should still be the same as the merge was aborted."); } @Test - public void testMergeFastForwardModeNoFF() throws Exception { + void testMergeFastForwardModeNoFF() throws Exception { workspace.commitEmpty("init"); final ObjectId base = workspace.head(); testGitClient.branch("branch1"); @@ -1213,14 +1195,14 @@ public void testMergeFastForwardModeNoFF() throws Exception { // The first merge will have base and branch1 as parents List revList = testGitClient.revList("HEAD^1"); assertEquals( - "Merge commit failed. base should be a parent of HEAD but it isn't.", revList.get(0).name(), - base.name()); + base.name(), + "Merge commit failed. base should be a parent of HEAD but it isn't."); revList = testGitClient.revList("HEAD^2"); assertEquals( - "Merge commit failed. branch1 should be a parent of HEAD but it isn't.", revList.get(0).name(), - branch1.name()); + branch1.name(), + "Merge commit failed. branch1 should be a parent of HEAD but it isn't."); final ObjectId base2 = workspace.head(); @@ -1234,18 +1216,18 @@ public void testMergeFastForwardModeNoFF() throws Exception { // The second merge will have base2 and branch2 as parents revList = testGitClient.revList("HEAD^1"); assertEquals( - "Merge commit failed. base2 should be a parent of HEAD but it isn't.", revList.get(0).name(), - base2.name()); + base2.name(), + "Merge commit failed. base2 should be a parent of HEAD but it isn't."); revList = testGitClient.revList("HEAD^2"); assertEquals( - "Merge commit failed. branch2 should be a parent of HEAD but it isn't.", revList.get(0).name(), - branch2.name()); + branch2.name(), + "Merge commit failed. branch2 should be a parent of HEAD but it isn't."); } @Test - public void testMergeSquash() throws Exception { + void testMergeSquash() throws Exception { workspace.commitEmpty("init"); // First commit to branch1 @@ -1275,11 +1257,11 @@ public void testMergeSquash() throws Exception { final int commitCountAfter = testGitClient.revList("HEAD").size(); assertEquals( - "Squash merge failed. Should have merged only one commit.", 1, commitCountAfter - commitCountBefore); + 1, commitCountAfter - commitCountBefore, "Squash merge failed. Should have merged only one commit."); } @Test - public void testMergeNoSquash() throws Exception { + void testMergeNoSquash() throws Exception { workspace.commitEmpty("init"); // First commit to branch1 @@ -1307,11 +1289,11 @@ public void testMergeNoSquash() throws Exception { final int commitCountAfter = testGitClient.revList("HEAD").size(); assertEquals( - "Squashless merge failed. Should have merged two commits.", 2, commitCountAfter - commitCountBefore); + 2, commitCountAfter - commitCountBefore, "Squashless merge failed. Should have merged two commits."); } @Test - public void testMergeNoCommit() throws Exception { + void testMergeNoCommit() throws Exception { workspace.commitEmpty("init"); // Create branch1 and commit a file @@ -1334,11 +1316,11 @@ public void testMergeNoCommit() throws Exception { final int commitCountAfter = testGitClient.revList("HEAD").size(); assertEquals( - "No Commit merge failed. Shouldn't have committed any changes.", commitCountBefore, commitCountAfter); + commitCountBefore, commitCountAfter, "No Commit merge failed. Shouldn't have committed any changes."); } @Test - public void testMergeCommit() throws Exception { + void testMergeCommit() throws Exception { workspace.commitEmpty("init"); // Create branch1 and commit a file @@ -1361,11 +1343,11 @@ public void testMergeCommit() throws Exception { .execute(); final int commitCountAfter = testGitClient.revList("HEAD").size(); - assertEquals("Commit merge failed. Should have committed the merge.", 2, commitCountAfter - commitCountBefore); + assertEquals(2, commitCountAfter - commitCountBefore, "Commit merge failed. Should have committed the merge."); } @Test - public void testMergeWithMessage() throws Exception { + void testMergeWithMessage() throws Exception { workspace.commitEmpty("init"); // Create branch1 and commit a file @@ -1399,11 +1381,11 @@ public void testMergeWithMessage() throws Exception { resultMessage = content.get(7).trim(); } - assertEquals("Custom message merge failed. Should have set custom merge message.", mergeMessage, resultMessage); + assertEquals(mergeMessage, resultMessage, "Custom message merge failed. Should have set custom merge message."); } @Test - public void testRebasePassesWithoutConflict() throws Exception { + void testRebasePassesWithoutConflict() throws Exception { workspace.commitEmpty("init"); // First commit to default branch @@ -1432,16 +1414,16 @@ public void testRebasePassesWithoutConflict() throws Exception { "Should've rebased feature1 onto default branch", testGitClient.revList("feature1").contains(testGitClient.revParse(defaultBranchName))); assertEquals( - "HEAD should be on the rebased branch", testGitClient.revParse("HEAD").name(), - testGitClient.revParse("feature1").name()); + testGitClient.revParse("feature1").name(), + "HEAD should be on the rebased branch"); assertThat( "Rebased file should be present in the worktree", testGitClient.getWorkTree().child("feature_file").exists()); } @Test - public void testRebaseFailsWithConflict() throws Exception { + void testRebaseFailsWithConflict() throws Exception { workspace.commitEmpty("init"); // First commit to default branch @@ -1464,28 +1446,28 @@ public void testRebaseFailsWithConflict() throws Exception { // Rebase feature commit onto default branch testGitClient.checkout().ref("feature1").execute(); - Exception exception = assertThrows(GitException.class, () -> { - testGitClient.rebase().setUpstream(defaultBranchName).execute(); - }); + Exception exception = assertThrows( + GitException.class, + () -> testGitClient.rebase().setUpstream(defaultBranchName).execute()); assertThat( exception.getMessage(), anyOf( containsString("Failed to rebase " + defaultBranchName), containsString("Could not rebase " + defaultBranchName))); assertEquals( - "HEAD not reset to the feature branch.", testGitClient.revParse("HEAD").name(), - testGitClient.revParse("feature1").name()); + testGitClient.revParse("feature1").name(), + "HEAD not reset to the feature branch."); Status status = new org.eclipse.jgit.api.Git(new FileRepository(new File(testGitDir, ".git"))) .status() .call(); - assertTrue("Workspace is not clean", status.isClean()); - assertFalse("Workspace has uncommitted changes", status.hasUncommittedChanges()); - assertTrue("Workspace has conflicting changes", status.getConflicting().isEmpty()); - assertTrue("Workspace has missing changes", status.getMissing().isEmpty()); - assertTrue("Workspace has modified files", status.getModified().isEmpty()); - assertTrue("Workspace has removed files", status.getRemoved().isEmpty()); - assertTrue("Workspace has untracked files", status.getUntracked().isEmpty()); + assertTrue(status.isClean(), "Workspace is not clean"); + assertFalse(status.hasUncommittedChanges(), "Workspace has uncommitted changes"); + assertTrue(status.getConflicting().isEmpty(), "Workspace has conflicting changes"); + assertTrue(status.getMissing().isEmpty(), "Workspace has missing changes"); + assertTrue(status.getModified().isEmpty(), "Workspace has modified files"); + assertTrue(status.getRemoved().isEmpty(), "Workspace has removed files"); + assertTrue(status.getUntracked().isEmpty(), "Workspace has untracked files"); } /** @@ -1493,7 +1475,7 @@ public void testRebaseFailsWithConflict() throws Exception { */ @Issue("JENKINS-11177") @Test - public void testJenkins11177() throws Exception { + void testJenkins11177() throws Exception { workspace.commitEmpty("init"); final ObjectId base = workspace.head(); final ObjectId defaultBranchObjectId = testGitClient.revParse(defaultBranchName); @@ -1502,13 +1484,13 @@ public void testJenkins11177() throws Exception { /* Make reference to default branch ambiguous, verify it is reported ambiguous by rev-parse */ workspace.tag(defaultBranchName); final String revParse = workspace.launchCommand("git", "rev-parse", defaultBranchName); - assertTrue("'" + revParse + "' does not contain 'ambiguous'", revParse.contains("ambiguous")); + assertTrue(revParse.contains("ambiguous"), "'" + revParse + "' does not contain 'ambiguous'"); final ObjectId ambiguousTag = testGitClient.revParse("refs/tags/" + defaultBranchName); - assertEquals("ambiguousTag != head", workspace.head(), ambiguousTag); + assertEquals(workspace.head(), ambiguousTag, "ambiguousTag != head"); /* Get reference to ambiguous branch name */ final ObjectId ambiguous = testGitClient.revParse(defaultBranchName); - assertEquals("ambiguous != default branch", ambiguous.toString(), defaultBranchObjectId.toString()); + assertEquals(ambiguous.toString(), defaultBranchObjectId.toString(), "ambiguous != default branch"); /* Exploring JENKINS-20991 ambiguous revision breaks checkout */ workspace.touch(testGitDir, "file-default-branch", "content-default-branch"); @@ -1535,14 +1517,14 @@ public void testJenkins11177() throws Exception { + ambiguousTag.name() + ", branch1=" + branch1.name(); if (testGitClient instanceof CliGitAPIImpl) { - assertEquals("head != default branch" + messageDetails, defaultBranchTip, workspace.head()); + assertEquals(defaultBranchTip, workspace.head(), "head != default branch" + messageDetails); } else { - assertEquals("head != ambiguous tag" + messageDetails, ambiguousTag, workspace.head()); + assertEquals(ambiguousTag, workspace.head(), "head != ambiguous tag" + messageDetails); } } @Test - public void testCloneNoCheckout() throws Exception { + void testCloneNoCheckout() throws Exception { // Create a repo for cloning purpose WorkspaceWithRepo repoToClone = new WorkspaceWithRepo(secondRepo.getRoot(), gitImplName, TaskListener.NULL); repoToClone.initializeWorkspace(); @@ -1563,7 +1545,7 @@ public void testCloneNoCheckout() throws Exception { @Issue("JENKINS-25444") @Test - public void testFetchDeleteCleans() throws Exception { + void testFetchDeleteCleans() throws Exception { workspace.touch(testGitDir, "file1", "old"); testGitClient.add("file1"); testGitClient.commit("commit1"); @@ -1581,37 +1563,37 @@ public void testFetchDeleteCleans() throws Exception { .status() .call(); - assertTrue("Workspace must be clean", status.isClean()); + assertTrue(status.isClean(), "Workspace must be clean"); } @Test - public void testRevListTag() throws Exception { + void testRevListTag() throws Exception { workspace.commitEmpty("c1"); FileRepository repo = new FileRepository(new File(testGitDir, ".git")); Ref commitRefC1 = repo.exactRef("HEAD"); workspace.tag("t1"); Ref tagRefT1 = repo.findRef("t1"); Ref head = repo.exactRef("HEAD"); - assertEquals("head != t1", head.getObjectId(), tagRefT1.getObjectId()); + assertEquals(head.getObjectId(), tagRefT1.getObjectId(), "head != t1"); workspace.commitEmpty("c2"); Ref commitRef2 = repo.exactRef("HEAD"); List revList = testGitClient.revList("t1"); - assertTrue("c1 not in revList", revList.contains(commitRefC1.getObjectId())); - assertEquals("wring list size: " + revList, 1, revList.size()); + assertTrue(revList.contains(commitRefC1.getObjectId()), "c1 not in revList"); + assertEquals(1, revList.size(), "wring list size: " + revList); } @Test - public void testRevListLocalBranch() throws Exception { + void testRevListLocalBranch() throws Exception { workspace.commitEmpty("c1"); workspace.tag("t1"); workspace.commitEmpty("c2"); List revList = testGitClient.revList(defaultBranchName); - assertEquals("Wrong list size: " + revList, 2, revList.size()); + assertEquals(2, revList.size(), "Wrong list size: " + revList); } @Issue("JENKINS-20153") @Test - public void testCheckOutBranchNull() throws Exception { + void testCheckOutBranchNull() throws Exception { workspace.commitEmpty("c1"); String sha1 = testGitClient.revParse("HEAD").name(); workspace.commitEmpty("c2"); @@ -1626,7 +1608,7 @@ public void testCheckOutBranchNull() throws Exception { @Issue("JENKINS-18988") @Test - public void testLocalCheckoutConflict() throws Exception { + void testLocalCheckoutConflict() throws Exception { workspace.touch(testGitDir, "foo", "old"); testGitClient.add("foo"); testGitClient.commit("c1"); @@ -1647,7 +1629,7 @@ public void testLocalCheckoutConflict() throws Exception { } @Test - public void testNoSubmodules() throws Exception { + void testNoSubmodules() throws Exception { workspace.touch(testGitDir, "committed-file", "committed-file content " + java.util.UUID.randomUUID()); testGitClient.add("committed-file"); testGitClient.commit("commit1"); @@ -1657,13 +1639,11 @@ public void testNoSubmodules() throws Exception { igit.submoduleUpdate().recursive(false).execute(); igit.submoduleUpdate().recursive(true).execute(); igit.submoduleSync(); - assertTrue( - "committed-file missing at commit1", - workspace.file("committed-file").exists()); + assertTrue(workspace.file("committed-file").exists(), "committed-file missing at commit1"); } @Test - public void testHasSubmodules() throws Exception { + void testHasSubmodules() throws Exception { workspace.launchCommand("git", "fetch", workspace.localMirror(), "tests/getSubmodules:t"); testGitClient.checkout().ref("t").execute(); assertTrue(testGitClient.hasGitModules()); @@ -1687,7 +1667,7 @@ public void testHasSubmodules() throws Exception { * releases resources. */ @Test - public void testChangeLogAbort() throws Exception { + void testChangeLogAbort() throws Exception { final String logMessage = "changelog-abort-test-commit"; workspace.touch( testGitDir, "file-changelog-abort", "changelog abort file contents " + java.util.UUID.randomUUID()); @@ -1700,14 +1680,14 @@ public void testChangeLogAbort() throws Exception { /* Abort the changelog, confirm no content was written */ changelogCommand.abort(); - assertEquals("aborted changelog wrote data", "", writer.toString()); + assertEquals("", writer.toString(), "aborted changelog wrote data"); /* Execute the changelog, confirm expected content was written */ changelogCommand = testGitClient.changelog(); changelogCommand.to(writer); changelogCommand.execute(); - assertTrue("No log message in " + writer, writer.toString().contains(logMessage)); - assertTrue("No SHA1 in " + writer, writer.toString().contains(sha1)); + assertTrue(writer.toString().contains(logMessage), "No log message in " + writer); + assertTrue(writer.toString().contains(sha1), "No SHA1 in " + writer); } @Test diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITestUpdate.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITestUpdate.java index 006f47d50d..a131b9eceb 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITestUpdate.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITestUpdate.java @@ -9,12 +9,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.jenkinsci.plugins.gitclient.GitAPITest.getConfigNoSystemEnvVars; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; @@ -38,7 +33,6 @@ import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; -import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.io.FileUtils; @@ -49,14 +43,14 @@ import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; -import org.junit.After; -import org.junit.Before; -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.TemporaryDirectoryAllocator; import org.objenesis.ObjenesisStd; -public abstract class GitAPITestUpdate { +abstract class GitAPITestUpdate { private final TemporaryDirectoryAllocator temporaryDirectoryAllocator = new TemporaryDirectoryAllocator(); @@ -78,7 +72,7 @@ public abstract class GitAPITestUpdate { protected int submoduleUpdateTimeout = -1; protected final Random random = new Random(); - protected hudson.EnvVars env = getConfigNoSystemEnvVars(); + protected final hudson.EnvVars env = getConfigNoSystemEnvVars(); private static boolean firstRun = true; @@ -123,7 +117,7 @@ class WorkingArea { final File repo; final GitClient git; - boolean bare = false; + final boolean bare = false; WorkingArea() throws Exception { this(temporaryDirectoryAllocator.allocate()); @@ -135,8 +129,7 @@ class WorkingArea { setupProxy(git); } - private void setupProxy(GitClient gitClient) - throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { + private void setupProxy(GitClient gitClient) throws Exception { final String proxyHost = getSystemProperty("proxyHost", "http.proxyHost", "https.proxyHost"); final String proxyPort = getSystemProperty("proxyPort", "http.proxyPort", "https.proxyPort"); final String proxyUser = getSystemProperty("proxyUser", "http.proxyUser", "https.proxyUser"); @@ -157,8 +150,7 @@ private void setupProxy(GitClient gitClient) gitClient.setProxy(proxyConfig); } - private void setField(Class clazz, String fieldName, Object object, Object value) - throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { + private void setField(Class clazz, String fieldName, Object object, Object value) throws Exception { Field declaredField = clazz.getDeclaredField(fieldName); declaredField.setAccessible(true); declaredField.set(object, value); @@ -174,11 +166,11 @@ private String getSystemProperty(String... keyVariants) { return null; } - String launchCommand(String... args) throws IOException, InterruptedException { + String launchCommand(String... args) throws Exception { return launchCommand(false, args); } - String launchCommand(boolean ignoreError, String... args) throws IOException, InterruptedException { + String launchCommand(boolean ignoreError, String... args) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); int st = new Launcher.LocalLauncher(listener) .launch() @@ -192,7 +184,7 @@ String launchCommand(boolean ignoreError, String... args) throws IOException, In if (s == null || s.isEmpty()) { s = StringUtils.join(args, ' '); } - assertEquals(s, 0, st); + assertEquals(0, st, s); /* Reports full output of failing commands */ } return s; @@ -202,7 +194,7 @@ String repoPath() { return repo.getAbsolutePath(); } - GitAPITestUpdate.WorkingArea init() throws GitException, IOException, InterruptedException { + GitAPITestUpdate.WorkingArea init() throws Exception { git.init(); String userName = "root"; String emailAddress = "root@mydomain.com"; @@ -213,16 +205,16 @@ GitAPITestUpdate.WorkingArea init() throws GitException, IOException, Interrupte return this; } - GitAPITestUpdate.WorkingArea init(boolean bare) throws GitException, IOException, InterruptedException { + GitAPITestUpdate.WorkingArea init(boolean bare) throws Exception { git.init_().workspace(repoPath()).bare(bare).execute(); return this; } - void tag(String tag) throws IOException, InterruptedException { + void tag(String tag) throws Exception { tag(tag, false); } - void tag(String tag, boolean force) throws IOException, InterruptedException { + void tag(String tag, boolean force) throws Exception { if (force) { launchCommand("git", "tag", "--force", tag); } else { @@ -230,7 +222,7 @@ void tag(String tag, boolean force) throws IOException, InterruptedException { } } - void commitEmpty(String msg) throws IOException, InterruptedException { + void commitEmpty(String msg) throws Exception { launchCommand("git", "commit", "--allow-empty", "-m", msg); } @@ -248,14 +240,14 @@ boolean exists(String path) { /** * Creates a file in the workspace. */ - void touch(String path) throws IOException { + void touch(String path) throws Exception { file(path).createNewFile(); } /** * Creates a file in the workspace. */ - File touch(String path, String content) throws IOException { + File touch(String path, String content) throws Exception { File f = file(path); Files.writeString(f.toPath(), content, StandardCharsets.UTF_8); return f; @@ -265,7 +257,7 @@ void rm(String path) { file(path).delete(); } - String contentOf(String path) throws IOException { + String contentOf(String path) throws Exception { return Files.readString(file(path).toPath(), StandardCharsets.UTF_8); } @@ -310,14 +302,14 @@ JGitAPIImpl jgit() throws Exception { /** * Creates a {@link Repository} object out of it. */ - FileRepository repo() throws IOException { + FileRepository repo() throws Exception { return bare ? new FileRepository(repo) : new FileRepository(new File(repo, ".git")); } /** * Obtain the current HEAD revision */ - ObjectId head() throws GitException, IOException, InterruptedException { + ObjectId head() throws Exception { return git.revParse("HEAD"); } @@ -328,8 +320,7 @@ IGitAPI igit() { return (IGitAPI) git; } - void initializeWorkingArea(String userName, String userEmail) - throws GitException, IOException, InterruptedException { + void initializeWorkingArea(String userName, String userEmail) throws Exception { CliGitCommand gitCmd = new CliGitCommand(git); gitCmd.initializeRepository(userName, userEmail); } @@ -347,14 +338,13 @@ protected WorkingArea clone(String src) throws Exception { return clonedArea; } - @Before + @BeforeEach public void setUp() throws Exception { if (firstRun) { firstRun = false; defaultBranchName = getDefaultBranchName(); defaultRemoteBranchName = "origin/" + defaultBranchName; } - setTimeoutVisibleInCurrentTest(true); checkoutTimeout = -1; submoduleUpdateTimeout = -1; Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++); @@ -381,7 +371,7 @@ private boolean isShallow() { * @throws IOException on I/O error * @throws InterruptedException when exception is interrupted */ - protected String localMirror() throws IOException, InterruptedException { + protected String localMirror() throws Exception { File base = new File(".").getAbsoluteFile(); for (File f = base; f != null; f = f.getParentFile()) { File targetDir = new File(f, "target"); @@ -466,7 +456,7 @@ private void renameAndDeleteDir(Path srcDir, String destDirName) { private List tempDirsToDelete = new ArrayList<>(); - @After + @AfterEach public void tearDown() throws Exception { try { temporaryDirectoryAllocator.dispose(); @@ -475,7 +465,7 @@ public void tearDown() throws Exception { } try { String messages = StringUtils.join(handler.getMessages(), ";"); - assertTrue("Logging not started: " + messages, handler.containsMessageSubstring(LOGGING_STARTED)); + assertTrue(handler.containsMessageSubstring(LOGGING_STARTED), "Logging not started: " + messages); assertCheckoutTimeout(); assertSubmoduleUpdateTimeout(); } finally { @@ -495,14 +485,16 @@ public void tearDown() throws Exception { private void checkGetHeadRev(String remote, String branchSpec, ObjectId expectedObjectId) throws Exception { ObjectId actualObjectId = w.git.getHeadRev(remote, branchSpec); assertNotNull( + expectedObjectId, "Expected ObjectId is null expectedObjectId '%s', remote '%s', branchSpec '%s'." - .formatted(expectedObjectId, remote, branchSpec), - expectedObjectId); + .formatted(expectedObjectId, remote, branchSpec)); assertNotNull( + actualObjectId, "Actual ObjectId is null. expectedObjectId '%s', remote '%s', branchSpec '%s'." - .formatted(expectedObjectId, remote, branchSpec), - actualObjectId); + .formatted(expectedObjectId, remote, branchSpec)); assertEquals( + expectedObjectId, + actualObjectId, (""" Actual ObjectId differs from expected one for branchSpec '%s', remote '%s': Actual %s, @@ -512,12 +504,10 @@ private void checkGetHeadRev(String remote, String branchSpec, ObjectId expected branchSpec, remote, StringUtils.join(getBranches(actualObjectId), ", "), - StringUtils.join(getBranches(expectedObjectId), ", ")), - expectedObjectId, - actualObjectId); + StringUtils.join(getBranches(expectedObjectId), ", "))); } - private List getBranches(ObjectId objectId) throws GitException, InterruptedException { + private List getBranches(ObjectId objectId) throws Exception { List matches = new ArrayList<>(); Set branches = w.git.getBranches(); for (Branch branch : branches) { @@ -793,7 +783,7 @@ public void testSubmoduleCheckoutAndCleanTransitions() throws Exception { Revision nullRevision = null; w.igit().setupSubmoduleUrls(nullRevision, listener); } catch (UnsupportedOperationException uoe) { - assertTrue("Unsupported operation not on JGit", w.igit() instanceof JGitAPIImpl); + assertInstanceOf(JGitAPIImpl.class, w.igit(), "Unsupported operation not on JGit"); } return; } @@ -825,9 +815,7 @@ private void assertSubmoduleRepository(File submoduleDir) throws Exception { * functioning repository object */ submoduleClient.withRepository((final Repository repo, VirtualChannel channel) -> { - assertTrue( - repo.getDirectory() + " is not a valid repository", - repo.getObjectDatabase().exists()); + assertTrue(repo.getObjectDatabase().exists(), repo.getDirectory() + " is not a valid repository"); return null; }); } @@ -845,7 +833,7 @@ private String listDir(File dir) { fileList.append(file.getName()); fileList.append(','); } - if (fileList.length() > 0) { + if (!fileList.isEmpty()) { fileList.deleteCharAt(fileList.length() - 1); } return fileList.toString(); @@ -853,11 +841,11 @@ private String listDir(File dir) { private void assertDirExists(File dir) { assertFileExists(dir); - assertTrue(dir + " is not a directory", dir.isDirectory()); + assertTrue(dir.isDirectory(), dir + " is not a directory"); } private void assertFileExists(File file) { - assertTrue(file + " not found, peer files: " + listDir(file.getParentFile()), file.exists()); + assertTrue(file.exists(), file + " not found, peer files: " + listDir(file.getParentFile())); } private void assertDirNotFound(File dir) { @@ -865,23 +853,23 @@ private void assertDirNotFound(File dir) { } private void assertFileNotFound(File file) { - assertFalse(file + " found, peer files: " + listDir(file.getParentFile()), file.exists()); + assertFalse(file.exists(), file + " found, peer files: " + listDir(file.getParentFile())); } - private void assertFileContains(File file, String expectedContent) throws IOException { + private void assertFileContains(File file, String expectedContent) throws Exception { assertFileExists(file); final String fileContent = Files.readString(file.toPath(), StandardCharsets.UTF_8); final String message = file + " does not contain '" + expectedContent + "', contains '" + fileContent + "'"; - assertTrue(message, fileContent.contains(expectedContent)); + assertTrue(fileContent.contains(expectedContent), message); } - private void assertFileContents(File file, String expectedContent) throws IOException { + private void assertFileContents(File file, String expectedContent) throws Exception { assertFileExists(file); final String fileContent = Files.readString(file.toPath(), StandardCharsets.UTF_8); - assertEquals(file + " wrong content", expectedContent, fileContent); + assertEquals(expectedContent, fileContent, file + " wrong content"); } - private void assertSubmoduleContents() throws IOException { + private void assertSubmoduleContents() throws Exception { final File modulesDir = new File(w.repo, "modules"); final File sshkeysDir = new File(modulesDir, "sshkeys"); @@ -959,7 +947,7 @@ public void testSubmoduleTagsNotFetchedIntoParent() throws Exception { String tagsBefore = w.launchCommand("git", "tag"); Set tagNamesBefore = w.git.getTagNames(null); for (String tag : tagNamesBefore) { - assertTrue(tag + " not in " + tagsBefore, tagsBefore.contains(tag)); + assertTrue(tagsBefore.contains(tag), tag + " not in " + tagsBefore); } w.git.checkout() @@ -972,22 +960,22 @@ public void testSubmoduleTagsNotFetchedIntoParent() throws Exception { String tagsAfter = w.launchCommand("git", "tag"); Set tagNamesAfter = w.git.getTagNames(null); for (String tag : tagNamesAfter) { - assertTrue(tag + " not in " + tagsAfter, tagsAfter.contains(tag)); + assertTrue(tagsAfter.contains(tag), tag + " not in " + tagsAfter); } - assertEquals("tags before != after", tagsBefore, tagsAfter); + assertEquals(tagsBefore, tagsAfter, "tags before != after"); GitClient gitNtp = w.git.subGit("modules/ntp"); Set tagNamesSubmodule = gitNtp.getTagNames(null); for (String tag : tagNamesSubmodule) { - assertFalse("Submodule tag " + tag + " in parent " + tagsAfter, tagsAfter.matches("^" + tag + "$")); + assertFalse(tagsAfter.matches("^" + tag + "$"), "Submodule tag " + tag + " in parent " + tagsAfter); } try { w.igit().fixSubmoduleUrls("origin", listener); - assertTrue("not CliGit", w.igit() instanceof CliGitAPIImpl); + assertInstanceOf(CliGitAPIImpl.class, w.igit(), "not CliGit"); } catch (UnsupportedOperationException uoe) { - assertTrue("Unsupported operation not on JGit", w.igit() instanceof JGitAPIImpl); + assertInstanceOf(JGitAPIImpl.class, w.igit(), "Unsupported operation not on JGit"); } } @@ -1011,11 +999,11 @@ public void testGetSubmodules() throws Exception { w.git.submoduleInit(); w.git.submoduleUpdate().execute(); - assertTrue("modules/firewall does not exist", w.exists("modules/firewall")); - assertTrue("modules/ntp does not exist", w.exists("modules/ntp")); + assertTrue(w.exists("modules/firewall"), "modules/firewall does not exist"); + assertTrue(w.exists("modules/ntp"), "modules/ntp does not exist"); // JGit submodule implementation doesn't handle renamed submodules if (w.igit() instanceof CliGitAPIImpl) { - assertTrue("modules/sshkeys does not exist", w.exists("modules/sshkeys")); + assertTrue(w.exists("modules/sshkeys"), "modules/sshkeys does not exist"); } assertFixSubmoduleUrlsThrows(); } @@ -1036,16 +1024,16 @@ public void testSubmoduleUpdateShallow() throws Exception { w.git instanceof CliGitAPIImpl && w.cgit().isAtLeastVersion(1, 8, 4, 0); String shallow = Path.of(".git", "modules", "submodule", "shallow").toString(); - assertEquals("shallow file existence: " + shallow, hasShallowSubmoduleSupport, w.exists(shallow)); + assertEquals(hasShallowSubmoduleSupport, w.exists(shallow), "shallow file existence: " + shallow); int localSubmoduleCommits = w.cgit().subGit("submodule").revList(defaultBranchName).size(); int remoteSubmoduleCommits = remote.cgit().subGit("dir-submodule").revList(defaultBranchName).size(); assertEquals( - "submodule commit count didn't match", hasShallowSubmoduleSupport ? 1 : remoteSubmoduleCommits, - localSubmoduleCommits); + localSubmoduleCommits, + "submodule commit count didn't match"); } @Test @@ -1064,16 +1052,16 @@ public void testSubmoduleUpdateShallowWithDepth() throws Exception { w.git instanceof CliGitAPIImpl && w.cgit().isAtLeastVersion(1, 8, 4, 0); String shallow = Path.of(".git", "modules", "submodule", "shallow").toString(); - assertEquals("shallow file existence: " + shallow, hasShallowSubmoduleSupport, w.exists(shallow)); + assertEquals(hasShallowSubmoduleSupport, w.exists(shallow), "shallow file existence: " + shallow); int localSubmoduleCommits = w.cgit().subGit("submodule").revList(defaultBranchName).size(); int remoteSubmoduleCommits = remote.cgit().subGit("dir-submodule").revList(defaultBranchName).size(); assertEquals( - "submodule commit count didn't match", hasShallowSubmoduleSupport ? 2 : remoteSubmoduleCommits, - localSubmoduleCommits); + localSubmoduleCommits, + "submodule commit count didn't match"); } /** @@ -1126,40 +1114,40 @@ public void testMergeRefspec() throws Exception { w.git.add("file2"); w.git.commit("commit2-branch2"); final ObjectId branch2 = w.head(); - assertTrue("file2 does not exist", f.exists()); + assertTrue(f.exists(), "file2 does not exist"); - assertFalse("file1 exists before merge", w.exists("file1")); - assertEquals("Wrong merge-base branch1 branch2", base, w.igit().mergeBase(branch1, branch2)); + assertFalse(w.exists("file1"), "file1 exists before merge"); + assertEquals(base, w.igit().mergeBase(branch1, branch2), "Wrong merge-base branch1 branch2"); String badSHA1 = "15c80fb1567f0e88ca855c69e3f17425d515a188"; ObjectId badBase = ObjectId.fromString(badSHA1); try { - assertNull("Base unexpected for bad SHA1", w.igit().mergeBase(branch1, badBase)); - assertTrue("Exception not thrown by CliGit", w.git instanceof CliGitAPIImpl); + assertNull(w.igit().mergeBase(branch1, badBase), "Base unexpected for bad SHA1"); + assertInstanceOf(CliGitAPIImpl.class, w.git, "Exception not thrown by CliGit"); } catch (GitException moa) { - assertFalse("Exception thrown by CliGit", w.git instanceof CliGitAPIImpl); + assertFalse(w.git instanceof CliGitAPIImpl, "Exception thrown by CliGit"); assertExceptionMessageContains(moa, badSHA1); } try { - assertNull("Base unexpected for bad SHA1", w.igit().mergeBase(badBase, branch1)); - assertTrue("Exception not thrown by CliGit", w.git instanceof CliGitAPIImpl); + assertNull(w.igit().mergeBase(badBase, branch1), "Base unexpected for bad SHA1"); + assertInstanceOf(CliGitAPIImpl.class, w.git, "Exception not thrown by CliGit"); } catch (GitException moa) { - assertFalse("Exception thrown by CliGit", w.git instanceof CliGitAPIImpl); + assertFalse(w.git instanceof CliGitAPIImpl, "Exception thrown by CliGit"); assertExceptionMessageContains(moa, badSHA1); } w.igit().merge("branch1"); - assertTrue("file1 does not exist after merge", w.exists("file1")); + assertTrue(w.exists("file1"), "file1 does not exist after merge"); w.launchCommand("git", "checkout", "--orphan", "newroot"); // Create an independent root w.commitEmpty("init-on-newroot"); final ObjectId newRootCommit = w.head(); - assertNull("Common root not expected", w.igit().mergeBase(newRootCommit, branch1)); + assertNull(w.igit().mergeBase(newRootCommit, branch1), "Common root not expected"); final String remoteUrl = "ssh://mwaite.example.com//var/lib/git/mwaite/jenkins/git-client-plugin.git"; w.git.setRemoteUrl("origin", remoteUrl); - assertEquals("Wrong origin default remote", "origin", w.igit().getDefaultRemote("origin")); - assertEquals("Wrong invalid default remote", "origin", w.igit().getDefaultRemote("invalid")); + assertEquals("origin", w.igit().getDefaultRemote("origin"), "Wrong origin default remote"); + assertEquals("origin", w.igit().getDefaultRemote("invalid"), "Wrong invalid default remote"); } /** @@ -1180,9 +1168,9 @@ public void testGetHeadRevFromPublicRepoWithInvalidCredential() throws Exception Map heads = remoteGit.getHeadRev(remoteMirrorURL); ObjectId defaultBranch = w.git.getHeadRev(remoteMirrorURL, "refs/heads/" + defaultBranchName); assertEquals( - "URL is " + remoteMirrorURL + ", heads is " + heads, defaultBranch, - heads.get("refs/heads/" + defaultBranchName)); + heads.get("refs/heads/" + defaultBranchName), + "URL is " + remoteMirrorURL + ", heads is " + heads); } /** @@ -1193,7 +1181,6 @@ public void testGetHeadRevFromPublicRepoWithInvalidCredential() throws Exception */ @Test public void testGetHeadRevNamespacesWithSimpleBranchNames() throws Exception { - setTimeoutVisibleInCurrentTest(false); File tempRemoteDir = temporaryDirectoryAllocator.allocate(); extract(new ZipFile("src/test/resources/namespaceBranchRepo.zip"), tempRemoteDir); Properties commits = parseLsRemote(new File("src/test/resources/namespaceBranchRepo.ls-remote")); @@ -1223,7 +1210,7 @@ public void testGetHeadRevNamespacesWithSimpleBranchNames() throws Exception { } } - private Properties parseLsRemote(File file) throws IOException { + private Properties parseLsRemote(File file) throws Exception { Properties properties = new Properties(); Pattern pattern = Pattern.compile("([a-f0-9]{40})\\s*(.*)"); for (String lineO : Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)) { @@ -1264,7 +1251,7 @@ public void testPushDeprecatedSignature() throws Exception { /* Set working repo origin to point to bare */ w.git.setRemoteUrl("origin", bare.repoPath()); - assertEquals("Wrong remote URL", w.git.getRemoteUrl("origin"), bare.repoPath()); + assertEquals(w.git.getRemoteUrl("origin"), bare.repoPath(), "Wrong remote URL"); /* Push to bare repo */ w.git.push("origin", defaultBranchName); @@ -1273,11 +1260,11 @@ public void testPushDeprecatedSignature() throws Exception { ? bare.head() : ObjectId.fromString(bare.launchCommand("git", "rev-parse", defaultBranchName) .substring(0, 40)); - assertEquals("Heads don't match", workHead, bareHead); + assertEquals(workHead, bareHead, "Heads don't match"); assertEquals( - "Heads don't match", w.git.getHeadRev(w.repoPath(), defaultBranchName), - bare.git.getHeadRev(bare.repoPath(), defaultBranchName)); + bare.git.getHeadRev(bare.repoPath(), defaultBranchName), + "Heads don't match"); /* Commit a new file */ w.touch("file1"); @@ -1299,29 +1286,29 @@ public void testPushDeprecatedSignature() throws Exception { ? bare.head() : ObjectId.fromString(bare.launchCommand("git", "rev-parse", defaultBranchName) .substring(0, 40)); - assertEquals("Working SHA1 != bare SHA1", workHead2, bareHead2); + assertEquals(workHead2, bareHead2, "Working SHA1 != bare SHA1"); assertEquals( - "Working SHA1 != bare SHA1", w.git.getHeadRev(w.repoPath(), defaultBranchName), - bare.git.getHeadRev(bare.repoPath(), defaultBranchName)); + bare.git.getHeadRev(bare.repoPath(), defaultBranchName), + "Working SHA1 != bare SHA1"); } private void assertExceptionMessageContains(GitException ge, String expectedSubstring) { String actual = ge.getMessage().toLowerCase(); assertTrue( - "Expected '" + expectedSubstring + "' exception message, but was: " + actual, - actual.contains(expectedSubstring)); + actual.contains(expectedSubstring), + "Expected '" + expectedSubstring + "' exception message, but was: " + actual); } - public void assertFixSubmoduleUrlsThrows() throws InterruptedException { + public void assertFixSubmoduleUrlsThrows() throws Exception { try { w.igit().fixSubmoduleUrls("origin", listener); fail("Expected exception not thrown"); } catch (UnsupportedOperationException uoe) { - assertTrue("Unsupported operation not on JGit", w.igit() instanceof JGitAPIImpl); + assertInstanceOf(JGitAPIImpl.class, w.igit(), "Unsupported operation not on JGit"); } catch (GitException ge) { - assertTrue("GitException not on CliGit", w.igit() instanceof CliGitAPIImpl); - assertTrue("Wrong message in " + ge.getMessage(), ge.getMessage().startsWith("Could not determine remote")); + assertInstanceOf(CliGitAPIImpl.class, w.igit(), "GitException not on CliGit"); + assertTrue(ge.getMessage().startsWith("Could not determine remote"), "Wrong message in " + ge.getMessage()); assertExceptionMessageContains(ge, "origin"); } } @@ -1352,8 +1339,8 @@ private void baseCheckoutReplacesTrackedChanges(boolean defineBranch) throws Exc /* Confirm first checkout */ String pomContent = w.contentOf("pom.xml"); - assertTrue("Missing inceptionYear ref in pom : " + pomContent, pomContent.contains("inceptionYear")); - assertFalse("Found untracked file", w.file("untracked-file").exists()); + assertTrue(pomContent.contains("inceptionYear"), "Missing inceptionYear ref in pom : " + pomContent); + assertFalse(w.file("untracked-file").exists(), "Found untracked file"); /* Modify the pom file by adding a comment */ String comment = " "; @@ -1365,7 +1352,7 @@ private void baseCheckoutReplacesTrackedChanges(boolean defineBranch) throws Exc * untracked files across checkout. */ w.touch("untracked-file", comment); - assertTrue("Missing untracked file", w.file("untracked-file").exists()); + assertTrue(w.file("untracked-file").exists(), "Missing untracked file"); /* Checkout should erase local modification */ CheckoutCommand cmd = w.git.checkout().ref("JENKINS-23424/1.4.x").deleteBranchIfExist(true); @@ -1376,12 +1363,12 @@ private void baseCheckoutReplacesTrackedChanges(boolean defineBranch) throws Exc /* Tracked file should not contain added comment, nor the inceptionYear reference */ pomContent = w.contentOf("pom.xml"); - assertFalse("Found inceptionYear ref in 1.4.x pom : " + pomContent, pomContent.contains("inceptionYear")); - assertFalse("Found comment in 1.4.x pom", pomContent.contains(comment)); - assertTrue("Missing untracked file", w.file("untracked-file").exists()); + assertFalse(pomContent.contains("inceptionYear"), "Found inceptionYear ref in 1.4.x pom : " + pomContent); + assertFalse(pomContent.contains(comment), "Found comment in 1.4.x pom"); + assertTrue(w.file("untracked-file").exists(), "Missing untracked file"); } - protected File createTempDirectoryWithoutSpaces() throws IOException { + protected File createTempDirectoryWithoutSpaces() throws Exception { // JENKINS-56175 notes that the plugin does not support submodule URL's // which contain a space character. Parent pom 3.36 and later use a // temporary directory containing a space to detect these problems. @@ -1403,19 +1390,19 @@ public void testLsTreeNonRecursive() throws Exception { w.git.commit("commit1"); String expectedBlobSHA1 = "3f5a898e0c8ea62362dbf359cf1a400f3cfd46ae"; List tree = w.igit().lsTree("HEAD", false); - assertEquals("Wrong blob sha1", expectedBlobSHA1, tree.get(0).getObject()); - assertEquals("Wrong number of tree entries", 1, tree.size()); + assertEquals(expectedBlobSHA1, tree.get(0).getObject(), "Wrong blob sha1"); + assertEquals(1, tree.size(), "Wrong number of tree entries"); final String remoteUrl = localMirror(); w.igit().setRemoteUrl("origin", remoteUrl, w.repoPath() + File.separator + ".git"); - assertEquals("Wrong origin default remote", "origin", w.igit().getDefaultRemote("origin")); - assertEquals("Wrong invalid default remote", "origin", w.igit().getDefaultRemote("invalid")); + assertEquals("origin", w.igit().getDefaultRemote("origin"), "Wrong origin default remote"); + assertEquals("origin", w.igit().getDefaultRemote("invalid"), "Wrong invalid default remote"); } @Deprecated @Test public void testLsTreeRecursive() throws Exception { w.init(); - assertTrue("mkdir dir1 failed", w.file("dir1").mkdir()); + assertTrue(w.file("dir1").mkdir(), "mkdir dir1 failed"); w.touch("dir1/file1", "dir1/file1 fixed content"); w.git.add("dir1/file1"); w.touch("file2", "file2 fixed content"); @@ -1424,13 +1411,13 @@ public void testLsTreeRecursive() throws Exception { String expectedBlob1SHA1 = "a3ee484019f0576fcdeb48e682fa1058d0c74435"; String expectedBlob2SHA1 = "aa1b259ac5e8d6cfdfcf4155a9ff6836b048d0ad"; List tree = w.igit().lsTree("HEAD", true); - assertEquals("Wrong blob 1 sha1", expectedBlob1SHA1, tree.get(0).getObject()); - assertEquals("Wrong blob 2 sha1", expectedBlob2SHA1, tree.get(1).getObject()); - assertEquals("Wrong number of tree entries", 2, tree.size()); + assertEquals(expectedBlob1SHA1, tree.get(0).getObject(), "Wrong blob 1 sha1"); + assertEquals(expectedBlob2SHA1, tree.get(1).getObject(), "Wrong blob 2 sha1"); + assertEquals(2, tree.size(), "Wrong number of tree entries"); final String remoteUrl = "https://github.com/jenkinsci/git-client-plugin.git"; w.git.setRemoteUrl("origin", remoteUrl); - assertEquals("Wrong origin default remote", "origin", w.igit().getDefaultRemote("origin")); - assertEquals("Wrong invalid default remote", "origin", w.igit().getDefaultRemote("invalid")); + assertEquals("origin", w.igit().getDefaultRemote("origin"), "Wrong origin default remote"); + assertEquals("origin", w.igit().getDefaultRemote("invalid"), "Wrong invalid default remote"); } private String getDefaultBranchName() throws Exception { @@ -1445,14 +1432,14 @@ private String getDefaultBranchName() throws Exception { defaultBranchValue = result; } } - assertTrue("Failed to delete temporary readGitConfig directory", configDir.delete()); + assertTrue(configDir.delete(), "Failed to delete temporary readGitConfig directory"); return defaultBranchValue; } /* HEAD ref of local mirror - all read access should use getMirrorHead */ private static ObjectId mirrorHead = null; - private ObjectId getMirrorHead() throws IOException, InterruptedException { + private ObjectId getMirrorHead() throws Exception { if (mirrorHead == null) { final String mirrorPath = new File(localMirror()).getAbsolutePath(); mirrorHead = ObjectId.fromString(w.launchCommand("git", "--git-dir=" + mirrorPath, "rev-parse", "HEAD") @@ -1461,7 +1448,7 @@ private ObjectId getMirrorHead() throws IOException, InterruptedException { return mirrorHead; } - private void extract(ZipFile zipFile, File outputDir) throws IOException { + private void extract(ZipFile zipFile, File outputDir) throws Exception { Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); @@ -1485,13 +1472,13 @@ private void extract(ZipFile zipFile, File outputDir) throws IOException { private void checkHeadRev(String repoURL, ObjectId expectedId) throws Exception { final ObjectId originDefaultBranch = w.git.getHeadRev(repoURL, DEFAULT_MIRROR_BRANCH_NAME); - assertEquals("origin default branch mismatch", expectedId, originDefaultBranch); + assertEquals(expectedId, originDefaultBranch, "origin default branch mismatch"); final ObjectId simpleDefaultBranch = w.git.getHeadRev(repoURL, DEFAULT_MIRROR_BRANCH_NAME); - assertEquals("simple default branch mismatch", expectedId, simpleDefaultBranch); + assertEquals(expectedId, simpleDefaultBranch, "simple default branch mismatch"); final ObjectId wildcardSCMDefaultBranch = w.git.getHeadRev(repoURL, "*/" + DEFAULT_MIRROR_BRANCH_NAME); - assertEquals("wildcard SCM default branch mismatch", expectedId, wildcardSCMDefaultBranch); + assertEquals(expectedId, wildcardSCMDefaultBranch, "wildcard SCM default branch mismatch"); /* This assertion may fail if the localMirror has more than * one branch matching the wildcard expression in the call to @@ -1505,26 +1492,7 @@ private void checkHeadRev(String repoURL, ObjectId expectedId) throws Exception final ObjectId wildcardEndDefaultBranch = w.git.getHeadRev( repoURL, DEFAULT_MIRROR_BRANCH_NAME.replace('a', '*').replace('t', '?').replace('n', '?')); - assertEquals("wildcard end default branch mismatch", expectedId, wildcardEndDefaultBranch); - } - - private boolean timeoutVisibleInCurrentTest; - - /** - * Returns true if the current test is expected to have a timeout value - * visible written to the listener log. Used to assert timeout values are - * passed correctly through the layers without requiring that the timeout - * actually expire. - * - * @see #setTimeoutVisibleInCurrentTest(boolean) - * @return true if timeout is expected to be visible in the current test - */ - protected boolean getTimeoutVisibleInCurrentTest() { - return timeoutVisibleInCurrentTest; - } - - protected void setTimeoutVisibleInCurrentTest(boolean visible) { - timeoutVisibleInCurrentTest = visible; + assertEquals(expectedId, wildcardEndDefaultBranch, "wildcard end default branch mismatch"); } /** @@ -1573,8 +1541,7 @@ public void testGetHeadRevRemote() throws Exception { @Test public void testHasGitRepoWithoutGitDirectory() throws Exception { - setTimeoutVisibleInCurrentTest(false); - assertFalse("Empty directory has a Git repo", w.git.hasGitRepo()); + assertFalse(w.git.hasGitRepo(), "Empty directory has a Git repo"); } @Issue("JENKINS-22343") @@ -1588,10 +1555,10 @@ public void testShowRevisionForFirstCommit() throws Exception { List revisionDetails = w.git.showRevision(first); List commits = revisionDetails.stream() .filter(detail -> detail.startsWith("commit ")) - .collect(Collectors.toList()); + .toList(); assertTrue( - "Commits '" + commits + "' missing " + first.getName(), commits.contains("commit " + first.getName())); - assertEquals("Commits '" + commits + "' wrong size", 1, commits.size()); + commits.contains("commit " + first.getName()), "Commits '" + commits + "' missing " + first.getName()); + assertEquals(1, commits.size(), "Commits '" + commits + "' wrong size"); } /** @@ -1607,41 +1574,41 @@ public void testReset() throws Exception { w.touch("committed-file", "committed-file content " + UUID.randomUUID()); w.git.add("committed-file"); w.git.commit("commit1"); - assertTrue("committed-file missing at commit1", w.file("committed-file").exists()); - assertFalse("added-file exists at commit1", w.file("added-file").exists()); - assertFalse("touched-file exists at commit1", w.file("added-file").exists()); + assertTrue(w.file("committed-file").exists(), "committed-file missing at commit1"); + assertFalse(w.file("added-file").exists(), "added-file exists at commit1"); + assertFalse(w.file("added-file").exists(), "touched-file exists at commit1"); w.launchCommand("git", "rm", "committed-file"); w.touch("added-file", "File 2 content " + UUID.randomUUID()); w.git.add("added-file"); w.touch("touched-file", "File 3 content " + UUID.randomUUID()); - assertFalse("committed-file exists", w.file("committed-file").exists()); - assertTrue("added-file missing", w.file("added-file").exists()); - assertTrue("touched-file missing", w.file("touched-file").exists()); + assertFalse(w.file("committed-file").exists(), "committed-file exists"); + assertTrue(w.file("added-file").exists(), "added-file missing"); + assertTrue(w.file("touched-file").exists(), "touched-file missing"); w.igit().reset(false); - assertFalse("committed-file exists", w.file("committed-file").exists()); - assertTrue("added-file missing", w.file("added-file").exists()); - assertTrue("touched-file missing", w.file("touched-file").exists()); + assertFalse(w.file("committed-file").exists(), "committed-file exists"); + assertTrue(w.file("added-file").exists(), "added-file missing"); + assertTrue(w.file("touched-file").exists(), "touched-file missing"); w.git.add("added-file"); /* Add the file which soft reset "unadded" */ w.igit().reset(true); - assertTrue("committed-file missing", w.file("committed-file").exists()); - assertFalse("added-file exists at hard reset", w.file("added-file").exists()); - assertTrue("touched-file missing", w.file("touched-file").exists()); + assertTrue(w.file("committed-file").exists(), "committed-file missing"); + assertFalse(w.file("added-file").exists(), "added-file exists at hard reset"); + assertTrue(w.file("touched-file").exists(), "touched-file missing"); final String remoteUrl = "git@github.com:MarkEWaite/git-client-plugin.git"; w.git.setRemoteUrl("origin", remoteUrl); w.git.setRemoteUrl("ndeloof", "git@github.com:ndeloof/git-client-plugin.git"); - assertEquals("Wrong origin default remote", "origin", w.igit().getDefaultRemote("origin")); - assertEquals("Wrong ndeloof default remote", "ndeloof", w.igit().getDefaultRemote("ndeloof")); + assertEquals("origin", w.igit().getDefaultRemote("origin"), "Wrong origin default remote"); + assertEquals("ndeloof", w.igit().getDefaultRemote("ndeloof"), "Wrong ndeloof default remote"); /* CliGitAPIImpl and JGitAPIImpl return different ordered lists for default remote if invalid */ assertEquals( - "Wrong invalid default remote", w.git instanceof CliGitAPIImpl ? "ndeloof" : "origin", - w.igit().getDefaultRemote("invalid")); + w.igit().getDefaultRemote("invalid"), + "Wrong invalid default remote"); } @Issue({"JENKINS-6203", "JENKINS-14798", "JENKINS-23091"}) @@ -1671,13 +1638,13 @@ public void testGetDefaultRemote() throws Exception { w.init(); w.launchCommand("git", "remote", "add", "origin", "https://github.com/jenkinsci/git-client-plugin.git"); w.launchCommand("git", "remote", "add", "ndeloof", "git@github.com:ndeloof/git-client-plugin.git"); - assertEquals("Wrong origin default remote", "origin", w.igit().getDefaultRemote("origin")); - assertEquals("Wrong ndeloof default remote", "ndeloof", w.igit().getDefaultRemote("ndeloof")); + assertEquals("origin", w.igit().getDefaultRemote("origin"), "Wrong origin default remote"); + assertEquals("ndeloof", w.igit().getDefaultRemote("ndeloof"), "Wrong ndeloof default remote"); /* CliGitAPIImpl and JGitAPIImpl return different ordered lists for default remote if invalid */ assertEquals( - "Wrong invalid default remote", w.git instanceof CliGitAPIImpl ? "ndeloof" : "origin", - w.igit().getDefaultRemote("invalid")); + w.igit().getDefaultRemote("invalid"), + "Wrong invalid default remote"); } /** @@ -1698,7 +1665,7 @@ public void testGetDefaultRemote() throws Exception { @Test public void testGitInitCreatesDirectoryIfNeeded() throws Exception { File nonexistentDir = new File(UUID.randomUUID().toString()); - assertFalse("Dir unexpectedly exists at start of test", nonexistentDir.exists()); + assertFalse(nonexistentDir.exists(), "Dir unexpectedly exists at start of test"); try { GitClient git = setupGitAPI(nonexistentDir); git.init(); @@ -1708,14 +1675,12 @@ public void testGitInitCreatesDirectoryIfNeeded() throws Exception { } private void checkBoundedChangelogSha1(final String sha1Begin, final String sha1End, final String branchName) - throws GitException, InterruptedException { + throws Exception { StringWriter writer = new StringWriter(); w.git.changelog(sha1Begin, sha1End, writer); - String splitLog[] = writer.toString().split("[\\n\\r]", 3); // Extract first line of changelog - assertEquals("Wrong bounded changelog line 1 on branch " + branchName, "commit " + sha1End, splitLog[0]); - assertTrue( - "Begin sha1 " + sha1Begin + " not in changelog: " + writer, - writer.toString().contains(sha1Begin)); + String[] splitLog = writer.toString().split("[\\n\\r]", 3); // Extract first line of changelog + assertEquals("commit " + sha1End, splitLog[0], "Wrong bounded changelog line 1 on branch " + branchName); + assertTrue(writer.toString().contains(sha1Begin), "Begin sha1 " + sha1Begin + " not in changelog: " + writer); } @Test @@ -1749,14 +1714,14 @@ public void testShowRevisionForMergeExcludeFiles() throws Exception { List commits = revisionDetails.stream() .filter(detail -> detail.startsWith("commit ")) - .collect(Collectors.toList()); + .toList(); assertEquals(2, commits.size()); assertTrue(commits.contains("commit 4f2964e476776cf59be3e033310f9177bedbf6a8")); assertTrue(commits.contains("commit b53374617e85537ec46f86911b5efe3e4e2fa54b")); List diffs = revisionDetails.stream() .filter(detail -> detail.startsWith(":")) - .collect(Collectors.toList()); + .toList(); assertTrue(diffs.isEmpty()); } @@ -1779,7 +1744,7 @@ public void testShowRevisionForSingleCommit() throws Exception { List revisionDetails = w.git.showRevision(null, to); List commits = revisionDetails.stream() .filter(detail -> detail.startsWith("commit ")) - .collect(Collectors.toList()); + .toList(); assertEquals(1, commits.size()); assertTrue(commits.contains("commit 51de9eda47ca8dcf03b2af58dfff7355585f0d0c")); } @@ -1788,9 +1753,9 @@ public void testShowRevisionForSingleCommit() throws Exception { public void testRevListRemoteBranch() throws Exception { w = clone(localMirror()); List revList = w.git.revList("origin/1.4.x"); - assertEquals("Wrong list size: " + revList, 267, revList.size()); + assertEquals(267, revList.size(), "Wrong list size: " + revList); Ref branchRef = w.repo().findRef("origin/1.4.x"); - assertTrue("origin/1.4.x not in revList", revList.contains(branchRef.getObjectId())); + assertTrue(revList.contains(branchRef.getObjectId()), "origin/1.4.x not in revList"); } /** @@ -1812,14 +1777,14 @@ public void testCheckoutNullRef() throws Exception { w = clone(localMirror()); String branches = w.launchCommand("git", "branch", "-l"); assertTrue( - "default branch not current branch in " + branches, - branches.contains("* " + DEFAULT_MIRROR_BRANCH_NAME)); + branches.contains("* " + DEFAULT_MIRROR_BRANCH_NAME), + "default branch not current branch in " + branches); final String branchName = "test-checkout-null-ref-branch-" + UUID.randomUUID(); branches = w.launchCommand("git", "branch", "-l"); - assertFalse("test branch originally listed in " + branches, branches.contains(branchName)); + assertFalse(branches.contains(branchName), "test branch originally listed in " + branches); w.git.checkout().ref(null).branch(branchName).execute(); branches = w.launchCommand("git", "branch", "-l"); - assertTrue("test branch not current branch in " + branches, branches.contains("* " + branchName)); + assertTrue(branches.contains("* " + branchName), "test branch not current branch in " + branches); } @Test @@ -1832,7 +1797,7 @@ public void testShowRevisionForMerge() throws Exception { List commits = revisionDetails.stream() .filter(detail -> detail.startsWith("commit ")) - .collect(Collectors.toList()); + .toList(); assertEquals(3, commits.size()); assertTrue(commits.contains("commit 4f2964e476776cf59be3e033310f9177bedbf6a8")); // Merge commit is duplicated as have to capture changes that may have been made as part of merge @@ -1844,7 +1809,7 @@ public void testShowRevisionForMerge() throws Exception { List paths = revisionDetails.stream() .filter(detail -> detail.startsWith(":")) .map(diff -> diff.substring(diff.indexOf('\t') + 1).trim()) // Windows diff output ^M removed by trim() - .collect(Collectors.toList()); + .toList(); assertTrue(paths.contains(".gitignore")); // Some irrelevant changes will be listed due to merge commit @@ -1921,17 +1886,17 @@ public void testGetHeadRevReturnsAccurateSHA1Values() throws Exception { w.git.add("file.2"); w.git.commit("commit2-branch.2"); final ObjectId branchDot2 = w.head(); - assertTrue("file.2 does not exist", f.exists()); + assertTrue(f.exists(), "file.2 does not exist"); Map heads = w.git.getHeadRev(w.repoPath()); assertEquals( - "Wrong default branch in " + heads, defaultBranch, - heads.get("refs/heads/" + DEFAULT_MIRROR_BRANCH_NAME)); - assertEquals("Wrong branch1 in " + heads, branch1, heads.get("refs/heads/branch1")); - assertEquals("Wrong branch.2 in " + heads, branchDot2, heads.get("refs/heads/branch.2")); + heads.get("refs/heads/" + DEFAULT_MIRROR_BRANCH_NAME), + "Wrong default branch in " + heads); + assertEquals(branch1, heads.get("refs/heads/branch1"), "Wrong branch1 in " + heads); + assertEquals(branchDot2, heads.get("refs/heads/branch.2"), "Wrong branch.2 in " + heads); - assertEquals("wildcard branch.2 mismatch", branchDot2, w.git.getHeadRev(w.repoPath(), "br*.2")); + assertEquals(branchDot2, w.git.getHeadRev(w.repoPath(), "br*.2"), "wildcard branch.2 mismatch"); checkHeadRev(w.repoPath(), getMirrorHead()); } @@ -1941,20 +1906,20 @@ public void testCheckout() throws Exception { w = clone(localMirror()); String branches = w.launchCommand("git", "branch", "-l"); assertTrue( - "default branch not current branch in " + branches, - branches.contains("* " + DEFAULT_MIRROR_BRANCH_NAME)); + branches.contains("* " + DEFAULT_MIRROR_BRANCH_NAME), + "default branch not current branch in " + branches); final String branchName = "test-checkout-branch-" + UUID.randomUUID(); branches = w.launchCommand("git", "branch", "-l"); - assertFalse("test branch originally listed in " + branches, branches.contains(branchName)); + assertFalse(branches.contains(branchName), "test branch originally listed in " + branches); w.git.checkout() .ref("6b7bbcb8f0e51668ddba349b683fb06b4bd9d0ea") .branch(branchName) .execute(); // git-client-1.6.0 branches = w.launchCommand("git", "branch", "-l"); - assertTrue("test branch not current branch in " + branches, branches.contains("* " + branchName)); + assertTrue(branches.contains("* " + branchName), "test branch not current branch in " + branches); String sha1 = w.git.revParse("HEAD").name(); String sha1Expected = "6b7bbcb8f0e51668ddba349b683fb06b4bd9d0ea"; - assertEquals("Wrong SHA1 as checkout of git-client-1.6.0", sha1Expected, sha1); + assertEquals(sha1Expected, sha1, "Wrong SHA1 as checkout of git-client-1.6.0"); } /** @@ -2060,8 +2025,8 @@ private WorkingArea setupRepositoryWithSubmodule() throws Exception { File repositoryDir = workingArea.file("dir-repository"); File submoduleDir = workingArea.file("dir-submodule"); - assertTrue("did not create dir " + repositoryDir.getName(), repositoryDir.mkdir()); - assertTrue("did not create dir " + submoduleDir.getName(), submoduleDir.mkdir()); + assertTrue(repositoryDir.mkdir(), "did not create dir " + repositoryDir.getName()); + assertTrue(submoduleDir.mkdir(), "did not create dir " + submoduleDir.getName()); WorkingArea submoduleWorkingArea = new WorkingArea(submoduleDir).init(); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITestUpdateCliGit.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITestUpdateCliGit.java index 51dbcb76c3..c155d2d8f6 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITestUpdateCliGit.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitAPITestUpdateCliGit.java @@ -2,9 +2,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -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 hudson.plugins.git.GitException; import java.io.File; @@ -12,14 +10,14 @@ import java.util.Arrays; import java.util.Collections; import java.util.UUID; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; -public abstract class GitAPITestUpdateCliGit extends GitAPITestUpdate { +abstract class GitAPITestUpdateCliGit extends GitAPITestUpdate { /* Shows the submodule update is broken now that tests/getSubmodule includes a renamed submodule */ @Test - public void testSubmoduleUpdate() throws Exception { + void testSubmoduleUpdate() throws Exception { w.init(); w.git.clone_().url(localMirror()).repositoryName("sub2_origin").execute(); w.git.checkout() @@ -30,20 +28,20 @@ public void testSubmoduleUpdate() throws Exception { w.git.submoduleInit(); w.git.submoduleUpdate().execute(); - assertTrue("modules/firewall does not exist", w.exists("modules/firewall")); - assertTrue("modules/ntp does not exist", w.exists("modules/ntp")); + assertTrue(w.exists("modules/firewall"), "modules/firewall does not exist"); + assertTrue(w.exists("modules/ntp"), "modules/ntp does not exist"); // JGit submodule implementation doesn't handle renamed submodules if (w.igit() instanceof CliGitAPIImpl) { - assertTrue("modules/sshkeys does not exist", w.exists("modules/sshkeys")); + assertTrue(w.exists("modules/sshkeys"), "modules/sshkeys does not exist"); } assertFixSubmoduleUrlsThrows(); String shallow = Path.of(".git", "modules", "module", "1", "shallow").toString(); - assertFalse("shallow file existence: " + shallow, w.exists(shallow)); + assertFalse(w.exists(shallow), "shallow file existence: " + shallow); } @Test - public void testSubmoduleUpdateWithError() throws Exception { + void testSubmoduleUpdateWithError() throws Exception { w.git.clone_().url(localMirror()).execute(); w.git.checkout().ref("origin/tests/getSubmodules").execute(); w.rm("modules/ntp"); @@ -67,7 +65,7 @@ public void testSubmoduleUpdateWithError() throws Exception { } @Test - public void testSubmoduleUpdateWithThreads() throws Exception { + void testSubmoduleUpdateWithThreads() throws Exception { w.init(); w.git.clone_().url(localMirror()).repositoryName("sub2_origin").execute(); w.git.checkout() @@ -78,17 +76,17 @@ public void testSubmoduleUpdateWithThreads() throws Exception { w.git.submoduleInit(); w.git.submoduleUpdate().threads(3).execute(); - assertTrue("modules/firewall does not exist", w.exists("modules/firewall")); - assertTrue("modules/ntp does not exist", w.exists("modules/ntp")); + assertTrue(w.exists("modules/firewall"), "modules/firewall does not exist"); + assertTrue(w.exists("modules/ntp"), "modules/ntp does not exist"); // JGit submodule implementation doesn't handle renamed submodules if (w.igit() instanceof CliGitAPIImpl) { - assertTrue("modules/sshkeys does not exist", w.exists("modules/sshkeys")); + assertTrue(w.exists("modules/sshkeys"), "modules/sshkeys does not exist"); } assertFixSubmoduleUrlsThrows(); } @Test - public void testTrackingSubmoduleBranches() throws Exception { + void testTrackingSubmoduleBranches() throws Exception { w.init(); // empty repository // create a new GIT repo. @@ -125,9 +123,9 @@ public void testTrackingSubmoduleBranches() throws Exception { w.cgit().allowFileProtocol(); w.git.addSubmodule(r.repoPath(), submodDir); w.git.submoduleInit(); - assertTrue("file1 does not exist and should be we imported the submodule.", w.exists(subFile1)); - assertFalse("file2 exists and should not because not on 'branch1'", w.exists(subFile2)); - assertFalse("file3 exists and should not because not on 'branch2'", w.exists(subFile3)); + assertTrue(w.exists(subFile1), "file1 does not exist and should be we imported the submodule."); + assertFalse(w.exists(subFile2), "file2 exists and should not because not on 'branch1'"); + assertFalse(w.exists(subFile3), "file3 exists and should not because not on 'branch2'"); // Windows tests fail if repoPath is more than 200 characters // CLI git support for longpaths on Windows is complicated @@ -142,8 +140,8 @@ public void testTrackingSubmoduleBranches() throws Exception { .useBranch(submodDir, "branch1") .timeout(submoduleUpdateTimeout) .execute(); - assertTrue("file2 does not exist and should because on branch1", w.exists(subFile2)); - assertFalse("file3 exists and should not because not on 'branch2'", w.exists(subFile3)); + assertTrue(w.exists(subFile2), "file2 does not exist and should because on branch1"); + assertFalse(w.exists(subFile3), "file3 exists and should not because not on 'branch2'"); // Switch to branch2 w.git.submoduleUpdate() @@ -151,8 +149,8 @@ public void testTrackingSubmoduleBranches() throws Exception { .useBranch(submodDir, "branch2") .timeout(submoduleUpdateTimeout) .execute(); - assertFalse("file2 exists and should not because not on 'branch1'", w.exists(subFile2)); - assertTrue("file3 does not exist and should because on branch2", w.exists(subFile3)); + assertFalse(w.exists(subFile2), "file2 exists and should not because not on 'branch1'"); + assertTrue(w.exists(subFile3), "file3 does not exist and should because on branch2"); // Switch to default branch w.git.submoduleUpdate() @@ -160,12 +158,12 @@ public void testTrackingSubmoduleBranches() throws Exception { .useBranch(submodDir, defaultBranchName) .timeout(submoduleUpdateTimeout) .execute(); - assertFalse("file2 exists and should not because not on 'branch1'", w.exists(subFile2)); - assertFalse("file3 exists and should not because not on 'branch2'", w.exists(subFile3)); + assertFalse(w.exists(subFile2), "file2 exists and should not because not on 'branch1'"); + assertFalse(w.exists(subFile3), "file3 exists and should not because not on 'branch2'"); } @Test - public void testTrackingSubmodule() throws Exception { + void testTrackingSubmodule() throws Exception { w.init(); // empty repository // create a new GIT repo. @@ -191,8 +189,8 @@ public void testTrackingSubmodule() throws Exception { String subFile = subModDir + File.separator + "file2"; w.git.submoduleUpdate().recursive(true).remoteTracking(false).execute(); assertFalse( - "file2 exists and should not because we didn't update to the tip of the default branch.", - w.exists(subFile)); + w.exists(subFile), + "file2 exists and should not because we didn't update to the tip of the default branch."); // Windows tests fail if repoPath is more than 200 characters // CLI git support for longpaths on Windows is complicated @@ -203,14 +201,14 @@ public void testTrackingSubmodule() throws Exception { // Run submodule update with remote tracking w.git.submoduleUpdate().recursive(true).remoteTracking(true).execute(); assertTrue( - "file2 does not exist and should because we updated to the tip of the default branch.", - w.exists(subFile)); + w.exists(subFile), + "file2 does not exist and should because we updated to the tip of the default branch."); assertFixSubmoduleUrlsThrows(); } @Issue("JENKINS-37185") @Test - public void testCheckoutHonorTimeout() throws Exception { + void testCheckoutHonorTimeout() throws Exception { w = clone(localMirror()); checkoutTimeout = 1 + random.nextInt(60 * 24); @@ -223,15 +221,15 @@ public void testCheckoutHonorTimeout() throws Exception { } @Test - public void testSparseCheckout() throws Exception { + void testSparseCheckout() throws Exception { // Create a repo for cloning purpose w.init(); w.commitEmpty("init"); - assertTrue("mkdir dir1 failed", w.file("dir1").mkdir()); + assertTrue(w.file("dir1").mkdir(), "mkdir dir1 failed"); w.touch("dir1/file1"); - assertTrue("mkdir dir2 failed", w.file("dir2").mkdir()); + assertTrue(w.file("dir2").mkdir(), "mkdir dir2 failed"); w.touch("dir2/file2"); - assertTrue("mkdir dir3 failed", w.file("dir3").mkdir()); + assertTrue(w.file("dir3").mkdir(), "mkdir dir3 failed"); w.touch("dir3/file3"); w.git.add("dir1/file1"); w.git.add("dir2/file2"); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientCliCloneTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientCliCloneTest.java index 15291794fe..2186a7c7da 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientCliCloneTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientCliCloneTest.java @@ -6,7 +6,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.io.FileMatchers.aReadableFile; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import hudson.Util; import hudson.model.TaskListener; @@ -18,19 +18,19 @@ import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; -import org.junit.Before; -import org.junit.BeforeClass; -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.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.Issue; /* * Tests that are specific to command line git. */ -public class GitClientCliCloneTest { +class GitClientCliCloneTest { - @Rule - public GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); private final Random random = new Random(); private LogHandler handler = null; @@ -40,8 +40,8 @@ public class GitClientCliCloneTest { private GitClient testGitClient; - @BeforeClass - public static void loadLocalMirror() throws Exception { + @BeforeAll + static void loadLocalMirror() throws Exception { /* Prime the local mirror cache before other tests run */ TaskListener mirrorListener = StreamTaskListener.fromStdout(); File tempDir = Files.createTempDirectory("PrimeCliCloneTest").toFile(); @@ -50,8 +50,8 @@ public static void loadLocalMirror() throws Exception { Util.deleteRecursive(tempDir); } - @Before - public void setUpRepositories() throws Exception { + @BeforeEach + void setUpRepositories() throws Exception { Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + random.nextInt()); handler = new LogHandler(); handler.setLevel(Level.ALL); @@ -65,7 +65,7 @@ public void setUpRepositories() throws Exception { } @Test - public void test_checkout_default_timeout_logging() throws Exception { + void test_checkout_default_timeout_logging() throws Exception { testGitClient .clone_() .url(workspace.localMirror()) @@ -76,7 +76,7 @@ public void test_checkout_default_timeout_logging() throws Exception { } @Test - public void test_checkout_timeout_logging() throws Exception { + void test_checkout_timeout_logging() throws Exception { int largerTimeout = CliGitAPIImpl.TIMEOUT + 1 + random.nextInt(600); testGitClient .clone_() @@ -88,7 +88,7 @@ public void test_checkout_timeout_logging() throws Exception { } @Test - public void test_submodule_update_timeout_logging() throws Exception { + void test_submodule_update_timeout_logging() throws Exception { int largerTimeout = CliGitAPIImpl.TIMEOUT + 1 + random.nextInt(600); testGitClient .clone_() @@ -103,7 +103,7 @@ public void test_submodule_update_timeout_logging() throws Exception { @Issue("JENKINS-25353") @Test - public void test_checkout_interrupted() throws Exception { + void test_checkout_interrupted() throws Exception { testGitClient .clone_() .url(workspace.localMirror()) @@ -115,16 +115,16 @@ public void test_checkout_interrupted() throws Exception { /* Configure next checkout to fail with an exception */ CliGitAPIImpl cli = workspace.cgit(); cli.interruptNextCheckoutWithMessage(exceptionMsg); - Exception exception = assertThrows(InterruptedException.class, () -> { - cli.checkout().ref("6b7bbcb8f0e51668ddba349b683fb06b4bd9d0ea").execute(); // git-client-1.6.0 - }); + Exception exception = assertThrows(InterruptedException.class, () -> cli.checkout() + .ref("6b7bbcb8f0e51668ddba349b683fb06b4bd9d0ea") + .execute()); assertThat(exception.getMessage(), is(exceptionMsg)); // Except exact exception message returned assertThat("Lock file removed by checkout", lockFile, is(not(aReadableFile()))); } @Issue("JENKINS-25353") @Test - public void test_checkout_interrupted_with_existing_lock() throws Exception { + void test_checkout_interrupted_with_existing_lock() throws Exception { testGitClient .clone_() .url(workspace.localMirror()) @@ -139,9 +139,9 @@ public void test_checkout_interrupted_with_existing_lock() throws Exception { /* Configure next checkout to fail with an exception */ CliGitAPIImpl cli = workspace.cgit(); cli.interruptNextCheckoutWithMessage(exceptionMsg); - Exception exception = assertThrows(InterruptedException.class, () -> { - cli.checkout().ref("6b7bbcb8f0e51668ddba349b683fb06b4bd9d0ea").execute(); // git-client-1.6.0 - }); + Exception exception = assertThrows(InterruptedException.class, () -> cli.checkout() + .ref("6b7bbcb8f0e51668ddba349b683fb06b4bd9d0ea") + .execute()); assertThat(exception.getMessage(), containsString(exceptionMsg)); assertThat("Lock file removed by checkout", lockFile, is(aReadableFile())); } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientCloneTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientCloneTest.java index b4ed636237..b1a25c23ae 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientCloneTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientCloneTest.java @@ -1,6 +1,5 @@ package org.jenkinsci.plugins.gitclient; -import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; @@ -9,7 +8,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.io.FileMatchers.*; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import hudson.Util; import hudson.model.TaskListener; @@ -18,7 +17,6 @@ import hudson.remoting.VirtualChannel; import hudson.util.StreamTaskListener; import java.io.File; -import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; @@ -34,51 +32,51 @@ import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.RefSpec; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -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.api.extension.RegisterExtension; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -public class GitClientCloneTest { +@ParameterizedClass(name = "{0}") +@MethodSource("gitObjects") +class GitClientCloneTest { - @Rule - public GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); - @Rule - public GitClientSampleRepoRule secondRepo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule secondRepo = new GitClientSampleRepoRule(); private int logCount = 0; private final Random random = new Random(); private LogHandler handler = null; private TaskListener listener; - private final String gitImplName; - WorkspaceWithRepo workspace; - WorkspaceWithRepo secondWorkspace; + @Parameter(0) + private String gitImplName; + + private WorkspaceWithRepo workspace; + private WorkspaceWithRepo secondWorkspace; private GitClient testGitClient; private File testGitDir; - public GitClientCloneTest(final String gitImplName) { - this.gitImplName = gitImplName; - } - - @Parameterized.Parameters(name = "{0}") - public static Collection gitObjects() { - List arguments = new ArrayList<>(); + static List gitObjects() { + List arguments = new ArrayList<>(); String[] gitImplNames = {"git", "jgit", "jgitapache"}; for (String gitImplName : gitImplNames) { - Object[] item = {gitImplName}; + Arguments item = Arguments.of(gitImplName); arguments.add(item); } return arguments; } - @BeforeClass - public static void loadLocalMirror() throws Exception { + @BeforeAll + static void loadLocalMirror() throws Exception { /* Prime the local mirror cache before other tests run */ /* Allow 3-8 second delay before priming the cache */ /* Allow other tests a better chance to prime the cache */ @@ -92,8 +90,8 @@ public static void loadLocalMirror() throws Exception { Util.deleteRecursive(tempDir); } - @Before - public void setUpRepositories() throws Exception { + @BeforeEach + void setUpRepositories() throws Exception { Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++); handler = new LogHandler(); handler.setLevel(Level.ALL); @@ -118,7 +116,7 @@ public void setUpRepositories() throws Exception { * command line git program, but consistent within the git API. */ @Test - public void test_clone() throws Exception { + void test_clone() throws Exception { int cloneTimeout = CliGitAPIImpl.TIMEOUT + random.nextInt(60 * 24); CloneCommand cmd = testGitClient .clone_() @@ -138,7 +136,7 @@ public void test_clone() throws Exception { } @Test - public void test_checkout_exception() throws Exception { + void test_checkout_exception() throws Exception { CloneCommand cmd = testGitClient.clone_().url(workspace.localMirror()).repositoryName("origin"); if (random.nextBoolean()) { cmd.noCheckout(); // Randomly confirm this deprecated call is a no-op @@ -153,7 +151,7 @@ public void test_checkout_exception() throws Exception { } @Test - public void test_clone_repositoryName() throws Exception { + void test_clone_repositoryName() throws Exception { CloneCommand cmd = testGitClient.clone_().url(workspace.localMirror()).repositoryName("upstream"); if (random.nextBoolean()) { cmd.noCheckout(); // Randomly confirm this deprecated call is a no-op @@ -166,7 +164,7 @@ public void test_clone_repositoryName() throws Exception { } @Test - public void test_clone_shallow() throws Exception { + void test_clone_shallow() throws Exception { CloneCommand cmd = testGitClient .clone_() .url(workspace.localMirror()) @@ -186,7 +184,7 @@ public void test_clone_shallow() throws Exception { } @Test - public void test_clone_shallow_with_depth() throws Exception { + void test_clone_shallow_with_depth() throws Exception { testGitClient .clone_() .url(workspace.localMirror()) @@ -204,7 +202,7 @@ public void test_clone_shallow_with_depth() throws Exception { } @Test - public void test_clone_shared() throws Exception { + void test_clone_shared() throws Exception { testGitClient .clone_() .url(workspace.localMirror()) @@ -220,7 +218,7 @@ public void test_clone_shared() throws Exception { } @Test - public void test_clone_null_branch() throws Exception { + void test_clone_null_branch() throws Exception { testGitClient .clone_() .url(workspace.localMirror()) @@ -235,7 +233,7 @@ public void test_clone_null_branch() throws Exception { } @Test - public void test_clone_unshared() throws Exception { + void test_clone_unshared() throws Exception { testGitClient .clone_() .url(workspace.localMirror()) @@ -249,7 +247,7 @@ public void test_clone_unshared() throws Exception { } @Test - public void test_clone_reference() throws Exception { + void test_clone_reference() throws Exception { testGitClient .clone_() .url(workspace.localMirror()) @@ -272,7 +270,7 @@ public void test_clone_reference() throws Exception { private static final String SRC_DIR = (new File(".")).getAbsolutePath(); @Test - public void test_clone_reference_working_repo() throws Exception { + void test_clone_reference_working_repo() throws Exception { assertThat(new File(SRC_DIR + File.separator + ".git"), is(anExistingDirectory())); final File shallowFile = new File(SRC_DIR + File.separator + ".git" + File.separator + "shallow"); if (shallowFile.exists()) { @@ -299,7 +297,7 @@ public void test_clone_reference_working_repo() throws Exception { } @Test - public void test_clone_refspec() throws Exception { + void test_clone_refspec() throws Exception { testGitClient .clone_() .url(workspace.localMirror()) @@ -329,7 +327,7 @@ public void test_clone_refspec() throws Exception { } @Test - public void test_clone_refspecs() throws Exception { + void test_clone_refspecs() throws Exception { List refspecs = Arrays.asList( new RefSpec("+refs/heads/master:refs/remotes/origin/master"), new RefSpec("+refs/heads/1.4.x:refs/remotes/origin/1.4.x")); @@ -354,7 +352,7 @@ public void test_clone_refspecs() throws Exception { } @Test - public void test_getRemoteURL_local_clone() throws Exception { + void test_getRemoteURL_local_clone() throws Exception { workspace.cloneRepo(workspace, workspace.localMirror()); assertThat("Origin URL", testGitClient.getRemoteUrl("origin"), is(workspace.localMirror())); String remotes = workspace.launchCommand("git", "remote", "-v"); @@ -362,7 +360,7 @@ public void test_getRemoteURL_local_clone() throws Exception { } @Test - public void test_setRemoteURL_local_clone() throws Exception { + void test_setRemoteURL_local_clone() throws Exception { workspace.cloneRepo(workspace, workspace.localMirror()); String originURL = "https://github.com/jenkinsci/git-client-plugin.git"; testGitClient.setRemoteUrl("origin", originURL); @@ -372,7 +370,7 @@ public void test_setRemoteURL_local_clone() throws Exception { } @Test - public void test_addRemoteUrl_local_clone() throws Exception { + void test_addRemoteUrl_local_clone() throws Exception { workspace.cloneRepo(workspace, workspace.localMirror()); assertThat("Origin URL before add", testGitClient.getRemoteUrl("origin"), is(workspace.localMirror())); String upstreamURL = "https://github.com/jenkinsci/git-client-plugin.git"; @@ -382,7 +380,7 @@ public void test_addRemoteUrl_local_clone() throws Exception { } @Test - public void test_clone_default_timeout_logging() throws Exception { + void test_clone_default_timeout_logging() throws Exception { testGitClient .clone_() .url(workspace.localMirror()) @@ -392,7 +390,7 @@ public void test_clone_default_timeout_logging() throws Exception { } @Test - public void test_clone_timeout_logging() throws Exception { + void test_clone_timeout_logging() throws Exception { int largerTimeout = CliGitAPIImpl.TIMEOUT + 1 + random.nextInt(600); testGitClient .clone_() @@ -404,7 +402,7 @@ public void test_clone_timeout_logging() throws Exception { } @Test - public void test_max_timeout_logging() throws Exception { + void test_max_timeout_logging() throws Exception { int maxTimeout = JGitAPIImpl.MAX_TIMEOUT; testGitClient .clone_() @@ -416,7 +414,7 @@ public void test_max_timeout_logging() throws Exception { } @Test - public void test_clone_huge_timeout_logging() throws Exception { + void test_clone_huge_timeout_logging() throws Exception { int hugeTimeout = JGitAPIImpl.MAX_TIMEOUT + 1 + random.nextInt(Integer.MAX_VALUE - 1 - JGitAPIImpl.MAX_TIMEOUT); testGitClient .clone_() @@ -453,7 +451,7 @@ private void assertNoObjectsInRepository() { } } - private void assertAlternateFilePointsToLocalMirror() throws IOException, InterruptedException { + private void assertAlternateFilePointsToLocalMirror() throws Exception { final String alternates = ".git" + File.separator + "objects" + File.separator + "info" + File.separator + "alternates"; @@ -466,7 +464,7 @@ private void assertAlternateFilePointsToLocalMirror() throws IOException, Interr } private Collection getBranchNames(Collection branches) { - return branches.stream().map(Branch::getName).collect(toList()); + return branches.stream().map(Branch::getName).toList(); } private void assertBranchesExist(Set branches, String... names) { diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientFetchTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientFetchTest.java index f8631fef72..f2764ff8ea 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientFetchTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientFetchTest.java @@ -1,6 +1,5 @@ package org.jenkinsci.plugins.gitclient; -import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.contains; @@ -13,7 +12,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.io.FileMatchers.*; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import hudson.Util; import hudson.model.TaskListener; @@ -37,54 +36,54 @@ import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -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.api.extension.RegisterExtension; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; -@RunWith(Parameterized.class) -public class GitClientFetchTest { +@ParameterizedClass(name = "{0}") +@MethodSource("gitObjects") +class GitClientFetchTest { - @Rule - public GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule repo = new GitClientSampleRepoRule(); - @Rule - public GitClientSampleRepoRule secondRepo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule secondRepo = new GitClientSampleRepoRule(); - @Rule - public GitClientSampleRepoRule thirdRepo = new GitClientSampleRepoRule(); + @RegisterExtension + private final GitClientSampleRepoRule thirdRepo = new GitClientSampleRepoRule(); - WorkspaceWithRepo workspace; - WorkspaceWithRepo bareWorkspace; - WorkspaceWithRepo newAreaWorkspace; + private WorkspaceWithRepo workspace; + private WorkspaceWithRepo bareWorkspace; + private WorkspaceWithRepo newAreaWorkspace; private GitClient testGitClient; private File testGitDir; private CliGitCommand cliGitCommand; - private final String gitImplName; + + @Parameter(0) + private String gitImplName; private final Random random = new Random(); private LogHandler handler = null; private TaskListener listener; - @Parameterized.Parameters(name = "{0}") - public static Collection gitObjects() { - List arguments = new ArrayList<>(); + static List gitObjects() { + List arguments = new ArrayList<>(); String[] gitImplNames = {"git", "jgit", "jgitapache"}; for (String gitImplName : gitImplNames) { - Object[] item = {gitImplName}; + Arguments item = Arguments.of(gitImplName); arguments.add(item); } return arguments; } - public GitClientFetchTest(final String gitImplName) { - this.gitImplName = gitImplName; - } - /** * Default branch name in the upstream repository. */ @@ -101,8 +100,8 @@ public GitClientFetchTest(final String gitImplName) { * Git 2.32.0 honors the configuration variable `init.defaultBranch` and uses it for the name of the initial branch. * This method reads the global configuration and uses it to set the value of `defaultBranchName`. */ - @BeforeClass - public static void computeDefaultBranchName() throws Exception { + @BeforeAll + static void computeDefaultBranchName() throws Exception { File configDir = Files.createTempDirectory("readGitConfig").toFile(); CliGitCommand getDefaultBranchNameCmd = new CliGitCommand(Git.with(TaskListener.NULL, new hudson.EnvVars()) .in(configDir) @@ -118,8 +117,8 @@ public static void computeDefaultBranchName() throws Exception { assertThat("Failed to delete temporary readGitConfig directory", configDir.delete(), is(true)); } - @BeforeClass - public static void loadLocalMirror() throws Exception { + @BeforeAll + static void loadLocalMirror() throws Exception { /* Prime the local mirror cache before other tests run */ /* Allow 2-6 second delay before priming the cache */ /* Allow other tests a better chance to prime the cache */ @@ -133,8 +132,8 @@ public static void loadLocalMirror() throws Exception { Util.deleteRecursive(tempDir); } - @Before - public void setUpRepositories() throws Exception { + @BeforeEach + void setUpRepositories() throws Exception { Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + random.nextInt()); handler = new LogHandler(); handler.setLevel(Level.ALL); @@ -153,7 +152,7 @@ public void setUpRepositories() throws Exception { /* Workspace -> original repo, bareWorkspace -> bare repo and newAreaWorkspace -> newArea repo */ @Test - public void test_fetch() throws Exception { + void test_fetch() throws Exception { /* Create a working repo containing a commit */ workspace.touch(testGitDir, "file1", "file1 content " + UUID.randomUUID()); testGitClient.add("file1"); @@ -299,7 +298,7 @@ public void test_fetch() throws Exception { @Test @Issue("JENKINS-19591") - public void test_fetch_needs_preceding_prune() throws Exception { + void test_fetch_needs_preceding_prune() throws Exception { /* Create a working repo containing a commit */ workspace.touch(testGitDir, "file1", "file1 content " + UUID.randomUUID()); testGitClient.add("file1"); @@ -424,7 +423,7 @@ public void test_fetch_needs_preceding_prune() throws Exception { } @Test - public void test_prune_without_remote() { + void test_prune_without_remote() { /* Prune when a remote is not yet defined */ String expectedMessage = testGitClient instanceof CliGitAPIImpl ? "returned status code 1" : "The uri was empty or null"; @@ -442,7 +441,7 @@ public void test_prune_without_remote() { */ @Test @Issue("JENKINS-26197") - public void test_fetch_with_prune() throws Exception { + void test_fetch_with_prune() throws Exception { bareWorkspace = new WorkspaceWithRepo(secondRepo.getRoot(), gitImplName, TaskListener.NULL); bareWorkspace.initBareRepo(bareWorkspace.getGitClient(), true); /* Create a working repo containing three branches */ @@ -517,7 +516,7 @@ public void test_fetch_with_prune() throws Exception { } @Test - public void test_fetch_from_url() throws Exception { + void test_fetch_from_url() throws Exception { newAreaWorkspace = new WorkspaceWithRepo(thirdRepo.getRoot(), gitImplName, TaskListener.NULL); newAreaWorkspace.initializeWorkspace( "Vojtěch fetch from URL Zweibrücken-Šafařík", "email.by.git.fetch.test@example.com"); @@ -533,7 +532,7 @@ public void test_fetch_from_url() throws Exception { } @Test - public void test_fetch_shallow() throws Exception { + void test_fetch_shallow() throws Exception { testGitClient.setRemoteUrl("origin", workspace.localMirror()); testGitClient .fetch_() @@ -569,17 +568,17 @@ private void fetch_shallow_depth(Integer fetchDepth) throws Exception { } @Test - public void test_fetch_shallow_depth() throws Exception { + void test_fetch_shallow_depth() throws Exception { fetch_shallow_depth(2); } @Test - public void test_fetch_shallow_null_depth() throws Exception { + void test_fetch_shallow_null_depth() throws Exception { fetch_shallow_depth(null); } @Test - public void test_fetch_noTags() throws Exception { + void test_fetch_noTags() throws Exception { testGitClient.setRemoteUrl("origin", workspace.localMirror()); testGitClient .fetch_() @@ -599,7 +598,7 @@ public void test_fetch_noTags() throws Exception { * creates a branch with a random name. The later assertion checks that * the random branch name is not mentioned in a call to git rev-parse. */ - private String checkoutRandomBranch() throws GitException, InterruptedException { + private String checkoutRandomBranch() throws Exception { String branchName = "rev-parse-branch-" + UUID.randomUUID(); testGitClient.checkout().ref("origin/master").branch(branchName).execute(); Set branchNames = @@ -609,7 +608,7 @@ private String checkoutRandomBranch() throws GitException, InterruptedException } @Test - public void test_fetch_default_timeout_logging() throws Exception { + void test_fetch_default_timeout_logging() throws Exception { testGitClient .clone_() .url(workspace.localMirror()) @@ -628,16 +627,8 @@ private void check_remote_url(WorkspaceWithRepo workspace, GitClient gitClient, assertThat("remote URL has not been updated", remotes.contains(workspace.localMirror()), is(true)); } - private void assertExceptionMessageContains(GitException ge, String expectedSubstring) { - String actual = ge.getMessage().toLowerCase(); - assertThat( - "Expected '" + expectedSubstring + "' exception message, but was: " + actual, - actual.contains(expectedSubstring), - is(true)); - } - - private Collection getBranchNames(Collection branches) { - return branches.stream().map(Branch::getName).collect(toList()); + private List getBranchNames(Collection branches) { + return branches.stream().map(Branch::getName).toList(); } private void assertBranchesExist(Set branches, String... names) { diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientMaintenanceTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientMaintenanceTest.java index 678d1990c5..2253de754c 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientMaintenanceTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientMaintenanceTest.java @@ -21,7 +21,6 @@ import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.List; import java.util.Random; import java.util.UUID; @@ -30,26 +29,28 @@ import org.apache.commons.io.FileUtils; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterAll; +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; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Git client maintenance tests. * * @author Hrushikesh Rao */ -@RunWith(Parameterized.class) -public class GitClientMaintenanceTest { +@ParameterizedClass(name = "{0}") +@MethodSource("gitObjects") +class GitClientMaintenanceTest { /* Git implementation name, either "git", "jgit", or "jgitapache". */ - private final String gitImplName; + @Parameter(0) + private String gitImplName; /* Git client plugin repository directory. */ private static File srcRepoDir = null; @@ -59,25 +60,17 @@ public class GitClientMaintenanceTest { private final Random random = new Random(); - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - @Rule - public ErrorCollector collector = new ErrorCollector(); + @TempDir + private File tempFolder; private File repoRoot = null; private LogHandler handler; - public GitClientMaintenanceTest(final String gitImplName) throws IOException, InterruptedException { - this.gitImplName = gitImplName; - } - - @Parameterized.Parameters(name = "{0}") - public static Collection gitObjects() { - List arguments = new ArrayList<>(); + static List gitObjects() { + List arguments = new ArrayList<>(); String[] gitImplNames = {"git", "jgit", "jgitapache"}; for (String gitImplName : gitImplNames) { - Object[] item = {gitImplName}; + Arguments item = Arguments.of(gitImplName); arguments.add(item); } return arguments; @@ -89,8 +82,8 @@ public static Collection gitObjects() { */ private static File mirrorParent = null; - @BeforeClass - public static void mirrorUpstreamRepositoryLocally() throws Exception { + @BeforeAll + static void mirrorUpstreamRepositoryLocally() throws Exception { File currentDir = new File("."); CliGitAPIImpl currentDirCliGit = (CliGitAPIImpl) Git.with(TaskListener.NULL, new EnvVars()) .in(currentDir) @@ -134,8 +127,8 @@ public static void mirrorUpstreamRepositoryLocally() throws Exception { srcRepoDir = new File(mirrorParent, "git-client-plugin"); } - @AfterClass - public static void removeMirrorAndSrcRepos() throws Exception { + @AfterAll + static void removeMirrorAndSrcRepos() { try { FileUtils.deleteDirectory(mirrorParent); } catch (IOException ioe) { @@ -149,9 +142,9 @@ public static void removeMirrorAndSrcRepos() throws Exception { private boolean prefetchSupported = true; private boolean looseObjectsSupported = true; - @Before - public void setGitClient() throws Exception { - repoRoot = tempFolder.newFolder(); + @BeforeEach + void setGitClient() throws Exception { + repoRoot = newFolder(tempFolder, "junit"); handler = new LogHandler(); TaskListener listener = newListener(handler); gitClient = Git.with(listener, new EnvVars()) @@ -159,9 +152,9 @@ public void setGitClient() throws Exception { .using(gitImplName) .getClient(); File gitDir = gitClient.withRepository((repo, channel) -> repo.getDirectory()); - collector.checkThat("Premature " + gitDir, gitDir, is(not(anExistingDirectory()))); + assertThat("Premature " + gitDir, gitDir, is(not(anExistingDirectory()))); gitClient.init_().workspace(repoRoot.getAbsolutePath()).execute(); - collector.checkThat("Missing " + gitDir, gitDir, is(anExistingDirectory())); + assertThat("Missing " + gitDir, gitDir, is(anExistingDirectory())); gitClient.setRemoteUrl("origin", srcRepoDir.getAbsolutePath()); CliGitCommand gitCmd = new CliGitCommand(gitClient); gitCmd.initializeRepository( @@ -202,8 +195,7 @@ private TaskListener newListener(LogHandler handler) { logger.setUseParentHandlers(false); logger.addHandler(handler); logger.setLevel(Level.ALL); - TaskListener listener = new hudson.util.LogTaskListener(logger, Level.ALL); - return listener; + return new hudson.util.LogTaskListener(logger, Level.ALL); } private static final String COMMITTED_ONE_TEXT_FILE = "A maintenance file "; @@ -226,7 +218,7 @@ private ObjectId commitFile(final String path, final String content, final Strin gitClient.add(path); gitClient.commit(commitMessage); List headList = gitClient.revList(Constants.HEAD); - collector.checkThat(headList.size(), is(greaterThan(0))); + assertThat(headList.size(), is(greaterThan(0))); return headList.get(0); } @@ -251,7 +243,7 @@ private String getExpectedMessage(String maintenanceTask, boolean expectedResult } @Test - public void test_loose_objects_maintenance() throws Exception { + void test_loose_objects_maintenance() throws Exception { if (!looseObjectsSupported) { return; } @@ -260,12 +252,12 @@ public void test_loose_objects_maintenance() throws Exception { File objectsPath = new File(repoRoot.getAbsolutePath(), ".git/objects"); - String expectedDirList[] = {"info", "pack"}; + String[] expectedDirList = {"info", "pack"}; // Assert loose objects are in the objects directory - String looseObjects[] = objectsPath.list(); - collector.checkThat(Arrays.asList(looseObjects), hasItems(expectedDirList)); - collector.checkThat( + String[] looseObjects = objectsPath.list(); + assertThat(Arrays.asList(looseObjects), hasItems(expectedDirList)); + assertThat( "Missing expected loose objects in objects dir, only found " + String.join(",", looseObjects), looseObjects.length, is(greaterThan(2))); // Initially loose objects are present @@ -273,7 +265,7 @@ public void test_loose_objects_maintenance() throws Exception { // Run the loose objects maintenance task, will create loose-objects pack file boolean isExecuted = gitClient.maintenance("loose-objects"); // Check if maintenance has executed successfully. - collector.checkThat(isExecuted, is(true)); + assertThat(isExecuted, is(true)); // Confirm loose-object pack file is present in the pack directory File looseObjectPackFilePath = new File(objectsPath.getAbsolutePath(), "pack"); @@ -281,78 +273,86 @@ public void test_loose_objects_maintenance() throws Exception { // CLI git 2.41 adds a new ".rev" suffixed file that is ignored in these assertions List fileNames = Arrays.asList(looseObjectPackFile); List requiredSuffixes = Arrays.asList(".idx", ".pack"); - requiredSuffixes.forEach(expected -> collector.checkThat(fileNames, hasItem(endsWith(expected)))); + requiredSuffixes.forEach(expected -> assertThat(fileNames, hasItem(endsWith(expected)))); // Clean the loose objects present in the repo. isExecuted = gitClient.maintenance("loose-objects"); // Assert that loose objects are no longer in the objects directory - collector.checkThat(objectsPath.list(), is(arrayContainingInAnyOrder(expectedDirList))); + assertThat(objectsPath.list(), is(arrayContainingInAnyOrder(expectedDirList))); - collector.checkThat(isExecuted, is(true)); + assertThat(isExecuted, is(true)); } @Test - public void test_incremental_repack_maintenance() throws Exception { + void test_incremental_repack_maintenance() throws Exception { String maintenanceTask = "incremental-repack"; commitSeveralFiles(); // Run incremental repack maintenance task // Need to create pack files to use incremental repack - collector.checkThat( - gitClient.maintenance("gc"), is(!gitImplName.startsWith("jgit"))); // No gc on JGit maintenance + assertThat(gitClient.maintenance("gc"), is(!gitImplName.startsWith("jgit"))); // No gc on JGit maintenance - collector.checkThat(gitClient.maintenance(maintenanceTask), is(incrementalRepackSupported)); + assertThat(gitClient.maintenance(maintenanceTask), is(incrementalRepackSupported)); String expectedMessage = getExpectedMessage(maintenanceTask, incrementalRepackSupported); - collector.checkThat(handler.getMessages(), hasItem(startsWith(expectedMessage))); + assertThat(handler.getMessages(), hasItem(startsWith(expectedMessage))); } @Test - public void test_commit_graph_maintenance() throws Exception { + void test_commit_graph_maintenance() throws Exception { String maintenanceTask = "commit-graph"; commitSeveralFiles(); - collector.checkThat(gitClient.maintenance(maintenanceTask), is(commitGraphSupported)); + assertThat(gitClient.maintenance(maintenanceTask), is(commitGraphSupported)); String expectedMessage = getExpectedMessage(maintenanceTask, commitGraphSupported); - collector.checkThat(handler.getMessages(), hasItem(startsWith(expectedMessage))); + assertThat(handler.getMessages(), hasItem(startsWith(expectedMessage))); } @Test - public void test_gc_maintenance() throws Exception { + void test_gc_maintenance() throws Exception { String maintenanceTask = "gc"; commitSeveralFiles(); - collector.checkThat(gitClient.maintenance("gc"), is(garbageCollectionSupported)); + assertThat(gitClient.maintenance("gc"), is(garbageCollectionSupported)); String expectedMessage = getExpectedMessage(maintenanceTask, garbageCollectionSupported); - collector.checkThat(handler.getMessages(), hasItem(startsWith(expectedMessage))); + assertThat(handler.getMessages(), hasItem(startsWith(expectedMessage))); } @Test - public void test_prefetch_maintenance() throws Exception { + void test_prefetch_maintenance() throws Exception { String maintenanceTask = "prefetch"; - collector.checkThat(gitClient.maintenance("prefetch"), is(prefetchSupported)); + assertThat(gitClient.maintenance("prefetch"), is(prefetchSupported)); String expectedMessage = getExpectedMessage(maintenanceTask, prefetchSupported); - collector.checkThat(handler.getMessages(), hasItem(startsWith(expectedMessage))); + assertThat(handler.getMessages(), hasItem(startsWith(expectedMessage))); } @Test - public void test_error_reported_by_invalid_maintenance_task() throws Exception { + void test_error_reported_by_invalid_maintenance_task() throws Exception { String maintenanceTask = "invalid-maintenance-task"; // Should always fail to execute - collector.checkThat(gitClient.maintenance(maintenanceTask), is(false)); + assertThat(gitClient.maintenance(maintenanceTask), is(false)); String expectedMessage = gitImplName.startsWith("jgit") ? "JGIT doesn't support git maintenance. Use CLIGIT to execute maintenance tasks." : "Error executing invalid-maintenance-task maintenance task"; - collector.checkThat(handler.getMessages(), hasItem(expectedMessage)); + assertThat(handler.getMessages(), hasItem(expectedMessage)); + } + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientSampleRepoRule.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientSampleRepoRule.java index 588b3b0979..48ebd8a297 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientSampleRepoRule.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientSampleRepoRule.java @@ -23,27 +23,18 @@ */ package org.jenkinsci.plugins.gitclient; -import hudson.Launcher; -import hudson.model.TaskListener; -import hudson.util.StreamTaskListener; -import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; import jenkins.scm.impl.mock.AbstractSampleDVCSRepoRule; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.RepositoryBuilder; -import org.htmlunit.WebResponse; -import org.htmlunit.util.NameValuePair; -import org.jvnet.hudson.test.JenkinsRule; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionConfigurationException; +import org.junit.jupiter.api.extension.ExtensionContext; /** * Manages a sample Git repository. */ -public final class GitClientSampleRepoRule extends AbstractSampleDVCSRepoRule { - - private static final Logger LOGGER = Logger.getLogger(GitClientSampleRepoRule.class.getName()); +public class GitClientSampleRepoRule extends AbstractSampleDVCSRepoRule + implements BeforeEachCallback, AfterEachCallback { public void git(String... cmds) throws Exception { run("git", cmds); @@ -60,85 +51,21 @@ public void init() throws Exception { git("commit", "--message=init"); } - public boolean mkdirs(String rel) { - return new File(this.sampleRepo, rel).mkdirs(); - } - - public void notifyCommit(JenkinsRule r) throws Exception { - synchronousPolling(r); - WebResponse webResponse = r.createWebClient() - .goTo("git/notifyCommit?url=" + bareUrl(), "text/plain") - .getWebResponse(); - LOGGER.log(Level.FINE, webResponse.getContentAsString()); - for (NameValuePair pair : webResponse.getResponseHeaders()) { - if (pair.getName().equals("Triggered")) { - LOGGER.log(Level.FINE, "Triggered: " + pair.getValue()); - } - } - r.waitUntilNoActivity(); - } - - public String head() throws Exception { - return new RepositoryBuilder() - .setWorkTree(sampleRepo) - .build() - .resolve(Constants.HEAD) - .name(); - } - public File getRoot() { return this.sampleRepo; } - public boolean gitVersionAtLeast(int neededMajor, int neededMinor) { - return gitVersionAtLeast(neededMajor, neededMinor, 0); - } - - public boolean gitVersionAtLeast(int neededMajor, int neededMinor, int neededPatch) { - final TaskListener procListener = StreamTaskListener.fromStderr(); - final ByteArrayOutputStream out = new ByteArrayOutputStream(); + @Override + public void beforeEach(ExtensionContext context) { try { - int returnCode = new Launcher.LocalLauncher(procListener) - .launch() - .cmds("git", "--version") - .stdout(out) - .join(); - if (returnCode != 0) { - LOGGER.log(Level.WARNING, "Command 'git --version' returned " + returnCode); - } - } catch (IOException | InterruptedException ex) { - LOGGER.log(Level.WARNING, "Exception checking git version " + ex); - } - final String versionOutput = out.toString().trim(); - final String[] fields = versionOutput - .split(" ")[2] - .replaceAll("msysgit.", "") - .replaceAll("windows.", "") - .split("\\."); - final int gitMajor = Integer.parseInt(fields[0]); - final int gitMinor = Integer.parseInt(fields[1]); - final int gitPatch = Integer.parseInt(fields[2]); - if (gitMajor < 1 || gitMajor > 3) { - LOGGER.log( - Level.WARNING, - "Unexpected git major version " + gitMajor + " parsed from '" + versionOutput + "', field:'" - + fields[0] + "'"); - } - if (gitMinor < 0 || gitMinor > 50) { - LOGGER.log( - Level.WARNING, - "Unexpected git minor version " + gitMinor + " parsed from '" + versionOutput + "', field:'" - + fields[1] + "'"); - } - if (gitPatch < 0 || gitPatch > 20) { - LOGGER.log( - Level.WARNING, - "Unexpected git patch version " + gitPatch + " parsed from '" + versionOutput + "', field:'" - + fields[2] + "'"); + this.before(); + } catch (Throwable t) { + throw new ExtensionConfigurationException(t.getMessage(), t); } + } - return gitMajor > neededMajor - || (gitMajor == neededMajor && gitMinor > neededMinor) - || (gitMajor == neededMajor && gitMinor == neededMinor && gitPatch >= neededPatch); + @Override + public void afterEach(ExtensionContext context) { + this.after(); } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientSecurityTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientSecurityTest.java index 304090441c..85a2830f4b 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientSecurityTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientSecurityTest.java @@ -2,30 +2,29 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitException; import java.io.File; +import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Random; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.URIish; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterAll; +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.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; /** @@ -33,13 +32,16 @@ * * @author Mark Waite */ -@RunWith(Parameterized.class) -public class GitClientSecurityTest { +@ParameterizedClass(name = "{1},{0}") +@MethodSource("testConfiguration") +class GitClientSecurityTest { /* Test parameter - remote URL that is expected to fail with known exception */ - private final String badRemoteUrl; + @Parameter(0) + private String badRemoteUrl; /* Test parameter - should remote URL check be enabled */ - private final boolean enableRemoteCheckUrl; + @Parameter(1) + private boolean enableRemoteCheckUrl; /* Git client plugin repository directory. */ private static final File SRC_REPO_DIR = new File(".git"); @@ -52,16 +54,11 @@ public class GitClientSecurityTest { private static final String DEFAULT_BRANCH_NAME = "master"; - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; private File repoRoot = null; - public GitClientSecurityTest(final String badRemoteUrl, final boolean enableRemoteCheckUrl) { - this.badRemoteUrl = badRemoteUrl; - this.enableRemoteCheckUrl = enableRemoteCheckUrl; - } - static { CliGitAPIImpl tempGitClient; try { @@ -106,10 +103,9 @@ private static boolean enableRemoteCheck(String attack) { return enabled; } - @Parameterized.Parameters(name = "{1},{0}") - public static Collection testConfiguration() { + static List testConfiguration() { markerFileName = markerFileName.formatted(CONFIG_RANDOM.nextInt()); // Unique enough file name - List arguments = new ArrayList<>(); + List arguments = new ArrayList<>(); for (String prefix : BAD_REMOTE_URL_PREFIXES) { /* insert markerFileName into test data */ String formattedPrefix = prefix.formatted(markerFileName); @@ -120,50 +116,50 @@ public static Collection testConfiguration() { String lastChar = CONFIG_RANDOM.nextBoolean() ? " " : ""; int remoteIndex = CONFIG_RANDOM.nextInt(VALID_REMOTES.length); String remoteUrl = firstChar + formattedPrefix + middleChar + VALID_REMOTES[remoteIndex] + lastChar; - Object[] remoteUrlItem = {remoteUrl, enableRemoteCheck(formattedPrefix)}; + Arguments remoteUrlItem = Arguments.of(remoteUrl, enableRemoteCheck(formattedPrefix)); arguments.add(remoteUrlItem); /* Random remote URL with prefix separated by a space */ remoteIndex = CONFIG_RANDOM.nextInt(VALID_REMOTES.length); remoteUrl = formattedPrefix + " " + VALID_REMOTES[remoteIndex]; - Object[] remoteUrlItemOneSpace = {remoteUrl, enableRemoteCheck(formattedPrefix)}; + Arguments remoteUrlItemOneSpace = Arguments.of(remoteUrl, enableRemoteCheck(formattedPrefix)); arguments.add(remoteUrlItemOneSpace); /* Random remote URL with prefix and no separator */ remoteIndex = CONFIG_RANDOM.nextInt(VALID_REMOTES.length); remoteUrl = formattedPrefix + VALID_REMOTES[remoteIndex]; - Object[] noSpaceItem = {remoteUrl, enableRemoteCheck(formattedPrefix)}; + Arguments noSpaceItem = Arguments.of(remoteUrl, enableRemoteCheck(formattedPrefix)); arguments.add(noSpaceItem); /* Remote URL with only the prefix */ - Object[] prefixItem = {formattedPrefix, enableRemoteCheck(formattedPrefix)}; + Arguments prefixItem = Arguments.of(formattedPrefix, enableRemoteCheck(formattedPrefix)); arguments.add(prefixItem); } Collections.shuffle(arguments); return arguments.subList(0, 25); } - @AfterClass - public static void resetRemoteCheckUrl() { + @AfterAll + static void resetRemoteCheckUrl() { org.jenkinsci.plugins.gitclient.CliGitAPIImpl.CHECK_REMOTE_URL = true; } - @Before - public void setRemoteCheckUrl() { + @BeforeEach + void setRemoteCheckUrl() { org.jenkinsci.plugins.gitclient.CliGitAPIImpl.CHECK_REMOTE_URL = enableRemoteCheckUrl; } - @Before - public void setGitClient() throws Exception { - repoRoot = tempFolder.newFolder(); + @BeforeEach + void setGitClient() throws Exception { + repoRoot = newFolder(tempFolder, "junit"); gitClient = Git.with(TaskListener.NULL, new EnvVars()) .in(repoRoot) .using("git") .getClient(); File gitDir = gitClient.getRepository().getDirectory(); - assertFalse("Already found " + gitDir, gitDir.isDirectory()); + assertFalse(gitDir.isDirectory(), "Already found " + gitDir); gitClient.init_().workspace(repoRoot.getAbsolutePath()).execute(); - assertTrue("Missing " + gitDir, gitDir.isDirectory()); + assertTrue(gitDir.isDirectory(), "Missing " + gitDir); gitClient.setRemoteUrl("origin", SRC_REPO_DIR.getAbsolutePath()); } @@ -229,24 +225,24 @@ public void setGitClient() throws Exception { "origin" }; - @Before - public void removeMarkerFile() throws Exception { + @BeforeEach + void removeMarkerFile() throws Exception { File markerFile = new File(markerFileName); Files.deleteIfExists(markerFile.toPath()); } - @After - public void checkMarkerFile() { + @AfterEach + void checkMarkerFile() { if (enableRemoteCheckUrl) { /* If remote checking is disabled, marker file is expected in several cases */ File markerFile = new File(markerFileName); - assertFalse("Marker file '" + markerFileName + "' detected after test", markerFile.exists()); + assertFalse(markerFile.exists(), "Marker file '" + markerFileName + "' detected after test"); } } @Test @Issue("SECURITY-1534") - public void testGetHeadRev_String_SECURITY_1534() { + void testGetHeadRev_String_SECURITY_1534() { String expectedMessage = enableRemoteCheckUrl ? "Invalid remote URL: " + badRemoteUrl : badRemoteUrl.trim(); GitException e = assertThrows(GitException.class, () -> gitClient.getHeadRev(badRemoteUrl)); assertThat(e.getMessage(), containsString(expectedMessage)); @@ -254,7 +250,7 @@ public void testGetHeadRev_String_SECURITY_1534() { @Test @Issue("SECURITY-1534") - public void testGetHeadRev_String_String_SECURITY_1534() { + void testGetHeadRev_String_String_SECURITY_1534() { String expectedMessage = enableRemoteCheckUrl ? "Invalid remote URL: " + badRemoteUrl : badRemoteUrl.trim(); GitException e = assertThrows(GitException.class, () -> gitClient.getHeadRev(badRemoteUrl, DEFAULT_BRANCH_NAME)); @@ -263,7 +259,7 @@ public void testGetHeadRev_String_String_SECURITY_1534() { @Test @Issue("SECURITY-1534") - public void testGetRemoteReferences_SECURITY_1534() { + void testGetRemoteReferences_SECURITY_1534() { boolean headsOnly = random.nextBoolean(); boolean tagsOnly = random.nextBoolean(); String expectedMessage = enableRemoteCheckUrl ? "Invalid remote URL: " + badRemoteUrl : badRemoteUrl.trim(); @@ -275,7 +271,7 @@ public void testGetRemoteReferences_SECURITY_1534() { @Test @Issue("SECURITY-1534") - public void testGetRemoteSymbolicReferences_SECURITY_1534() { + void testGetRemoteSymbolicReferences_SECURITY_1534() { String expectedMessage = enableRemoteCheckUrl ? "Invalid remote URL: " + badRemoteUrl : badRemoteUrl.trim(); GitException e = assertThrows( GitException.class, () -> gitClient.getRemoteSymbolicReferences(badRemoteUrl, DEFAULT_BRANCH_NAME)); @@ -284,7 +280,7 @@ public void testGetRemoteSymbolicReferences_SECURITY_1534() { @Test @Issue("SECURITY-1534") - public void testFetch_URIish_SECURITY_1534() throws Exception { + void testFetch_URIish_SECURITY_1534() throws Exception { String refSpecString = "+refs/heads/*:refs/remotes/origin/*"; List refSpecs = new ArrayList<>(); RefSpec refSpec = new RefSpec(refSpecString); @@ -300,7 +296,7 @@ public void testFetch_URIish_SECURITY_1534() throws Exception { @Test @Issue("SECURITY-1534") - public void testFetch_String_SECURITY_1534() throws Exception { + void testFetch_String_SECURITY_1534() throws Exception { RefSpec refSpec = new RefSpec("+refs/heads/*:refs/remotes/origin/*"); gitClient.setRemoteUrl("origin", badRemoteUrl); GitException e = assertThrows(GitException.class, () -> gitClient.fetch("origin", refSpec)); @@ -311,7 +307,7 @@ public void testFetch_String_SECURITY_1534() throws Exception { @Test @Issue("SECURITY-1534") - public void testFetch_String_RefSpec_SECURITY_1534() throws Exception { + void testFetch_String_RefSpec_SECURITY_1534() throws Exception { RefSpec refSpec = new RefSpec("+refs/heads/*:refs/remotes/origin/*"); gitClient.setRemoteUrl("origin", badRemoteUrl); GitException e = assertThrows(GitException.class, () -> gitClient.fetch("origin", refSpec, refSpec, refSpec)); @@ -319,4 +315,13 @@ public void testFetch_String_RefSpec_SECURITY_1534() throws Exception { assertThat(e.getMessage(), containsString("Invalid remote URL: " + badRemoteUrl.trim())); } } + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientTest.java index 7fc5e22140..7ed538c815 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitClientTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitClientTest.java @@ -14,13 +14,9 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.io.FileMatchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -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 static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; @@ -43,11 +39,8 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; @@ -62,14 +55,16 @@ import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.URIish; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.CleanupMode; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; /** @@ -78,11 +73,13 @@ * * @author Mark Waite */ -@RunWith(Parameterized.class) -public class GitClientTest { +@ParameterizedClass(name = "{0}") +@MethodSource("gitObjects") +class GitClientTest { /* Git implementation name, either "git", "jgit", or "jgitapache". */ - private final String gitImplName; + @Parameter(0) + private String gitImplName; /* Git client plugin repository directory. */ private static File srcRepoDir = null; @@ -106,76 +103,23 @@ public class GitClientTest { private GitClient gitClient = null; /* Instance of object of another test class*/ - private CliGitAPIImplTest cliGitAPIImplTest = new CliGitAPIImplTest(); + private final CliGitAPIImplTest cliGitAPIImplTest = new CliGitAPIImplTest(); /* Capabilities of command line git in current environment */ - private final boolean CLI_GIT_HAS_GIT_LFS; - private final boolean CLI_GIT_HAS_GIT_LFS_CONFIGURED; - private final boolean LFS_SUPPORTS_SPARSE_CHECKOUT; + private boolean CLI_GIT_HAS_GIT_LFS; + private boolean CLI_GIT_HAS_GIT_LFS_CONFIGURED; + private boolean LFS_SUPPORTS_SPARSE_CHECKOUT; - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir(cleanup = CleanupMode.NEVER) + private File tempFolder; private File repoRoot = null; - public GitClientTest(final String gitImplName) throws Exception { - this.gitImplName = gitImplName; - this.srcGitClient = Git.with(TaskListener.NULL, new EnvVars()) - .in(srcRepoDir) - .using(gitImplName) - .getClient(); - - CliGitAPIImpl cliGitClient; - if (this.srcGitClient instanceof CliGitAPIImpl impl) { - cliGitClient = impl; - } else { - cliGitClient = (CliGitAPIImpl) Git.with(TaskListener.NULL, new EnvVars()) - .in(srcRepoDir) - .using("git") - .getClient(); - } - - boolean gitLFSExists; - boolean gitSparseCheckoutWithLFS; - try { - // If git-lfs is installed then the version string should look like this: - // git-lfs/1.5.6 (GitHub; linux amd64; go 1.7.4) - String lfsVersionOutput = - cliGitClient.launchCommand("lfs", "version").trim(); - gitLFSExists = lfsVersionOutput.startsWith("git-lfs"); - gitSparseCheckoutWithLFS = - lfsVersionOutput.matches("git-lfs/[3-9][.].*|git-lfs/2[.]1[0-9].*|git-lfs/2[.][89].*"); - // Avoid test failures on ci.jenkins.io agents by calling `git lfs install` - // Intentionally ignores the return value, assumes that failure will throw an exception - // and disable the git LFS tests - cliGitClient.launchCommand("lfs", "install"); - } catch (GitException exception) { - // This is expected when git-lfs is not installed. - gitLFSExists = false; - gitSparseCheckoutWithLFS = false; - } - CLI_GIT_HAS_GIT_LFS = gitLFSExists; - - boolean gitLFSConfigured; - try { - // If git-lfs is configured then the smudge filter will not be empty - gitLFSConfigured = - cliGitClient.launchCommand("config", "filter.lfs.smudge").contains("git-lfs"); - } catch (GitException exception) { - // This is expected when git-lfs is not installed. - gitLFSConfigured = false; - } - CLI_GIT_HAS_GIT_LFS_CONFIGURED = gitLFSConfigured; - LFS_SUPPORTS_SPARSE_CHECKOUT = - CLI_GIT_HAS_GIT_LFS_CONFIGURED && gitSparseCheckoutWithLFS && cliGitClient.isAtLeastVersion(2, 0, 0, 0); - } - - @Parameterized.Parameters(name = "{0}") - public static Collection gitObjects() { - List arguments = new ArrayList<>(); + static List gitObjects() { + List arguments = new ArrayList<>(); String[] gitImplNames = {"git", "jgit", "jgitapache"}; for (String gitImplName : gitImplNames) { - Object[] item = {gitImplName}; + Arguments item = Arguments.of(gitImplName); arguments.add(item); } return arguments; @@ -187,8 +131,8 @@ public static Collection gitObjects() { */ private static File mirrorParent = null; - @BeforeClass - public static void mirrorUpstreamRepositoryLocally() throws Exception { + @BeforeAll + static void mirrorUpstreamRepositoryLocally() throws Exception { File currentDir = new File("."); CliGitAPIImpl currentDirCliGit = (CliGitAPIImpl) Git.with(TaskListener.NULL, new EnvVars()) .in(currentDir) @@ -217,7 +161,7 @@ public static void mirrorUpstreamRepositoryLocally() throws Exception { "https://github.com/jenkinsci/git-client-plugin"); } File mirrorDir = new File(mirrorParent, "git-client-plugin.git"); - assertTrue("Git client mirror repo not created at " + mirrorDir.getAbsolutePath(), mirrorDir.exists()); + assertTrue(mirrorDir.exists(), "Git client mirror repo not created at " + mirrorDir.getAbsolutePath()); GitClient mirrorClient = Git.with(TaskListener.NULL, new EnvVars()) .in(mirrorDir) .using("git") @@ -240,8 +184,8 @@ public static void mirrorUpstreamRepositoryLocally() throws Exception { * Git 2.32.0 honors the configuration variable `init.defaultBranch` and uses it for the name of the initial branch. * This method reads the global configuration and uses it to set the value of `defaultBranchName`. */ - @BeforeClass - public static void computeDefaultBranchName() throws Exception { + @BeforeAll + static void computeDefaultBranchName() throws Exception { File configDir = Files.createTempDirectory("readGitConfig").toFile(); CliGitCommand getDefaultBranchNameCmd = new CliGitCommand(Git.with(TaskListener.NULL, new EnvVars()) .in(configDir) @@ -250,15 +194,15 @@ public static void computeDefaultBranchName() throws Exception { String[] output = getDefaultBranchNameCmd.runWithoutAssert("config", "--get", "init.defaultBranch"); for (String s : output) { String result = s.trim(); - if (result != null && !result.isEmpty()) { + if (!result.isEmpty()) { defaultBranchName = result; } } - assertTrue("Failed to delete temporary readGitConfig directory", configDir.delete()); + assertTrue(configDir.delete(), "Failed to delete temporary readGitConfig directory"); } - @BeforeClass - public static void addLocalGitConfigChanges() throws Exception { + @BeforeAll + static void addLocalGitConfigChanges() throws Exception { File currentDir = new File("."); CliGitAPIImpl currentDirCliGit = (CliGitAPIImpl) Git.with(TaskListener.NULL, new EnvVars()) .in(currentDir) @@ -268,8 +212,8 @@ public static void addLocalGitConfigChanges() throws Exception { gitCmd.initializeRepository(); } - @AfterClass - public static void removeLocalGitConfigChanges() throws Exception { + @AfterAll + static void removeLocalGitConfigChanges() throws Exception { File currentDir = new File("."); CliGitAPIImpl currentDirCliGit = (CliGitAPIImpl) Git.with(TaskListener.NULL, new EnvVars()) .in(currentDir) @@ -279,8 +223,8 @@ public static void removeLocalGitConfigChanges() throws Exception { gitCmd.removeRepositorySettings(); } - @AfterClass - public static void removeMirrorAndSrcRepos() throws Exception { + @AfterAll + static void removeMirrorAndSrcRepos() { try { FileUtils.deleteDirectory(mirrorParent); } catch (IOException ioe) { @@ -288,20 +232,69 @@ public static void removeMirrorAndSrcRepos() throws Exception { } } - @Before - public void setGitClient() throws Exception { - repoRoot = tempFolder.newFolder(); + @BeforeEach + void setGitClient() throws Exception { + repoRoot = newFolder(tempFolder, "junit-" + System.nanoTime()); gitClient = Git.with(TaskListener.NULL, new EnvVars()) .in(repoRoot) .using(gitImplName) .getClient(); File gitDir = gitClient.withRepository((repo, channel) -> repo.getDirectory()); - assertFalse("Already found " + gitDir, gitDir.isDirectory()); + assertFalse(gitDir.isDirectory(), "Already found " + gitDir); gitClient.init_().workspace(repoRoot.getAbsolutePath()).execute(); - assertTrue("Missing " + gitDir, gitDir.isDirectory()); + assertTrue(gitDir.isDirectory(), "Missing " + gitDir); gitClient.setRemoteUrl("origin", srcRepoDir.getAbsolutePath()); CliGitCommand gitCmd = new CliGitCommand(gitClient); gitCmd.initializeRepository("Vojtěch GitClientTest Zweibrücken-Šafařík", "email.from.git.client@example.com"); + + this.srcGitClient = Git.with(TaskListener.NULL, new EnvVars()) + .in(srcRepoDir) + .using(gitImplName) + .getClient(); + + CliGitAPIImpl cliGitClient; + if (this.srcGitClient instanceof CliGitAPIImpl impl) { + cliGitClient = impl; + } else { + cliGitClient = (CliGitAPIImpl) Git.with(TaskListener.NULL, new EnvVars()) + .in(srcRepoDir) + .using("git") + .getClient(); + } + + boolean gitLFSExists; + boolean gitSparseCheckoutWithLFS; + try { + // If git-lfs is installed then the version string should look like this: + // git-lfs/1.5.6 (GitHub; linux amd64; go 1.7.4) + String lfsVersionOutput = + cliGitClient.launchCommand("lfs", "version").trim(); + gitLFSExists = lfsVersionOutput.startsWith("git-lfs"); + gitSparseCheckoutWithLFS = + lfsVersionOutput.matches("git-lfs/[3-9][.].*|git-lfs/2[.]1[0-9].*|git-lfs/2[.][89].*"); + // Avoid test failures on ci.jenkins.io agents by calling `git lfs install` + // Intentionally ignores the return value, assumes that failure will throw an exception + // and disable the git LFS tests + cliGitClient.launchCommand("lfs", "install"); + } catch (GitException exception) { + // This is expected when git-lfs is not installed. + gitLFSExists = false; + gitSparseCheckoutWithLFS = false; + } + CLI_GIT_HAS_GIT_LFS = gitLFSExists; + + boolean gitLFSConfigured; + try { + // If git-lfs is configured then the smudge filter will not be empty + gitLFSConfigured = + cliGitClient.launchCommand("config", "filter.lfs.smudge").contains("git-lfs"); + } catch (GitException exception) { + // This is expected when git-lfs is not installed. + gitLFSConfigured = false; + } + CLI_GIT_HAS_GIT_LFS_CONFIGURED = gitLFSConfigured; + LFS_SUPPORTS_SPARSE_CHECKOUT = + CLI_GIT_HAS_GIT_LFS_CONFIGURED && gitSparseCheckoutWithLFS && cliGitClient.isAtLeastVersion(2, 0, 0, 0); } /** @@ -314,7 +307,7 @@ public void setGitClient() throws Exception { * The change resolves a security issue but that security issue is * not a threat to these tests. */ - private void allowFileProtocol(GitClient client) throws Exception { + private void allowFileProtocol(GitClient client) { if (client instanceof CliGitAPIImpl cliGit) { cliGit.allowFileProtocol(); } @@ -385,7 +378,7 @@ private String randomEmail(String name) { */ @Test @Issue("JENKINS-29977") - public void testChangelogVeryLong() throws Exception { + void testChangelogVeryLong() throws Exception { final String gitMessage = """ @@ -412,9 +405,10 @@ public void testChangelogVeryLong() throws Exception { assertThat(changelogStringWriter.toString(), containsString("conubia nostra")); } + // Diagnostics of ChangelogCommand were insufficient @Test - @Issue("JENKINS-39832") // Diagnostics of ChangelogCommand were insufficient - public void testChangelogExceptionMessage() throws Exception { + @Issue("JENKINS-39832") + void testChangelogExceptionMessage() throws Exception { final ObjectId commitA = commitOneFile(); ChangelogCommand changelog = gitClient.changelog(); StringWriter changelogStringWriter = new StringWriter(); @@ -475,7 +469,7 @@ public void testChangelogExceptionMessage() throws Exception { } @Test - public void testNullChangelogDestinationIncludes() throws Exception { + void testNullChangelogDestinationIncludes() throws Exception { final ObjectId commitA = commitOneFile(); ChangelogCommand changelog = gitClient.changelog(); changelog.includes(commitA); @@ -483,7 +477,7 @@ public void testNullChangelogDestinationIncludes() throws Exception { } @Test - public void testNullChangelogDestinationExcludes() throws Exception { + void testNullChangelogDestinationExcludes() throws Exception { final ObjectId commitA = commitOneFile(); ChangelogCommand changelog = gitClient.changelog(); changelog.excludes(commitA); @@ -492,7 +486,7 @@ public void testNullChangelogDestinationExcludes() throws Exception { @Test @Issue("JENKINS-43198") - public void testCleanSubdirGitignore() throws Exception { + void testCleanSubdirGitignore() throws Exception { final String filename1 = "this_is/not_ok/more/subdirs/file.txt"; final String filename2 = "this_is_also/not_ok_either/more/subdirs/file.txt"; commitFile(".gitignore", "/this_is/not_ok\n/this_is_also/not_ok_either\n", "set up gitignore"); @@ -507,7 +501,7 @@ public void testCleanSubdirGitignore() throws Exception { @Test @Issue("JENKINS-37794") - public void tagWithSlashes() throws Exception { + void tagWithSlashes() throws Exception { commitOneFile(); gitClient.tag("has/a/slash", "This tag has a slash ('/')"); assertThat(gitClient.getTagMessage("has/a/slash"), is("This tag has a slash ('/')")); @@ -515,7 +509,7 @@ public void tagWithSlashes() throws Exception { } private void assertLogContains(ObjectId commitA, ObjectId commitB, String prefix, String expected) - throws GitException, InterruptedException { + throws Exception { boolean found = false; StringBuilder builder = new StringBuilder(); for (String revisionMessage : gitClient.showRevision(commitA, commitB)) { @@ -525,25 +519,23 @@ private void assertLogContains(ObjectId commitA, ObjectId commitB, String prefix found = true; } } - assertTrue("no " + prefix + ", expected: '" + expected + "' in " + builder, found); + assertTrue(found, "no " + prefix + ", expected: '" + expected + "' in " + builder); } - private void assertAuthor(ObjectId commitA, ObjectId commitB, String name, String email) - throws GitException, InterruptedException { + private void assertAuthor(ObjectId commitA, ObjectId commitB, String name, String email) throws Exception { final String prefix = "author "; final String expected = prefix + name + " <" + email + ">"; assertLogContains(commitA, commitB, prefix, expected); } - private void assertCommitter(ObjectId commitA, ObjectId commitB, String name, String email) - throws GitException, InterruptedException { + private void assertCommitter(ObjectId commitA, ObjectId commitB, String name, String email) throws Exception { final String prefix = "committer "; final String expected = prefix + name + " <" + email + ">"; assertLogContains(commitA, commitB, prefix, expected); } @Test - public void testSetAuthor_String_String() throws Exception { + void testSetAuthor_String_String() throws Exception { final ObjectId commitA = commitOneFile(); final String name = randomName(); final String email = randomEmail(name); @@ -552,14 +544,18 @@ public void testSetAuthor_String_String() throws Exception { assertAuthor(commitA, commitB, name, email); } - @Test(expected = GitException.class) - public void testCommitNotFoundException() throws GitException, InterruptedException { - /* Search wrong repository for a commit */ - assertAuthor(upstreamCommitPredecessor, upstreamCommit, upstreamCommitAuthor, upstreamCommitEmail); + @Test + void testCommitNotFoundException() { + assertThrows( + GitException.class, + () -> + /* Search wrong repository for a commit */ + assertAuthor( + upstreamCommitPredecessor, upstreamCommit, upstreamCommitAuthor, upstreamCommitEmail)); } @Test - public void testSetAuthor_PersonIdent() throws Exception { + void testSetAuthor_PersonIdent() throws Exception { final ObjectId commitA = commitOneFile(); final String name = randomName(); final String email = randomEmail(name); @@ -569,12 +565,12 @@ public void testSetAuthor_PersonIdent() throws Exception { } @Test - public void testGetWorkTree() { + void testGetWorkTree() { assertThat(gitClient.getWorkTree(), is(new FilePath(repoRoot))); } @Test - public void testSetCommitter_String_String() throws Exception { + void testSetCommitter_String_String() throws Exception { final ObjectId commitA = commitOneFile(); final String name = randomName(); final String email = randomEmail(name); @@ -584,7 +580,7 @@ public void testSetCommitter_String_String() throws Exception { } @Test - public void testSetCommitter_PersonIdent() throws Exception { + void testSetCommitter_PersonIdent() throws Exception { final ObjectId commitA = commitOneFile(); final String name = randomName(); final String email = randomEmail(name); @@ -594,35 +590,35 @@ public void testSetCommitter_PersonIdent() throws Exception { } @Test - public void testGetRepository() throws Exception { + void testGetRepository() { File expectedRepo = new File(repoRoot, ".git"); assertEquals(expectedRepo, gitClient.getRepository().getDirectory()); } @Test - public void testInit() throws Exception { + void testInit() throws Exception { File gitDir = gitClient.withRepository((repo, channel) -> repo.getDirectory()); gitClient.init(); - assertTrue("init did not create " + gitDir, gitDir.isDirectory()); + assertTrue(gitDir.isDirectory(), "init did not create " + gitDir); } @Test - public void testInit_Bare() throws Exception { - File repoRootTemp = tempFolder.newFolder(); + void testInit_Bare() throws Exception { + File repoRootTemp = newFolder(tempFolder, "junit-" + System.nanoTime()); GitClient gitClientTemp = Git.with(TaskListener.NULL, new EnvVars()) .in(repoRootTemp) .using(gitImplName) .getClient(); File tempDir = gitClientTemp.withRepository((repo, channel) -> repo.getDirectory()); - assertFalse("Missing", tempDir.isDirectory()); + assertFalse(tempDir.isDirectory(), "Missing"); gitClientTemp.init_().workspace(repoRootTemp.getPath()).bare(true).execute(); // Bare git_init contains no working tree file tempDir = gitClientTemp.withRepository((repo, channel) -> repo.getWorkTree()); - assertFalse(".refs not found", tempDir.isFile()); + assertFalse(tempDir.isFile(), ".refs not found"); } @Test - public void testInitFailureWindows() throws Exception { + void testInitFailureWindows() throws Exception { if (!isWindows()) { return; } @@ -632,7 +628,8 @@ public void testInitFailureWindows() throws Exception { .in(badDir) .using(gitImplName) .getClient(); - Class expectedExceptionClass = gitImplName.equals("git") ? GitException.class : JGitInternalException.class; + Class expectedExceptionClass = + gitImplName.equals("git") ? GitException.class : JGitInternalException.class; assertThrows(expectedExceptionClass, () -> badGitClient .init_() .bare(random.nextBoolean()) @@ -641,7 +638,7 @@ public void testInitFailureWindows() throws Exception { } @Test - public void testInitFailureNotWindowsNotSuperUser() throws Exception { + void testInitFailureNotWindowsNotSuperUser() throws Exception { if (isWindows() || (new File("/").canWrite())) { // Windows or running as root return; } @@ -651,7 +648,8 @@ public void testInitFailureNotWindowsNotSuperUser() throws Exception { .in(badDir) .using(gitImplName) .getClient(); - Class expectedExceptionClass = gitImplName.equals("git") ? GitException.class : JGitInternalException.class; + Class expectedExceptionClass = + gitImplName.equals("git") ? GitException.class : JGitInternalException.class; assertThrows(expectedExceptionClass, () -> badGitClient .init_() .bare(random.nextBoolean()) @@ -660,13 +658,13 @@ public void testInitFailureNotWindowsNotSuperUser() throws Exception { } @Test - public void testAdd() throws Exception { + void testAdd() throws Exception { final ObjectId commitA = commitOneFile(); assertNotNull(commitA); } @Test - public void testCommit_String() throws Exception { + void testCommit_String() throws Exception { final ObjectId commitA = commitOneFile(); final String name = randomName(); final String email = randomEmail(name); @@ -677,7 +675,7 @@ public void testCommit_String() throws Exception { } @Test - public void testCommit_3args() throws Exception { + void testCommit_3args() throws Exception { final ObjectId commitA = commitOneFile(); final String authorName = randomName(); final String authorEmail = randomEmail(authorName); @@ -693,89 +691,89 @@ public void testCommit_3args() throws Exception { } @Test - public void testHasGitRepo() throws Exception { - assertTrue("Test repo '" + repoRoot.getAbsolutePath() + "' not initialized", gitClient.hasGitRepo()); + void testHasGitRepo() throws Exception { + assertTrue(gitClient.hasGitRepo(), "Test repo '" + repoRoot.getAbsolutePath() + "' not initialized"); StringBuilder fileList = new StringBuilder(); for (File file : srcRepoDir.listFiles()) { fileList.append(file.getAbsolutePath()); fileList.append(" "); } assertTrue( - "Source repo '" + srcRepoDir.getAbsolutePath() + "' not initialized, contains " + fileList, - srcGitClient.hasGitRepo()); + srcGitClient.hasGitRepo(), + "Source repo '" + srcRepoDir.getAbsolutePath() + "' not initialized, contains " + fileList); - File emptyDir = tempFolder.newFolder(); + File emptyDir = newFolder(tempFolder, "junit-" + System.nanoTime()); assertTrue(emptyDir.exists()); GitClient emptyClient = Git.with(TaskListener.NULL, new EnvVars()) .in(emptyDir) .using(gitImplName) .getClient(); - assertFalse("Empty repo '" + emptyDir.getAbsolutePath() + "' initialized", emptyClient.hasGitRepo()); + assertFalse(emptyClient.hasGitRepo(), "Empty repo '" + emptyDir.getAbsolutePath() + "' initialized"); } @Test - public void testHasGitRepoFalse() throws Exception { + void testHasGitRepoFalse() throws Exception { /* Use system temp directory so that no parent directory has a git repository */ Path tempDir = Files.createTempDirectory("git-client-hasGitRepo"); GitClient noRepoClient = Git.with(TaskListener.NULL, new EnvVars()) .in(tempDir.toFile()) .using(gitImplName) .getClient(); - assertFalse("New empty temp dir has a git repo(1)", noRepoClient.hasGitRepo()); - assertFalse("New empty temp dir has a git repo(2)", noRepoClient.hasGitRepo(false)); - assertFalse("New empty temp dir has a git repo(3)", noRepoClient.hasGitRepo(true)); + assertFalse(noRepoClient.hasGitRepo(), "New empty temp dir has a git repo(1)"); + assertFalse(noRepoClient.hasGitRepo(false), "New empty temp dir has a git repo(2)"); + assertFalse(noRepoClient.hasGitRepo(true), "New empty temp dir has a git repo(3)"); tempDir.toFile().delete(); // Remove the temporary directory } @Issue("JENKINS-38699") @Test - public void testHasGitRepoNestedDir() throws Exception { - File childDir = tempFolder.newFolder("parentDir", "childDir"); + void testHasGitRepoNestedDir() throws Exception { + File childDir = newFolder(tempFolder, "parentDir", "childDir-" + System.nanoTime()); File parentDir = childDir.getParentFile(); GitClient parentDirClient = Git.with(TaskListener.NULL, new EnvVars()) .in(parentDir) .using(gitImplName) .getClient(); - assertFalse("Unexpected has git repo before init(1)", parentDirClient.hasGitRepo()); - assertFalse("Unexpected has git repo before init(2)", parentDirClient.hasGitRepo(true)); - assertFalse("Unexpected has git repo before init(3)", parentDirClient.hasGitRepo(false)); + assertFalse(parentDirClient.hasGitRepo(), "Unexpected has git repo before init(1)"); + assertFalse(parentDirClient.hasGitRepo(true), "Unexpected has git repo before init(2)"); + assertFalse(parentDirClient.hasGitRepo(false), "Unexpected has git repo before init(3)"); parentDirClient.init(); - assertTrue("Missing git repo after init(1)", parentDirClient.hasGitRepo()); - assertTrue("Missing git repo after init(2)", parentDirClient.hasGitRepo(true)); - assertTrue("Missing git repo after init(3)", parentDirClient.hasGitRepo(false)); + assertTrue(parentDirClient.hasGitRepo(), "Missing git repo after init(1)"); + assertTrue(parentDirClient.hasGitRepo(true), "Missing git repo after init(2)"); + assertTrue(parentDirClient.hasGitRepo(false), "Missing git repo after init(3)"); GitClient childDirClient = Git.with(TaskListener.NULL, new EnvVars()) .in(childDir) .using(gitImplName) .getClient(); - assertFalse("Unexpected has child git repo before child init(1)", childDirClient.hasGitRepo()); - assertFalse("Unexpected has child git repo before child init(2)", childDirClient.hasGitRepo(true)); - assertFalse("Unexpected has child git repo before child init(3)", childDirClient.hasGitRepo(false)); + assertFalse(childDirClient.hasGitRepo(), "Unexpected has child git repo before child init(1)"); + assertFalse(childDirClient.hasGitRepo(true), "Unexpected has child git repo before child init(2)"); + assertFalse(childDirClient.hasGitRepo(false), "Unexpected has child git repo before child init(3)"); File childGitDir = new File(childDir, ".git"); boolean dirCreated = childGitDir.mkdir(); - assertTrue("Failed to create empty .git dir in childDir", dirCreated); + assertTrue(dirCreated, "Failed to create empty .git dir in childDir"); if (gitImplName.equals("git")) { // JENKINS-38699 - if an empty .git directory exists, CLI git searches upwards to perform operations - assertTrue("Missing parent git repo before child init(1)", childDirClient.hasGitRepo()); + assertTrue(childDirClient.hasGitRepo(), "Missing parent git repo before child init(1)"); } else { // JENKINS-38699 - if an empty .git directory exists, JGit does NOT search upwards to perform operations assertFalse( - "Unexpected parent git repo detected by JGit before child init(1)", childDirClient.hasGitRepo()); + childDirClient.hasGitRepo(), "Unexpected parent git repo detected by JGit before child init(1)"); } - assertTrue("Missing parent git repo before child init(2)", childDirClient.hasGitRepo(true)); - assertFalse("Unexpected has child repo before child init(3)", childDirClient.hasGitRepo(false)); + assertTrue(childDirClient.hasGitRepo(true), "Missing parent git repo before child init(2)"); + assertFalse(childDirClient.hasGitRepo(false), "Unexpected has child repo before child init(3)"); childDirClient.init(); - assertTrue("Missing git repo after child init(1)", childDirClient.hasGitRepo()); - assertTrue("Missing git repo after child init(2)", childDirClient.hasGitRepo(true)); - assertTrue("Missing git repo after child init(3)", childDirClient.hasGitRepo(false)); + assertTrue(childDirClient.hasGitRepo(), "Missing git repo after child init(1)"); + assertTrue(childDirClient.hasGitRepo(true), "Missing git repo after child init(2)"); + assertTrue(childDirClient.hasGitRepo(false), "Missing git repo after child init(3)"); } @Test - public void testIsCommitInRepo() throws Exception { + void testIsCommitInRepo() throws Exception { assertTrue(srcGitClient.isCommitInRepo(upstreamCommit)); assertFalse(gitClient.isCommitInRepo(upstreamCommit)); assertFalse(gitClient.isCommitInRepo(null)); // NPE safety check @@ -786,13 +784,13 @@ public void testIsCommitInRepo() throws Exception { private void assertExceptionMessageContains(GitException ge, String expectedSubstring) { String actual = ge.getMessage().toLowerCase(); assertTrue( - "Expected '" + expectedSubstring + "' exception message, but was: " + actual, - actual.contains(expectedSubstring)); + actual.contains(expectedSubstring), + "Expected '" + expectedSubstring + "' exception message, but was: " + actual); } private IGitAPI IGitAPIForTrueBareRepositoryTests() throws Exception { // provides iGitAPI with bare repository initialization - File repoRootTemp = tempFolder.newFolder(); + File repoRootTemp = newFolder(tempFolder, "junit-" + System.nanoTime()); GitClient gitClientTemp = Git.with(TaskListener.NULL, new EnvVars()) .in(repoRootTemp) .using(gitImplName) @@ -807,26 +805,26 @@ private IGitAPI IGitAPIForTrueBareRepositoryTests() throws Exception { @Test @Deprecated - public void testIsBareRepositoryBareDot() throws Exception { + void testIsBareRepositoryBareDot() throws Exception { IGitAPI gitAPI = IGitAPIForTrueBareRepositoryTests(); - assertTrue(". is not a bare repository", gitAPI.isBareRepository(".")); + assertTrue(gitAPI.isBareRepository("."), ". is not a bare repository"); } @Test @Deprecated - public void testIsBareRepositoryWorkingDotGit() throws Exception { + void testIsBareRepositoryWorkingDotGit() throws Exception { gitClient.init_().workspace(repoRoot.getAbsolutePath()).bare(true).execute(); IGitAPI gitAPI = (IGitAPI) gitClient; FilePath gitClientFilePath = gitClient.getWorkTree(); gitClientFilePath.createTextTempFile("aPre", ".txt", "file contents"); gitClient.add("."); gitClient.commit("Not-a-bare-repository-dot-git"); - assertFalse(".git is a bare repository", gitAPI.isBareRepository(".git")); + assertFalse(gitAPI.isBareRepository(".git"), ".git is a bare repository"); } @Test @Deprecated - public void testIsBareRepositoryBareDotGit() throws Exception { + void testIsBareRepositoryBareDotGit() throws Exception { IGitAPI gitAPI = IGitAPIForTrueBareRepositoryTests(); /* Bare repository does not have a .git directory. This is * another no-such-location test but is included here for @@ -838,10 +836,10 @@ public void testIsBareRepositoryBareDotGit() throws Exception { * a specific file that the repository is bare. JGit behaves better * than CliGit in this case. */ - assertTrue("non-existent .git is in a bare repository", gitAPI.isBareRepository(".git")); + assertTrue(gitAPI.isBareRepository(".git"), "non-existent .git is in a bare repository"); /* JGit will not throw an exception - it knows the repo is bare */ /* CliGit throws an exception so should not reach the next assertion */ - assertFalse("CliGitAPIImpl did not throw expected exception", gitAPI instanceof CliGitAPIImpl); + assertFalse(gitAPI instanceof CliGitAPIImpl, "CliGitAPIImpl did not throw expected exception"); } catch (GitException ge) { /* Only enters this path for CliGit */ assertExceptionMessageContains(ge, "not a git repository"); @@ -850,7 +848,7 @@ public void testIsBareRepositoryBareDotGit() throws Exception { @Test @Deprecated - public void testIsBareRepositoryWorkingNoSuchLocation() throws Exception { + void testIsBareRepositoryWorkingNoSuchLocation() throws Exception { gitClient.init_().workspace(repoRoot.getAbsolutePath()).bare(true).execute(); IGitAPI gitAPI = (IGitAPI) gitClient; FilePath gitClientFilePath = gitClient.getWorkTree(); @@ -858,10 +856,10 @@ public void testIsBareRepositoryWorkingNoSuchLocation() throws Exception { gitClient.add("."); gitClient.commit("Not-a-bare-repository-working-no-such-location"); try { - assertFalse("non-existent location is in a bare repository", gitAPI.isBareRepository("no-such-location")); + assertFalse(gitAPI.isBareRepository("no-such-location"), "non-existent location is in a bare repository"); /* JGit will not throw an exception - it knows the repo is not bare */ /* CliGit throws an exception so should not reach the next assertion */ - assertFalse("CliGitAPIImpl did not throw expected exception", gitAPI instanceof CliGitAPIImpl); + assertFalse(gitAPI instanceof CliGitAPIImpl, "CliGitAPIImpl did not throw expected exception"); } catch (GitException ge) { /* Only enters this path for CliGit */ assertExceptionMessageContains(ge, "not a git repository"); @@ -870,13 +868,13 @@ public void testIsBareRepositoryWorkingNoSuchLocation() throws Exception { @Test @Deprecated - public void testIsBareRepositoryBareNoSuchLocation() throws Exception { + void testIsBareRepositoryBareNoSuchLocation() throws Exception { IGitAPI gitAPI = IGitAPIForTrueBareRepositoryTests(); try { - assertTrue("non-existent location is in a bare repository", gitAPI.isBareRepository("no-such-location")); + assertTrue(gitAPI.isBareRepository("no-such-location"), "non-existent location is in a bare repository"); /* JGit will not throw an exception - it knows the repo is not bare */ /* CliGit throws an exception so should not reach the next assertion */ - assertFalse("CliGitAPIImpl did not throw expected exception", gitAPI instanceof CliGitAPIImpl); + assertFalse(gitAPI instanceof CliGitAPIImpl, "CliGitAPIImpl did not throw expected exception"); } catch (GitException ge) { /* Only enters this path for CliGit */ assertExceptionMessageContains(ge, "not a git repository"); @@ -885,52 +883,52 @@ public void testIsBareRepositoryBareNoSuchLocation() throws Exception { @Deprecated @Test - public void testIsBareRepositoryBareEmptyString() throws Exception { + void testIsBareRepositoryBareEmptyString() throws Exception { IGitAPI gitAPI = IGitAPIForTrueBareRepositoryTests(); - assertTrue("empty string is not a bare repository", gitAPI.isBareRepository("")); + assertTrue(gitAPI.isBareRepository(""), "empty string is not a bare repository"); } @Deprecated @Test - public void testIsBareRepositoryWorkingEmptyString() throws Exception { + void testIsBareRepositoryWorkingEmptyString() throws Exception { gitClient.init_().workspace(repoRoot.getAbsolutePath()).bare(true).execute(); IGitAPI gitAPI = (IGitAPI) gitClient; FilePath gitClientFilePath = gitClient.getWorkTree(); gitClientFilePath.createTextTempFile("aPre", ".txt", "file contents"); gitClient.add("."); gitClient.commit("Not-a-bare-repository-empty-string"); - assertFalse("empty string is a bare repository", gitAPI.isBareRepository("")); + assertFalse(gitAPI.isBareRepository(""), "empty string is a bare repository"); } @Deprecated @Test - public void testIsBareRepositoryBareNoArg() throws Exception { + void testIsBareRepositoryBareNoArg() throws Exception { IGitAPI gitAPI = IGitAPIForTrueBareRepositoryTests(); - assertTrue("no arg is not a bare repository", gitAPI.isBareRepository()); + assertTrue(gitAPI.isBareRepository(), "no arg is not a bare repository"); } @Deprecated @Test - public void testIsBareRepositoryWorkingNoArg() throws Exception { + void testIsBareRepositoryWorkingNoArg() throws Exception { gitClient.init_().workspace(repoRoot.getAbsolutePath()).bare(true).execute(); IGitAPI gitAPI = (IGitAPI) gitClient; FilePath gitClientFilePath = gitClient.getWorkTree(); gitClientFilePath.createTextTempFile("aPre", ".txt", "file contents"); gitClient.add("."); gitClient.commit("Not-a-bare-repository-no-arg"); - assertFalse("no arg is a bare repository", gitAPI.isBareRepository()); + assertFalse(gitAPI.isBareRepository(), "no arg is a bare repository"); } @Test - public void testBareRepoInit() throws Exception { + void testBareRepoInit() throws Exception { IGitAPI gitAPI = IGitAPIForTrueBareRepositoryTests(); File tempDir = gitAPI.withRepository((repo, channel) -> repo.getWorkTree()); File gitFile = new File(tempDir, ".git"); File gitObjFile = new File(tempDir, ".git/objects"); File objFile = new File(tempDir, "objects"); - assertFalse(".git exists unexpectedly", gitFile.exists()); - assertFalse(".git/objects exists unexpectedly", gitObjFile.exists()); - assertTrue("objects is not a directory", objFile.isDirectory()); + assertFalse(gitFile.exists(), ".git exists unexpectedly"); + assertFalse(gitObjFile.exists(), ".git/objects exists unexpectedly"); + assertTrue(objFile.isDirectory(), "objects is not a directory"); } /* The most critical use cases of isBareRepository respond the @@ -941,7 +939,7 @@ public void testBareRepoInit() throws Exception { @Deprecated @Test - public void testIsBareRepositoryWorkingRepoPathDotGit() throws Exception { + void testIsBareRepositoryWorkingRepoPathDotGit() throws Exception { gitClient.init_().workspace(repoRoot.getAbsolutePath()).bare(true).execute(); IGitAPI gitAPI = (IGitAPI) gitClient; FilePath gitClientFilePath = gitClient.getWorkTree(); @@ -949,13 +947,13 @@ public void testIsBareRepositoryWorkingRepoPathDotGit() throws Exception { gitClient.add("."); gitClient.commit("Not-a-bare-repository-false-repoPath-dot-git"); assertFalse( - "repoPath/.git is a bare repository", - gitAPI.isBareRepository(repoRoot.getPath() + File.separator + ".git")); + gitAPI.isBareRepository(repoRoot.getPath() + File.separator + ".git"), + "repoPath/.git is a bare repository"); } @Deprecated @Test - public void testIsBareRepositoryWorkingNull() throws Exception { + void testIsBareRepositoryWorkingNull() throws Exception { gitClient.init_().workspace(repoRoot.getAbsolutePath()).bare(true).execute(); IGitAPI gitAPI = (IGitAPI) gitClient; FilePath gitClientFilePath = gitClient.getWorkTree(); @@ -963,7 +961,7 @@ public void testIsBareRepositoryWorkingNull() throws Exception { gitClient.add("."); gitClient.commit("Not-a-bare-repository-working-null"); try { - assertFalse("null is a bare repository", gitAPI.isBareRepository(null)); + assertFalse(gitAPI.isBareRepository(null), "null is a bare repository"); fail("Did not throw expected exception"); } catch (GitException ge) { assertExceptionMessageContains(ge, "not a git repository"); @@ -972,10 +970,10 @@ public void testIsBareRepositoryWorkingNull() throws Exception { @Deprecated @Test - public void testIsBareRepositoryBareNull() throws Exception { + void testIsBareRepositoryBareNull() throws Exception { IGitAPI gitAPI = IGitAPIForTrueBareRepositoryTests(); try { - assertTrue("null is not a bare repository", gitAPI.isBareRepository(null)); + assertTrue(gitAPI.isBareRepository(null), "null is not a bare repository"); fail("Did not throw expected exception"); } catch (GitException ge) { assertExceptionMessageContains(ge, "not a git repository"); @@ -984,22 +982,22 @@ public void testIsBareRepositoryBareNull() throws Exception { @Deprecated @Test - public void test_isBareRepository_bare_repoPath() throws Exception { + void test_isBareRepository_bare_repoPath() throws Exception { IGitAPI gitAPI = IGitAPIForTrueBareRepositoryTests(); File tempRepoDir = gitAPI.withRepository((repo, channel) -> repo.getWorkTree()); File dotFile = new File(tempRepoDir, "."); - assertTrue("repoPath is not a bare repository", gitAPI.isBareRepository(tempRepoDir.getPath())); - assertTrue("abs(.) is not a bare repository", gitAPI.isBareRepository(dotFile.getAbsolutePath())); + assertTrue(gitAPI.isBareRepository(tempRepoDir.getPath()), "repoPath is not a bare repository"); + assertTrue(gitAPI.isBareRepository(dotFile.getAbsolutePath()), "abs(.) is not a bare repository"); } @Test - public void testGetRemoteUrl() throws Exception { + void testGetRemoteUrl() throws Exception { assertEquals(srcRepoDir.getAbsolutePath(), gitClient.getRemoteUrl("origin")); } @Test @Deprecated - public void testGetRemoteUrl_two_args() throws Exception { + void testGetRemoteUrl_two_args() throws Exception { IGitAPI iGitAPI = (IGitAPI) gitClient; String originUrl = gitClient.getRemoteUrl("origin"); assertThat("Null URL arg", iGitAPI.getRemoteUrl("origin", null), is(originUrl)); @@ -1007,22 +1005,22 @@ public void testGetRemoteUrl_two_args() throws Exception { } @Test - public void testSetRemoteUrl() throws Exception { + void testSetRemoteUrl() throws Exception { assertEquals(srcRepoDir.getAbsolutePath(), gitClient.getRemoteUrl("origin")); gitClient.setRemoteUrl("origin", upstreamRepoURL); assertEquals(upstreamRepoURL, gitClient.getRemoteUrl("origin")); } @Test - public void testAddRemoteUrl() throws Exception { + void testAddRemoteUrl() throws Exception { gitClient.addRemoteUrl("upstream", upstreamRepoURL); assertEquals(srcRepoDir.getAbsolutePath(), gitClient.getRemoteUrl("origin")); assertEquals(upstreamRepoURL, gitClient.getRemoteUrl("upstream")); } @Test - public void testAutocreateFailsOnMultipleMatchingOrigins() throws Exception { - File repoRootTemp = tempFolder.newFolder(); + void testAutocreateFailsOnMultipleMatchingOrigins() throws Exception { + File repoRootTemp = newFolder(tempFolder, "junit-" + System.nanoTime()); GitClient gitClientTemp = Git.with(TaskListener.NULL, new EnvVars()) .in(repoRootTemp) .using(gitImplName) @@ -1057,7 +1055,7 @@ public void testAutocreateFailsOnMultipleMatchingOrigins() throws Exception { } catch (GitException e) { // expected Set refNames = gitClient.getRefNames("refs/heads/"); - assertFalse("RefNames will not contain master", refNames.contains("refs/heads/master")); + assertFalse(refNames.contains("refs/heads/master"), "RefNames will not contain master"); } } @@ -1067,8 +1065,8 @@ public void testAutocreateFailsOnMultipleMatchingOrigins() throws Exception { * @throws Exception on exceptions occur */ @Test - public void testCheckoutRemoteAutocreatesLocal() throws Exception { - File repoRootTemp = tempFolder.newFolder(); + void testCheckoutRemoteAutocreatesLocal() throws Exception { + File repoRootTemp = newFolder(tempFolder, "junit-" + System.nanoTime()); GitClient gitClientTemp = Git.with(TaskListener.NULL, new EnvVars()) .in(repoRootTemp) .using(gitImplName) @@ -1104,11 +1102,11 @@ private void assertFileNotInWorkingDir(GitClient client, String fileName) { assertThat(fileInRepo, is(not(anExistingFile()))); } - private void assertFileContent(String fileName, String expectedContent) throws IOException { + private void assertFileContent(String fileName, String expectedContent) throws Exception { File file = new File(repoRoot, fileName); String actualContent = Files.readString(file.toPath(), StandardCharsets.UTF_8).trim(); - assertEquals("Incorrect file content in " + fileName, expectedContent, actualContent); + assertEquals(expectedContent, actualContent, "Incorrect file content in " + fileName); } private void assertDirInWorkingDir(GitClient client, String dirName) { @@ -1121,22 +1119,6 @@ private void assertDirNotInWorkingDir(GitClient client, String dirName) { assertThat(dirInRepo, is(not(anExistingDirectory()))); } - private boolean removeMatchingBranches(Set filtered, Set toRemove) { - Set objectIds = new HashSet<>(); - for (Branch removeBranch : toRemove) { - objectIds.add(removeBranch.getSHA1()); - } - boolean modified = false; - for (Iterator i = filtered.iterator(); i.hasNext(); ) { - Branch checkBranch = i.next(); - if (objectIds.contains(checkBranch.getSHA1())) { - modified = true; - i.remove(); - } - } - return modified; - } - private void assertEmptyWorkingDir(GitClient gitClient) throws Exception { assertTrue(gitClient.hasGitRepo()); File gitDir = new File(repoRoot, ".git"); @@ -1211,7 +1193,7 @@ private void fetchWithTags(GitClient client, String remote) throws Exception { } @Test - public void testCheckout_String() throws Exception { + void testCheckout_String() throws Exception { /* Confirm files not visible in empty repo */ assertEmptyWorkingDir(gitClient); /* Fetch from origin repo */ @@ -1241,7 +1223,7 @@ public void testCheckout_String() throws Exception { } @Test - public void testCheckout_String_String() throws Exception { + void testCheckout_String_String() throws Exception { fetch(gitClient, "origin", "+refs/heads/*:refs/remotes/origin/*"); int branchNumber = 10 + random.nextInt(80); String baseName = "branchA-"; @@ -1273,7 +1255,7 @@ public void testCheckout_String_String() throws Exception { } @Test - public void testCheckout_0args() throws Exception { + void testCheckout_0args() throws Exception { fetch(gitClient, "origin", "+refs/heads/*:refs/remotes/origin/*"); int branchNumber = 10 + random.nextInt(80); String baseName = "branchA-"; @@ -1305,7 +1287,7 @@ public void testCheckout_0args() throws Exception { } @Test - public void testCheckoutBranch() throws Exception { + void testCheckoutBranch() throws Exception { File src = new File(repoRoot, "src"); assertFalse(src.isDirectory()); String branch = "master"; @@ -1315,7 +1297,7 @@ public void testCheckoutBranch() throws Exception { } @Test - public void testBranchExistsException() throws Exception { + void testBranchExistsException() throws Exception { File src = new File(repoRoot, "src"); assertFalse(src.isDirectory()); String branch = "master"; @@ -1326,7 +1308,7 @@ public void testBranchExistsException() throws Exception { } @Test - public void testEmptyCommitException() throws Exception { + void testEmptyCommitException() throws Exception { File src = new File(repoRoot, "src"); assertFalse(src.isDirectory()); String branch = "master"; @@ -1342,7 +1324,7 @@ public void testEmptyCommitException() throws Exception { } @Test - public void testDeleteNonExistingBranchException() throws Exception { + void testDeleteNonExistingBranchException() throws Exception { File src = new File(repoRoot, "src"); assertFalse(src.isDirectory()); String branch = "master"; @@ -1357,9 +1339,10 @@ public void testDeleteNonExistingBranchException() throws Exception { } } - @Issue("JENKINS-35687") // Git LFS support + @Issue("JENKINS-35687") + // Git LFS support @Test - public void testCheckoutWithCliGitLFS() throws Exception { + void testCheckoutWithCliGitLFS() throws Exception { if (!gitImplName.equals("git") || !CLI_GIT_HAS_GIT_LFS) { return; } @@ -1381,7 +1364,7 @@ public void testCheckoutWithCliGitLFS() throws Exception { @Issue("JENKINS-43427") // Git LFS sparse checkout support @Test - public void testSparseCheckoutWithCliGitLFS() throws Exception { + void testSparseCheckoutWithCliGitLFS() throws Exception { if (!gitImplName.equals("git") || !LFS_TOKEN_PATH.toFile().exists()) { /* Git LFS not implemented in JGitAPIImpl */ /* Test requires an LFS credential for checkout, otherwise fails with GitHub error 'bad credentials' */ @@ -1746,51 +1729,58 @@ public void testSparseCheckoutWithCliGitLFS() throws Exception { } } - @Issue("JENKINS-35687") // Git LFS support - JGit not supported - @Test(expected = org.eclipse.jgit.api.errors.JGitInternalException.class) - public void testCheckoutWithJGitLFS() throws Exception { - if (!gitImplName.startsWith("jgit") || !CLI_GIT_HAS_GIT_LFS) { - throw new org.eclipse.jgit.api.errors.JGitInternalException( - "Skipping testCheckoutWithJGitLFS for CLI git exception"); - } + @Issue("JENKINS-35687") + // Git LFS support - JGit not supported + @Test + void testCheckoutWithJGitLFS() throws Exception { + assumeFalse( + !gitImplName.startsWith("jgit") || !CLI_GIT_HAS_GIT_LFS, + "Skipping testCheckoutWithJGitLFS for CLI git exception"); String branch = "tests/largeFileSupport"; String remote = fetchLFSTestRepo(branch); - gitClient + assertThrows(org.eclipse.jgit.api.errors.JGitInternalException.class, () -> gitClient .checkout() .branch(branch) .ref(remote + "/" + branch) .lfsRemote(remote) - .execute(); + .execute()); } // If LFS installed and not enabled, throw an exception - @Issue("JENKINS-35687") // Git LFS support - @Test(expected = GitException.class) - public void testCLICheckoutWithoutLFSWhenLFSAvailable() throws Exception { - if (!gitImplName.equals("git") || !CLI_GIT_HAS_GIT_LFS) { - throw new GitException("Test requires CLI git with LFS enabled"); - } + @Issue("JENKINS-35687") + // Git LFS support + @Test + void testCLICheckoutWithoutLFSWhenLFSAvailable() throws Exception { + assumeFalse(!gitImplName.equals("git") || !CLI_GIT_HAS_GIT_LFS, "Test requires CLI git with LFS enabled"); String branch = "tests/largeFileSupport"; String remote = fetchLFSTestRepo(branch); - gitClient.checkout().branch(branch).ref(remote + "/" + branch).execute(); + assertThrows(GitException.class, () -> gitClient + .checkout() + .branch(branch) + .ref(remote + "/" + branch) + .execute()); } // If LFS installed and not enabled, throw an exception if branch includes LFS reference - @Issue("JENKINS-35687") // Git LFS support - @Test(expected = org.eclipse.jgit.api.errors.JGitInternalException.class) - public void testJGitCheckoutWithoutLFSWhenLFSAvailable() throws Exception { - if (!gitImplName.startsWith("jgit") || !CLI_GIT_HAS_GIT_LFS) { - throw new org.eclipse.jgit.api.errors.JGitInternalException("Test requires CLI git with LFS enabled"); - } + @Issue("JENKINS-35687") + // Git LFS support + @Test + void testJGitCheckoutWithoutLFSWhenLFSAvailable() throws Exception { + assumeFalse(!gitImplName.startsWith("jgit") || !CLI_GIT_HAS_GIT_LFS, "Test requires CLI git with LFS enabled"); String branch = "tests/largeFileSupport"; String remote = fetchLFSTestRepo(branch); - gitClient.checkout().branch(branch).ref(remote + "/" + branch).execute(); + assertThrows(org.eclipse.jgit.api.errors.JGitInternalException.class, () -> gitClient + .checkout() + .branch(branch) + .ref(remote + "/" + branch) + .execute()); } // If LFS not installed and not enabled, checkout content without download - @Issue("JENKINS-35687") // Git LFS support + @Issue("JENKINS-35687") + // Git LFS support @Test - public void testCheckoutWithoutLFSWhenLFSNotAvailable() throws Exception { + void testCheckoutWithoutLFSWhenLFSNotAvailable() throws Exception { if (CLI_GIT_HAS_GIT_LFS || CLI_GIT_HAS_GIT_LFS_CONFIGURED) { return; } @@ -1806,7 +1796,7 @@ public void testCheckoutWithoutLFSWhenLFSNotAvailable() throws Exception { oid sha256:75d122e4160dc91480257ff72403e77ef276e24d7416ed2be56d4e726482d86e size 33\ """; - assertEquals("Incorrect non-LFS file contents in " + uuidFile, expectedContent, fileContent); + assertEquals(expectedContent, fileContent, "Incorrect non-LFS file contents in " + uuidFile); } /* @@ -1817,7 +1807,7 @@ public void testCheckoutWithoutLFSWhenLFSNotAvailable() throws Exception { * removal of the work around (from JGitAPIImpl). */ @Test - public void testDeleteRef() throws Exception { + void testDeleteRef() throws Exception { assertThat(gitClient.getRefNames(""), is(empty())); if (gitImplName.startsWith("jgit")) { // JGit won't delete refs from a repo without local commits @@ -1832,21 +1822,20 @@ public void testDeleteRef() throws Exception { gitClient.getRefNames("refs/remotes/upstream/"), hasItems("refs/remotes/upstream/tests/getSubmodules")); } - @Test(expected = GitException.class) - public void testDeleteRefException() throws Exception { - /* JGit won't delete current branch, CliGit will */ - if (!gitImplName.startsWith("jgit")) { - throw new GitException("Skipping JGit test in CLI git specific test testDeleteRefException"); - } + @Test + void testDeleteRefException() throws Exception { + assumeFalse( + !gitImplName.startsWith("jgit"), "Skipping JGit test in CLI git specific test testDeleteRefException"); assertThat(gitClient.getRefNames(""), is(empty())); - commitOneFile(); // Creates commit on default branch + commitOneFile(); Set refNames = gitClient.getRefNames(""); assertThat(refNames, hasItems("refs/heads/" + defaultBranchName)); - gitClient.deleteRef("refs/heads/" + defaultBranchName); // Throws - JGit cannot delete current branch + String x = "refs/heads/" + defaultBranchName; + assertThrows(GitException.class, () -> gitClient.deleteRef(x)); // Throws - JGit cannot delete current branch } @Test - public void testGetHeadRev_String() throws Exception { + void testGetHeadRev_String() throws Exception { String url = repoRoot.getAbsolutePath(); ObjectId commitA = commitOneFile(); @@ -1861,7 +1850,7 @@ public void testGetHeadRev_String() throws Exception { } @Test - public void testGetHeadRev_String_String() throws Exception { + void testGetHeadRev_String_String() throws Exception { String url = repoRoot.getAbsolutePath(); ObjectId commitA = commitOneFile(); @@ -1871,25 +1860,25 @@ public void testGetHeadRev_String_String() throws Exception { assertThat(gitClient.getHeadRev(url, defaultBranchName), is(commitB)); } - @Test(expected = GitException.class) - public void testGetHeadRev_Exception() throws Exception { - gitClient.getHeadRev("protocol://hostname:port/not-a-URL"); + @Test + void testGetHeadRev_Exception() { + assertThrows(GitException.class, () -> gitClient.getHeadRev("protocol://hostname:port/not-a-URL")); } - @Test(expected = GitException.class) - public void testGetHeadRev_String_String_URI_Exception() throws Exception { - gitClient.getHeadRev("protocol://hostname:port/not-a-URL", "master"); + @Test + void testGetHeadRev_String_String_URI_Exception() { + assertThrows(GitException.class, () -> gitClient.getHeadRev("protocol://hostname:port/not-a-URL", "master")); } @Test - public void testGetHeadRev_String_String_Empty_Result() throws Exception { + void testGetHeadRev_String_String_Empty_Result() throws Exception { String url = repoRoot.getAbsolutePath(); ObjectId nonExistent = gitClient.getHeadRev(url, "this branch doesn't exist"); assertNull(nonExistent); } @Test - public void testRefExists() throws Exception { + void testRefExists() throws Exception { String getSubmodulesRef = "refs/remotes/origin/tests/getSubmodules"; assertFalse(gitClient.refExists(getSubmodulesRef)); assertTrue(srcGitClient.refExists(getSubmodulesRef)); @@ -1907,7 +1896,7 @@ public void testGetRemoteReferences() throws Exception { @Issue("JENKINS-30589") @Test - public void testGetRemoteReferences_ReturnsEmptyMapIfNoTags() throws Exception { + void testGetRemoteReferences_ReturnsEmptyMapIfNoTags() throws Exception { String url = repoRoot.getAbsolutePath(); String pattern = "**"; boolean headsOnly = false; @@ -1917,7 +1906,7 @@ public void testGetRemoteReferences_ReturnsEmptyMapIfNoTags() throws Exception { } @Test - public void testGetRemoteReferencesNonExistingPattern() throws Exception { + void testGetRemoteReferencesNonExistingPattern() throws Exception { String url = repoRoot.getAbsolutePath(); String pattern = "non-existent-name"; boolean headsOnly = false; @@ -1927,21 +1916,22 @@ public void testGetRemoteReferencesNonExistingPattern() throws Exception { } @Test - public void testRevParse() throws Exception { + void testRevParse() throws Exception { ObjectId commitA = commitOneFile(); assertThat(gitClient.revParse(defaultBranchName), is(commitA)); ObjectId commitB = commitOneFile(); assertThat(gitClient.revParse(defaultBranchName), is(commitB)); } - @Test(expected = GitException.class) - public void testRevParseException() throws Exception { + @Test + void testRevParseException() throws Exception { ObjectId commitA = commitOneFile(); - gitClient.revParse("non-existent-ref-" + random.nextInt()); + String x = "non-existent-ref-" + random.nextInt(); + assertThrows(GitException.class, () -> gitClient.revParse(x)); } @Test - public void testRevList_() throws Exception { + void testRevList_() throws Exception { ObjectId commitA = commitOneFile(); List resultAll = new ArrayList<>(); @@ -1954,7 +1944,7 @@ public void testRevList_() throws Exception { } @Test - public void testRevListAll() throws Exception { + void testRevListAll() throws Exception { ObjectId commitA = commitOneFile(); assertThat(gitClient.revListAll(), contains(commitA)); /* Also test RevListCommand implementation */ @@ -1971,7 +1961,7 @@ public void testRevListAll() throws Exception { } @Test - public void testRevList() throws Exception { + void testRevList() throws Exception { ObjectId commitA = commitOneFile(); assertThat(gitClient.revList(defaultBranchName), contains(commitA)); /* Also test RevListCommand implementation */ @@ -1988,28 +1978,23 @@ public void testRevList() throws Exception { } @Test - public void testRevListNoWalk() throws Exception { + void testRevListNoWalk() throws Exception { ObjectId commitA = commitOneFile(); List resultA = new ArrayList<>(); gitClient.revList_().to(resultA).reference(commitA.name()).nowalk(true).execute(); assertThat(resultA, contains(commitA)); - assertEquals(resultA.size(), 1); + assertEquals(1, resultA.size()); /* Make sure it's correct when there's more than one commit in the history */ ObjectId commitB = commitOneFile(); List resultB = new ArrayList<>(); gitClient.revList_().to(resultB).reference(commitB.name()).nowalk(true).execute(); assertThat(resultB, contains(commitB)); - assertEquals(resultB.size(), 1); - } - - // @Test - public void testSubGit() { - // Tested in assertSubmoduleContents + assertEquals(1, resultB.size()); } @Test - public void testHasGitModulesEmptyRepo() throws Exception { + void testHasGitModulesEmptyRepo() throws Exception { assertFalse(gitClient.hasGitModules()); } @@ -2055,21 +2040,21 @@ private void assertModulesDir(boolean modulesDirExpected) { } @Test - public void testHasGitModulesFalse() throws Exception { + void testHasGitModulesFalse() throws Exception { assertModulesDir(false); checkoutAndAssertHasGitModules("master", false); assertModulesDir(false); // repo has no modules dir and no submodules } @Test - public void testHasGitModulesFalseNotSubmodule() throws Exception { + void testHasGitModulesFalseNotSubmodule() throws Exception { assertModulesDir(false); checkoutAndAssertHasGitModules("tests/notSubmodules", false); assertModulesDir(true); // repo has a modules dir but no submodules } @Test - public void testHasGitModulesTrue() throws Exception { + void testHasGitModulesTrue() throws Exception { String branchName = "tests/getSubmodules"; if (!gitImplName.equals("git")) { branchName = branchName + "-jgit"; @@ -2094,7 +2079,7 @@ private void assertSubmoduleStatus(GitClient testGitClient, boolean initialized, } else { assertThat(statusLine + lastUpdateSubmodulePath, startsWith(" ")); } - assertTrue("Bad submodule status: '" + statusLine + "'", statusLine.matches("[-U+ ][0-9a-f]{40} .*")); + assertTrue(statusLine.matches("[-U+ ][0-9a-f]{40} .*"), "Bad submodule status: '" + statusLine + "'"); String submoduleName = statusLine.substring(42).split(" ")[0]; if (submodulesFound.containsKey(submoduleName)) { submodulesFound.put(submoduleName, Boolean.TRUE); @@ -2103,18 +2088,15 @@ private void assertSubmoduleStatus(GitClient testGitClient, boolean initialized, } } for (String submoduleName : submodulesFound.keySet()) { - assertTrue("Submodule " + submoduleName + " not found", submodulesFound.get(submoduleName)); + assertTrue(submodulesFound.get(submoduleName), "Submodule " + submoduleName + " not found"); } - assertFalse("git submodule status reported no output", emptyStatus); + assertFalse(emptyStatus, "git submodule status reported no output"); } - private void assertSubmoduleStatus(boolean initialized) throws Exception { - assertSubmoduleStatus(gitClient, initialized); - } - - @Issue("JENKINS-37495") // submodule update fails if path and name differ + @Issue("JENKINS-37495") + // submodule update fails if path and name differ @Test - public void testSubmoduleUpdateRecursiveRenameModule() throws Exception { + void testSubmoduleUpdateRecursiveRenameModule() throws Exception { // JGit implementation doesn't handle renamed submodules if (!gitImplName.equals("git") || isWindows()) { /* Slow test that does not tell us much more on Windows than Linux */ @@ -2135,9 +2117,10 @@ public void testSubmoduleUpdateRecursiveRenameModule() throws Exception { assertSubmoduleStatus(gitClient, true, "firewall", "ntp-moved", "sshkeys"); } - @Issue("JENKINS-37495") // submodule update fails if path and name differ + @Issue("JENKINS-37495") + // submodule update fails if path and name differ @Test - public void testSubmoduleRenameModuleUpdateRecursive() throws Exception { + void testSubmoduleRenameModuleUpdateRecursive() throws Exception { // JGit implementation doesn't handle renamed submodules if (!gitImplName.equals("git") || isWindows()) { /* Slow test that does not tell us much more on Windows than Linux */ @@ -2158,7 +2141,7 @@ public void testSubmoduleRenameModuleUpdateRecursive() throws Exception { } @Test - public void testModifiedTrackedFilesReset() throws Exception { + void testModifiedTrackedFilesReset() throws Exception { ObjectId commitA = commitOneFile("First commit"); /* Modify every plain file in the root of the repository */ @@ -2174,7 +2157,7 @@ public void testModifiedTrackedFilesReset() throws Exception { lastModifiedFile = file; } } - assertNotNull("No files modified " + repoRoot, lastModifiedFile); + assertNotNull(lastModifiedFile, "No files modified " + repoRoot); /* Checkout a new branch - verify no files retain modification */ gitClient @@ -2190,11 +2173,12 @@ public void testModifiedTrackedFilesReset() throws Exception { for (String line : lines) { if (line.contains(randomString)) { lastModifiedFile = file; + break; } } } } - assertNull("Checkout did not revert change in " + lastModifiedFile, lastModifiedFile); + assertNull(lastModifiedFile, "Checkout did not revert change in " + lastModifiedFile); } private void assertSubmoduleDirectories(GitClient gitClient, boolean expectLicense, String... expectedDirs) @@ -2202,12 +2186,12 @@ private void assertSubmoduleDirectories(GitClient gitClient, boolean expectLicen File myRepoRoot = gitClient.withRepository((repo, channel) -> repo.getWorkTree()); for (String expectedDir : expectedDirs) { File dir = new File(myRepoRoot, "modules/" + expectedDir); - assertTrue("Missing " + expectedDir + " dir (path:" + lastUpdateSubmodulePath + ")", dir.isDirectory()); + assertTrue(dir.isDirectory(), "Missing " + expectedDir + " dir (path:" + lastUpdateSubmodulePath + ")"); File license = new File(dir, "LICENSE"); assertEquals( - "Checking " + expectedDir + " LICENSE (path:" + lastUpdateSubmodulePath + ")", expectLicense, - license.isFile()); + license.isFile(), + "Checking " + expectedDir + " LICENSE (path:" + lastUpdateSubmodulePath + ")"); } } @@ -2216,7 +2200,7 @@ private void assertSubmoduleContents(GitClient client, String... directories) th for (String directory : directories) { File licenseDir = new File(myRepoRoot, "modules/" + directory); File licenseFile = new File(licenseDir, "LICENSE"); - assertTrue("Missing file " + licenseFile + " (path:" + lastUpdateSubmodulePath + ")", licenseFile.isFile()); + assertTrue(licenseFile.isFile(), "Missing file " + licenseFile + " (path:" + lastUpdateSubmodulePath + ")"); GitClient subGitClient = client.subGit("modules/" + directory); assertThat(subGitClient.hasGitModules(), is(false)); assertThat(subGitClient.getWorkTree().getName(), is(directory)); @@ -2238,7 +2222,7 @@ private void assertSubmoduleContents(String... directories) throws Exception { private int lastUpdateSubmodulePath = -1; - private void updateSubmoduleJGit(String remote, String branch) throws Exception { + private void updateSubmoduleJGit() throws Exception { // Choose a random submodule update command // These submodule update variants are equivalent for JGit // JGitAPIImpl does not implement either reference or remote tracking @@ -2273,7 +2257,7 @@ private void updateSubmoduleJGit(String remote, String branch) throws Exception private void updateSubmodule(String remote, String branch, Boolean remoteTracking) throws Exception { if (!gitImplName.equals("git")) { - updateSubmoduleJGit(remote, branch); + updateSubmoduleJGit(); return; } if (remoteTracking == null) { @@ -2342,9 +2326,10 @@ private void updateSubmodule(String remote, String branch, Boolean remoteTrackin } // @Issue("JENKINS-8053") // outdated submodules not removed by checkout - @Issue("JENKINS-37419") // Git plugin checking out non-existent submodule from different branch + @Issue("JENKINS-37419") + // Git plugin checking out non-existent submodule from different branch @Test - public void testOutdatedSubmodulesNotRemoved() throws Exception { + void testOutdatedSubmodulesNotRemoved() throws Exception { if (isWindows()) { /* Slow test that does not tell us much more on Windows than Linux */ return; @@ -2383,7 +2368,7 @@ public void testOutdatedSubmodulesNotRemoved() throws Exception { assertSubmoduleContents(expectedDirs); /* Clone, checkout and submodule update a repository copy before submodule deletion */ - File cloneDir = tempFolder.newFolder(); + File cloneDir = newFolder(tempFolder, "junit-" + System.nanoTime()); GitClient cloneGitClient = Git.with(TaskListener.NULL, new EnvVars()) .in(cloneDir) .using(gitImplName) @@ -2404,7 +2389,7 @@ public void testOutdatedSubmodulesNotRemoved() throws Exception { CliGitCommand gitCmd = new CliGitCommand(gitClient); File firewallDir = new File(repoRoot, "modules/firewall"); FileUtils.forceDelete(firewallDir); - assertFalse("firewallDir not deleted " + firewallDir, firewallDir.isDirectory()); + assertFalse(firewallDir.isDirectory(), "firewallDir not deleted " + firewallDir); gitCmd.run("submodule", "deinit", "modules/firewall"); gitCmd.assertOutputContains(".*unregistered.*modules/firewall.*"); gitCmd.run("add", "."); // gitClient.add() doesn't work in this JGit case @@ -2437,13 +2422,13 @@ public void testOutdatedSubmodulesNotRemoved() throws Exception { /* BUG: JENKINS-8053 Cloned modules/firewall not deleted by checkoutBranch in clone */ File cloneFirewallDir = new File(cloneDir, "modules/firewall"); - assertTrue("cloneFirewallDir missing at " + cloneFirewallDir, cloneFirewallDir.isDirectory()); + assertTrue(cloneFirewallDir.isDirectory(), "cloneFirewallDir missing at " + cloneFirewallDir); /* "Feature": clean does not remove modules/firewall (because it contains a git repo) * See JENKINS-26660 */ gitClient.clean(); - assertTrue("cloneFirewallDir unexpectedly cleaned at " + cloneFirewallDir, cloneFirewallDir.isDirectory()); + assertTrue(cloneFirewallDir.isDirectory(), "cloneFirewallDir unexpectedly cleaned at " + cloneFirewallDir); /* Fixed JENKINS-37419 - submodules only from current branch */ if (gitImplName.equals("git")) { @@ -2457,11 +2442,10 @@ public void testOutdatedSubmodulesNotRemoved() throws Exception { */ CliGitCommand cloneRepoCmd = new CliGitCommand(cloneGitClient); cloneRepoCmd.run("clean", "-xffd"); - assertFalse("cloneFirewallDir not deleted " + cloneFirewallDir, cloneFirewallDir.isDirectory()); + assertFalse(cloneFirewallDir.isDirectory(), "cloneFirewallDir not deleted " + cloneFirewallDir); } - private void assertBranches(GitClient client, String... expectedBranchNames) - throws GitException, InterruptedException { + private void assertBranches(GitClient client, String... expectedBranchNames) throws Exception { List branchNames = new ArrayList<>(); // Arrays.asList(expectedBranchNames); for (Branch branch : client.getBranches()) { if (branch.getName().startsWith("remotes/")) { @@ -2489,9 +2473,10 @@ private void enableLongPaths(GitClient gitClient) throws Exception { } } - @Issue("JENKINS-37419") // Submodules from other branches are used in checkout + @Issue("JENKINS-37419") + // Submodules from other branches are used in checkout @Test - public void testSubmodulesUsedFromOtherBranches() throws Exception { + void testSubmodulesUsedFromOtherBranches() throws Exception { /* Submodules not fully supported with JGit */ // JGit implementation doesn't handle renamed submodules if (!gitImplName.equals("git") || isWindows()) { @@ -2574,11 +2559,11 @@ public void testSubmodulesUsedFromOtherBranches() throws Exception { @Issue("JENKINS-46054") @Test - public void testSubmoduleUrlEndsWithDotUrl() throws Exception { + void testSubmoduleUrlEndsWithDotUrl() throws Exception { // Create a new repository that includes ".url" in directory name - File baseDir = tempFolder.newFolder(); + File baseDir = newFolder(tempFolder, "junit-" + System.nanoTime()); File urlRepoDir = new File(baseDir, "my-submodule.url"); - assertTrue("Failed to create URL repo dir", urlRepoDir.mkdir()); + assertTrue(urlRepoDir.mkdir(), "Failed to create URL repo dir"); GitClient urlRepoClient = Git.with(TaskListener.NULL, new EnvVars()) .in(urlRepoDir) .using(gitImplName) @@ -2597,7 +2582,7 @@ public void testSubmoduleUrlEndsWithDotUrl() throws Exception { // Add new repository as submodule to repository that ends in .url File repoHasSubmodule = new File(baseDir, "has-submodule.url"); - assertTrue("Failed to create repo dir that will have submodule", repoHasSubmodule.mkdir()); + assertTrue(repoHasSubmodule.mkdir(), "Failed to create repo dir that will have submodule"); GitClient repoHasSubmoduleClient = Git.with(TaskListener.NULL, new EnvVars()) .in(repoHasSubmodule) .using(gitImplName) @@ -2617,7 +2602,7 @@ public void testSubmoduleUrlEndsWithDotUrl() throws Exception { repoHasSubmoduleClient.commit("Added README to repo that will include a submodule whose URL ends in '.url'"); String moduleDirBaseName = "module.named.url"; File modulesDir = new File(repoHasSubmodule, "modules"); - assertTrue("Failed to create modules dir in repoHasSubmodule", modulesDir.mkdir()); + assertTrue(modulesDir.mkdir(), "Failed to create modules dir in repoHasSubmodule"); /* The test fails on Windows CLI git if modulesDir is more than about 200 characters, even with long paths enabled */ if (this.srcGitClient instanceof CliGitAPIImpl @@ -2635,7 +2620,7 @@ && isWindows() // Clone repoHasSubmodule to new repository with submodule File cloneDir = new File(baseDir, "cloned-submodule"); - assertTrue("Failed to create clone dir", cloneDir.mkdir()); + assertTrue(cloneDir.mkdir(), "Failed to create clone dir"); GitClient cloneGitClient = Git.with(TaskListener.NULL, new EnvVars()) .in(cloneDir) .using(gitImplName) @@ -2652,7 +2637,7 @@ && isWindows() } @Test - public void testGetSubmodules() throws Exception { + void testGetSubmodules() throws Exception { // JGit implementation doesn't handle renamed submodules if (!gitImplName.equals("git")) { return; @@ -2669,7 +2654,7 @@ public void testGetSubmodules() throws Exception { } @Test - public void testFixSubmoduleUrls() throws Exception { + void testFixSubmoduleUrls() throws Exception { // CliGit if (!gitImplName.equals("git")) { return; @@ -2683,7 +2668,7 @@ public void testFixSubmoduleUrls() throws Exception { } @Test - public void testFixSubmoduleUrlsInvalidRemote() { + void testFixSubmoduleUrlsInvalidRemote() { // CliGit if (!gitImplName.equals("git")) { return; @@ -2695,7 +2680,7 @@ public void testFixSubmoduleUrlsInvalidRemote() { } @Test - public void testFixSubmoduleUrlsJGitUnsupported() { + void testFixSubmoduleUrlsJGitUnsupported() { // JGit does not support fixSubmoduleUrls if (gitImplName.equals("git")) { return; @@ -2714,11 +2699,11 @@ private void assertStatusUntrackedContent(GitClient client, boolean expectUntrac } output.append(line); } - assertEquals("Untracked content: " + output, expectUntrackedContent, foundUntrackedContent); + assertEquals(expectUntrackedContent, foundUntrackedContent, "Untracked content: " + output); } @Test - public void testSubmoduleClean() throws Exception { + void testSubmoduleClean() throws Exception { String branchName = "tests/getSubmodules"; String upstream = checkoutAndAssertHasGitModules(branchName, true); gitClient.submoduleInit(); @@ -2785,58 +2770,58 @@ public void testSetupSubmoduleUrls() throws Exception { * include these tags, the describe tests will fail. */ @Test - public void testDescribeSrcCommit() throws Exception { + void testDescribeSrcCommit() throws Exception { assertThat(srcGitClient.describe(upstreamCommit.getName()), startsWith("git-client-1.6.3-23-gf75720d")); } @Test - public void testDescribeSrcCommitPredecessor() throws Exception { + void testDescribeSrcCommitPredecessor() throws Exception { assertThat( srcGitClient.describe(upstreamCommitPredecessor.getName()), startsWith("git-client-1.6.3-22-g867e5f1")); } @Test - public void testDescribeTag() throws Exception { + void testDescribeTag() throws Exception { assertThat(srcGitClient.describe("git-client-1.19.6"), startsWith("git-client-1.19.6")); } @Test - public void testDescribeTagFromMerge() throws Exception { + void testDescribeTagFromMerge() throws Exception { assertThat( srcGitClient.describe("40d44ffce5fa589605dd6b6ad92ab7235a92b330"), startsWith("git-client-1.0.7-74-g40d44ff")); } @Test - public void testDescribeTagDeepGraph() throws Exception { + void testDescribeTagDeepGraph() throws Exception { assertThat( srcGitClient.describe("640ef19f4157d9a5508d46c3f9ad0c41d7d7ef51"), startsWith("git-client-1.19.0-38-g640ef19")); } @Test - public void testDescribeTagDeeperGraph() throws Exception { + void testDescribeTagDeeperGraph() throws Exception { assertThat( srcGitClient.describe("88ca6b449dd155a03d7142c9ad5f17fd7ca2b34e"), startsWith("git-client-1.11.0-24-g88ca6b4")); } - @Test(expected = GitException.class) - public void testDescribeNoTag() throws Exception { - srcGitClient.describe("5a865818566c9d03738cdcd49cc0a1543613fd41"); + @Test + void testDescribeNoTag() { + assertThrows(GitException.class, () -> srcGitClient.describe("5a865818566c9d03738cdcd49cc0a1543613fd41")); } /* A SHA1 that exists in src repo, but unlikely to be referenced from a local branch in src repo */ private final String TESTS_NOT_SUBMODULE_SHA1 = "f04fae26f6b612c4a575314222d72c20ca4090a5"; @Test - public void testgetBranchesContainingTrue_existing_sha1() throws Exception { + void testGetBranchesContainingTrue_existing_sha1() throws Exception { List branches = srcGitClient.getBranchesContaining(TESTS_NOT_SUBMODULE_SHA1, true); assertThat(branches, is(not(empty()))); } @Test - public void testgetBranchesContainingFalse_existing_sha1() throws Exception { + void testGetBranchesContainingFalse_existing_sha1() throws Exception { List branches = srcGitClient.getBranchesContaining(TESTS_NOT_SUBMODULE_SHA1, false); assertThat(branches, is(empty())); } @@ -2844,18 +2829,18 @@ public void testgetBranchesContainingFalse_existing_sha1() throws Exception { /* A SHA1 that doesn't exist in src repo */ private final String NON_EXISTENT_SHA1 = "adbadcaddadfadba11adbeefb1abbedb1adebed5"; - @Test(expected = GitException.class) - public void testgetBranchesContainingTrue_non_existent_sha1() throws Exception { - srcGitClient.getBranchesContaining(NON_EXISTENT_SHA1, true); + @Test + void testGetBranchesContainingTrue_non_existent_sha1() { + assertThrows(GitException.class, () -> srcGitClient.getBranchesContaining(NON_EXISTENT_SHA1, true)); } - @Test(expected = GitException.class) - public void testgetBranchesContainingFalse_non_existent_sha1() throws Exception { - srcGitClient.getBranchesContaining(NON_EXISTENT_SHA1, false); + @Test + void testGetBranchesContainingFalse_non_existent_sha1() { + assertThrows(GitException.class, () -> srcGitClient.getBranchesContaining(NON_EXISTENT_SHA1, false)); } @Test - public void testgetRemoteSymbolicReferences_null() throws Exception { + void testGetRemoteSymbolicReferences_null() throws Exception { commitOneFile("A-Single-File-Commit"); assertThat( gitClient.getRemoteSymbolicReferences(repoRoot.getAbsolutePath(), null), @@ -2863,7 +2848,7 @@ public void testgetRemoteSymbolicReferences_null() throws Exception { } @Test - public void testgetRemoteSymbolicReferences_null_old_git() throws Exception { + void testGetRemoteSymbolicReferences_null_old_git() throws Exception { commitOneFile("A-Single-File-Commit"); assertThat( gitClient.getRemoteSymbolicReferences(repoRoot.getAbsolutePath(), null), @@ -2871,7 +2856,7 @@ public void testgetRemoteSymbolicReferences_null_old_git() throws Exception { } @Test - public void testgetRemoteSymbolicReferences_with_non_matching_pattern() throws Exception { + void testGetRemoteSymbolicReferences_with_non_matching_pattern() throws Exception { commitOneFile("A-Single-File-Commit"); assertThat( gitClient @@ -2881,7 +2866,7 @@ public void testgetRemoteSymbolicReferences_with_non_matching_pattern() throws E } @Test - public void testgetRemoteSymbolicReferences_with_matching_pattern() throws Exception { + void testGetRemoteSymbolicReferences_with_matching_pattern() throws Exception { commitOneFile("A-Single-File-Commit"); assertThat( gitClient.getRemoteSymbolicReferences(repoRoot.getAbsolutePath(), Constants.HEAD), @@ -2889,7 +2874,7 @@ public void testgetRemoteSymbolicReferences_with_matching_pattern() throws Excep } @Test - public void testgetRemoteSymbolicReferences_with_matching_pattern_old() throws Exception { + void testGetRemoteSymbolicReferences_with_matching_pattern_old() throws Exception { commitOneFile("A-Single-File-Commit"); assertThat( gitClient.getRemoteSymbolicReferences(repoRoot.getAbsolutePath(), Constants.HEAD), @@ -2897,7 +2882,7 @@ public void testgetRemoteSymbolicReferences_with_matching_pattern_old() throws E } @Test - public void testgetRemoteSymbolicReferences_with_non_default_HEAD() throws Exception { + void testGetRemoteSymbolicReferences_with_non_default_HEAD() throws Exception { commitOneFile("A-Single-File-Commit"); CliGitCommand gitCmd = new CliGitCommand(gitClient); @@ -2917,21 +2902,24 @@ public void testgetRemoteSymbolicReferences_with_non_default_HEAD() throws Excep hasEntry(Constants.HEAD, "refs/heads/new-branch")); } - @Test(expected = GitException.class) - public void testgetRemoteSymbolicReferences_URI_Syntax() throws Exception { - gitClient.getRemoteSymbolicReferences("error: invalid repo URL", Constants.HEAD); + @Test + void testGetRemoteSymbolicReferences_URI_Syntax() { + assertThrows( + GitException.class, + () -> gitClient.getRemoteSymbolicReferences("error: invalid repo URL", Constants.HEAD)); } - @Test(expected = GitException.class) - public void testgetRemoteSymbolicReferences_URI_Syntax_old_jgit() throws Exception { - if (gitImplName.equals("git")) { - throw new GitException("Skipping JGit tests in testgetRemoteSymbolicReferences_URI_Syntax_old_jgit"); - } - gitClient.getRemoteSymbolicReferences("error: invalid repo URL", Constants.HEAD); + @Test + void testGetRemoteSymbolicReferences_URI_Syntax_old_jgit() { + assumeTrue( + gitImplName.equals("git"), + "Skipping JGit tests in testGetRemoteSymbolicReferences_URI_Syntax_old_jgit"); + String x = Constants.HEAD; + assertThrows(GitException.class, () -> gitClient.getRemoteSymbolicReferences("error: invalid repo URL", x)); } @Test - public void testgetRemoteSymbolicReferences_URI_Syntax_old_git() throws Exception { + void testGetRemoteSymbolicReferences_URI_Syntax_old_git() throws Exception { if (!gitImplName.equals("git")) { return; } @@ -2942,26 +2930,28 @@ public void testgetRemoteSymbolicReferences_URI_Syntax_old_git() throws Exceptio hasSize(0)); } - @Test(expected = GitException.class) - public void testgetRemoteReferences_URI_Syntax() throws Exception { - gitClient.getRemoteReferences("error: invalid repo URL", Constants.HEAD, false, false); + @Test + void testGetRemoteReferences_URI_Syntax() { + assertThrows( + GitException.class, + () -> gitClient.getRemoteReferences("error: invalid repo URL", Constants.HEAD, false, false)); } @Test - public void testGetTags() throws Exception { + void testGetTags() throws Exception { Set result = gitClient.getTags(); assertThat(result, is(empty())); } @Test - public void testGetTags_NoTags() throws Exception { + void testGetTags_NoTags() throws Exception { ObjectId commitOne = commitOneFile(); Set result = gitClient.getTags(); assertThat(result, is(empty())); } @Test - public void testGetTags_OneTag() throws Exception { + void testGetTags_OneTag() throws Exception { ObjectId commitOne = commitOneFile(); String tagName = "tag-one"; gitClient.tag(tagName, "Comment for annotated " + tagName); @@ -2972,7 +2962,7 @@ public void testGetTags_OneTag() throws Exception { } @Test - public void testGetTags_ThreeTags() throws Exception { + void testGetTags_ThreeTags() throws Exception { ObjectId commitOne = commitOneFile(); String tagName = "tag-one-annotated"; gitClient.tag(tagName, "Comment for annotated " + tagName); @@ -3010,7 +3000,7 @@ private String padLinesWithSpaces(String src, int spacePadCount) { @Test @Issue("JENKINS-29977") - public void testChangelogFirstLineTruncation() throws Exception { + void testChangelogFirstLineTruncation() throws Exception { // 1 2 3 4 5 6 7 8 // 12345678901234567890123456789012345678901234567890123456789012345678901234567890 final String longFirstLine = @@ -3046,9 +3036,10 @@ public void testChangelogFirstLineTruncation() throws Exception { assertThat(changelogStringWriter.toString(), containsString(padLinesWithSpaces(commitMessage, 4))); } + // Pull must overwrite existing tags @Test - @Issue("JENKINS-55284") // Pull must overwrite existing tags - public void testFetchOverwritesExistingTags() throws Exception { + @Issue("JENKINS-55284") + void testFetchOverwritesExistingTags() throws Exception { fetchWithTags(gitClient, "origin"); /* Confirm expected tag exists */ @@ -3079,7 +3070,7 @@ public void testFetchOverwritesExistingTags() throws Exception { // Tests ported from CliGitAPIImplTest @Test - public void test_git_version_debian_wheezy() { + void test_git_version_debian_wheezy() { if (!gitImplName.equals("git")) { return; } @@ -3092,7 +3083,7 @@ public void test_git_version_debian_wheezy() { } @Test - public void test_git_version_debian_testing() { + void test_git_version_debian_testing() { if (!gitImplName.equals("git")) { return; } @@ -3106,7 +3097,7 @@ public void test_git_version_debian_testing() { } @Test - public void test_git_version_debian_testing_old() { + void test_git_version_debian_testing_old() { if (!gitImplName.equals("git")) { return; } @@ -3123,7 +3114,7 @@ public void test_git_version_debian_testing_old() { } @Test - public void test_git_version_debian_testing_older() { + void test_git_version_debian_testing_older() { if (!gitImplName.equals("git")) { return; } @@ -3136,7 +3127,7 @@ public void test_git_version_debian_testing_older() { } @Test - public void test_git_version_windows_1800() { + void test_git_version_windows_1800() { if (!gitImplName.equals("git")) { return; } @@ -3149,7 +3140,7 @@ public void test_git_version_windows_1800() { } @Test - public void test_git_version_windows_1840() { + void test_git_version_windows_1840() { if (!gitImplName.equals("git")) { return; } @@ -3162,7 +3153,7 @@ public void test_git_version_windows_1840() { } @Test - public void test_git_version_windows_1852() { + void test_git_version_windows_1852() { if (!gitImplName.equals("git")) { return; } @@ -3175,7 +3166,7 @@ public void test_git_version_windows_1852() { } @Test - public void test_git_version_windows_1900() { + void test_git_version_windows_1900() { if (!gitImplName.equals("git")) { return; } @@ -3188,7 +3179,7 @@ public void test_git_version_windows_1900() { } @Test - public void test_git_version_windows_1920() { + void test_git_version_windows_1920() { if (!gitImplName.equals("git")) { return; } @@ -3201,7 +3192,7 @@ public void test_git_version_windows_1920() { } @Test - public void test_git_version_windows_1940() { + void test_git_version_windows_1940() { if (!gitImplName.equals("git")) { return; } @@ -3214,7 +3205,7 @@ public void test_git_version_windows_1940() { } @Test - public void test_git_version_windows_2501() { + void test_git_version_windows_2501() { if (!gitImplName.equals("git")) { return; } @@ -3227,7 +3218,7 @@ public void test_git_version_windows_2501() { } @Test - public void test_git_version_windows_2_10_1_1() { + void test_git_version_windows_2_10_1_1() { if (!gitImplName.equals("git")) { return; } @@ -3242,7 +3233,7 @@ public void test_git_version_windows_2_10_1_1() { } @Test - public void test_git_version_redhat_5() { + void test_git_version_redhat_5() { if (!gitImplName.equals("git")) { return; } @@ -3255,7 +3246,7 @@ public void test_git_version_redhat_5() { } @Test - public void test_git_version_redhat_65() { + void test_git_version_redhat_65() { if (!gitImplName.equals("git")) { return; } @@ -3269,7 +3260,7 @@ public void test_git_version_redhat_65() { } @Test - public void test_git_version_opensuse_13() { + void test_git_version_opensuse_13() { if (!gitImplName.equals("git")) { return; } @@ -3282,7 +3273,7 @@ public void test_git_version_opensuse_13() { } @Test - public void test_git_version_ubuntu_13() { + void test_git_version_ubuntu_13() { if (!gitImplName.equals("git")) { return; } @@ -3295,7 +3286,7 @@ public void test_git_version_ubuntu_13() { } @Test - public void test_git_version_ubuntu_14_04_ppa() { + void test_git_version_ubuntu_14_04_ppa() { if (!gitImplName.equals("git")) { return; } @@ -3308,7 +3299,7 @@ public void test_git_version_ubuntu_14_04_ppa() { } @Test - public void test_git_version_ubuntu_14_04_ppa_2_3_0() { + void test_git_version_ubuntu_14_04_ppa_2_3_0() { if (!gitImplName.equals("git")) { return; } @@ -3321,7 +3312,7 @@ public void test_git_version_ubuntu_14_04_ppa_2_3_0() { } @Test - public void test_git_version_ubuntu_14_04_ppa_2_3_5() { + void test_git_version_ubuntu_14_04_ppa_2_3_5() { if (!gitImplName.equals("git")) { return; } @@ -3336,34 +3327,43 @@ public void test_git_version_ubuntu_14_04_ppa_2_3_5() { } @Test - public void test_git_ssh_executable_found_on_windows() { + void test_git_ssh_executable_found_on_windows() { if (!gitImplName.equals("git") || !isWindows()) { return; } - cliGitAPIImplTest.setTimeoutVisibleInCurrentTest(false); CliGitAPIImpl git = new CliGitAPIImpl("git", new File("."), cliGitAPIImplTest.listener, cliGitAPIImplTest.env); - assertTrue("ssh.exe not found", git.getSSHExecutable().exists()); + assertTrue(git.getSSHExecutable().exists(), "ssh.exe not found"); } @Test - public void test_git_branch_with_line_breaks_and_long_strings() throws Exception { + void test_git_branch_with_line_breaks_and_long_strings() { if (!gitImplName.equals("git")) { return; } // Embedded \r (carriage return) must be retained in the gitBranchOutput String gitBranchOutput = - "* (HEAD detached at b297853) b297853e667d5989801937beea30fcec7d1d2595 Commit message with line breaks\r very-long-string-with-more-than-44-characters\n" - + " remotes/origin/master e0d3f46c4fdb8acd068b6b127356931411d16e23 Commit message with line breaks\r very-long-string-with-more-than-44-characters and some more text\n" - + " remotes/origin/develop fc8996efc1066d9dae529e5187800f84995ca56f Single-line commit message\n"; + """ + * (HEAD detached at b297853) b297853e667d5989801937beea30fcec7d1d2595 Commit message with line breaks\r very-long-string-with-more-than-44-characters + remotes/origin/master e0d3f46c4fdb8acd068b6b127356931411d16e23 Commit message with line breaks\r very-long-string-with-more-than-44-characters and some more text + remotes/origin/develop fc8996efc1066d9dae529e5187800f84995ca56f Single-line commit message + """; - cliGitAPIImplTest.setTimeoutVisibleInCurrentTest(false); CliGitAPIImpl git = new CliGitAPIImpl("git", new File("."), cliGitAPIImplTest.listener, cliGitAPIImplTest.env); Set branches = git.parseBranches(gitBranchOutput); - assertEquals("\"git branch -a -v --no-abbrev\" output correctly parsed", 2, branches.size()); + assertEquals(2, branches.size(), "\"git branch -a -v --no-abbrev\" output correctly parsed"); } private boolean isWindows() { return File.pathSeparatorChar == ';'; } + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitHostKeyVerificationConfigurationTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitHostKeyVerificationConfigurationTest.java index b534613982..76ab44fb62 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitHostKeyVerificationConfigurationTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitHostKeyVerificationConfigurationTest.java @@ -8,17 +8,17 @@ import org.jenkinsci.plugins.gitclient.verifier.KnownHostsFileVerificationStrategy; import org.jenkinsci.plugins.gitclient.verifier.ManuallyProvidedKeyVerificationStrategy; import org.jenkinsci.plugins.gitclient.verifier.NoHostKeyVerificationStrategy; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension; -public class GitHostKeyVerificationConfigurationTest { +class GitHostKeyVerificationConfigurationTest { - @Rule - public RestartableJenkinsRule r = new RestartableJenkinsRule(); + @RegisterExtension + private final JenkinsSessionExtension r = new JenkinsSessionExtension(); @Test - public void testGitHostKeyVerificationConfigurationSavedBetweenSessions() { + void testGitHostKeyVerificationConfigurationSavedBetweenSessions() throws Throwable { String hostKey = "github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl"; ManuallyProvidedKeyVerificationStrategy manuallyProvidedKeyVerificationStrategy = new ManuallyProvidedKeyVerificationStrategy(hostKey); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitJenkinsRuleTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitJenkinsRuleTest.java index 58dcf1f37c..adadd0fcec 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitJenkinsRuleTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitJenkinsRuleTest.java @@ -1,24 +1,29 @@ package org.jenkinsci.plugins.gitclient; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import hudson.EnvVars; import hudson.model.TaskListener; import java.io.File; -import java.io.IOException; import org.hamcrest.core.IsInstanceOf; -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 GitJenkinsRuleTest { +@WithJenkins +class GitJenkinsRuleTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; + + @BeforeEach + void setUp(JenkinsRule rule) { + r = rule; + } @Test - public void testMockClient() throws IOException, InterruptedException { + void testMockClient() throws Exception { System.setProperty(Git.class.getName() + ".mockClient", MyMockGitClient.class.getName()); try { Git git = new Git(null, null).in(new File(".")).using("Hello World"); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitTest.java index 79ed884eb4..1855114c77 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitTest.java @@ -1,98 +1,105 @@ package org.jenkinsci.plugins.gitclient; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; import hudson.FilePath; import java.io.File; -import java.util.Arrays; -import java.util.Collection; +import java.util.List; import org.eclipse.jgit.lib.ObjectId; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Trivial tests of defaults asserted in the javadoc of Git class. * * @author Mark Waite */ -@RunWith(Parameterized.class) -public class GitTest { +@ParameterizedClass(name = "{0}") +@MethodSource("gitImplementation") +class GitTest { /* A known commit from the git-client-plugin repository */ - private ObjectId expectedCommit = null; + private ObjectId expectedCommit; - @Parameterized.Parameters(name = "{0}") - public static Collection gitImplementation() { - return Arrays.asList(new Object[][] {{"git"}, {"jgit"}}); + static List gitImplementation() { + return List.of(Arguments.of("git"), Arguments.of("jgit")); } - private final String implementation; + @Parameter(0) + private String implementation; - public GitTest(String implementation) throws Exception { - this.implementation = implementation; - Git git = new Git(null, null).using(implementation).in(new File(".")); - expectedCommit = git.getClient().revParse("HEAD"); + @BeforeEach + void setUp() throws Exception { + expectedCommit = new Git(null, null) + .using(implementation) + .in(new File(".")) + .getClient() + .revParse("HEAD"); } @Test - public void testWith() throws Exception { + void testWith() throws Exception { Git git = Git.with(null, null); - assertTrue("Wrong default client type", git.getClient() instanceof JGitAPIImpl); - assertTrue("Missing expected commit", git.getClient().isCommitInRepo(expectedCommit)); + assertInstanceOf(JGitAPIImpl.class, git.getClient(), "Wrong default client type"); + assertTrue(git.getClient().isCommitInRepo(expectedCommit), "Missing expected commit"); git = Git.with(null, null).using(implementation); assertTrue( - "Wrong client type", implementation.equals("git") ? git.getClient() instanceof CliGitAPIImpl - : git.getClient() instanceof JGitAPIImpl); - assertTrue("Missing expected commit", git.getClient().isCommitInRepo(expectedCommit)); + : git.getClient() instanceof JGitAPIImpl, + "Wrong client type"); + assertTrue(git.getClient().isCommitInRepo(expectedCommit), "Missing expected commit"); } @Test - public void testIn_File() throws Exception { + void testIn_File() throws Exception { Git git = new Git(null, null).in(new File(".")); - assertTrue("Wrong client type", git.getClient() instanceof JGitAPIImpl); - assertTrue("Missing expected commit", git.getClient().isCommitInRepo(expectedCommit)); + assertInstanceOf(JGitAPIImpl.class, git.getClient(), "Wrong client type"); + assertTrue(git.getClient().isCommitInRepo(expectedCommit), "Missing expected commit"); } @Test - public void testIn_FileUsing() throws Exception { + void testIn_FileUsing() throws Exception { Git git = new Git(null, null).in(new File(".")).using(implementation); assertTrue( - "Wrong client type", implementation.equals("git") ? git.getClient() instanceof CliGitAPIImpl - : git.getClient() instanceof JGitAPIImpl); - assertTrue("Missing expected commit", git.getClient().isCommitInRepo(expectedCommit)); + : git.getClient() instanceof JGitAPIImpl, + "Wrong client type"); + assertTrue(git.getClient().isCommitInRepo(expectedCommit), "Missing expected commit"); } @Test - public void testIn_FilePath() throws Exception { + void testIn_FilePath() throws Exception { Git git = new Git(null, null).in(new FilePath(new File("."))); - assertTrue("Wrong client type", git.getClient() instanceof JGitAPIImpl); - assertTrue("Missing expected commit", git.getClient().isCommitInRepo(expectedCommit)); + assertInstanceOf(JGitAPIImpl.class, git.getClient(), "Wrong client type"); + assertTrue(git.getClient().isCommitInRepo(expectedCommit), "Missing expected commit"); } @Test - public void testIn_FilePathUsing() throws Exception { + void testIn_FilePathUsing() throws Exception { Git git = new Git(null, null).in(new File(".")).using(implementation); assertTrue( - "Wrong client type", implementation.equals("git") ? git.getClient() instanceof CliGitAPIImpl - : git.getClient() instanceof JGitAPIImpl); - assertTrue("Missing expected commit", git.getClient().isCommitInRepo(expectedCommit)); + : git.getClient() instanceof JGitAPIImpl, + "Wrong client type"); + assertTrue(git.getClient().isCommitInRepo(expectedCommit), "Missing expected commit"); } @Test - public void testUsing() throws Exception { + void testUsing() throws Exception { Git git = new Git(null, null).using(implementation); assertTrue( - "Wrong client type", implementation.equals("git") ? git.getClient() instanceof CliGitAPIImpl - : git.getClient() instanceof JGitAPIImpl); - assertTrue("Missing expected commit", git.getClient().isCommitInRepo(expectedCommit)); + : git.getClient() instanceof JGitAPIImpl, + "Wrong client type"); + assertTrue(git.getClient().isCommitInRepo(expectedCommit), "Missing expected commit"); } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitToolConfiguratorJenkinsRuleTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitToolConfiguratorJenkinsRuleTest.java index 582987603c..f33b6632c5 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitToolConfiguratorJenkinsRuleTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitToolConfiguratorJenkinsRuleTest.java @@ -40,23 +40,25 @@ import io.jenkins.plugins.casc.model.Sequence; import java.util.ArrayList; import java.util.List; -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 GitToolConfiguratorJenkinsRuleTest { +@WithJenkins +class GitToolConfiguratorJenkinsRuleTest { - private final GitToolConfigurator gitToolConfigurator; + private final GitToolConfigurator gitToolConfigurator = new GitToolConfigurator(); - public GitToolConfiguratorJenkinsRuleTest() { - gitToolConfigurator = new GitToolConfigurator(); - } + private JenkinsRule r; - @Rule - public JenkinsRule r = new JenkinsRule(); + @BeforeEach + void setUp(JenkinsRule rule) { + r = rule; + } @Test - public void testDescribeGitToolEmptyProperties() throws Exception { + void testDescribeGitToolEmptyProperties() throws Exception { String gitName = "git-2.19.1-name"; String gitHome = "/opt/git-2.19.1/bin/git"; @@ -78,7 +80,7 @@ public void testDescribeGitToolEmptyProperties() throws Exception { } @Test - public void testDescribeGitTool() throws Exception { + void testDescribeGitTool() throws Exception { String gitName = "git-2.19.1-name"; String gitHome = "/opt/git-2.19.1/bin/git"; diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitToolConfiguratorTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitToolConfiguratorTest.java index a39d04d709..6b8e251fb3 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitToolConfiguratorTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitToolConfiguratorTest.java @@ -30,9 +30,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -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.*; import hudson.plugins.git.GitTool; import hudson.tools.ToolProperty; @@ -42,56 +40,52 @@ import io.jenkins.plugins.casc.model.CNode; import io.jenkins.plugins.casc.model.Mapping; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GitToolConfiguratorTest { +class GitToolConfiguratorTest { - private final GitToolConfigurator gitToolConfigurator; + private final GitToolConfigurator gitToolConfigurator = new GitToolConfigurator(); private static final ConfigurationContext NULL_CONFIGURATION_CONTEXT = null; - public GitToolConfiguratorTest() { - gitToolConfigurator = new GitToolConfigurator(); - } - @Test - public void testGetName() { + void testGetName() { assertThat(gitToolConfigurator.getName(), is("git")); } @Test - public void testGetDisplayName() { + void testGetDisplayName() { assertThat(gitToolConfigurator.getDisplayName(), is("Git")); } @Test - public void testGetTarget() { - assertEquals("Wrong target class", gitToolConfigurator.getTarget(), GitTool.class); + void testGetTarget() { + assertEquals(GitTool.class, gitToolConfigurator.getTarget(), "Wrong target class"); } @Test - public void testCanConfigure() { - assertTrue("Can't configure GitTool", gitToolConfigurator.canConfigure(GitTool.class)); - assertFalse("Can configure GitToolConfigurator", gitToolConfigurator.canConfigure(GitToolConfigurator.class)); + void testCanConfigure() { + assertTrue(gitToolConfigurator.canConfigure(GitTool.class), "Can't configure GitTool"); + assertFalse(gitToolConfigurator.canConfigure(GitToolConfigurator.class), "Can configure GitToolConfigurator"); } @Test - public void testGetImplementedAPI() { - assertEquals("Wrong implemented API", gitToolConfigurator.getImplementedAPI(), GitTool.class); + void testGetImplementedAPI() { + assertEquals(GitTool.class, gitToolConfigurator.getImplementedAPI(), "Wrong implemented API"); } @Test - public void testGetConfigurators() { + void testGetConfigurators() { assertThat(gitToolConfigurator.getConfigurators(NULL_CONFIGURATION_CONTEXT), contains(gitToolConfigurator)); } @Test - public void testDescribe() throws Exception { + void testDescribe() throws Exception { GitTool nullGitTool = null; assertThat(gitToolConfigurator.describe(nullGitTool, NULL_CONFIGURATION_CONTEXT), is(new Mapping())); } @Test - public void testDescribeJGitTool() throws Exception { + void testDescribeJGitTool() throws Exception { GitTool gitTool = new JGitTool(); CNode cNode = gitToolConfigurator.describe(gitTool, NULL_CONFIGURATION_CONTEXT); assertThat(cNode, is(notNullValue())); @@ -101,7 +95,7 @@ public void testDescribeJGitTool() throws Exception { } @Test - public void testDescribeJGitApacheTool() throws Exception { + void testDescribeJGitApacheTool() throws Exception { GitTool gitTool = new JGitApacheTool(); CNode cNode = gitToolConfigurator.describe(gitTool, NULL_CONFIGURATION_CONTEXT); assertThat(cNode, is(notNullValue())); @@ -111,7 +105,7 @@ public void testDescribeJGitApacheTool() throws Exception { } @Test - public void testDescribeGitToolWithoutProperties() throws Exception { + void testDescribeGitToolWithoutProperties() throws Exception { String gitName = "git-name"; String gitHome = "/opt/git-2.23.0/bin/git"; GitTool gitTool = new GitTool(gitName, gitHome, null); @@ -124,7 +118,7 @@ public void testDescribeGitToolWithoutProperties() throws Exception { } @Test - public void testInstance() throws Exception { + void testInstance() { Mapping mapping = null; ConfigurationContext context = new ConfigurationContext(null); GitTool gitTool = gitToolConfigurator.instance(mapping, context); @@ -134,7 +128,7 @@ public void testInstance() throws Exception { } @Test - public void testInstanceJGitTool() throws Exception { + void testInstanceJGitTool() { Mapping mapping = new Mapping(); mapping.put("name", JGitTool.MAGIC_EXENAME); ConfigurationContext context = new ConfigurationContext(null); @@ -144,7 +138,7 @@ public void testInstanceJGitTool() throws Exception { } @Test - public void testInstanceJGitToolWithHome() throws Exception { + void testInstanceJGitToolWithHome() { Mapping mapping = new Mapping(); mapping.put("name", JGitTool.MAGIC_EXENAME); mapping.put("home", "unused-value-for-home"); // Will log a message @@ -155,7 +149,7 @@ public void testInstanceJGitToolWithHome() throws Exception { } @Test - public void testInstanceJGitApacheTool() throws Exception { + void testInstanceJGitApacheTool() { Mapping mapping = new Mapping(); mapping.put("name", JGitApacheTool.MAGIC_EXENAME); ConfigurationContext context = new ConfigurationContext(null); @@ -165,7 +159,7 @@ public void testInstanceJGitApacheTool() throws Exception { } @Test - public void testInstanceJGitApacheToolWithHome() throws Exception { + void testInstanceJGitApacheToolWithHome() { Mapping mapping = new Mapping(); mapping.put("name", JGitApacheTool.MAGIC_EXENAME); mapping.put("home", "unused-value-for-home"); // Will log a message @@ -175,16 +169,16 @@ public void testInstanceJGitApacheToolWithHome() throws Exception { assertThat(gitTool, is(not(instanceOf(JGitTool.class)))); } - @Test(expected = ConfiguratorException.class) - public void testInstanceGitToolWithoutHome() throws Exception { + @Test + void testInstanceGitToolWithoutHome() { Mapping mapping = new Mapping(); - mapping.put("name", "testGitName"); // No home mapping defined + mapping.put("name", "testGitName"); ConfigurationContext context = new ConfigurationContext(null); - gitToolConfigurator.instance(mapping, context); + assertThrows(ConfiguratorException.class, () -> gitToolConfigurator.instance(mapping, context)); } @Test - public void testInstanceGitTool() throws Exception { + void testInstanceGitTool() { Mapping mapping = new Mapping(); String gitHome = "testGitHome"; String gitName = "testGitName"; @@ -200,7 +194,7 @@ public void testInstanceGitTool() throws Exception { } @Test - public void testGetAttributes() { + void testGetAttributes() { List> gitToolAttributes = gitToolConfigurator.getAttributes(); Attribute name = new Attribute<>("name", String.class); Attribute home = new Attribute<>("home", String.class); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/GitURIRequirementsBuilderTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/GitURIRequirementsBuilderTest.java index 3ee5459b53..efce9e5f31 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/GitURIRequirementsBuilderTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/GitURIRequirementsBuilderTest.java @@ -11,16 +11,16 @@ import com.cloudbees.plugins.credentials.domains.PathRequirement; import com.cloudbees.plugins.credentials.domains.SchemeRequirement; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author stephenc * @since 30/08/2013 15:05 */ -public class GitURIRequirementsBuilderTest { +class GitURIRequirementsBuilderTest { @Test - public void smokes() { + void smokes() { List list = GitURIRequirementsBuilder.fromUri("ssh://bob@foo.bar.com:8080/path/to/repo.git/") .build(); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/JGitAPIImplTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/JGitAPIImplTest.java index 7c2429ce1f..c2a8c6a64d 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/JGitAPIImplTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/JGitAPIImplTest.java @@ -5,17 +5,13 @@ /** * @author Nicolas De Loof */ -public class JGitAPIImplTest extends GitAPITestUpdate { +class JGitAPIImplTest extends GitAPITestUpdate { + @Override protected GitClient setupGitAPI(File ws) throws Exception { return Git.with(listener, env).in(ws).using("jgit").getClient(); } - @Override - protected boolean getTimeoutVisibleInCurrentTest() { - return true; // git client plugin 3.11.0 supports JGit timeout - } - @Override protected String getRemoteBranchPrefix() { return ""; diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/JGitAPIImplUnsupportedProtocolTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/JGitAPIImplUnsupportedProtocolTest.java index 0d62516fe7..9b13b58d5c 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/JGitAPIImplUnsupportedProtocolTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/JGitAPIImplUnsupportedProtocolTest.java @@ -2,54 +2,55 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import hudson.model.TaskListener; import hudson.plugins.git.GitException; +import java.io.File; import java.util.List; import java.util.Random; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; -import org.junit.Before; -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; +import org.junit.jupiter.api.io.TempDir; /** * JGit supports the 'amazon-s3' protocol but the Jenkins git client * plugin is not tested with that protocol. Command line git does not * support the 'amazon-s3' protocol. Since command line git is the * reference implementation for the git client plugin, there is no - * reason to support the 'amazon-s3' protocol. Plugin releases 6.2.0 + * reason to support the 'amazon-s3' protocol. Plugin releases 6.3.2 * and before would report a class cast exception if a user used the - * 'amazon-s3' protocol. It was not usable by users. + * 'amazon-s3' protocol. It was not usable by users. Plugin releases + * since 6.3.3 report that the amazon-s3 protocol is not supported. */ public class JGitAPIImplUnsupportedProtocolTest { - private JGitAPIImpl jgit = null; + private static JGitAPIImpl jgit = null; - private URIish url = null; - private String urlStr = null; + private static URIish url = null; + private static String urlStr = null; - private String expectedMessage = null; + private static String expectedMessage = null; - private final Random random = new Random(); + private static final Random random = new Random(); - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + private static File folder; - @Before - public void setup() throws Exception { + @BeforeAll + static void setup() throws Exception { url = new URIish("amazon-s3://@host/path-" + random.nextInt()); urlStr = url.toString(); - jgit = new JGitAPIImpl(folder.getRoot(), TaskListener.NULL); + jgit = new JGitAPIImpl(folder, TaskListener.NULL); expectedMessage = "unsupported protocol in URL " + urlStr; } @Test - public void testFetchCommand() throws Exception { + void testFetchCommand() throws Exception { List refspecs = null; var thrown = assertThrows( GitException.class, () -> jgit.fetch_().from(url, refspecs).execute()); @@ -57,7 +58,7 @@ public void testFetchCommand() throws Exception { } @Test - public void testGetRemoteReferences() throws Exception { + void testGetRemoteReferences() throws Exception { String pattern = ".*"; boolean headsOnly = random.nextBoolean(); boolean tagsOnly = random.nextBoolean(); @@ -67,56 +68,56 @@ public void testGetRemoteReferences() throws Exception { } @Test - public void testGetRemoteSymbolicReferences() throws Exception { + void testGetRemoteSymbolicReferences() throws Exception { String pattern = ".*"; var thrown = assertThrows(GitException.class, () -> jgit.getRemoteSymbolicReferences(urlStr, pattern)); assertThat(thrown.getMessage(), is(expectedMessage)); } @Test - public void testGetHeadRev() throws Exception { + void testGetHeadRev() throws Exception { String branchSpec = "origin/my-branch-" + random.nextInt(); var thrown = assertThrows(GitException.class, () -> jgit.getHeadRev(urlStr, branchSpec)); assertThat(thrown.getMessage(), is(expectedMessage)); } @Test - public void testSetRemoteUrl() throws Exception { + void testSetRemoteUrl() throws Exception { String name = "upstream-" + random.nextInt(); var thrown = assertThrows(GitException.class, () -> jgit.setRemoteUrl(name, urlStr)); assertThat(thrown.getMessage(), is(expectedMessage)); } @Test - public void testAddRemoteUrl() throws Exception { + void testAddRemoteUrl() throws Exception { String name = "upstream-" + random.nextInt(); var thrown = assertThrows(GitException.class, () -> jgit.addRemoteUrl(name, urlStr)); assertThat(thrown.getMessage(), is(expectedMessage)); } @Test - public void testCloneCommand() throws Exception { + void testCloneCommand() throws Exception { var thrown = assertThrows(GitException.class, () -> jgit.clone_().url(urlStr).execute()); assertThat(thrown.getMessage(), is(expectedMessage)); } @Test - public void testAddSubmodule() throws Exception { + void testAddSubmodule() throws Exception { var thrown = assertThrows(GitException.class, () -> jgit.addSubmodule(urlStr, "subdir")); assertThat(thrown.getMessage(), is(expectedMessage)); } @Test - public void testPushCommand() throws Exception { + void testPushCommand() throws Exception { var thrown = assertThrows(GitException.class, () -> jgit.push().to(url).execute()); assertThat(thrown.getMessage(), is(expectedMessage)); } @Test - public void testPrune() throws Exception { + void testPrune() throws Exception { // Create a local git repository - jgit.init_().workspace(folder.getRoot().getAbsolutePath()).execute(); + jgit.init_().workspace(folder.getAbsolutePath()).execute(); // Locally modify the remote URL inside existing local git repository String remoteName = "amazons3-remote"; jgit.config(GitClient.ConfigLevel.LOCAL, "remote." + remoteName + ".url", urlStr); @@ -127,16 +128,16 @@ public void testPrune() throws Exception { @Test @Deprecated - public void testSetSubmoduleUrl() throws Exception { + void testSetSubmoduleUrl() throws Exception { var thrown = assertThrows(GitException.class, () -> jgit.setSubmoduleUrl("submodule-name", urlStr)); assertThat(thrown.getMessage(), is(expectedMessage)); } @Test @Deprecated - public void testSetRemoteUrl3Args() throws Exception { + void testSetRemoteUrl3Args() throws Exception { // Create a local git repository so that remote URL is not altered in working directory - String repoDir = folder.getRoot().getAbsolutePath(); + String repoDir = folder.getAbsolutePath(); jgit.init_().workspace(repoDir).execute(); var thrown = assertThrows(GitException.class, () -> jgit.setRemoteUrl("remote-name", urlStr, repoDir)); assertThat(thrown.getMessage(), is(expectedMessage)); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/JGitApacheAPIImplTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/JGitApacheAPIImplTest.java index 5f49983a11..f9d017a2cd 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/JGitApacheAPIImplTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/JGitApacheAPIImplTest.java @@ -5,17 +5,13 @@ /** * @author Nicolas De Loof */ -public class JGitApacheAPIImplTest extends GitAPITestUpdate { +class JGitApacheAPIImplTest extends GitAPITestUpdate { + @Override protected GitClient setupGitAPI(File ws) throws Exception { return Git.with(listener, env).in(ws).using("jgitapache").getClient(); } - @Override - protected boolean getTimeoutVisibleInCurrentTest() { - return true; // git client plugin 3.11.0 supports JGit timeout - } - @Override protected String getRemoteBranchPrefix() { return ""; diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/JGitLightweightTagTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/JGitLightweightTagTest.java index 1c967ad738..f45e10b8ee 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/JGitLightweightTagTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/JGitLightweightTagTest.java @@ -15,16 +15,16 @@ import hudson.model.TaskListener; import hudson.plugins.git.GitObject; import java.io.File; +import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.lib.ObjectId; -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 org.jvnet.hudson.test.Issue; /** @@ -33,22 +33,22 @@ * * @author Brian Ray */ -public class JGitLightweightTagTest { +class JGitLightweightTagTest { /* These tests are only for the JGit client. */ private static final String GIT_IMPL_NAME = "jgit"; /* Instance under test. */ private GitClient gitClient; - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; private File repoRoot; // root directory of temporary repository private File repoRootGitDir; // .git directory in temporary repository - @Before - public void setGitClientEtc() throws Exception { - repoRoot = tempFolder.newFolder(); + @BeforeEach + void setGitClientEtc() throws Exception { + repoRoot = newFolder(tempFolder, "junit"); gitClient = Git.with(TaskListener.NULL, new EnvVars()) .in(repoRoot) .using(GIT_IMPL_NAME) @@ -96,9 +96,10 @@ private void lightweightTag(String tagName) throws Exception { } } - @Issue("JENKINS-57205") // NPE on PreBuildMerge with packed lightweight tag + @Issue("JENKINS-57205") + // NPE on PreBuildMerge with packed lightweight tag @Test - public void testGetTags_packedRefs() throws Exception { + void testGetTags_packedRefs() throws Exception { // JENKINS-57205 is triggered by lightweight tags ObjectId firstCommit = commitFile("first.txt", "Great info here", "First commit"); String lightweightTagName = "lightweight_tag"; @@ -124,4 +125,13 @@ public void testGetTags_packedRefs() throws Exception { hasProperty("name", equalTo(annotatedTagName)), hasProperty("SHA1", equalTo(secondCommit))))); assertThat(tags, hasSize(2)); } + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/JcascTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/JcascTest.java index 829eb8f055..bda165f56b 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/JcascTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/JcascTest.java @@ -20,15 +20,17 @@ import hudson.tools.ToolPropertyDescriptor; import hudson.tools.ZipExtractionInstaller; import hudson.util.DescribableList; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; +import io.jenkins.plugins.casc.misc.junit.jupiter.AbstractRoundTripTest; import java.util.Arrays; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +@WithJenkins +class JcascTest extends AbstractRoundTripTest { -public class JcascTest extends RoundTripAbstractTest { @Override - protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { - final ToolDescriptor descriptor = - (ToolDescriptor) restartableJenkinsRule.j.jenkins.getDescriptor(GitTool.class); + protected void assertConfiguredAsExpected(JenkinsRule j, String s) { + final ToolDescriptor descriptor = (ToolDescriptor) j.jenkins.getDescriptor(GitTool.class); final ToolInstallation[] installations = descriptor.getInstallations(); assertThat(installations, arrayWithSize(4)); assertThat( diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/LegacyCompatibleGitAPIImplJGitTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/LegacyCompatibleGitAPIImplJGitTest.java index 07040d2abb..8eb1cf3232 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/LegacyCompatibleGitAPIImplJGitTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/LegacyCompatibleGitAPIImplJGitTest.java @@ -1,8 +1,9 @@ package org.jenkinsci.plugins.gitclient; -public class LegacyCompatibleGitAPIImplJGitTest extends LegacyCompatibleGitAPIImplTest { +class LegacyCompatibleGitAPIImplJGitTest extends LegacyCompatibleGitAPIImplTest { - public LegacyCompatibleGitAPIImplJGitTest() { - gitImpl = "jgit"; + @Override + protected String getGitImplementation() { + return "jgit"; } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/LegacyCompatibleGitAPIImplTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/LegacyCompatibleGitAPIImplTest.java index 6633a299ba..04a8e380da 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/LegacyCompatibleGitAPIImplTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/LegacyCompatibleGitAPIImplTest.java @@ -1,6 +1,6 @@ package org.jenkinsci.plugins.gitclient; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import hudson.model.TaskListener; import hudson.plugins.git.GitException; @@ -18,16 +18,15 @@ import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.transport.RemoteConfig; -import org.junit.Before; -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.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -public class LegacyCompatibleGitAPIImplTest { +class LegacyCompatibleGitAPIImplTest { - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; private LegacyCompatibleGitAPIImpl git; private File repo; @@ -39,10 +38,10 @@ public class LegacyCompatibleGitAPIImplTest { private static String defaultBranchName = "mast" + "er"; // Intentionally split string - protected String gitImpl; + protected final String gitImpl = getGitImplementation(); - public LegacyCompatibleGitAPIImplTest() { - gitImpl = "git"; + protected String getGitImplementation() { + return "git"; } /** @@ -51,8 +50,8 @@ public LegacyCompatibleGitAPIImplTest() { * Git 2.32.0 honors the configuration variable `init.defaultBranch` and uses it for the name of the initial branch. * This method reads the global configuration and uses it to set the value of `defaultBranchName`. */ - @BeforeClass - public static void computeDefaultBranchName() throws Exception { + @BeforeAll + static void computeDefaultBranchName() throws Exception { File configDir = Files.createTempDirectory("readGitConfig").toFile(); CliGitCommand getDefaultBranchNameCmd = new CliGitCommand(Git.with(TaskListener.NULL, new hudson.EnvVars()) .in(configDir) @@ -65,12 +64,12 @@ public static void computeDefaultBranchName() throws Exception { defaultBranchName = result; } } - assertTrue("Failed to delete temporary readGitConfig directory", configDir.delete()); + assertTrue(configDir.delete(), "Failed to delete temporary readGitConfig directory"); } - @Before - public void setUp() throws Exception { - repo = tempFolder.newFolder(); + @BeforeEach + void setUp() throws Exception { + repo = newFolder(tempFolder, "junit"); assertNotGitRepo(repo); git = (LegacyCompatibleGitAPIImpl) Git.with(listener, env).in(repo).using(gitImpl).getClient(); @@ -82,18 +81,18 @@ public void setUp() throws Exception { } private void assertNotGitRepo(File dir) { - assertTrue(dir + " is not a directory", dir.isDirectory()); + assertTrue(dir.isDirectory(), dir + " is not a directory"); File gitDir = new File(dir, ".git"); - assertFalse(gitDir + " is a directory", gitDir.isDirectory()); + assertFalse(gitDir.isDirectory(), gitDir + " is a directory"); } private void assertIsGitRepo(File dir) { - assertTrue(dir + " is not a directory", dir.isDirectory()); + assertTrue(dir.isDirectory(), dir + " is not a directory"); File gitDir = new File(dir, ".git"); - assertTrue(gitDir + " is not a directory", gitDir.isDirectory()); + assertTrue(gitDir.isDirectory(), gitDir + " is not a directory"); } - private File touch(String path, String content) throws IOException { + private File touch(String path, String content) throws Exception { File f = new File(repo, path); Files.writeString(f.toPath(), content, StandardCharsets.UTF_8); return f; @@ -101,7 +100,7 @@ private File touch(String path, String content) throws IOException { @Test @Deprecated - public void testCloneRemoteConfig() throws Exception { + void testCloneRemoteConfig() throws Exception { if (gitImpl.equals("jgit")) { return; } @@ -116,25 +115,25 @@ public void testCloneRemoteConfig() throws Exception { RemoteConfig remoteConfig = new RemoteConfig(config, remoteName); git.clone(remoteConfig); File[] files = git.workspace.listFiles(); - assertEquals(files.length + "files in " + Arrays.toString(files), 1, files.length); - assertEquals("Wrong file name", ".git", files[0].getName()); + assertEquals(1, files.length, files.length + "files in " + Arrays.toString(files)); + assertEquals(".git", files[0].getName(), "Wrong file name"); } @Test @Deprecated - public void testHasGitModules_default_ignored_arg() throws Exception { + void testHasGitModules_default_ignored_arg() { assertFalse((new File(repo, ".gitmodules")).exists()); assertFalse(git.hasGitModules("ignored treeIsh argument 1")); } @Test @Deprecated - public void testHasGitModules_default_no_arg() throws Exception { + void testHasGitModules_default_no_arg() { assertFalse((new File(repo, ".gitmodules")).exists()); assertFalse(git.hasGitModules()); } - private File commitTrackedFile() throws IOException, GitException, InterruptedException { + private File commitTrackedFile() throws Exception { File trackedFile = touch("tracked-file", "tracked content " + UUID.randomUUID()); git.add("tracked-file"); git.commit("First commit"); @@ -145,14 +144,14 @@ private File commitTrackedFile() throws IOException, GitException, InterruptedEx @Test @Deprecated - public void testShowRevisionThrowsGitException() throws Exception { + void testShowRevisionThrowsGitException() throws Exception { commitTrackedFile(); assertThrows(GitException.class, () -> git.showRevision(new Revision(gitClientCommit))); } @Test @Deprecated - public void testShowRevisionTrackedFile() throws Exception { + void testShowRevisionTrackedFile() throws Exception { commitTrackedFile(); ObjectId head = git.getHeadRev(repo.getPath(), defaultBranchName); List revisions = git.showRevision(new Revision(head)); @@ -161,31 +160,31 @@ public void testShowRevisionTrackedFile() throws Exception { @Test @Deprecated - public void testGetTagsOnCommit_empty() throws Exception { + void testGetTagsOnCommit_empty() throws Exception { List result = git.getTagsOnCommit(taggedCommit.name()); - assertTrue("Tag list not empty: " + result, result.isEmpty()); + assertTrue(result.isEmpty(), "Tag list not empty: " + result); } @Test @Deprecated - public void testGetTagsOnCommit_non_empty() throws Exception { + void testGetTagsOnCommit_non_empty() throws Exception { commitTrackedFile(); List result = git.getTagsOnCommit(taggedCommit.name()); - assertTrue("Tag list not empty: " + result, result.isEmpty()); + assertTrue(result.isEmpty(), "Tag list not empty: " + result); } @Test @Deprecated - public void testGetTagsOnCommit_SHA1() throws Exception { + void testGetTagsOnCommit_SHA1() throws Exception { LegacyCompatibleGitAPIImpl myGit = (LegacyCompatibleGitAPIImpl) Git.with(listener, env).in(repo).using(gitImpl).getClient(); List result = myGit.getTagsOnCommit(taggedCommit.name()); - assertTrue("Tag list not empty: " + result, result.isEmpty()); + assertTrue(result.isEmpty(), "Tag list not empty: " + result); } @Test @Deprecated - public void testGetTagsOnCommit() throws Exception { + void testGetTagsOnCommit() throws Exception { LegacyCompatibleGitAPIImpl myGit = (LegacyCompatibleGitAPIImpl) Git.with(listener, env).in(repo).using(gitImpl).getClient(); commitTrackedFile(); @@ -194,41 +193,42 @@ public void testGetTagsOnCommit() throws Exception { myGit.tag(uniqueTagName, tagMessage); List result = myGit.getTagsOnCommit(uniqueTagName); myGit.deleteTag(uniqueTagName); - assertFalse("Tag list empty for " + uniqueTagName, result.isEmpty()); + assertFalse(result.isEmpty(), "Tag list empty for " + uniqueTagName); assertNull( - "Unexpected SHA1 for commit: " + result.get(0).getCommitMessage(), - result.get(0).getCommitSHA1()); + result.get(0).getCommitSHA1(), + "Unexpected SHA1 for commit: " + result.get(0).getCommitMessage()); assertNull( - "Unexpected message for commit: " + result.get(0).getCommitSHA1(), - result.get(0).getCommitMessage()); + result.get(0).getCommitMessage(), + "Unexpected message for commit: " + result.get(0).getCommitSHA1()); } @Test @Deprecated - public void testGetTagsOnCommit_sha1() throws Exception { + void testGetTagsOnCommit_sha1() throws Exception { LegacyCompatibleGitAPIImpl myGit = (LegacyCompatibleGitAPIImpl) Git.with(listener, env).in(repo).using(gitImpl).getClient(); String revName = "2db88a20bba8e98b6710f06213f3b60940a63c7c"; List result = myGit.getTagsOnCommit(revName); - assertTrue("Tag list not empty for " + revName, result.isEmpty()); + assertTrue(result.isEmpty(), "Tag list not empty for " + revName); } @Test - public void testLsTreeThrows() { - Class expectedExceptionClass = git instanceof CliGitAPIImpl ? GitException.class : NullPointerException.class; + void testLsTreeThrows() { + Class expectedExceptionClass = + git instanceof CliGitAPIImpl ? GitException.class : NullPointerException.class; assertThrows(expectedExceptionClass, () -> git.lsTree("HEAD")); } @Test - public void testLsTreeOneCommit() throws Exception { + void testLsTreeOneCommit() throws Exception { commitTrackedFile(); List lsTree = git.lsTree("HEAD"); - assertEquals("lsTree wrong size - " + lsTree, 1, lsTree.size()); + assertEquals(1, lsTree.size(), "lsTree wrong size - " + lsTree); assertEquals("tracked-file", lsTree.get(0).getFile()); } @Test - public void testExtractBranchNameFromBranchSpec() { + void testExtractBranchNameFromBranchSpec() { assertEquals(defaultBranchName, git.extractBranchNameFromBranchSpec(defaultBranchName)); assertEquals(defaultBranchName, git.extractBranchNameFromBranchSpec("origin/" + defaultBranchName)); assertEquals(defaultBranchName, git.extractBranchNameFromBranchSpec("*/" + defaultBranchName)); @@ -248,4 +248,13 @@ public void testExtractBranchNameFromBranchSpec() { git.extractBranchNameFromBranchSpec("refs/remotes/origin/" + defaultBranchName)); assertEquals("refs/tags/mytag", git.extractBranchNameFromBranchSpec("refs/tags/mytag")); } + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/LogHandlerTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/LogHandlerTest.java index 3065198ecc..9907b93430 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/LogHandlerTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/LogHandlerTest.java @@ -1,24 +1,24 @@ package org.jenkinsci.plugins.gitclient; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.util.List; import java.util.logging.Level; import java.util.logging.LogRecord; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class LogHandlerTest { +class LogHandlerTest { private LogHandler handler; - @Before - public void setUp() { + @BeforeEach + void setUp() { handler = new LogHandler(); } @Test - public void testPublish() { + void testPublish() { String message = "testing publish"; publishMessage(message); } @@ -28,56 +28,56 @@ private void publishMessage(String message) { handler.publish(lr); List messages = handler.getMessages(); assertEquals(message, messages.get(0)); - assertEquals("Wrong size list of messages", 1, messages.size()); + assertEquals(1, messages.size(), "Wrong size list of messages"); } @Test - public void testFlush() { + void testFlush() { String message = "testing flush"; publishMessage(message); handler.flush(); /* no-op */ } @Test - public void testClose() { + void testClose() { String message = "testing close"; publishMessage(message); handler.close(); List messages = handler.getMessages(); - assertEquals("Wrong size list of messages after close", 0, messages.size()); + assertEquals(0, messages.size(), "Wrong size list of messages after close"); } @Test - public void testGetMessages() { + void testGetMessages() { String message = "testing getMessages"; publishMessage(message); } @Test - public void testContainsMessageSubstring() { + void testContainsMessageSubstring() { String message = "testing containsMessageSubstring"; publishMessage(message); - assertTrue("Missing message 'contains'", handler.containsMessageSubstring("contains")); + assertTrue(handler.containsMessageSubstring("contains"), "Missing message 'contains'"); } @Test - public void testContainsMessageSubstringFalse() { + void testContainsMessageSubstringFalse() { String message = "testing containsMessageSubstring"; publishMessage(message); - assertFalse("Found message 'Contains'", handler.containsMessageSubstring("Contains")); + assertFalse(handler.containsMessageSubstring("Contains"), "Found message 'Contains'"); } @Test - public void testGetTimeouts() { + void testGetTimeouts() { String message = "test timeout" + CliGitAPIImpl.TIMEOUT_LOG_PREFIX + "42"; publishMessage(message); List timeouts = handler.getTimeouts(); - assertEquals("Wrong timeout", Integer.valueOf(42), timeouts.get(0)); - assertEquals("Wrong size list", 1, timeouts.size()); + assertEquals(Integer.valueOf(42), timeouts.get(0), "Wrong timeout"); + assertEquals(1, timeouts.size(), "Wrong size list"); } @Test - public void testGetTimeoutsMultiple() { + void testGetTimeoutsMultiple() { int timeout0 = 37; int timeout1 = 15; publishMessage("test timeout" + CliGitAPIImpl.TIMEOUT_LOG_PREFIX + timeout0); @@ -85,8 +85,8 @@ public void testGetTimeoutsMultiple() { handler.publish(new LogRecord(Level.INFO, "Another timeout" + CliGitAPIImpl.TIMEOUT_LOG_PREFIX + timeout1)); handler.publish(new LogRecord(Level.FINEST, "no timeout in this message either")); List timeouts = handler.getTimeouts(); - assertEquals("Wrong timeout 0", timeout0, timeouts.get(0).intValue()); - assertEquals("Wrong timeout 1", timeout1, timeouts.get(1).intValue()); - assertEquals("Wrong size list", 2, timeouts.size()); + assertEquals(timeout0, timeouts.get(0).intValue(), "Wrong timeout 0"); + assertEquals(timeout1, timeouts.get(1).intValue(), "Wrong timeout 1"); + assertEquals(2, timeouts.size(), "Wrong size list"); } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/MergeCommandTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/MergeCommandTest.java index d4f2295764..71d6f2c8ab 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/MergeCommandTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/MergeCommandTest.java @@ -2,10 +2,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import hudson.EnvVars; import hudson.model.TaskListener; @@ -17,28 +14,29 @@ import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import org.eclipse.jgit.lib.ObjectId; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) -public class MergeCommandTest { +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; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@ParameterizedClass(name = "{0}") +@MethodSource("gitImplementations") +class MergeCommandTest { private static final String BRANCH_2_README_CONTENT = "# Branch 2 README "; - private final String gitImpl; - public MergeCommandTest(String implementation) { - gitImpl = implementation; - } + @Parameter(0) + private String gitImpl; private GitClient git; private MergeCommand mergeCmd; @@ -53,8 +51,8 @@ public MergeCommandTest(String implementation) { private ObjectId commit1Branch2; private ObjectId commitConflict; - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; private static String defaultBranchName = "mast" + "er"; // Intentionally split string @@ -64,10 +62,9 @@ public MergeCommandTest(String implementation) { * Git 2.32.0 honors the configuration variable `init.defaultBranch` and uses it for the name of the initial branch. * This method reads the global configuration and uses it to set the value of `defaultBranchName`. */ - @BeforeClass - public static void computeDefaultBranchName() throws Exception { - File configDir = - java.nio.file.Files.createTempDirectory("readGitConfig").toFile(); + @BeforeAll + static void computeDefaultBranchName() throws Exception { + File configDir = Files.createTempDirectory("readGitConfig").toFile(); CliGitCommand getDefaultBranchNameCmd = new CliGitCommand(Git.with(TaskListener.NULL, new hudson.EnvVars()) .in(configDir) .using("git") @@ -79,14 +76,14 @@ public static void computeDefaultBranchName() throws Exception { defaultBranchName = result; } } - assertTrue("Failed to delete temporary readGitConfig directory", configDir.delete()); + assertTrue(configDir.delete(), "Failed to delete temporary readGitConfig directory"); } - @Before - public void createMergeTestRepo() throws Exception { + @BeforeEach + void createMergeTestRepo() throws Exception { EnvVars env = new hudson.EnvVars(); TaskListener listener = StreamTaskListener.fromStdout(); - File repo = tempFolder.newFolder(); + File repo = newFolder(tempFolder, "junit"); git = Git.with(listener, env).in(repo).using(gitImpl).getClient(); git.init_().workspace(repo.getAbsolutePath()).execute(); CliGitCommand gitCmd = new CliGitCommand(git); @@ -102,10 +99,8 @@ public void createMergeTestRepo() throws Exception { git.add("README.adoc"); git.commit("Commit README on default branch"); commit1Master = git.revParse("HEAD"); - assertTrue( - "master commit 1 missing on default branch", - git.revList(defaultBranchName).contains(commit1Master)); - assertTrue("README missing on default branch", readme.exists()); + assertTrue(git.revList(defaultBranchName).contains(commit1Master), "master commit 1 missing on default branch"); + assertTrue(readme.exists(), "README missing on default branch"); // Create branch-1 readmeOne = new File(repo, "README-branch-1.md"); @@ -116,13 +111,10 @@ public void createMergeTestRepo() throws Exception { git.add(readmeOne.getName()); git.commit("Commit README on branch 1"); commit1Branch = git.revParse("HEAD"); - assertFalse( - "branch commit 1 on default branch", - git.revList(defaultBranchName).contains(commit1Branch)); - assertTrue( - "branch commit 1 missing on branch 1", git.revList("branch-1").contains(commit1Branch)); - assertTrue("Branch README missing on branch 1", readmeOne.exists()); - assertTrue("Master README missing on branch 1", readme.exists()); + assertFalse(git.revList(defaultBranchName).contains(commit1Branch), "branch commit 1 on default branch"); + assertTrue(git.revList("branch-1").contains(commit1Branch), "branch commit 1 missing on branch 1"); + assertTrue(readmeOne.exists(), "Branch README missing on branch 1"); + assertTrue(readme.exists(), "Master README missing on branch 1"); // Commit a second change to branch-1 try (PrintWriter writer = new PrintWriter(readmeOne, StandardCharsets.UTF_8)) { @@ -133,12 +125,10 @@ public void createMergeTestRepo() throws Exception { git.add(readmeOne.getName()); git.commit("Commit 2nd README change on branch 1"); commit2Branch = git.revParse("HEAD"); - assertFalse( - "branch commit 2 on default branch", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("branch commit 2 not on branch 1", git.revList("branch-1").contains(commit2Branch)); - assertTrue("Branch README missing on branch 1", readmeOne.exists()); - assertTrue("Master README missing on branch 1", readme.exists()); + assertFalse(git.revList(defaultBranchName).contains(commit2Branch), "branch commit 2 on default branch"); + assertTrue(git.revList("branch-1").contains(commit2Branch), "branch commit 2 not on branch 1"); + assertTrue(readmeOne.exists(), "Branch README missing on branch 1"); + assertTrue(readme.exists(), "Master README missing on branch 1"); git.checkoutBranch("branch-2", defaultBranchName); try (PrintWriter writer = new PrintWriter(readme, StandardCharsets.UTF_8)) { @@ -149,10 +139,10 @@ public void createMergeTestRepo() throws Exception { git.add("README.adoc"); git.commit("Commit README change on branch 2"); commit1Branch2 = git.revParse("HEAD"); - assertTrue("Change README commit not on branch 2", git.revListAll().contains(commit1Branch2)); + assertTrue(git.revListAll().contains(commit1Branch2), "Change README commit not on branch 2"); assertFalse( - "Change README commit on default branch unexpectedly", - git.revList(defaultBranchName).contains(commit1Branch2)); + git.revList(defaultBranchName).contains(commit1Branch2), + "Change README commit on default branch unexpectedly"); // Commit a second change to default branch git.checkout().ref(defaultBranchName).execute(); @@ -164,20 +154,20 @@ public void createMergeTestRepo() throws Exception { git.add("README.adoc"); git.commit("Commit 2nd README change on default branch"); commit2Master = git.revParse("HEAD"); - assertTrue("commit 2 not on default branch", git.revListAll().contains(commit2Master)); + assertTrue(git.revListAll().contains(commit2Master), "commit 2 not on default branch"); assertFalse( - "Branch commit 2 on default branch unexpectedly", - git.revList(defaultBranchName).contains(commit2Branch)); - assertFalse("README 1 on default branch unexpectedly", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "Branch commit 2 on default branch unexpectedly"); + assertFalse(readmeOne.exists(), "README 1 on default branch unexpectedly"); mergeCmd = git.merge(); assertFalse( - "branch commit 1 on default branch prematurely", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 on default branch prematurely"); assertFalse( - "branch commit 2 on default branch prematurely", - git.revList(defaultBranchName).contains(commit2Branch)); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 on default branch prematurely"); } private void createConflictingCommit() throws Exception { @@ -193,251 +183,258 @@ private void createConflictingCommit() throws Exception { git.commit("Commit conflicting README on branch branch-conflict"); commitConflict = git.revParse("HEAD"); assertFalse( - "branch branch-conflict on default branch", - git.revList(defaultBranchName).contains(commitConflict)); + git.revList(defaultBranchName).contains(commitConflict), "branch branch-conflict on default branch"); assertTrue( - "commit commitConflict missing on branch branch-conflict", - git.revList("branch-conflict").contains(commitConflict)); - assertTrue("Conflicting README missing on branch branch-conflict", readmeOne.exists()); + git.revList("branch-conflict").contains(commitConflict), + "commit commitConflict missing on branch branch-conflict"); + assertTrue(readmeOne.exists(), "Conflicting README missing on branch branch-conflict"); git.checkout().ref(defaultBranchName).execute(); } - @Parameterized.Parameters(name = "{0}") - public static Collection gitImplementations() { - List args = new ArrayList<>(); + static Collection gitImplementations() { + List args = new ArrayList<>(); String[] implementations = new String[] {"git", "jgit"}; for (String implementation : implementations) { - Object[] gitImpl = {implementation}; + Arguments gitImpl = Arguments.of(implementation); args.add(gitImpl); } return args; } @Test - public void testSetRevisionToMergeCommit1() throws GitException, InterruptedException { + void testSetRevisionToMergeCommit1() throws Exception { mergeCmd.setRevisionToMerge(commit1Branch).execute(); assertTrue( - "branch commit 1 not on default branch after merge", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 not on default branch after merge"); assertFalse( - "branch commit 2 on default branch prematurely", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing on default branch", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 on default branch prematurely"); + assertTrue(readmeOne.exists(), "README 1 missing on default branch"); } @Test - public void testSetRevisionToMergeCommit2() throws GitException, InterruptedException { + void testSetRevisionToMergeCommit2() throws Exception { mergeCmd.setRevisionToMerge(commit2Branch).execute(); assertTrue( - "branch commit 1 not on default branch after merge", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 not on default branch after merge"); assertTrue( - "branch commit 2 not on default branch after merge", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing on default branch", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 not on default branch after merge"); + assertTrue(readmeOne.exists(), "README 1 missing on default branch"); } - private void assertMessageInGitLog(ObjectId head, String substring) throws GitException, InterruptedException { + private void assertMessageInGitLog(ObjectId head, String substring) throws Exception { List logged = git.showRevision(head); boolean found = false; for (String logLine : logged) { if (logLine.contains(substring)) { found = true; + break; } } - assertTrue("Message '" + substring + "' not in log '" + logged + "'", found); + assertTrue(found, "Message '" + substring + "' not in log '" + logged + "'"); } @Test - public void testCustomMergeMessage() throws GitException, InterruptedException { + void testCustomMergeMessage() throws Exception { String customMessage = "Custom merge message from test"; mergeCmd.setMessage(customMessage).setRevisionToMerge(commit2Branch).execute(); assertMessageInGitLog(git.revParse("HEAD"), customMessage); } @Test - public void testDefaultMergeMessage() throws GitException, InterruptedException { + void testDefaultMergeMessage() throws Exception { String defaultMessage = "Merge commit '" + commit2Branch.getName() + "'"; mergeCmd.setRevisionToMerge(commit2Branch).execute(); assertMessageInGitLog(git.revParse("HEAD"), defaultMessage); } @Test - public void testEmptyMergeMessage() throws GitException, InterruptedException { + void testEmptyMergeMessage() throws Exception { String emptyMessage = ""; mergeCmd.setMessage(emptyMessage).setRevisionToMerge(commit2Branch).execute(); /* Asserting an empty string in the merge message is too hard, only check for exceptions thrown */ } @Test - public void testDefaultStrategy() throws GitException, InterruptedException { + void testDefaultStrategy() throws Exception { mergeCmd.setStrategy(MergeCommand.Strategy.DEFAULT) .setRevisionToMerge(commit2Branch) .execute(); assertTrue( - "branch commit 1 not on default branch after merge", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 not on default branch after merge"); assertTrue( - "branch commit 2 not on default branch after merge", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing on default branch", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 not on default branch after merge"); + assertTrue(readmeOne.exists(), "README 1 missing on default branch"); } @Test - public void testResolveStrategy() throws GitException, InterruptedException { + void testResolveStrategy() throws Exception { mergeCmd.setStrategy(MergeCommand.Strategy.RESOLVE) .setRevisionToMerge(commit2Branch) .execute(); assertTrue( - "branch commit 1 not on default branch after merge", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 not on default branch after merge"); assertTrue( - "branch commit 2 not on default branch after merge", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing on default branch", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 not on default branch after merge"); + assertTrue(readmeOne.exists(), "README 1 missing on default branch"); } @Test - public void testRecursiveStrategy() throws GitException, InterruptedException { + void testRecursiveStrategy() throws Exception { mergeCmd.setStrategy(MergeCommand.Strategy.RECURSIVE) .setRevisionToMerge(commit2Branch) .execute(); assertTrue( - "branch commit 1 not on default branch after merge", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 not on default branch after merge"); assertTrue( - "branch commit 2 not on default branch after merge", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing on default branch", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 not on default branch after merge"); + assertTrue(readmeOne.exists(), "README 1 missing on default branch"); } @Test - public void testRecursiveTheirsStrategy() throws GitException, InterruptedException, IOException { + void testRecursiveTheirsStrategy() throws Exception, IOException { mergeCmd.setStrategy(MergeCommand.Strategy.RECURSIVE_THEIRS) .setRevisionToMerge(commit1Branch2) .execute(); assertTrue( - "branch 2 commit 1 not on default branch after merge", - git.revList(defaultBranchName).contains(commit1Branch2)); - assertTrue("README.adoc is missing on master", readme.exists()); + git.revList(defaultBranchName).contains(commit1Branch2), + "branch 2 commit 1 not on default branch after merge"); + assertTrue(readme.exists(), "README.adoc is missing on master"); try (FileReader reader = new FileReader(readme); BufferedReader br = new BufferedReader(reader)) { assertTrue( - "README.adoc does not contain expected content", - br.readLine().startsWith(BRANCH_2_README_CONTENT)); + br.readLine().startsWith(BRANCH_2_README_CONTENT), "README.adoc does not contain expected content"); } } /* Octopus merge strategy is not implemented in JGit, not exposed in CliGitAPIImpl */ @Test - public void testOctopusStrategy() throws GitException, InterruptedException { + void testOctopusStrategy() throws Exception { mergeCmd.setStrategy(MergeCommand.Strategy.OCTOPUS) .setRevisionToMerge(commit2Branch) .execute(); assertTrue( - "branch commit 1 not on default branch after merge", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 not on default branch after merge"); assertTrue( - "branch commit 2 not on default branch after merge", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing on default branch", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 not on default branch after merge"); + assertTrue(readmeOne.exists(), "README 1 missing on default branch"); } @Test - public void testOursStrategy() throws GitException, InterruptedException { + void testOursStrategy() throws Exception { mergeCmd.setStrategy(MergeCommand.Strategy.OURS) .setRevisionToMerge(commit2Branch) .execute(); assertTrue( - "branch commit 1 not on default branch after merge", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 not on default branch after merge"); assertTrue( - "branch commit 2 not on default branch after merge", - git.revList(defaultBranchName).contains(commit2Branch)); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 not on default branch after merge"); /* Note that next assertion is different than similar assertions */ - assertFalse("README 1 found on default branch, Ours strategy should have not included it", readmeOne.exists()); + assertFalse(readmeOne.exists(), "README 1 found on default branch, Ours strategy should have not included it"); } @Test - public void testSubtreeStrategy() throws GitException, InterruptedException { + void testSubtreeStrategy() throws Exception { mergeCmd.setStrategy(MergeCommand.Strategy.SUBTREE) .setRevisionToMerge(commit2Branch) .execute(); assertTrue( - "branch commit 1 not on default branch after merge", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 not on default branch after merge"); assertTrue( - "branch commit 2 not on default branch after merge", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing on default branch", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 not on default branch after merge"); + assertTrue(readmeOne.exists(), "README 1 missing on default branch"); } @Test - public void testSquash() throws GitException, InterruptedException { + void testSquash() throws Exception { mergeCmd.setSquash(true).setRevisionToMerge(commit2Branch).execute(); assertFalse( - "branch commit 1 on default branch after squash merge", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 on default branch after squash merge"); assertFalse( - "branch commit 2 on default branch after squash merge", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing on default branch", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 on default branch after squash merge"); + assertTrue(readmeOne.exists(), "README 1 missing on default branch"); } @Test - public void testCommitOnMerge() throws GitException, InterruptedException { + void testCommitOnMerge() throws Exception { mergeCmd.setCommit(true).setRevisionToMerge(commit2Branch).execute(); assertTrue( - "branch commit 1 not on default branch after merge with commit", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 not on default branch after merge with commit"); assertTrue( - "branch commit 2 not on default branch after merge with commit", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing in working directory", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 not on default branch after merge with commit"); + assertTrue(readmeOne.exists(), "README 1 missing in working directory"); } @Test - public void testNoCommitOnMerge() throws GitException, InterruptedException { + void testNoCommitOnMerge() throws Exception { mergeCmd.setCommit(false).setRevisionToMerge(commit2Branch).execute(); assertFalse( - "branch commit 1 on default branch after merge without commit", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 on default branch after merge without commit"); assertFalse( - "branch commit 2 on default branch after merge without commit", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing in working directory", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 on default branch after merge without commit"); + assertTrue(readmeOne.exists(), "README 1 missing in working directory"); } @Test - public void testConflictOnMerge() throws Exception { + void testConflictOnMerge() throws Exception { createConflictingCommit(); mergeCmd.setRevisionToMerge(commit2Branch).execute(); assertTrue( - "branch commit 1 not on default branch after merge", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 not on default branch after merge"); assertTrue( - "branch commit 2 not on default branch after merge", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing in working directory", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 not on default branch after merge"); + assertTrue(readmeOne.exists(), "README 1 missing in working directory"); GitException e = assertThrows(GitException.class, () -> mergeCmd.setRevisionToMerge(commitConflict) .execute()); assertThat(e.getMessage(), containsString(commitConflict.getName())); } @Test - public void testConflictNoCommitOnMerge() throws Exception { + void testConflictNoCommitOnMerge() throws Exception { createConflictingCommit(); mergeCmd.setCommit(false).setRevisionToMerge(commit2Branch).execute(); assertFalse( - "branch commit 1 on default branch after merge without commit", - git.revList(defaultBranchName).contains(commit1Branch)); + git.revList(defaultBranchName).contains(commit1Branch), + "branch commit 1 on default branch after merge without commit"); assertFalse( - "branch commit 2 on default branch after merge without commit", - git.revList(defaultBranchName).contains(commit2Branch)); - assertTrue("README 1 missing in working directory", readmeOne.exists()); + git.revList(defaultBranchName).contains(commit2Branch), + "branch commit 2 on default branch after merge without commit"); + assertTrue(readmeOne.exists(), "README 1 missing in working directory"); GitException e = assertThrows(GitException.class, () -> mergeCmd.setRevisionToMerge(commitConflict) .execute()); assertThat(e.getMessage(), containsString(commitConflict.getName())); } + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/NetrcTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/NetrcTest.java index 7a0c6dba1f..2f533028f4 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/NetrcTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/NetrcTest.java @@ -1,9 +1,8 @@ package org.jenkinsci.plugins.gitclient; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.File; -import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; @@ -11,14 +10,14 @@ import org.apache.commons.io.IOUtils; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; -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; -public class NetrcTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); +class NetrcTest { + + @TempDir + private File folder; private static final String TEST_NETRC_FILE_1 = "netrc_1"; private static final String TEST_NETRC_FILE_1A = "netrc_1a"; @@ -42,8 +41,8 @@ private enum TestHost { H1_12("12-last-lp", "lager", "topaz"), // H1_05 deleted - H1a_06("6-slv2-p_.example.com", "builduser", "passwd"), - H1a_08("8-empt-__.nowhere.com", "master", "key"), + H1A_06("6-slv2-p_.example.com", "builduser", "passwd"), + H1A_08("8-empt-__.nowhere.com", "master", "key"), // H1_09 deleted // H1_10 deleted // H1_11 deleted @@ -57,68 +56,68 @@ private enum TestHost { private final String login; private final String password; - private TestHost(String _machine, String _login, String _password) { - this.machine = _machine; - this.login = _login; - this.password = _password; + TestHost(String machine, String login, String password) { + this.machine = machine; + this.login = login; + this.password = password; } } private void assertCredentials(TestHost host, Credentials cred) { if (cred == null) { assertTrue( + host.login == null || host.password == null, "Host." + host.name() + ": Credentials are null, although both login and password are set. (" - + host.login + ":" + host.password + ")", - host.login == null || host.password == null); + + host.login + ":" + host.password + ")"); } else { assertEquals( - "Host." + host.name() + ": Login mismatch.", host.login, - ((UsernamePasswordCredentials) cred).getUserName()); - assertEquals("Host." + host.name() + ": Password mismatch.", host.password, cred.getPassword()); + ((UsernamePasswordCredentials) cred).getUserName(), + "Host." + host.name() + ": Login mismatch."); + assertEquals(host.password, cred.getPassword(), "Host." + host.name() + ": Password mismatch."); } } - private void copyFileContents(String source, String destination) throws IOException { + private void copyFileContents(String source, String destination) throws Exception { try (InputStream sourceStream = Files.newInputStream(Path.of(source)); OutputStream out = Files.newOutputStream(Path.of(destination))) { IOUtils.copy(sourceStream, out); } } - private void copyResourceContents(String resource, String destination) throws IOException { + private void copyResourceContents(String resource, String destination) throws Exception { try (InputStream sourceStream = this.getClass().getClassLoader().getResourceAsStream(resource); OutputStream out = Files.newOutputStream(Path.of(destination))) { IOUtils.copy(sourceStream, out); } } - @Before - public void setup() throws IOException { - testFilePath_1 = folder.newFile(TEST_NETRC_FILE_1).getAbsolutePath(); + @BeforeEach + void setup() throws Exception { + testFilePath_1 = newFile(folder, TEST_NETRC_FILE_1).getAbsolutePath(); copyResourceContents(TEST_NETRC_FILE_1 + ".in", testFilePath_1); - testFilePath_1a = folder.newFile(TEST_NETRC_FILE_1A).getAbsolutePath(); + testFilePath_1a = newFile(folder, TEST_NETRC_FILE_1A).getAbsolutePath(); copyResourceContents(TEST_NETRC_FILE_1A + ".in", testFilePath_1a); - testFilePath_2 = folder.newFile(TEST_NETRC_FILE_2).getAbsolutePath(); + testFilePath_2 = newFile(folder, TEST_NETRC_FILE_2).getAbsolutePath(); copyResourceContents(TEST_NETRC_FILE_2 + ".in", testFilePath_2); } @Test - public void testGetInstanceString() throws Exception { + void testGetInstanceString() { Netrc netrc = Netrc.getInstance(testFilePath_1); assertNotNull(netrc); } @Test - public void testGetInstanceFile() throws Exception { + void testGetInstanceFile() { Netrc netrc = Netrc.getInstance(new File(testFilePath_1)); assertNotNull(netrc); } @Test - public void testGetCredentialsPath() throws Exception { + void testGetCredentialsPath() { Netrc netrc = Netrc.getInstance(testFilePath_1); assertNotNull(netrc); @@ -135,14 +134,14 @@ public void testGetCredentialsPath() throws Exception { assertCredentials(TestHost.H1_11, netrc.getCredentials(TestHost.H1_11.machine)); assertCredentials(TestHost.H1_12, netrc.getCredentials(TestHost.H1_12.machine)); - assertNull("Credentials for H2_01 should be null.", netrc.getCredentials(TestHost.H2_01.machine)); - assertNull("Credentials for H2_02 should be null.", netrc.getCredentials(TestHost.H2_02.machine)); - assertNull("Credentials for H2_03 should be null.", netrc.getCredentials(TestHost.H2_03.machine)); - assertNull("Credentials for H2_04 should be null.", netrc.getCredentials(TestHost.H2_04.machine)); + assertNull(netrc.getCredentials(TestHost.H2_01.machine), "Credentials for H2_01 should be null."); + assertNull(netrc.getCredentials(TestHost.H2_02.machine), "Credentials for H2_02 should be null."); + assertNull(netrc.getCredentials(TestHost.H2_03.machine), "Credentials for H2_03 should be null."); + assertNull(netrc.getCredentials(TestHost.H2_04.machine), "Credentials for H2_04 should be null."); } @Test - public void testGetCredentialsFile() throws Exception { + void testGetCredentialsFile() { Netrc netrc = Netrc.getInstance(new File(testFilePath_1)); assertNotNull(netrc); @@ -159,14 +158,14 @@ public void testGetCredentialsFile() throws Exception { assertCredentials(TestHost.H1_11, netrc.getCredentials(TestHost.H1_11.machine)); assertCredentials(TestHost.H1_12, netrc.getCredentials(TestHost.H1_12.machine)); - assertNull("Credentials for H2_01 should be null.", netrc.getCredentials(TestHost.H2_01.machine)); - assertNull("Credentials for H2_02 should be null.", netrc.getCredentials(TestHost.H2_02.machine)); - assertNull("Credentials for H2_03 should be null.", netrc.getCredentials(TestHost.H2_03.machine)); - assertNull("Credentials for H2_04 should be null.", netrc.getCredentials(TestHost.H2_04.machine)); + assertNull(netrc.getCredentials(TestHost.H2_01.machine), "Credentials for H2_01 should be null."); + assertNull(netrc.getCredentials(TestHost.H2_02.machine), "Credentials for H2_02 should be null."); + assertNull(netrc.getCredentials(TestHost.H2_03.machine), "Credentials for H2_03 should be null."); + assertNull(netrc.getCredentials(TestHost.H2_04.machine), "Credentials for H2_04 should be null."); } @Test - public void testGetCredentialsModifyFile() throws Exception { + void testGetCredentialsModifyFile() throws Exception { String testFilePath = testFilePath_1 + "_m"; copyFileContents(testFilePath_1, testFilePath); @@ -199,21 +198,21 @@ public void testGetCredentialsModifyFile() throws Exception { assertCredentials(TestHost.H1_03, netrc.getCredentials(TestHost.H1_03.machine)); assertCredentials(TestHost.H1_04, netrc.getCredentials(TestHost.H1_04.machine)); - assertNull("Credentials for H1_05 should be null.", netrc.getCredentials(TestHost.H1_05.machine)); - assertCredentials(TestHost.H1a_06, netrc.getCredentials(TestHost.H1_06.machine)); + assertNull(netrc.getCredentials(TestHost.H1_05.machine), "Credentials for H1_05 should be null."); + assertCredentials(TestHost.H1A_06, netrc.getCredentials(TestHost.H1_06.machine)); assertCredentials(TestHost.H1_07, netrc.getCredentials(TestHost.H1_07.machine)); - assertCredentials(TestHost.H1a_08, netrc.getCredentials(TestHost.H1_08.machine)); - assertNull("Credentials for H1_09 should be null.", netrc.getCredentials(TestHost.H1_09.machine)); - assertNull("Credentials for H1_10 should be null.", netrc.getCredentials(TestHost.H1_10.machine)); - assertNull("Credentials for H1_11 should be null.", netrc.getCredentials(TestHost.H1_11.machine)); + assertCredentials(TestHost.H1A_08, netrc.getCredentials(TestHost.H1_08.machine)); + assertNull(netrc.getCredentials(TestHost.H1_09.machine), "Credentials for H1_09 should be null."); + assertNull(netrc.getCredentials(TestHost.H1_10.machine), "Credentials for H1_10 should be null."); + assertNull(netrc.getCredentials(TestHost.H1_11.machine), "Credentials for H1_11 should be null."); assertCredentials(TestHost.H1_12, netrc.getCredentials(TestHost.H1_12.machine)); } @Test - public void testGetCredentialsOtherFile() throws Exception { + void testGetCredentialsOtherFile() { Netrc netrc = Netrc.getInstance(testFilePath_1); assertNotNull(netrc); @@ -229,10 +228,10 @@ public void testGetCredentialsOtherFile() throws Exception { assertCredentials(TestHost.H1_10, netrc.getCredentials(TestHost.H1_10.machine)); assertCredentials(TestHost.H1_11, netrc.getCredentials(TestHost.H1_11.machine)); assertCredentials(TestHost.H1_12, netrc.getCredentials(TestHost.H1_12.machine)); - assertNull("Credentials for H2_01 should be null.", netrc.getCredentials(TestHost.H2_01.machine)); - assertNull("Credentials for H2_02 should be null.", netrc.getCredentials(TestHost.H2_02.machine)); - assertNull("Credentials for H2_03 should be null.", netrc.getCredentials(TestHost.H2_03.machine)); - assertNull("Credentials for H2_04 should be null.", netrc.getCredentials(TestHost.H2_04.machine)); + assertNull(netrc.getCredentials(TestHost.H2_01.machine), "Credentials for H2_01 should be null."); + assertNull(netrc.getCredentials(TestHost.H2_02.machine), "Credentials for H2_02 should be null."); + assertNull(netrc.getCredentials(TestHost.H2_03.machine), "Credentials for H2_03 should be null."); + assertNull(netrc.getCredentials(TestHost.H2_04.machine), "Credentials for H2_04 should be null."); netrc = Netrc.getInstance(testFilePath_2); assertNotNull(netrc); @@ -241,9 +240,15 @@ public void testGetCredentialsOtherFile() throws Exception { assertCredentials(TestHost.H2_02, netrc.getCredentials(TestHost.H2_02.machine)); assertCredentials(TestHost.H2_03, netrc.getCredentials(TestHost.H2_03.machine)); assertCredentials(TestHost.H2_04, netrc.getCredentials(TestHost.H2_04.machine)); - assertNull("Credentials for H1_01 should be null.", netrc.getCredentials(TestHost.H1_01.machine)); - assertNull("Credentials for H1_02 should be null.", netrc.getCredentials(TestHost.H1_02.machine)); - assertNull("Credentials for H1_03 should be null.", netrc.getCredentials(TestHost.H1_03.machine)); - assertNull("Credentials for H1_04 should be null.", netrc.getCredentials(TestHost.H1_04.machine)); + assertNull(netrc.getCredentials(TestHost.H1_01.machine), "Credentials for H1_01 should be null."); + assertNull(netrc.getCredentials(TestHost.H1_02.machine), "Credentials for H1_02 should be null."); + assertNull(netrc.getCredentials(TestHost.H1_03.machine), "Credentials for H1_03 should be null."); + assertNull(netrc.getCredentials(TestHost.H1_04.machine), "Credentials for H1_04 should be null."); + } + + private static File newFile(File parent, String child) throws Exception { + File result = new File(parent, child); + result.createNewFile(); + return result; } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/PushSimpleTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/PushSimpleTest.java index c827718107..fee600a76e 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/PushSimpleTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/PushSimpleTest.java @@ -1,25 +1,22 @@ package org.jenkinsci.plugins.gitclient; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import hudson.plugins.git.GitException; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import org.eclipse.jgit.transport.URIish; -import org.junit.Test; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -public class PushSimpleTest extends PushTest { - - public PushSimpleTest(String gitImpl, String branchName, String refSpec, Class expectedException) { - super(gitImpl, branchName, refSpec, expectedException); - } +@ParameterizedClass(name = "{0} with {1}") +@MethodSource("pushParameters") +class PushSimpleTest extends PushTest { @Test - public void pushNonFastForwardThrows() throws IOException, GitException, InterruptedException { + void pushNonFastForwardThrows() throws Exception { checkoutOldBranchAndCommitFile(); // Old branch can't be pushed without force() assertThrows(GitException.class, () -> workingGitClient .push() @@ -30,7 +27,7 @@ public void pushNonFastForwardThrows() throws IOException, GitException, Interru } @Test - public void pushBadURIThrows() throws IOException, GitException, InterruptedException, URISyntaxException { + void pushBadURIThrows() throws Exception { checkoutBranchAndCommitFile(); URIish bad = new URIish(bareURI.toString() + "-bad"); assertThrows( @@ -38,12 +35,11 @@ public void pushBadURIThrows() throws IOException, GitException, InterruptedExce () -> workingGitClient.push().to(bad).ref(refSpec).execute()); } - @Parameterized.Parameters(name = "{0} with {1}") - public static Collection pushParameters() { - List parameters = new ArrayList<>(); - Object[] gitParameter = {"git", "master", "master", null}; + static List pushParameters() { + List parameters = new ArrayList<>(); + Arguments gitParameter = Arguments.of("git", "master", "master", null); parameters.add(gitParameter); - Object[] jgitParameter = {"jgit", "master", "master", null}; + Arguments jgitParameter = Arguments.of("jgit", "master", "master", null); parameters.add(jgitParameter); return parameters; } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/PushTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/PushTest.java index 3b6db8484b..a705698001 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/PushTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/PushTest.java @@ -1,13 +1,8 @@ package org.jenkinsci.plugins.gitclient; -import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertEquals; -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 org.junit.jupiter.api.Assertions.*; import hudson.model.TaskListener; import hudson.plugins.git.Branch; @@ -18,24 +13,16 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Random; +import java.util.*; import org.apache.commons.io.FileUtils; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.transport.URIish; -import org.junit.After; -import org.junit.AfterClass; -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.junit.rules.TestName; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Test various permutations of push refspecs. JENKINS-20393 highlights that @@ -46,20 +33,28 @@ * * @author Mark Waite */ -@RunWith(Parameterized.class) -public class PushTest { +@ParameterizedClass(name = "{0} with {1} refspec {2}") +@MethodSource("pushParameters") +class PushTest { - private final String gitImpl; - protected final String refSpec; - private final String branchName; - private final Class expectedException; + @Parameter(0) + protected String gitImpl; + + @Parameter(1) + protected String branchName; + + @Parameter(2) + protected String refSpec; + + @Parameter(3) + protected Class expectedException; private static File bareRepo; protected static URIish bareURI; private static GitClient bareGitClient; private static ObjectId bareFirstCommit; - private static final String BRANCH_NAMES[] = {"master", "feature/push-test"}; + private static final String[] BRANCH_NAMES = {"master", "feature/push-test"}; private ObjectId previousCommit; @@ -67,24 +62,14 @@ public class PushTest { protected GitClient workingGitClient; private ObjectId workingCommit; - @Rule - public TestName name = new TestName(); - - @ClassRule - public static TemporaryFolder staticTemporaryFolder = new TemporaryFolder(); + @TempDir + private static File staticTemporaryFolder; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - public PushTest(String gitImpl, String branchName, String refSpec, Class expectedException) { - this.gitImpl = gitImpl; - this.branchName = branchName; - this.refSpec = refSpec; - this.expectedException = expectedException; - } + @TempDir + private File temporaryFolder; @Test - public void push() throws IOException, GitException, InterruptedException { + void push() throws Exception { checkoutBranchAndCommitFile(); if (expectedException != null) { @@ -97,7 +82,7 @@ public void push() throws IOException, GitException, InterruptedException { } @Test - public void pushNonFastForwardForce() throws IOException, GitException, InterruptedException { + void pushNonFastForwardForce() throws Exception { checkoutOldBranchAndCommitFile(); if (expectedException != null) { @@ -112,9 +97,8 @@ public void pushNonFastForwardForce() throws IOException, GitException, Interrup } } - @Parameterized.Parameters(name = "{0} with {1} refspec {2}") - public static Collection pushParameters() { - List parameters = new ArrayList<>(); + static List pushParameters() { + List parameters = new ArrayList<>(); final String[] implementations = {"git", "jgit"}; final String[] goodRefSpecs = { "{0}", "HEAD", "HEAD:{0}", "{0}:{0}", "refs/heads/{0}", "{0}:heads/{0}", "{0}:refs/heads/{0}" @@ -133,12 +117,12 @@ public static Collection pushParameters() { for (String branch : BRANCH_NAMES) { for (String paramRefSpec : goodRefSpecs) { String spec = MessageFormat.format(paramRefSpec, branch); - Object[] parameter = {implementation, branch, spec, null}; + Arguments parameter = Arguments.of(implementation, branch, spec, null); parameters.add(parameter); } for (String paramRefSpec : badRefSpecs) { String spec = MessageFormat.format(paramRefSpec, branch); - Object[] parameter = {implementation, branch, spec, GitException.class}; + Arguments parameter = Arguments.of(implementation, branch, spec, GitException.class); parameters.add(parameter); } } @@ -146,11 +130,11 @@ public static Collection pushParameters() { return parameters; } - @Before - public void createWorkingRepository() throws Exception { + @BeforeEach + void createWorkingRepository() throws Exception { hudson.EnvVars env = new hudson.EnvVars(); TaskListener listener = StreamTaskListener.fromStderr(); - workingRepo = temporaryFolder.newFolder(); + workingRepo = newFolder(temporaryFolder, "junit-" + System.nanoTime()); workingGitClient = Git.with(listener, env).in(workingRepo).using(gitImpl).getClient(); workingGitClient @@ -166,36 +150,37 @@ public void createWorkingRepository() throws Exception { .execute(); assertNotNull(bareFirstCommit); assertTrue( - "Clone does not contain " + bareFirstCommit, - workingGitClient.revList("origin/" + branchName).contains(bareFirstCommit)); + workingGitClient.revList("origin/" + branchName).contains(bareFirstCommit), + "Clone does not contain " + bareFirstCommit); ObjectId workingHead = workingGitClient.getHeadRev(workingRepo.getAbsolutePath(), branchName); ObjectId bareHead = bareGitClient.getHeadRev(bareRepo.getAbsolutePath(), branchName); - assertEquals("Initial checkout of " + branchName + " has different HEAD than bare repo", bareHead, workingHead); + assertEquals(bareHead, workingHead, "Initial checkout of " + branchName + " has different HEAD than bare repo"); CliGitCommand gitCmd = new CliGitCommand(workingGitClient); gitCmd.initializeRepository( "Vojtěch PushTest working repo Zweibrücken-Šafařík", "email.from.git.client@example.com"); } - @After - public void verifyPushResultAndDeleteDirectory() throws GitException, InterruptedException { + @AfterEach + void verifyPushResultAndDeleteDirectory(TestInfo info) throws Exception { /* Confirm push reached bare repo */ - if (expectedException == null && !name.getMethodName().contains("Throws")) { + if (expectedException == null + && !info.getTestMethod().orElseThrow().getName().contains("Throws")) { ObjectId latestBareHead = bareGitClient.getHeadRev(bareRepo.getAbsolutePath(), branchName); - assertEquals(branchName + " commit not pushed to " + refSpec, workingCommit, latestBareHead); + assertEquals(workingCommit, latestBareHead, branchName + " commit not pushed to " + refSpec); assertNotEquals(previousCommit, workingCommit); assertNotEquals(previousCommit, latestBareHead); } } - @BeforeClass - public static void createBareRepository() throws Exception { + @BeforeAll + static void createBareRepository() throws Exception { /* Randomly choose git implementation to create bare repository */ final String[] gitImplementations = {"git", "jgit"}; Random random = new Random(); String gitImpl = gitImplementations[random.nextInt(gitImplementations.length)]; /* Create the bare repository */ - bareRepo = staticTemporaryFolder.newFolder(); + bareRepo = newFolder(staticTemporaryFolder, "junit-" + System.nanoTime()); bareURI = new URIish(bareRepo.getAbsolutePath()); hudson.EnvVars env = new hudson.EnvVars(); TaskListener listener = StreamTaskListener.fromStderr(); @@ -203,7 +188,7 @@ public static void createBareRepository() throws Exception { bareGitClient.init_().workspace(bareRepo.getAbsolutePath()).bare(true).execute(); /* Clone the bare repository into a working copy */ - File cloneRepo = staticTemporaryFolder.newFolder(); + File cloneRepo = newFolder(staticTemporaryFolder, "junit-" + System.nanoTime()); GitClient cloneGitClient = Git.with(listener, env).in(cloneRepo).using(gitImpl).getClient(); cloneGitClient @@ -236,26 +221,26 @@ public static void createBareRepository() throws Exception { bareFirstCommit = bareGitClient.getHeadRev(bareRepo.getAbsolutePath(), "master"); } - @AfterClass - public static void removeBareRepository() throws IOException { + @AfterAll + static void removeBareRepository() throws Exception { FileUtils.deleteDirectory(bareRepo); } - protected void checkoutBranchAndCommitFile() throws GitException, InterruptedException, IOException { + protected void checkoutBranchAndCommitFile() throws Exception { previousCommit = checkoutBranch(false); workingCommit = commitFileToCurrentBranch(); } - protected void checkoutOldBranchAndCommitFile() throws GitException, InterruptedException, IOException { + protected void checkoutOldBranchAndCommitFile() throws Exception { previousCommit = checkoutBranch(true); workingCommit = commitFileToCurrentBranch(); } private Collection getBranchNames(List branches) { - return branches.stream().map(Branch::getName).collect(toList()); + return branches.stream().map(Branch::getName).toList(); } - private ObjectId checkoutBranch(boolean useOldCommit) throws GitException, InterruptedException { + private ObjectId checkoutBranch(boolean useOldCommit) throws Exception { /* Checkout branchName */ workingGitClient.checkoutBranch(branchName, "origin/" + branchName + (useOldCommit ? "^" : "")); List branches = workingGitClient.getBranchesContaining(branchName, false); @@ -263,7 +248,7 @@ private ObjectId checkoutBranch(boolean useOldCommit) throws GitException, Inter return bareGitClient.getHeadRev(bareRepo.getAbsolutePath(), branchName); } - private ObjectId commitFileToCurrentBranch() throws InterruptedException, GitException, IOException { + private ObjectId commitFileToCurrentBranch() throws Exception { /* Add a file with random content to the current branch of working repo */ File added = File.createTempFile("added-", ".txt", workingRepo); String randomContent = java.util.UUID.randomUUID().toString(); @@ -291,8 +276,12 @@ private static void shuffleArray(String[] ar) { } } - /** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */ - private static boolean isWindows() { - return File.pathSeparatorChar == ';'; + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/RemoteGitImplTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/RemoteGitImplTest.java index 817103faa6..6355946fa3 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/RemoteGitImplTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/RemoteGitImplTest.java @@ -27,9 +27,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.common.StandardCredentials; @@ -42,33 +40,31 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; +import java.util.Random; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; -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; -public class RemoteGitImplTest { +class RemoteGitImplTest { - public RemoteGitImplTest() {} - - @Rule - public TemporaryFolder temporaryFolderRule = new TemporaryFolder(); + @TempDir + private File temporaryFolderRule; private File localFolder; private GitClient defaultClient; private RemoteGitImpl remoteGit; private String gitImplName; - private java.util.Random random = new java.util.Random(); + private final Random random = new Random(); - @Before - public void setUp() throws IOException, InterruptedException { + @BeforeEach + void setUp() throws Exception { /* Use a randomly selected git implementation in hopes of detecting more issues with fewer tests */ String[] gitImplAlternatives = {"git", "jgit", "jgitapache"}; gitImplName = gitImplAlternatives[random.nextInt(gitImplAlternatives.length)]; - localFolder = temporaryFolderRule.newFolder(); + localFolder = newFolder(temporaryFolderRule, "junit"); defaultClient = Git.with(TaskListener.NULL, new EnvVars()) .in(localFolder) .using(gitImplName) @@ -77,17 +73,17 @@ public void setUp() throws IOException, InterruptedException { } @Test - public void testGetRepository() { + void testGetRepository() { assertThrows(UnsupportedOperationException.class, () -> remoteGit.getRepository()); } @Test - public void testClearCredentials() { + void testClearCredentials() { remoteGit.clearCredentials(); } @Test - public void testAddCredentials() throws Exception { + void testAddCredentials() throws Exception { CredentialsScope scope = CredentialsScope.GLOBAL; String password = "password"; String url = "https://github.com/jenkinsci/git-client-plugin"; @@ -99,7 +95,7 @@ public void testAddCredentials() throws Exception { } @Test - public void testSetCredentials() throws Exception { + void testSetCredentials() throws Exception { CredentialsScope scope = CredentialsScope.GLOBAL; String password = "password"; String username = "user"; @@ -110,7 +106,7 @@ public void testSetCredentials() throws Exception { } @Test - public void testAddDefaultCredentials() throws Exception { + void testAddDefaultCredentials() throws Exception { CredentialsScope scope = CredentialsScope.GLOBAL; String password = "password"; String username = "user"; @@ -121,14 +117,14 @@ public void testAddDefaultCredentials() throws Exception { } @Test - public void testSetAuthor_String_String() throws Exception { + void testSetAuthor_String_String() { String name = "charlie"; String email = "charlie@example.com"; remoteGit.setAuthor(name, email); } @Test - public void testSetAuthor_PersonIdent() throws Exception { + void testSetAuthor_PersonIdent() { String name = "charlie"; String email = "charlie@example.com"; PersonIdent p = new PersonIdent(name, email); @@ -136,14 +132,14 @@ public void testSetAuthor_PersonIdent() throws Exception { } @Test - public void testSetCommitter_String_String() throws Exception { + void testSetCommitter_String_String() { String name = "charlie"; String email = "charlie@example.com"; remoteGit.setCommitter(name, email); } @Test - public void testSetCommitter_PersonIdent() throws Exception { + void testSetCommitter_PersonIdent() { String name = "charlie"; String email = "charlie@example.com"; PersonIdent p = new PersonIdent(name, email); @@ -151,17 +147,17 @@ public void testSetCommitter_PersonIdent() throws Exception { } @Test - public void testGetWorkTree() { + void testGetWorkTree() { FilePath folderPath = new FilePath(localFolder); FilePath remoteFolderPath = remoteGit.getWorkTree(); assertThat(remoteFolderPath, is(folderPath)); } @Test - public void testInit() throws Exception { - assertFalse("defaultClient has repo before init", defaultClient.hasGitRepo()); + void testInit() throws Exception { + assertFalse(defaultClient.hasGitRepo(), "defaultClient has repo before init"); remoteGit.init(); - assertTrue("defaultClient missing repo after init", defaultClient.hasGitRepo()); + assertTrue(defaultClient.hasGitRepo(), "defaultClient missing repo after init"); } private void firstAdd(String fileName) throws Exception { @@ -184,38 +180,38 @@ private ObjectId firstCommit(String fileName) throws Exception { } @Test - public void testAddAndCommit() throws Exception { + void testAddAndCommit() throws Exception { assertThat(firstCommit("testAddAndCommit"), is(not(nullValue()))); } @Test - public void testCommit_3args() throws Exception { + void testCommit_3args() throws Exception { firstAdd("testCommit_3args_abc"); String message = "Committing with authorName and commiterName"; PersonIdent author = new PersonIdent("authorName", "authorEmail@example.com"); PersonIdent committer = new PersonIdent("committerName", "committerEmail@example.com"); remoteGit.commit(message, author, committer); ObjectId commit = remoteGit.revParse("HEAD"); - assertTrue("Commit not in repo", remoteGit.isCommitInRepo(commit)); + assertTrue(remoteGit.isCommitInRepo(commit), "Commit not in repo"); } @Test - public void testHasGitRepo() throws Exception { - assertFalse("remoteGit has repo before init", remoteGit.hasGitRepo()); + void testHasGitRepo() throws Exception { + assertFalse(remoteGit.hasGitRepo(), "remoteGit has repo before init"); remoteGit.init(); - assertTrue("remoteGit missing repo after init", remoteGit.hasGitRepo()); + assertTrue(remoteGit.hasGitRepo(), "remoteGit missing repo after init"); } @Test - public void testIsCommitInRepo() throws Exception { + void testIsCommitInRepo() throws Exception { ObjectId commit = firstCommit("testIsCommitInRepo-abc"); - assertTrue("Commit not in repo", remoteGit.isCommitInRepo(commit)); + assertTrue(remoteGit.isCommitInRepo(commit), "Commit not in repo"); ObjectId missingCommit = ObjectId.fromString("deededbeadedcededaddedbedded5ea6b842da60"); - assertFalse("Missing commit found in repo", remoteGit.isCommitInRepo(missingCommit)); + assertFalse(remoteGit.isCommitInRepo(missingCommit), "Missing commit found in repo"); } @Test - public void testGetRemoteUrl_String() throws Exception { + void testGetRemoteUrl_String() throws Exception { String name = "originName"; String url = "https://github.com/jenkinsci/git-client-plugin"; remoteGit.init(); @@ -227,4 +223,13 @@ public void testGetRemoteUrl_String() throws Exception { remoteGit.addRemoteUrl(name + "2", url + "-2"); assertThat(remoteGit.getRemoteUrl(name + "2"), is(url + "-2")); } + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/SubmodulePatternStringTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/SubmodulePatternStringTest.java index f582219e2a..d2c8b1e962 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/SubmodulePatternStringTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/SubmodulePatternStringTest.java @@ -2,32 +2,40 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; -@RunWith(Parameterized.class) -public class SubmodulePatternStringTest { +@ParameterizedClass(name = "{0}-{1}") +@MethodSource("repoAndRemote") +class SubmodulePatternStringTest { - private final String remoteName; - private final String submoduleConfigOutput; - private final Matcher matcher; + @Parameter(0) + private String repoUrl; + + @Parameter(1) + private String remoteName; + + private String submoduleConfigOutput; + private Matcher matcher; private static final Pattern SUBMODULE_CONFIG_PATTERN = Pattern.compile(CliGitAPIImpl.SUBMODULE_REMOTE_PATTERN_STRING, Pattern.MULTILINE); - public SubmodulePatternStringTest(String repoUrl, String remoteName) { - this.remoteName = remoteName; - this.submoduleConfigOutput = "submodule." + remoteName + ".url " + repoUrl; - this.matcher = SUBMODULE_CONFIG_PATTERN.matcher(submoduleConfigOutput); + @BeforeEach + void setUp() { + submoduleConfigOutput = "submodule." + remoteName + ".url " + repoUrl; + matcher = SUBMODULE_CONFIG_PATTERN.matcher(submoduleConfigOutput); } /* @@ -36,9 +44,8 @@ public SubmodulePatternStringTest(String repoUrl, String remoteName) { * * Tests file, ssh (both forms), git, and https. */ - @Parameterized.Parameters(name = "{0}-{1}") - public static Collection repoAndRemote() { - List arguments = new ArrayList<>(); + static List repoAndRemote() { + List arguments = new ArrayList<>(); String[] repoUrls = { "file://gitroot/thirdparty.url.repo", "git://gitroot/repo", @@ -61,7 +68,7 @@ public static Collection repoAndRemote() { for (String repoUrlSuffix : suffixes) { for (String remoteNameParam : remoteNames) { for (String remoteNameSuffix : suffixes) { - Object[] item = {repoUrlParam + repoUrlSuffix, remoteNameParam + remoteNameSuffix}; + Arguments item = Arguments.of(repoUrlParam + repoUrlSuffix, remoteNameParam + remoteNameSuffix); arguments.add(item); } } @@ -72,8 +79,8 @@ public static Collection repoAndRemote() { @Issue("JENKINS-46054") @Test - public void urlFoundInSubmoduleConfigOutput() { - assertTrue("Match not found for '" + submoduleConfigOutput + "'", matcher.find()); + void urlFoundInSubmoduleConfigOutput() { + assertTrue(matcher.find(), "Match not found for '" + submoduleConfigOutput + "'"); assertThat(matcher.group(1), is(remoteName)); } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/UnsupportedCommandTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/UnsupportedCommandTest.java index 6e366662dc..4f975b2806 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/UnsupportedCommandTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/UnsupportedCommandTest.java @@ -23,7 +23,8 @@ */ package org.jenkinsci.plugins.gitclient; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.cloudbees.plugins.credentials.CredentialsDescriptor; import com.cloudbees.plugins.credentials.CredentialsScope; @@ -31,31 +32,27 @@ import edu.umd.cs.findbugs.annotations.NonNull; import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class UnsupportedCommandTest { +class UnsupportedCommandTest { - private final UnsupportedCommand unsupportedCommand; - - public UnsupportedCommandTest() { - unsupportedCommand = new UnsupportedCommand(); - } + private final UnsupportedCommand unsupportedCommand = new UnsupportedCommand(); @Test - public void testSparseCheckoutPathsNull() { + void testSparseCheckoutPathsNull() { unsupportedCommand.sparseCheckoutPaths(null); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testSparseCheckoutPathsEmptyList() { + void testSparseCheckoutPathsEmptyList() { List emptyList = new ArrayList<>(); unsupportedCommand.sparseCheckoutPaths(emptyList); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testSparseCheckoutPaths() { + void testSparseCheckoutPaths() { List sparseList = new ArrayList<>(); sparseList.add("a-file-for-sparse-checkout"); unsupportedCommand.sparseCheckoutPaths(sparseList); @@ -63,185 +60,185 @@ public void testSparseCheckoutPaths() { } @Test - public void testTimeoutNull() { + void testTimeoutNull() { unsupportedCommand.timeout(null); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testTimeout() { + void testTimeout() { Integer five = 5; unsupportedCommand.timeout(five); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testLfsRemoteNull() { + void testLfsRemoteNull() { unsupportedCommand.lfsRemote(null); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testLfsRemote() { + void testLfsRemote() { unsupportedCommand.lfsRemote("https://github.com/MarkEWaite/docker-lfs"); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testLfsCredentialsNull() { + void testLfsCredentialsNull() { unsupportedCommand.lfsCredentials(null); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testLfsCredentials() { + void testLfsCredentials() { FakeCredentials credentials = new FakeCredentials(); unsupportedCommand.lfsCredentials(credentials); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testNotShallow() { + void testNotShallow() { unsupportedCommand.shallow(false); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testShallow() { + void testShallow() { unsupportedCommand.shallow(true); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testDepthNull() { + void testDepthNull() { unsupportedCommand.depth(null); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testDepthNegative() { + void testDepthNegative() { unsupportedCommand.depth(-1); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testDepth() { + void testDepth() { unsupportedCommand.depth(1); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testNotFirstParent() { + void testNotFirstParent() { unsupportedCommand.firstParent(false); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testFirstParent() { + void testFirstParent() { unsupportedCommand.firstParent(true); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testThreadsNull() { + void testThreadsNull() { unsupportedCommand.threads(null); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testThreadsZero() { + void testThreadsZero() { unsupportedCommand.threads(0); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testThreads() { + void testThreads() { unsupportedCommand.threads(42); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testNotRemoteTracking() { + void testNotRemoteTracking() { unsupportedCommand.remoteTracking(false); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testRemoteTracking() { + void testRemoteTracking() { unsupportedCommand.remoteTracking(true); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testRefNull() { + void testRefNull() { unsupportedCommand.ref(null); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testRefEmpty() { + void testRefEmpty() { unsupportedCommand.ref(""); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testRef() { + void testRef() { unsupportedCommand.ref("beadeddeededcededadded"); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testNotParentCredentials() { + void testNotParentCredentials() { unsupportedCommand.parentCredentials(false); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testParentCredentials() { + void testParentCredentials() { unsupportedCommand.remoteTracking(true); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testUseBranchNull() { + void testUseBranchNull() { unsupportedCommand.useBranch(null, null); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testUseBranchNullBranchName() { + void testUseBranchNullBranchName() { unsupportedCommand.useBranch("some-submodule", null); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testUseBranchNullSubmodule() { + void testUseBranchNullSubmodule() { unsupportedCommand.useBranch(null, "some-branch"); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testUseBranch() { + void testUseBranch() { unsupportedCommand.useBranch("some-submodule", "some-branch"); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testGitPublisherDisabled() { + void testGitPublisherDisabled() { /* Disabled git publisher is allowed to use JGit */ unsupportedCommand.gitPublisher(false); assertTrue(unsupportedCommand.determineSupportForJGit()); } @Test - public void testGitPublisher() { + void testGitPublisher() { /* Enabled git publisher must not use JGit */ unsupportedCommand.gitPublisher(true); assertFalse(unsupportedCommand.determineSupportForJGit()); } @Test - public void testDetermineSupportForJGit() { + void testDetermineSupportForJGit() { /* Confirm default is true */ assertTrue(unsupportedCommand.determineSupportForJGit()); } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/WarnTempDirValueTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/WarnTempDirValueTest.java index 030c59ed7b..831fce5a78 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/WarnTempDirValueTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/WarnTempDirValueTest.java @@ -1,25 +1,23 @@ package org.jenkinsci.plugins.gitclient; -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.*; import hudson.EnvVars; import hudson.util.LogTaskListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +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.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; /** @@ -33,17 +31,15 @@ * * @author Mark Waite */ -@RunWith(Parameterized.class) -public class WarnTempDirValueTest { +@ParameterizedClass(name = "{0}") +@MethodSource("envVarsToCheck") +class WarnTempDirValueTest { - private final String envVarName; + @Parameter(0) + private String envVarName; - public WarnTempDirValueTest(String envVarName) { - this.envVarName = envVarName; - } - - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; private File repo = null; private int logCount = 0; @@ -51,13 +47,13 @@ public WarnTempDirValueTest(String envVarName) { private LogTaskListener listener = null; private static final String LOGGING_STARTED = "** Logging started **"; - @Before - public void createRepo() throws IOException { - repo = tempFolder.newFolder(); + @BeforeEach + void createRepo() throws Exception { + repo = newFolder(tempFolder, "junit"); } - @Before - public void createLogger() { + @BeforeEach + void createLogger() { Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++); handler = new LogHandler(); handler.setLevel(Level.ALL); @@ -68,23 +64,22 @@ public void createLogger() { listener.getLogger().println(LOGGING_STARTED); } - @After - public void checkLogger() { + @AfterEach + void checkLogger() { assertTrue(handler.containsMessageSubstring(LOGGING_STARTED)); } - @Parameterized.Parameters(name = "{0}") - public static Collection envVarsToCheck() { - List envVarNames = new ArrayList<>(); - Object[] tmp = {"TMP"}; + static List envVarsToCheck() { + List envVarNames = new ArrayList<>(); + Arguments tmp = Arguments.of("TMP"); envVarNames.add(tmp); - Object[] temp = {"TEMP"}; + Arguments temp = Arguments.of("TEMP"); envVarNames.add(temp); return envVarNames; } @Test - public void noWarningForDefaultValue() throws Exception { + void noWarningForDefaultValue() throws Exception { EnvVars env = new hudson.EnvVars(); assertFalse(env.get(envVarName, "/tmp").contains(" ")); GitClient git = Git.with(listener, env).in(repo).using("git").getClient(); @@ -94,7 +89,7 @@ public void noWarningForDefaultValue() throws Exception { @Test @Issue("JENKINS-22706") - public void warnWhenValueContainsSpaceCharacter() throws Exception { + void warnWhenValueContainsSpaceCharacter() throws Exception { EnvVars env = new hudson.EnvVars(); assertFalse(env.get(envVarName, "/tmp").contains(" ")); env.put(envVarName, "/tmp/has a space/"); @@ -108,4 +103,13 @@ public void warnWhenValueContainsSpaceCharacter() throws Exception { private boolean isWindows() { return File.pathSeparatorChar == ';'; } + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/WorkspaceWithRepo.java b/src/test/java/org/jenkinsci/plugins/gitclient/WorkspaceWithRepo.java index 97ec79d8bf..f8a95abb86 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/WorkspaceWithRepo.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/WorkspaceWithRepo.java @@ -8,7 +8,6 @@ import hudson.Launcher; import hudson.Util; import hudson.model.TaskListener; -import hudson.plugins.git.GitException; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -21,7 +20,7 @@ import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.lib.ObjectId; -public class WorkspaceWithRepo { +class WorkspaceWithRepo { private GitClient gitClient; private File gitFileDir; @@ -85,7 +84,7 @@ private boolean isShallow() { * @throws IOException on I/O error * @throws InterruptedException when exception is interrupted */ - String localMirror() throws IOException, InterruptedException { + String localMirror() throws Exception { File base = new File(".").getAbsoluteFile(); for (File f = base; f != null; f = f.getParentFile()) { File targetDir = new File(f, "target"); @@ -143,11 +142,11 @@ String localMirror() throws IOException, InterruptedException { throw new IllegalStateException(); } - String launchCommand(String... args) throws IOException, InterruptedException { + String launchCommand(String... args) throws Exception { return launchCommand(false, args); } - String launchCommand(boolean ignoreError, String... args) throws IOException, InterruptedException { + String launchCommand(boolean ignoreError, String... args) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); int returnCode = new Launcher.LocalLauncher(listener) .launch() @@ -167,7 +166,7 @@ String launchCommand(boolean ignoreError, String... args) throws IOException, In return output; } - void initBareRepo(GitClient gitClient, boolean bare) throws GitException, InterruptedException { + void initBareRepo(GitClient gitClient, boolean bare) throws Exception { gitClient.init_().workspace(gitFileDir.getAbsolutePath()).bare(bare).execute(); } @@ -181,11 +180,11 @@ void touch(File gitDir, String fileName, String content) throws Exception { Files.writeString(f.toPath(), content, StandardCharsets.UTF_8); } - void tag(String tag) throws IOException, InterruptedException { + void tag(String tag) throws Exception { tag(tag, false); } - void tag(String tag, boolean force) throws IOException, InterruptedException { + void tag(String tag, boolean force) throws Exception { if (force) { launchCommand("git", "tag", "--force", tag); } else { @@ -193,7 +192,7 @@ void tag(String tag, boolean force) throws IOException, InterruptedException { } } - void commitEmpty(String msg) throws IOException, InterruptedException { + void commitEmpty(String msg) throws Exception { launchCommand("git", "commit", "--allow-empty", "-m", msg); } @@ -207,7 +206,7 @@ JGitAPIImpl jgit() throws Exception { Git.with(listener, new EnvVars()).in(gitFileDir).using("jgit").getClient(); } - ObjectId head() throws GitException, IOException, InterruptedException { + ObjectId head() throws Exception { return gitClient.revParse("HEAD"); } @@ -227,7 +226,7 @@ boolean exists(String path) { return file(path).exists(); } - String contentOf(String path) throws IOException { + String contentOf(String path) throws Exception { return Files.readString(file(path).toPath(), StandardCharsets.UTF_8); } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/cgit/GitCommandsExecutorTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/cgit/GitCommandsExecutorTest.java index d8b7b1c4f9..72e2322321 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/cgit/GitCommandsExecutorTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/cgit/GitCommandsExecutorTest.java @@ -8,9 +8,7 @@ import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.theInstance; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import hudson.model.TaskListener; import hudson.plugins.git.GitException; @@ -23,52 +21,44 @@ import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public class GitCommandsExecutorTest { - - private final int threads; - private final TaskListener listener; - private final ByteArrayOutputStream logStream; - - @Rule - public TestName testName = new TestName(); - - public GitCommandsExecutorTest(int threads) { - this.threads = threads; - this.logStream = new ByteArrayOutputStream(); - this.listener = new StreamTaskListener(new PrintStream(logStream), StandardCharsets.UTF_8); - } +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; - @After - public void verifyCorrectExecutorServiceShutdown() { - loggedNoOutput(); - } +@ParameterizedClass(name = "threads={0}") +@MethodSource("threadsParameter") +class GitCommandsExecutorTest { + + private final ByteArrayOutputStream logStream = new ByteArrayOutputStream(); + private final TaskListener listener = new StreamTaskListener(new PrintStream(logStream), StandardCharsets.UTF_8); + + @Parameter(0) + private int threads; private String value = null; private String error = null; - @Before - public void defineValues() { - value = "some value " + testName.getMethodName(); - error = "some error " + testName.getMethodName(); + static List threadsParameter() { + return List.of(1, 2, 100); } - @Parameters(name = "threads={0}") - public static Iterable threadsParameter() { - return asList(1, 2, 100); + @BeforeEach + void defineValues(TestInfo testInfo) { + value = "some value " + testInfo.getTestMethod().orElseThrow().getName(); + error = "some error " + testInfo.getTestMethod().orElseThrow().getName(); + } + + @AfterEach + void verifyCorrectExecutorServiceShutdown() { + loggedNoOutput(); } @Test - public void allCommandsSucceed() throws Exception { + void allCommandsSucceed() throws Exception { List> commands = new ArrayList<>(); for (int i = 0; i < threads; i++) { commands.add(new GoodCommand(value)); @@ -82,21 +72,20 @@ public void allCommandsSucceed() throws Exception { } @Test - public void allCommandsFail() throws Exception { + void allCommandsFail() { List> commands = new ArrayList<>(); for (int i = 0; i < threads; i++) { commands.add(new BadCommand(new RuntimeException(error))); } - Exception e = assertThrows(GitException.class, () -> { - new GitCommandsExecutor(threads, listener).invokeAll(commands); - }); + Exception e = + assertThrows(GitException.class, () -> new GitCommandsExecutor(threads, listener).invokeAll(commands)); assertThat(e.getMessage(), is("java.lang.RuntimeException: " + error)); assertThat(e.getCause(), instanceOf(RuntimeException.class)); } @Test - public void firstCommandFails() throws Exception { + void firstCommandFails() { long commandExecutionTime = 60_000; List> commands = asList( new BadCommand(new RuntimeException(error)), @@ -104,9 +93,8 @@ public void firstCommandFails() throws Exception { new GoodCommand(value, commandExecutionTime)); long executionStartMillis = System.currentTimeMillis(); - Exception e = assertThrows(GitException.class, () -> { - new GitCommandsExecutor(threads, listener).invokeAll(commands); - }); + Exception e = + assertThrows(GitException.class, () -> new GitCommandsExecutor(threads, listener).invokeAll(commands)); assertThat(e.getMessage(), is("java.lang.RuntimeException: " + error)); assertThat(e.getCause(), instanceOf(RuntimeException.class)); long executionStopMillis = System.currentTimeMillis(); @@ -120,13 +108,12 @@ public void firstCommandFails() throws Exception { } @Test - public void lastCommandFails() throws Exception { + void lastCommandFails() { List> commands = asList(new GoodCommand(value), new GoodCommand(value), new BadCommand(new RuntimeException(error))); - Exception e = assertThrows(GitException.class, () -> { - new GitCommandsExecutor(threads, listener).invokeAll(commands); - }); + Exception e = + assertThrows(GitException.class, () -> new GitCommandsExecutor(threads, listener).invokeAll(commands)); assertThat(e.getMessage(), is("java.lang.RuntimeException: " + error)); assertThat(e.getCause(), instanceOf(RuntimeException.class)); @@ -136,7 +123,7 @@ public void lastCommandFails() throws Exception { } @Test - public void moreCommandsThanThreads() throws Exception { + void moreCommandsThanThreads() throws Exception { List> commands = new ArrayList<>(); for (int i = 0; i < threads + 1; i++) { commands.add(new GoodCommand(value)); @@ -150,7 +137,7 @@ public void moreCommandsThanThreads() throws Exception { } @Test - public void lessCommandsThanThreads() throws Exception { + void lessCommandsThanThreads() throws Exception { List> commands = new ArrayList<>(); for (int i = 0; i < threads - 1; i++) { commands.add(new GoodCommand(value)); @@ -164,7 +151,7 @@ public void lessCommandsThanThreads() throws Exception { } @Test - public void callerThreadWasInterrupted() throws Exception { + void callerThreadWasInterrupted() throws Exception { long commandExecutionTime = 60_000; List> commands = new ArrayList<>(); for (int i = 0; i < threads + 1; i++) { @@ -201,7 +188,7 @@ public void callerThreadWasInterrupted() throws Exception { } @Test - public void commandWasInterrupted() throws Exception { + void commandWasInterrupted() { Exception commandException = new InterruptedException("some interrupt"); List> commands = Collections.singletonList(new BadCommand(commandException)); Exception e = assertThrows( @@ -215,25 +202,23 @@ public void commandWasInterrupted() throws Exception { } @Test - public void commandHadGitProblem() throws Exception { + void commandHadGitProblem() { Exception commandException = new GitException(error); List> commands = Collections.singletonList(new BadCommand(commandException)); - Exception e = assertThrows(GitException.class, () -> { - new GitCommandsExecutor(threads, listener).invokeAll(commands); - }); + Exception e = + assertThrows(GitException.class, () -> new GitCommandsExecutor(threads, listener).invokeAll(commands)); assertThat(e.getMessage(), is("hudson.plugins.git.GitException: " + error)); assertThat(e.getCause(), is(theInstance(commandException))); } @Test - public void commandHadUnknownProblem() throws Exception { + void commandHadUnknownProblem() { Exception commandException = new RuntimeException(error); List> commands = Collections.singletonList(new BadCommand(commandException)); - Exception e = assertThrows(GitException.class, () -> { - new GitCommandsExecutor(threads, listener).invokeAll(commands); - }); + Exception e = + assertThrows(GitException.class, () -> new GitCommandsExecutor(threads, listener).invokeAll(commands)); assertThat(e.getMessage(), is("java.lang.RuntimeException: " + error)); assertThat(e.getCause(), is(theInstance(commandException))); } @@ -254,7 +239,7 @@ private void wasCalled(Callable command) { } /* A callable that always returns a value, sometimes after a delay */ - private class GoodCommand implements Callable { + private static class GoodCommand implements Callable { private final String value; private final long commandExecutionTime; @@ -274,7 +259,7 @@ boolean wasCalled() { } @Override - public Object call() throws Exception { + public String call() throws Exception { called = true; if (commandExecutionTime > 0) { Thread.sleep(commandExecutionTime); @@ -284,7 +269,7 @@ public Object call() throws Exception { } /* A callable that always throws an exception */ - private class BadCommand implements Callable { + private static class BadCommand implements Callable { private final Exception exception; private boolean called = false; @@ -298,7 +283,7 @@ boolean wasCalled() { } @Override - public Object call() throws Exception { + public String call() throws Exception { called = true; throw exception; } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/credentials/CredentialsProviderImplTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/credentials/CredentialsProviderImplTest.java index d9b9bd6a17..218905194a 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/credentials/CredentialsProviderImplTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/credentials/CredentialsProviderImplTest.java @@ -1,55 +1,48 @@ package org.jenkinsci.plugins.gitclient.credentials; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import com.cloudbees.plugins.credentials.CredentialsDescriptor; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import edu.umd.cs.findbugs.annotations.NonNull; -import hudson.model.TaskListener; import hudson.util.Secret; -import hudson.util.StreamTaskListener; -import java.net.URISyntaxException; import org.eclipse.jgit.errors.UnsupportedCredentialItem; import org.eclipse.jgit.transport.CredentialItem; import org.eclipse.jgit.transport.URIish; import org.jenkinsci.plugins.gitclient.jgit.CredentialsProviderImpl; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class CredentialsProviderImplTest { +class CredentialsProviderImplTest { + + private static final String USER_NAME = "user-name"; + private static final String SECRET_VALUE = "secret-credentials-provider-impl-test"; private CredentialsProviderImpl provider; - private TaskListener listener; - private final String USER_NAME = "user-name"; - private final URIish uri; - private final String SECRET_VALUE = "secret-credentials-provider-impl-test"; + private URIish uri; - public CredentialsProviderImplTest() throws URISyntaxException { + @BeforeEach + void setUp() throws Exception { uri = new URIish("git://example.com/someone/somewhere.git"); - } - - @Before - public void setUp() { Secret secret = Secret.fromString(SECRET_VALUE); - listener = StreamTaskListener.fromStdout(); StandardUsernameCredentials cred = new StandardUsernamePasswordCredentialsImpl(USER_NAME, secret); provider = new CredentialsProviderImpl(cred); } @Test - public void testIsInteractive() { + void testIsInteractive() { assertFalse(provider.isInteractive()); } @Test - public void testSupportsNullItems() { + void testSupportsNullItems() { CredentialItem.Username nullItem = null; assertFalse(provider.supports(nullItem)); } @Test - public void testSupportsUsername() { + void testSupportsUsername() { CredentialItem.Username username = new CredentialItem.Username(); assertNull(username.getValue()); assertTrue(provider.supports(username)); @@ -58,7 +51,7 @@ public void testSupportsUsername() { } @Test - public void testSupportsPassword() { + void testSupportsPassword() { CredentialItem.Password password = new CredentialItem.Password(); assertNull(password.getValue()); assertTrue(provider.supports(password)); @@ -67,7 +60,7 @@ public void testSupportsPassword() { } @Test - public void testSupportsSpecialStringType() { + void testSupportsSpecialStringType() { CredentialItem.StringType specialStringType = new CredentialItem.StringType("Password: ", false); assertNull(specialStringType.getValue()); @@ -82,22 +75,21 @@ public void testSupportsSpecialStringType() { } @Test - public void testSpecialStringTypeThrowsException() { + void testSpecialStringTypeThrowsException() { CredentialItem.StringType specialStringType = new CredentialItem.StringType("Bad Password: ", false); assertFalse(provider.supports(specialStringType)); assertThrows(UnsupportedCredentialItem.class, () -> provider.get(uri, specialStringType)); } @Test - public void testThrowsUnsupportedOperationException() { + void testThrowsUnsupportedOperationException() { CredentialItem.InformationalMessage message = new CredentialItem.InformationalMessage("Some info"); assertFalse(provider.supports(message)); assertThrows(UnsupportedCredentialItem.class, () -> provider.get(uri, message)); } @Test - public void testSupportsDisallowed() { - listener = StreamTaskListener.fromStdout(); + void testSupportsDisallowed() { StandardUsernameCredentials badCred = new MyUsernameCredentialsImpl(USER_NAME); CredentialsProviderImpl badProvider = new CredentialsProviderImpl(badCred); CredentialItem.Username username = new CredentialItem.Username(); @@ -107,13 +99,7 @@ public void testSupportsDisallowed() { assertNull(username.getValue()); } - private static class MyUsernameCredentialsImpl implements StandardUsernameCredentials { - - private final String username; - - MyUsernameCredentialsImpl(String username) { - this.username = username; - } + private record MyUsernameCredentialsImpl(String username) implements StandardUsernameCredentials { @Override @NonNull diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/credentials/SmartCredentialsProviderTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/credentials/SmartCredentialsProviderTest.java index b1b7b45c31..8c2c992674 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/credentials/SmartCredentialsProviderTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/credentials/SmartCredentialsProviderTest.java @@ -1,27 +1,32 @@ package org.jenkinsci.plugins.gitclient.credentials; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import hudson.model.TaskListener; import hudson.util.Secret; import hudson.util.StreamTaskListener; -import java.net.URISyntaxException; import org.eclipse.jgit.errors.UnsupportedCredentialItem; import org.eclipse.jgit.transport.CredentialItem; import org.eclipse.jgit.transport.URIish; import org.jenkinsci.plugins.gitclient.jgit.SmartCredentialsProvider; import org.jenkinsci.plugins.gitclient.jgit.StandardUsernameCredentialsCredentialItem; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class SmartCredentialsProviderTest { +class SmartCredentialsProviderTest { + + private static final String MASKED_USER_NAME_PROMPT = "masked user name prompt"; + private static final String UNMASKED_USER_NAME_PROMPT = "unmasked user name prompt"; + private static final String MASKED_STRING_TYPE_PROMPT = "masked string type prompt"; + private static final String UNMASKED_STRING_TYPE_PROMPT = "unmasked string type prompt"; + private static final String SPECIAL_STRING_TYPE_PROMPT = "Password: "; private TaskListener listener; private SmartCredentialsProvider provider; - private final URIish gitURI; - private final URIish gitURISlash; - private final URIish gitURIShort; + private URIish gitURI; + private URIish gitURISlash; + private URIish gitURIShort; private CredentialItem.Username username; private CredentialItem.Password password; private CredentialItem.StringType maskedStringType; @@ -29,21 +34,14 @@ public class SmartCredentialsProviderTest { private CredentialItem.StringType specialStringType; private StandardUsernameCredentialsCredentialItem maskedUsername; private StandardUsernameCredentialsCredentialItem unmaskedUsername; - private final String MASKED_USER_NAME_PROMPT = "masked user name prompt"; - private final String UNMASKED_USER_NAME_PROMPT = "unmasked user name prompt"; - private final String MASKED_STRING_TYPE_PROMPT = "masked string type prompt"; - private final String UNMASKED_STRING_TYPE_PROMPT = "unmasked string type prompt"; - private final String SPECIAL_STRING_TYPE_PROMPT = "Password: "; - public SmartCredentialsProviderTest() throws URISyntaxException { + @BeforeEach + void setUp() throws Exception { String baseUri = "git://example.com/someone/somewhere"; gitURI = new URIish(baseUri + ".git"); gitURISlash = new URIish(baseUri + ".git/"); gitURIShort = new URIish(baseUri); - } - @Before - public void setUp() { listener = StreamTaskListener.fromStdout(); provider = new SmartCredentialsProvider(listener); username = new CredentialItem.Username(); @@ -65,7 +63,7 @@ public void setUp() { } @Test - public void testClearCredentials() { + void testClearCredentials() { provider.clearCredentials(); assertFalse(provider.supports(username, password)); @@ -92,7 +90,7 @@ public void testClearCredentials() { } @Test - public void testAddCredentials() { + void testAddCredentials() { String expectedUsername = "expected-add-credentials-username"; String secretValue = "secret-value"; Secret secret = Secret.fromString(secretValue); @@ -158,7 +156,7 @@ public void testAddCredentials() { } @Test - public void testAddDefaultCredentials() { + void testAddDefaultCredentials() { String expectedUsername = "expected-add-credentials-username"; String secretValue = "secret-value"; Secret secret = Secret.fromString(secretValue); @@ -217,12 +215,12 @@ public void testAddDefaultCredentials() { } @Test - public void testIsInteractive() { + void testIsInteractive() { assertTrue(provider.isInteractive()); } @Test - public void testClearCredentialsItem() { + void testClearCredentialsItem() { String expectedUsername = "expected-add-credentials-username"; String secretValue = "secret-value"; Secret secret = Secret.fromString(secretValue); @@ -235,7 +233,7 @@ public void testClearCredentialsItem() { } @Test - public void testGetThrowsException() { + void testGetThrowsException() { String expectedUsername = "expected-add-credentials-username"; Secret secret = Secret.fromString("password-secret"); StandardUsernamePasswordCredentials credentials = @@ -247,7 +245,7 @@ public void testGetThrowsException() { } @Test - public void testSimilarUrlsAcceptedForCredentials() { + void testSimilarUrlsAcceptedForCredentials() { String expectedUsername = "expected-add-credentials-username"; String secretValue = "secret-value"; Secret secret = Secret.fromString(secretValue); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/jgit/AuthzTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/jgit/AuthzTest.java index 9a65342b7a..1e01e7a6f8 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/jgit/AuthzTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/jgit/AuthzTest.java @@ -4,6 +4,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; import static org.hamcrest.collection.IsMapWithSize.anEmptyMap; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey; import com.cloudbees.plugins.credentials.CredentialsScope; @@ -16,23 +17,23 @@ import com.github.sparsick.testcontainers.gitserver.plain.SshIdentity; import hudson.EnvVars; import hudson.model.TaskListener; +import java.io.File; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.Map; -import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.Strings; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.transport.URIish; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.verifier.NoHostKeyVerifier; import org.jetbrains.annotations.NotNull; -import org.junit.Assume; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.GenericContainer; @@ -45,15 +46,14 @@ * * */ -public class AuthzTest { +class AuthzTest { - @Rule - public TemporaryFolder testFolder = - TemporaryFolder.builder().assureDeletion().build(); + @TempDir + private File testFolder; @Test - public void sshKeyAuth() throws Exception { - Assume.assumeTrue(DockerClientFactory.instance().isDockerAvailable()); + void sshKeyAuth() throws Exception { + assumeTrue(DockerClientFactory.instance().isDockerAvailable()); try (GitServerContainer containerUnderTest = new GitServerContainer( GitServerVersions.V2_45.getDockerImageName()) .withGitRepo("someRepo") @@ -66,8 +66,8 @@ public void sshKeyAuth() throws Exception { } @Test - public void sshWithPassword() throws Exception { - Assume.assumeTrue(DockerClientFactory.instance().isDockerAvailable()); + void sshWithPassword() throws Exception { + assumeTrue(DockerClientFactory.instance().isDockerAvailable()); try (GitServerContainer containerUnderTest = new GitServerContainer( GitServerVersions.V2_45.getDockerImageName()) .withGitRepo("someRepo") @@ -85,8 +85,8 @@ public void sshWithPassword() throws Exception { } @Test - public void httpWithPassword() throws Exception { - Assume.assumeTrue(DockerClientFactory.instance().isDockerAvailable()); + void httpWithPassword() throws Exception { + assumeTrue(DockerClientFactory.instance().isDockerAvailable()); BasicAuthenticationCredentials credentials = new BasicAuthenticationCredentials("testuser", "testPassword"); try (GitHttpServerContainer containerUnderTest = new GitHttpServerContainer(GitServerVersions.V2_45.getDockerImageName(), credentials)) { @@ -109,13 +109,13 @@ protected void testRepo(StandardCredentials standardCredentials, GenericContaine // ssh://git@localhost:33011/srv/git/someRepo.git // 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 - repoUrl = StringUtils.remove(repoUrl, "git@"); + repoUrl = Strings.CS.remove(repoUrl, "git@"); } if (containerUnderTest instanceof GitHttpServerContainer container) { repoUrl = container.getGitRepoURIAsHttp().toString(); } - Path testRepo = testFolder.newFolder().toPath(); + Path testRepo = newFolder(testFolder, "junit-" + System.nanoTime()).toPath(); GitClient client = buildClient(testRepo, standardCredentials, repoUrl); Map rev = client.getHeadRev(repoUrl); @@ -139,7 +139,7 @@ protected void testRepo(StandardCredentials standardCredentials, GenericContaine client.commit("Very useful change"); client.push().to(new URIish(repoUrl)).execute(); - testRepo = testFolder.newFolder().toPath(); + testRepo = newFolder(testFolder, "junit-" + System.nanoTime()).toPath(); client = buildClient(testRepo, standardCredentials, repoUrl); rev = client.getHeadRev(repoUrl); // check there is now one ref remotely after the push @@ -173,4 +173,13 @@ public List getPrivateKeys() { new String(sshIdentity.getPassphrase()), "description"); } + + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/jgit/PreemptiveAuthHttpClientConnectionTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/jgit/PreemptiveAuthHttpClientConnectionTest.java index edfc1a511c..3f939c42a4 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/jgit/PreemptiveAuthHttpClientConnectionTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/jgit/PreemptiveAuthHttpClientConnectionTest.java @@ -1,18 +1,18 @@ package org.jenkinsci.plugins.gitclient.jgit; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import org.apache.http.auth.NTCredentials; import org.eclipse.jgit.transport.URIish; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * A class to test {@link PreemptiveAuthHttpClientConnectionTest}. */ -public class PreemptiveAuthHttpClientConnectionTest { +class PreemptiveAuthHttpClientConnectionTest { @Test - public void goUp_noPath() throws Exception { + void goUp_noPath() throws Exception { final URIish input = new URIish("https://example.com"); final URIish actual = PreemptiveAuthHttpClientConnection.goUp(input); @@ -21,7 +21,7 @@ public void goUp_noPath() throws Exception { } @Test - public void goUp_slash() throws Exception { + void goUp_slash() throws Exception { final URIish input = new URIish("https://example.com/"); final URIish actual = PreemptiveAuthHttpClientConnection.goUp(input); @@ -30,7 +30,7 @@ public void goUp_slash() throws Exception { } @Test - public void goUp_slashSlash() throws Exception { + void goUp_slashSlash() throws Exception { final URIish input = new URIish("https://example.com//"); final URIish actual = PreemptiveAuthHttpClientConnection.goUp(input); @@ -40,7 +40,7 @@ public void goUp_slashSlash() throws Exception { } @Test - public void goUp_one() throws Exception { + void goUp_one() throws Exception { final URIish input = new URIish("https://example.com/one"); final URIish actual = PreemptiveAuthHttpClientConnection.goUp(input); @@ -50,7 +50,7 @@ public void goUp_one() throws Exception { } @Test - public void goUp_oneSlash() throws Exception { + void goUp_oneSlash() throws Exception { final URIish input = new URIish("https://example.com/one/"); final URIish actual = PreemptiveAuthHttpClientConnection.goUp(input); @@ -60,7 +60,7 @@ public void goUp_oneSlash() throws Exception { } @Test - public void goUp_oneSlashTwo() throws Exception { + void goUp_oneSlashTwo() throws Exception { final URIish input = new URIish("https://example.com/one/two"); final URIish actual = PreemptiveAuthHttpClientConnection.goUp(input); @@ -70,7 +70,7 @@ public void goUp_oneSlashTwo() throws Exception { } @Test - public void goUp_oneSlashSlashTwoSlash() throws Exception { + void goUp_oneSlashSlashTwoSlash() throws Exception { final URIish input = new URIish("https://example.com/one//two/"); final URIish actual = PreemptiveAuthHttpClientConnection.goUp(input); @@ -80,7 +80,7 @@ public void goUp_oneSlashSlashTwoSlash() throws Exception { } @Test - public void goUp_oneSlashTwoSlash() throws Exception { + void goUp_oneSlashTwoSlash() throws Exception { final URIish input = new URIish("https://example.com/one/two/"); final URIish actual = PreemptiveAuthHttpClientConnection.goUp(input); @@ -105,25 +105,25 @@ private static void createNTCredentials( } @Test - public void createNTCredentials_plainUser() { + void createNTCredentials_plainUser() { createNTCredentials("cnorris", "roundhouse", null, "cnorris", "roundhouse"); createNTCredentials("cnorris", "round\\:/house", null, "cnorris", "round\\:/house"); } @Test - public void createNTCredentials_domainBackslashUser() { + void createNTCredentials_domainBackslashUser() { createNTCredentials("WALKER\\cnorris", "roundhouse", "WALKER", "cnorris", "roundhouse"); createNTCredentials("WALKER\\cnorris", "round\\:/house", "WALKER", "cnorris", "round\\:/house"); } @Test - public void createNTCredentials_domainSlashUser() { + void createNTCredentials_domainSlashUser() { createNTCredentials("WALKER/cnorris", "roundhouse", "WALKER", "cnorris", "roundhouse"); createNTCredentials("WALKER/cnorris", "round\\:/house", "WALKER", "cnorris", "round\\:/house"); } @Test - public void createNTCredentials_userAtDomain() { + void createNTCredentials_userAtDomain() { createNTCredentials("cnorris@walker.example.com", "roundhouse", "WALKER.EXAMPLE.COM", "cnorris", "roundhouse"); createNTCredentials( "cnorris@walker.example.com", "round\\:/house", "WALKER.EXAMPLE.COM", "cnorris", "round\\:/house"); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/verifier/AcceptFirstConnectionVerifierTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/verifier/AcceptFirstConnectionVerifierTest.java index 1a99ef1e0f..626f5f3f01 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/verifier/AcceptFirstConnectionVerifierTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/verifier/AcceptFirstConnectionVerifierTest.java @@ -6,25 +6,24 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.io.FileMatchers.anExistingFile; import static org.jenkinsci.plugins.gitclient.verifier.KnownHostsTestUtil.runKnownHostsTests; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import hudson.model.StreamBuildListener; import hudson.model.TaskListener; import java.io.File; -import java.io.IOException; import java.nio.file.Files; import java.time.Duration; import java.util.Collections; import java.util.List; import org.awaitility.Awaitility; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -public class AcceptFirstConnectionVerifierTest { +class AcceptFirstConnectionVerifierTest { private static final String FILE_CONTENT = """ @@ -33,38 +32,42 @@ public class AcceptFirstConnectionVerifierTest { AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl\ """; - private static final String KEY_ecdsa_sha2_nistp256 = + private static final String KEY_ECDSA_SHA_2_NISTP_256 = """ |1|owDOW+8aankl2aFSPKPIXsIf31E=|lGZ9BEWUfa9HoQteyYE5wIqHJdo=,|1|eGv/ezgtZ9YMw7OHcykKKOvAINk=|3lpkF7XiveRl/D7XvTOMc3ra2kU=\ ecdsa-sha2-nistp256\ AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg=\ """; - private static final String KEY_ssh_rsa = + private static final String KEY_SSH_RSA = """ |1|HnmPCP38pBhCY0NUtBXSraOg9pM=|L6YZ9asEeb2xplTDEThGOxRq7ZY=\ ssh-rsa\ AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==\ """; - @Rule - public TemporaryFolder testFolder = - TemporaryFolder.builder().assureDeletion().build(); + @TempDir + private File testFolder; - private final KnownHostsTestUtil knownHostsTestUtil = new KnownHostsTestUtil(testFolder); + private KnownHostsTestUtil knownHostsTestUtil; + + @BeforeEach + void setUp() { + knownHostsTestUtil = new KnownHostsTestUtil(testFolder); + } @Test - public void testVerifyHostKeyOption() throws IOException { - Assume.assumeTrue(runKnownHostsTests()); + void testVerifyHostKeyOption() throws Exception { + assumeTrue(runKnownHostsTests()); assertThat( new AcceptFirstConnectionVerifier().forCliGit(TaskListener.NULL).getVerifyHostKeyOption(null), is("-o StrictHostKeyChecking=accept-new -o HashKnownHosts=yes")); } @Test - public void testVerifyServerHostKeyWhenFirstConnection() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); - File file = new File(testFolder.getRoot() + "path/to/file"); + void testVerifyServerHostKeyWhenFirstConnection() throws Exception { + assumeTrue(runKnownHostsTests()); + File file = new File(testFolder + "path/to/file"); AcceptFirstConnectionVerifier acceptFirstConnectionVerifier = spy(new AcceptFirstConnectionVerifier()); when(acceptFirstConnectionVerifier.getKnownHostsFile()).thenReturn(file); @@ -84,12 +87,12 @@ public void testVerifyServerHostKeyWhenFirstConnection() throws Exception { assertThat(file, is(anExistingFile())); assertThat( Files.readAllLines(file.toPath()), - hasItem(containsString(KEY_ecdsa_sha2_nistp256.substring(KEY_ecdsa_sha2_nistp256.indexOf(" "))))); + hasItem(containsString(KEY_ECDSA_SHA_2_NISTP_256.substring(KEY_ECDSA_SHA_2_NISTP_256.indexOf(" "))))); } @Test - public void testVerifyServerHostKeyWhenSecondConnectionWithEqualKeys() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); + void testVerifyServerHostKeyWhenSecondConnectionWithEqualKeys() throws Exception { + assumeTrue(runKnownHostsTests()); String hostKeyEntry = "|1|FJGXVAi7jMQIsl1J6uE6KnCiteM=|xlH92KQ91GuBgRxvRbU/sBo60Bo= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg="; @@ -118,8 +121,8 @@ public void testVerifyServerHostKeyWhenSecondConnectionWithEqualKeys() throws Ex } @Test - public void testVerifyServerHostKeyWhenHostnameWithoutPort() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); + void testVerifyServerHostKeyWhenHostnameWithoutPort() throws Exception { + assumeTrue(runKnownHostsTests()); String hostKeyEntry = "github.com ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg="; File mockedKnownHosts = knownHostsTestUtil.createFakeKnownHosts(hostKeyEntry); @@ -143,8 +146,8 @@ public void testVerifyServerHostKeyWhenHostnameWithoutPort() throws Exception { } @Test - public void testVerifyServerHostKeyWhenSecondConnectionWhenNotDefaultAlgorithm() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); + void testVerifyServerHostKeyWhenSecondConnectionWhenNotDefaultAlgorithm() throws Exception { + assumeTrue(runKnownHostsTests()); String fileContent = """ github.com,140.82.121.4\ @@ -174,9 +177,9 @@ public void testVerifyServerHostKeyWhenSecondConnectionWhenNotDefaultAlgorithm() } @Test - @Ignore("FIXME not sure what is the test here") - public void testVerifyServerHostKeyWhenSecondConnectionWithNonEqualKeys() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); + @Disabled("FIXME not sure what is the test here") + void testVerifyServerHostKeyWhenSecondConnectionWithNonEqualKeys() throws Exception { + assumeTrue(runKnownHostsTests()); String fileContent = """ |1|f7esvmtaiBk+EMHjPzWbRYRpBPY=|T7Qe4QAksYPZPwYEx5QxQykSjfc=\ @@ -207,8 +210,8 @@ public void testVerifyServerHostKeyWhenSecondConnectionWithNonEqualKeys() throws } @Test - public void testVerifyServerHostKeyWhenConnectionWithAnotherHost() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); + void testVerifyServerHostKeyWhenConnectionWithAnotherHost() throws Exception { + assumeTrue(runKnownHostsTests()); String bitbucketFileContent = """ |1|HnmPCP38pBhCY0NUtBXSraOg9pM=|L6YZ9asEeb2xplTDEThGOxRq7ZY=\ @@ -235,12 +238,12 @@ public void testVerifyServerHostKeyWhenConnectionWithAnotherHost() throws Except .close(); List actual = Files.readAllLines(fakeKnownHosts.toPath()); assertThat(actual, hasItem(bitbucketFileContent)); - assertThat(actual, hasItem(containsString(KEY_ssh_rsa.substring(KEY_ssh_rsa.indexOf(" "))))); + assertThat(actual, hasItem(containsString(KEY_SSH_RSA.substring(KEY_SSH_RSA.indexOf(" "))))); } @Test - public void testVerifyServerHostKeyWhenHostnamePortProvided() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); + void testVerifyServerHostKeyWhenHostnamePortProvided() throws Exception { + assumeTrue(runKnownHostsTests()); String fileContent = """ |1|6uMj3M7sLgZpn54vQbGqgPNTCVM=|OkV9Lu9REJZR5QCVrITAIY34I1M= \ diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/verifier/KnownHostsFileVerifierTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/verifier/KnownHostsFileVerifierTest.java index 0a2751697c..b53a3db48c 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/verifier/KnownHostsFileVerifierTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/verifier/KnownHostsFileVerifierTest.java @@ -4,46 +4,44 @@ import static org.hamcrest.Matchers.is; import static org.jenkinsci.plugins.gitclient.verifier.KnownHostsTestUtil.nonGitHubHost; import static org.jenkinsci.plugins.gitclient.verifier.KnownHostsTestUtil.runKnownHostsTests; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import hudson.model.StreamBuildListener; import hudson.model.TaskListener; import java.io.File; -import java.io.IOException; import java.time.Duration; import org.awaitility.Awaitility; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class KnownHostsFileVerifierTest { +@ExtendWith(MockitoExtension.class) +class KnownHostsFileVerifierTest { private static final String FILE_CONTENT = "github.com ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg="; // Create a temporary folder and assert folder deletion at end of tests - @Rule - public TemporaryFolder testFolder = - TemporaryFolder.builder().assureDeletion().build(); + @TempDir + private File testFolder; private File fakeKnownHosts; - private final KnownHostsTestUtil knownHostsTestUtil = new KnownHostsTestUtil(testFolder); + private KnownHostsTestUtil knownHostsTestUtil; - @Before - public void assignVerifiers() throws IOException { + @BeforeEach + void assignVerifiers() throws Exception { + knownHostsTestUtil = new KnownHostsTestUtil(testFolder); fakeKnownHosts = knownHostsTestUtil.createFakeKnownHosts(FILE_CONTENT); } @Test - public void connectWhenHostKeyNotInKnownHostsFileForOtherHostNameThenShouldFail() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); + void connectWhenHostKeyNotInKnownHostsFileForOtherHostNameThenShouldFail() throws Exception { + assumeTrue(runKnownHostsTests()); fakeKnownHosts = knownHostsTestUtil.createFakeKnownHosts("fake2.ssh", "known_hosts_fake2", FILE_CONTENT); KnownHostsFileVerifier knownHostsFileVerifier = spy(new KnownHostsFileVerifier()); when(knownHostsFileVerifier.getKnownHostsFile()).thenReturn(fakeKnownHosts); @@ -64,8 +62,8 @@ public void connectWhenHostKeyNotInKnownHostsFileForOtherHostNameThenShouldFail( } @Test - public void connectWhenHostKeyProvidedThenShouldNotFail() throws IOException { - Assume.assumeTrue(runKnownHostsTests()); + void connectWhenHostKeyProvidedThenShouldNotFail() throws Exception { + assumeTrue(runKnownHostsTests()); KnownHostsFileVerifier knownHostsFileVerifier = spy(new KnownHostsFileVerifier()); when(knownHostsFileVerifier.getKnownHostsFile()).thenReturn(fakeKnownHosts); @@ -86,8 +84,8 @@ public void connectWhenHostKeyProvidedThenShouldNotFail() throws IOException { } @Test - public void connectWhenHostKeyInKnownHostsFileWithNotDefaultAlgorithmThenShouldNotFail() throws IOException { - Assume.assumeTrue(runKnownHostsTests()); + void connectWhenHostKeyInKnownHostsFileWithNotDefaultAlgorithmThenShouldNotFail() throws Exception { + assumeTrue(runKnownHostsTests()); fakeKnownHosts = knownHostsTestUtil.createFakeKnownHosts( "fake2.ssh", "known_hosts_fake2", @@ -111,7 +109,7 @@ public void connectWhenHostKeyInKnownHostsFileWithNotDefaultAlgorithmThenShouldN } @Test - public void testVerifyHostKeyOptionWithDefaultFile() throws Exception { + void testVerifyHostKeyOptionWithDefaultFile() throws Exception { KnownHostsFileVerifier verifier = new KnownHostsFileVerifier(); assertThat( verifier.forCliGit(TaskListener.NULL).getVerifyHostKeyOption(null), is("-o StrictHostKeyChecking=yes")); diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/verifier/KnownHostsTestUtil.java b/src/test/java/org/jenkinsci/plugins/gitclient/verifier/KnownHostsTestUtil.java index 9127fcd362..065d39cffb 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/verifier/KnownHostsTestUtil.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/verifier/KnownHostsTestUtil.java @@ -9,13 +9,11 @@ import java.io.IOException; import java.lang.reflect.Method; import java.net.SocketAddress; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.PublicKey; import java.time.Duration; import java.util.ArrayList; -import java.util.List; import java.util.Objects; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Predicate; @@ -33,53 +31,45 @@ import org.eclipse.jgit.internal.transport.sshd.JGitServerKeyVerifier; import org.eclipse.jgit.internal.transport.sshd.JGitSshClient; import org.eclipse.jgit.transport.sshd.IdentityPasswordProvider; -import org.junit.rules.TemporaryFolder; public class KnownHostsTestUtil { - private final TemporaryFolder testFolder; + private final File testFolder; - public KnownHostsTestUtil(TemporaryFolder testFolder) { + public KnownHostsTestUtil(File testFolder) { this.testFolder = testFolder; } - public File createFakeSSHDir(String dir) throws IOException { + public File createFakeSSHDir(String dir) throws Exception { // Create a fake directory for use with a known_hosts file - return testFolder.newFolder(dir); + return newFolder(testFolder, dir + "-" + System.nanoTime()); } - public File createFakeKnownHosts(String dir, String name) throws IOException { + public File createFakeKnownHosts(String dir, String name) throws Exception { // Create fake known hosts file File fakeSSHDir = createFakeSSHDir(dir); return new File(fakeSSHDir, name); } - public File createFakeKnownHosts(String dir, String name, String fileContent) throws IOException { + public File createFakeKnownHosts(String dir, String name, String fileContent) throws Exception { File fakeKnownHosts = createFakeKnownHosts(dir, name); - byte[] fakeKnownHostsBytes = fileContent.getBytes(StandardCharsets.UTF_8); - Files.write(fakeKnownHosts.toPath(), fakeKnownHostsBytes); + Files.writeString(fakeKnownHosts.toPath(), fileContent); return fakeKnownHosts; } - public File createFakeKnownHosts(String fileContent) throws IOException { + public File createFakeKnownHosts(String fileContent) throws Exception { File fakeKnownHosts = createFakeKnownHosts("fake.ssh", "known_hosts_fake"); - byte[] fakeKnownHostsBytes = fileContent.getBytes(StandardCharsets.UTF_8); - Files.write(fakeKnownHosts.toPath(), fakeKnownHostsBytes); + Files.writeString(fakeKnownHosts.toPath(), fileContent); return fakeKnownHosts; } - public List getKnownHostsContent(File file) throws IOException { - return Files.readAllLines(file.toPath()); - } - protected static JGitClientSession connectToHost( String host, int port, File knownHostsFile, AbstractJGitHostKeyVerifier verifier, String algorithm, - Predicate asserts) - throws IOException { + Predicate asserts) { try (SshClient client = ClientBuilder.builder() .factory(JGitSshClient::new) @@ -139,7 +129,7 @@ protected static boolean checkKeys(JGitClientSession s) { } // Several different git providers with ssh access, use one randomly - private static String[] nonGitHubHosts = { + private static final String[] nonGitHubHosts = { // bitbucket.org blocks requests from ci.jenkins.io agents // "bitbucket.org", "git.assembla.com", "gitea.com", "gitlab.com", "vs-ssh.visualstudio.com", "ssh.dev.azure.com" @@ -160,8 +150,12 @@ public static boolean runKnownHostsTests() { return !JENKINS_URL.contains("ci.jenkins.io"); } - /* Always return false, retained for test compatibility */ - public static boolean isKubernetesCI() { - return false; + private static File newFolder(File root, String... subDirs) throws Exception { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + result); + } + return result; } } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/verifier/ManuallyProvidedKeyVerifierTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/verifier/ManuallyProvidedKeyVerifierTest.java index 8c35104f33..dbd79c3052 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/verifier/ManuallyProvidedKeyVerifierTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/verifier/ManuallyProvidedKeyVerifierTest.java @@ -4,50 +4,46 @@ import static org.hamcrest.Matchers.is; import static org.jenkinsci.plugins.gitclient.verifier.KnownHostsTestUtil.nonGitHubHost; import static org.jenkinsci.plugins.gitclient.verifier.KnownHostsTestUtil.runKnownHostsTests; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import hudson.model.StreamBuildListener; import hudson.model.TaskListener; import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.Collections; import org.awaitility.Awaitility; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class ManuallyProvidedKeyVerifierTest { +@ExtendWith(MockitoExtension.class) +class ManuallyProvidedKeyVerifierTest { // Create a temporary folder and assert folder deletion at end of tests - @Rule - public TemporaryFolder testFolder = - TemporaryFolder.builder().assureDeletion().build(); + @TempDir + private File testFolder; private String hostKey; - @Before - public void assignVerifier() { // For github.com + @BeforeEach + void assignVerifier() { // For github.com hostKey = "|1|7qEjynZk0IodegnbgoPEhWtdgA8=|bGs7a1ktbGWwPuZqqTbAazUAULM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg="; } @Test - public void connectWhenHostKeyProvidedForOtherHostNameThenShouldFail() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); + void connectWhenHostKeyProvidedForOtherHostNameThenShouldFail() throws Exception { + assumeTrue(runKnownHostsTests()); HostKeyVerifierFactory verifier = new ManuallyProvidedKeyVerifier(hostKey); KnownHostsTestUtil.connectToHost( nonGitHubHost(), 22, - new File(testFolder.getRoot() + "/path/to/file/random"), + new File(testFolder + "/path/to/file/random"), verifier.forJGit(StreamBuildListener.fromStdout()), "ecdsa-sha2-nistp256", s -> { @@ -60,14 +56,14 @@ public void connectWhenHostKeyProvidedForOtherHostNameThenShouldFail() throws Ex } @Test - public void connectWhenHostKeyProvidedThenShouldNotFail() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); + void connectWhenHostKeyProvidedThenShouldNotFail() throws Exception { + assumeTrue(runKnownHostsTests()); ManuallyProvidedKeyVerifier verifier = new ManuallyProvidedKeyVerifier(hostKey); ManuallyProvidedKeyVerifier.ManuallyProvidedKeyJGitHostKeyVerifier jGitHostKeyVerifier = (ManuallyProvidedKeyVerifier.ManuallyProvidedKeyJGitHostKeyVerifier) verifier.forJGit(StreamBuildListener.fromStdout()); Path tempKnownHosts = Files.createTempFile("known_hosts", ""); - Files.write(tempKnownHosts, (hostKey + System.lineSeparator()).getBytes(StandardCharsets.UTF_8)); + Files.writeString(tempKnownHosts, hostKey + System.lineSeparator()); KnownHostsTestUtil.connectToHost( "github.com", 22, tempKnownHosts.toFile(), jGitHostKeyVerifier, "ecdsa-sha2-nistp256", s -> { assertThat(s.isOpen(), is(true)); @@ -80,8 +76,8 @@ public void connectWhenHostKeyProvidedThenShouldNotFail() throws Exception { } @Test - public void connectWhenWrongHostKeyProvidedThenShouldFail() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); + void connectWhenWrongHostKeyProvidedThenShouldFail() throws Exception { + assumeTrue(runKnownHostsTests()); String key = "github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9OOOO"; HostKeyVerifierFactory verifier = new ManuallyProvidedKeyVerifier(key); @@ -89,7 +85,7 @@ public void connectWhenWrongHostKeyProvidedThenShouldFail() throws Exception { (ManuallyProvidedKeyVerifier.ManuallyProvidedKeyJGitHostKeyVerifier) verifier.forJGit(StreamBuildListener.fromStdout()); Path tempKnownHosts = Files.createTempFile("known_hosts", ""); - Files.write(tempKnownHosts, (key + System.lineSeparator()).getBytes(StandardCharsets.UTF_8)); + Files.writeString(tempKnownHosts, key + System.lineSeparator()); KnownHostsTestUtil.connectToHost( "github.com", 22, tempKnownHosts.toFile(), jGitHostKeyVerifier, "ssh-ed25519", s -> { assertThat(s.isOpen(), is(true)); @@ -101,8 +97,8 @@ public void connectWhenWrongHostKeyProvidedThenShouldFail() throws Exception { } @Test - public void connectWhenHostKeyProvidedWithPortThenShouldNotFail() throws Exception { - Assume.assumeTrue(runKnownHostsTests()); + void connectWhenHostKeyProvidedWithPortThenShouldNotFail() throws Exception { + assumeTrue(runKnownHostsTests()); String key = "github.com:22 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg="; HostKeyVerifierFactory verifier = new ManuallyProvidedKeyVerifier(key); @@ -111,7 +107,7 @@ public void connectWhenHostKeyProvidedWithPortThenShouldNotFail() throws Excepti (ManuallyProvidedKeyVerifier.ManuallyProvidedKeyJGitHostKeyVerifier) verifier.forJGit(StreamBuildListener.fromStdout()); Path tempKnownHosts = Files.createTempFile("known_hosts", ""); - Files.write(tempKnownHosts, (key + System.lineSeparator()).getBytes(StandardCharsets.UTF_8)); + Files.writeString(tempKnownHosts, key + System.lineSeparator()); KnownHostsTestUtil.connectToHost( "github.com", 22, tempKnownHosts.toFile(), jGitHostKeyVerifier, "ecdsa-sha2-nistp256", s -> { assertThat(s.isOpen(), is(true)); @@ -123,11 +119,11 @@ public void connectWhenHostKeyProvidedWithPortThenShouldNotFail() throws Excepti } @Test - public void testGetVerifyHostKeyOption() throws IOException { + void testGetVerifyHostKeyOption() throws Exception { if (isWindows()) { return; // Skip test without generating a Maven surefire warning } - Path tempFile = testFolder.newFile().toPath(); + Path tempFile = File.createTempFile("junit", null, testFolder).toPath(); String actual = new ManuallyProvidedKeyVerifier(hostKey) .forCliGit(TaskListener.NULL) .getVerifyHostKeyOption(tempFile); @@ -139,15 +135,15 @@ public void testGetVerifyHostKeyOption() throws IOException { } @Test - public void testGetVerifyHostKeyOptionOnWindows() throws IOException { + void testGetVerifyHostKeyOptionOnWindows() throws Exception { if (!isWindows()) { return; // Skip test without generating a Maven surefire warning } - Path tempFile = testFolder.newFile().toPath(); + Path tempFile = File.createTempFile("junit", null, testFolder).toPath(); String actual = new ManuallyProvidedKeyVerifier(hostKey) .forCliGit(TaskListener.NULL) .getVerifyHostKeyOption(tempFile); - assertThat(actual, is("-o StrictHostKeyChecking=yes -o UserKnownHostsFile=" + tempFile.toAbsolutePath() + "")); + assertThat(actual, is("-o StrictHostKeyChecking=yes -o UserKnownHostsFile=" + tempFile.toAbsolutePath())); assertThat(Files.readAllLines(tempFile), is(Collections.singletonList(hostKey))); } diff --git a/src/test/java/org/jenkinsci/plugins/gitclient/verifier/NoHostKeyVerifierTest.java b/src/test/java/org/jenkinsci/plugins/gitclient/verifier/NoHostKeyVerifierTest.java index 4eed151696..5d3811b898 100644 --- a/src/test/java/org/jenkinsci/plugins/gitclient/verifier/NoHostKeyVerifierTest.java +++ b/src/test/java/org/jenkinsci/plugins/gitclient/verifier/NoHostKeyVerifierTest.java @@ -3,29 +3,28 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.jenkinsci.plugins.gitclient.verifier.KnownHostsTestUtil.runKnownHostsTests; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import hudson.model.StreamBuildListener; import hudson.model.TaskListener; -import java.io.IOException; import java.nio.file.Path; import java.time.Duration; import org.awaitility.Awaitility; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class NoHostKeyVerifierTest { +class NoHostKeyVerifierTest { private NoHostKeyVerifier verifier; - @Before - public void assignVerifier() { + @BeforeEach + void assignVerifier() { verifier = new NoHostKeyVerifier(); } @Test - public void verifyServerHostKey() throws IOException { - Assume.assumeTrue(runKnownHostsTests()); + void verifyServerHostKey() throws Exception { + assumeTrue(runKnownHostsTests()); NoHostKeyVerifier acceptFirstConnectionVerifier = new NoHostKeyVerifier(); KnownHostsTestUtil.connectToHost( @@ -45,7 +44,7 @@ public void verifyServerHostKey() throws IOException { } @Test - public void testVerifyHostKeyOption() throws IOException { + void testVerifyHostKeyOption() throws Exception { assertThat( verifier.forCliGit(TaskListener.NULL).getVerifyHostKeyOption(Path.of("")), is("-o StrictHostKeyChecking=no"));