From de7b198230401b48fda93403d46c72b2a04af3ab Mon Sep 17 00:00:00 2001 From: strangelookingnerd <49242855+strangelookingnerd@users.noreply.github.com> Date: Tue, 11 Mar 2025 11:33:05 +0100 Subject: [PATCH] Migrate tests to JUnit5 * Migrate annotations and imports * Migrate assertions * Remove public visibility for test classes and methods * Minor code cleanup --- pom.xml | 2 +- .../plugins/docker/commons/CasCTest.java | 105 ------ .../plugins/docker/commons/ConfigTest.java | 53 +-- .../plugins/docker/commons/JCasCTest.java | 119 +++++++ .../DockerRegistryEndpointTest.java | 100 +++--- .../DockerServerCredentialsBindingTest.java | 136 ++++---- .../DockerServerCredentialsHandlerTest.java | 77 ++--- .../DockerServerCredentialsTest.java | 129 ++++--- .../DockerServerDomainSpecificationTest.java | 41 +-- .../credentials/DockerServerEndpointTest.java | 44 ++- .../credentials/ImageNameValidatorTest.java | 35 +- .../fingerprint/DockerFingerprintsTest.java | 23 +- .../DockerRunFingerprintFacetTest.java | 49 ++- ...ostOnlyRegistryKeyMaterialFactoryTest.java | 284 ++++++++-------- .../impl/RegistryKeyMaterialFactoryTest.java | 314 +++++++++--------- .../tools/DockerToolInstallerTest.java | 124 ++++--- .../docker/commons/tools/DockerToolTest.java | 29 +- .../commons/util/SampleDockerBuilder.java | 40 ++- 18 files changed, 912 insertions(+), 792 deletions(-) delete mode 100644 src/test/java/org/jenkinsci/plugins/docker/commons/CasCTest.java create mode 100644 src/test/java/org/jenkinsci/plugins/docker/commons/JCasCTest.java diff --git a/pom.xml b/pom.xml index 43ff8eeb..f475f831 100644 --- a/pom.xml +++ b/pom.xml @@ -157,7 +157,7 @@ io.jenkins.tools.bom bom-${jenkins.baseline}.x - 3944.v1a_e4f8b_452db_ + 4136.vca_c3202a_7fd1 import pom diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/CasCTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/CasCTest.java deleted file mode 100644 index ff34d0e5..00000000 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/CasCTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.jenkinsci.plugins.docker.commons; - -import com.cloudbees.plugins.credentials.CredentialsMatchers; -import com.cloudbees.plugins.credentials.CredentialsProvider; -import com.cloudbees.plugins.credentials.common.IdCredentials; -import hudson.security.ACL; -import hudson.tools.InstallSourceProperty; -import hudson.tools.ToolProperty; -import hudson.tools.ToolPropertyDescriptor; -import hudson.util.DescribableList; -import hudson.util.Secret; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; -import org.jenkinsci.plugins.docker.commons.credentials.DockerServerCredentials; -import org.jenkinsci.plugins.docker.commons.credentials.DockerServerDomainRequirement; -import org.jenkinsci.plugins.docker.commons.tools.DockerTool; -import org.jenkinsci.plugins.docker.commons.tools.DockerToolInstaller; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.jvnet.hudson.test.RestartableJenkinsRule; - -import java.util.Collections; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; -import static org.hamcrest.collection.ArrayMatching.arrayContaining; -import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; -import static org.hamcrest.collection.IsIterableContainingInOrder.contains; -import static org.hamcrest.core.AllOf.allOf; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(Parameterized.class) -public class CasCTest extends RoundTripAbstractTest { - - final String resource; - - public CasCTest(final String resource) { - this.resource = resource; - } - - @Parameterized.Parameters(name = "{0}") - public static Object[][] params() { - return new Object[][]{{"casc_bare.yaml"}, {"casc_symbols.yaml"}}; - } - - @Override - protected void assertConfiguredAsExpected(final RestartableJenkinsRule j, final String s) { - - //The credentials - final IdCredentials cred = CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentialsInItemGroup(IdCredentials.class, j.j.jenkins, - ACL.SYSTEM2, Collections.singletonList(new DockerServerDomainRequirement())), CredentialsMatchers.withId("dockerx509")); - assertNotNull(cred); - assertThat(cred, instanceOf(DockerServerCredentials.class)); - DockerServerCredentials dCreds = (DockerServerCredentials) cred; - assertEquals("THE CLIENT", dCreds.getClientCertificate()); - assertEquals("THE SERVER", dCreds.getServerCaCertificate()); - assertEquals("Be wewy wewy cuwiet", Secret.toString(dCreds.getClientKeySecret())); - assertEquals("Docker X.509", dCreds.getDescription()); - - - //The ToolInstaller - final DockerTool[] installations = j.j.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class).getInstallations(); - assertNotNull(installations); - assertThat(installations, arrayWithSize(2)); - assertThat(installations, arrayContaining( - allOf( - hasProperty("name", equalTo("docker-latest")), - hasProperty("home", nullValue()) - ), - allOf( - hasProperty("name", equalTo("docker-native")), - hasProperty("home", equalTo("/etc/docket/docker")) - ) - )); - final DescribableList, ToolPropertyDescriptor> properties = installations[0].getProperties(); - assertThat(properties, contains(instanceOf(InstallSourceProperty.class))); - final InstallSourceProperty property = (InstallSourceProperty) properties.get(0); - assertThat(property.installers, contains( - allOf( - instanceOf(DockerToolInstaller.class), - hasProperty("version", equalTo("latest")) - ) - )); - - /* - * DockerRegistryEndpoint is not directly used in this plugin in any global config sense, - * So it is better tested in the plugins that uses it for example docker workflow plugin: - * https://github.com/jenkinsci/docker-workflow-plugin/blob/2ba1ac97b75a3f188e243333b31ef06d55b9221a/src/main/java/org/jenkinsci/plugins/docker/workflow/declarative/GlobalConfig.java - */ - - } - - @Override - protected String configResource() { - return resource; - } - - @Override - protected String stringInLogExpected() { - return DockerServerCredentials.class.getName(); - } -} diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/ConfigTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/ConfigTest.java index 9044953e..ebb0bd70 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/ConfigTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/ConfigTest.java @@ -24,42 +24,53 @@ package org.jenkinsci.plugins.docker.commons; -import hudson.util.Secret; -import org.jenkinsci.plugins.docker.commons.tools.DockerTool; -import org.jenkinsci.plugins.docker.commons.util.SampleDockerBuilder; -import org.jenkinsci.plugins.docker.commons.credentials.DockerServerCredentials; -import org.jenkinsci.plugins.docker.commons.credentials.DockerServerEndpoint; -import org.jenkinsci.plugins.docker.commons.credentials.DockerRegistryEndpoint; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.common.IdCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; -import hudson.tools.ToolProperty; +import hudson.util.Secret; import java.util.Collections; -import org.junit.Test; -import org.junit.Rule; +import org.jenkinsci.plugins.docker.commons.credentials.DockerRegistryEndpoint; +import org.jenkinsci.plugins.docker.commons.credentials.DockerServerCredentials; +import org.jenkinsci.plugins.docker.commons.credentials.DockerServerEndpoint; +import org.jenkinsci.plugins.docker.commons.tools.DockerTool; +import org.jenkinsci.plugins.docker.commons.util.SampleDockerBuilder; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +@WithJenkins +class ConfigTest { -public class ConfigTest { - - @Rule public JenkinsRule r = new JenkinsRule(); - - @Test public void configRoundTrip() throws Exception { - CredentialsStore store = CredentialsProvider.lookupStores(r.jenkins).iterator().next(); - IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, Secret.fromString("clientKey"), "clientCertificate", "serverCaCertificate"); + @Test + void configRoundTrip(JenkinsRule r) throws Exception { + CredentialsStore store = + CredentialsProvider.lookupStores(r.jenkins).iterator().next(); + IdCredentials serverCredentials = new DockerServerCredentials( + CredentialsScope.GLOBAL, + "serverCreds", + null, + Secret.fromString("clientKey"), + "clientCertificate", + "serverCaCertificate"); store.addCredentials(Domain.global(), serverCredentials); - IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass"); + IdCredentials registryCredentials = + new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass"); store.addCredentials(Domain.global(), registryCredentials); - SampleDockerBuilder b1 = new SampleDockerBuilder(new DockerServerEndpoint("", ""), new DockerRegistryEndpoint("http://dhe.mycorp.com/", registryCredentials.getId())); + SampleDockerBuilder b1 = new SampleDockerBuilder( + new DockerServerEndpoint("", ""), + new DockerRegistryEndpoint("http://dhe.mycorp.com/", registryCredentials.getId())); r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1)); - b1 = new SampleDockerBuilder(new DockerServerEndpoint("tcp://192.168.1.104:8333", serverCredentials.getId()), new DockerRegistryEndpoint("", "")); + b1 = new SampleDockerBuilder( + new DockerServerEndpoint("tcp://192.168.1.104:8333", serverCredentials.getId()), + new DockerRegistryEndpoint("", "")); r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1)); - r.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class).setInstallations(new DockerTool("Docker 1.5", "/usr/local/docker15", Collections.>emptyList())); + r.jenkins + .getDescriptorByType(DockerTool.DescriptorImpl.class) + .setInstallations(new DockerTool("Docker 1.5", "/usr/local/docker15", Collections.emptyList())); b1.setToolName("Docker 1.5"); r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1)); } - } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/JCasCTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/JCasCTest.java new file mode 100644 index 00000000..ba0860a9 --- /dev/null +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/JCasCTest.java @@ -0,0 +1,119 @@ +package org.jenkinsci.plugins.docker.commons; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; +import static org.hamcrest.collection.ArrayMatching.arrayContaining; +import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.hamcrest.core.AllOf.allOf; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.hamcrest.core.IsNull.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import com.cloudbees.plugins.credentials.CredentialsMatchers; +import com.cloudbees.plugins.credentials.CredentialsProvider; +import com.cloudbees.plugins.credentials.common.IdCredentials; +import hudson.security.ACL; +import hudson.tools.InstallSourceProperty; +import hudson.tools.ToolProperty; +import hudson.tools.ToolPropertyDescriptor; +import hudson.util.DescribableList; +import hudson.util.Secret; +import io.jenkins.plugins.casc.misc.junit.jupiter.AbstractRoundTripTest; +import java.util.Collections; +import org.jenkinsci.plugins.docker.commons.credentials.DockerServerCredentials; +import org.jenkinsci.plugins.docker.commons.credentials.DockerServerDomainRequirement; +import org.jenkinsci.plugins.docker.commons.tools.DockerTool; +import org.jenkinsci.plugins.docker.commons.tools.DockerToolInstaller; +import org.junit.jupiter.api.Nested; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +class JCasCTest { + + @Nested + @WithJenkins + class Bare extends AbstractRoundTripTest { + + @Override + protected void assertConfiguredAsExpected(JenkinsRule j, String configContent) { + JCasCTest.assertConfiguredAsExpected(j); + } + + @Override + protected String configResource() { + return "casc_bare.yaml"; + } + + @Override + protected String stringInLogExpected() { + return DockerServerCredentials.class.getName(); + } + } + + @Nested + @WithJenkins + class Symbols extends AbstractRoundTripTest { + + @Override + protected void assertConfiguredAsExpected(JenkinsRule j, String configContent) { + JCasCTest.assertConfiguredAsExpected(j); + } + + @Override + protected String configResource() { + return "casc_symbols.yaml"; + } + + @Override + protected String stringInLogExpected() { + return DockerServerCredentials.class.getName(); + } + } + + private static void assertConfiguredAsExpected(JenkinsRule j) { + // The credentials + final IdCredentials cred = CredentialsMatchers.firstOrNull( + CredentialsProvider.lookupCredentialsInItemGroup( + IdCredentials.class, + j.jenkins, + ACL.SYSTEM2, + Collections.singletonList(new DockerServerDomainRequirement())), + CredentialsMatchers.withId("dockerx509")); + assertNotNull(cred); + assertThat(cred, instanceOf(DockerServerCredentials.class)); + DockerServerCredentials dCreds = (DockerServerCredentials) cred; + assertEquals("THE CLIENT", dCreds.getClientCertificate()); + assertEquals("THE SERVER", dCreds.getServerCaCertificate()); + assertEquals("Be wewy wewy cuwiet", Secret.toString(dCreds.getClientKeySecret())); + assertEquals("Docker X.509", dCreds.getDescription()); + + // The ToolInstaller + final DockerTool[] installations = + j.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class).getInstallations(); + assertNotNull(installations); + assertThat(installations, arrayWithSize(2)); + assertThat( + installations, + arrayContaining( + allOf(hasProperty("name", equalTo("docker-latest")), hasProperty("home", nullValue())), + allOf( + hasProperty("name", equalTo("docker-native")), + hasProperty("home", equalTo("/etc/docket/docker"))))); + final DescribableList, ToolPropertyDescriptor> properties = installations[0].getProperties(); + assertThat(properties, contains(instanceOf(InstallSourceProperty.class))); + final InstallSourceProperty property = (InstallSourceProperty) properties.get(0); + assertThat( + property.installers, + contains(allOf(instanceOf(DockerToolInstaller.class), hasProperty("version", equalTo("latest"))))); + + /* + * DockerRegistryEndpoint is not directly used in this plugin in any global config sense, + * So it is better tested in the plugins that uses it for example docker workflow plugin: + * https://github.com/jenkinsci/docker-workflow-plugin/blob/2ba1ac97b75a3f188e243333b31ef06d55b9221a/src/main/java/org/jenkinsci/plugins/docker/workflow/declarative/GlobalConfig.java + */ + + } +} diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerRegistryEndpointTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerRegistryEndpointTest.java index 974fa3c4..5f3a2745 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerRegistryEndpointTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerRegistryEndpointTest.java @@ -23,11 +23,7 @@ */ package org.jenkinsci.plugins.docker.commons.credentials; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Base64; +import static org.junit.jupiter.api.Assertions.*; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; @@ -41,28 +37,28 @@ import hudson.model.User; import hudson.security.ACL; import hudson.security.ACLContext; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Base64; import jenkins.model.Jenkins; import jenkins.security.QueueItemAuthenticatorConfiguration; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.MockQueueItemAuthenticator; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * @author Carlos Sanchez */ -public class DockerRegistryEndpointTest { - - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class DockerRegistryEndpointTest { @Test @WithoutJenkins - public void testParse() throws Exception { + void testParse() throws Exception { assertRegistry("https://index.docker.io/v1/", "acme/test"); assertRegistry("https://index.docker.io/v1/", "busybox"); assertRegistry("https://docker.acme.com:8080", "docker.acme.com:8080/acme/test"); @@ -77,7 +73,7 @@ public void testParse() throws Exception { @Test @WithoutJenkins - public void testParseWithTags() throws Exception { + void testParseWithTags() throws Exception { assertRegistry("https://index.docker.io/v1/", "acme/test:tag"); assertRegistry("https://index.docker.io/v1/", "busybox:tag"); assertRegistry("https://docker.acme.com:8080", "docker.acme.com:8080/acme/test:tag"); @@ -94,42 +90,59 @@ public void testParseWithTags() throws Exception { @Issue("JENKINS-39181") @Test @WithoutJenkins - public void testParseFullyQualifiedImageName() throws Exception { - assertEquals("private-repo:5000/test-image", new DockerRegistryEndpoint("http://private-repo:5000/", null).imageName("private-repo:5000/test-image")); - assertEquals("private-repo:5000/test-image", new DockerRegistryEndpoint("http://private-repo:5000/", null).imageName("test-image")); - assertEquals("private-repo:5000/test-image:dev", new DockerRegistryEndpoint("http://private-repo:5000/", null).imageName("private-repo:5000/test-image:dev")); - assertEquals("private-repo:5000/test-image:dev", new DockerRegistryEndpoint("http://private-repo:5000/", null).imageName("test-image:dev")); + void testParseFullyQualifiedImageName() throws Exception { + assertEquals( + "private-repo:5000/test-image", + new DockerRegistryEndpoint("http://private-repo:5000/", null) + .imageName("private-repo:5000/test-image")); + assertEquals( + "private-repo:5000/test-image", + new DockerRegistryEndpoint("http://private-repo:5000/", null).imageName("test-image")); + assertEquals( + "private-repo:5000/test-image:dev", + new DockerRegistryEndpoint("http://private-repo:5000/", null) + .imageName("private-repo:5000/test-image:dev")); + assertEquals( + "private-repo:5000/test-image:dev", + new DockerRegistryEndpoint("http://private-repo:5000/", null).imageName("test-image:dev")); } @Issue("JENKINS-39181") - @Test(expected = IllegalArgumentException.class) + @Test @WithoutJenkins - public void testParseNullImageName() throws Exception { - new DockerRegistryEndpoint("http://private-repo:5000/", null).imageName(null); + void testParseNullImageName() { + assertThrows(IllegalArgumentException.class, () -> new DockerRegistryEndpoint("http://private-repo:5000/", null) + .imageName(null)); } @Issue("JENKINS-39181") - @Test(expected = IllegalArgumentException.class) + @Test @WithoutJenkins - public void testParseNullUrlAndImageName() throws Exception { - new DockerRegistryEndpoint(null, null).imageName(null); + void testParseNullUrlAndImageName() { + assertThrows(IllegalArgumentException.class, () -> new DockerRegistryEndpoint(null, null).imageName(null)); } @Issue("JENKINS-48437") @Test - public void testGetTokenForRun() throws Exception { + void testGetTokenForRun(JenkinsRule j) throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); MockAuthorizationStrategy auth = new MockAuthorizationStrategy() - .grant(Jenkins.READ).everywhere().to("alice", "bob") - .grant(Computer.BUILD).everywhere().to("alice", "bob") + .grant(Jenkins.READ) + .everywhere() + .to("alice", "bob") + .grant(Computer.BUILD) + .everywhere() + .to("alice", "bob") // Item.CONFIGURE implies Credentials.USE_ITEM, which is what CredentialsProvider.findCredentialById // uses when determining whether to include item-scope credentials in the search. - .grant(Item.CONFIGURE).everywhere().to("alice"); + .grant(Item.CONFIGURE) + .everywhere() + .to("alice"); j.jenkins.setAuthorizationStrategy(auth); String globalCredentialsId = "global-creds"; - IdCredentials credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, - globalCredentialsId, "test-global-creds", "user", "password"); + IdCredentials credentials = new UsernamePasswordCredentialsImpl( + CredentialsScope.GLOBAL, globalCredentialsId, "test-global-creds", "user", "password"); CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), credentials); FreeStyleProject p1 = j.createFreeStyleProject(); @@ -145,21 +158,28 @@ public void testGetTokenForRun() throws Exception { FreeStyleBuild r1 = j.buildAndAssertSuccess(p1); try (ACLContext as = ACL.as(User.getById("alice", false))) { - DockerRegistryToken token = new DockerRegistryEndpoint("https://index.docker.io/v1/", globalCredentialsId).getToken(r1); - Assert.assertNotNull("Alice has Credentials.USE_ITEM and should be able to use the credential", token); - Assert.assertEquals("user", token.getEmail()); - Assert.assertEquals(Base64.getEncoder().encodeToString("user:password".getBytes(StandardCharsets.UTF_8)), token.getToken()); + DockerRegistryToken token = + new DockerRegistryEndpoint("https://index.docker.io/v1/", globalCredentialsId).getToken(r1); + assertNotNull(token, "Alice has Credentials.USE_ITEM and should be able to use the credential"); + assertEquals("user", token.getEmail()); + assertEquals( + Base64.getEncoder().encodeToString("user:password".getBytes(StandardCharsets.UTF_8)), + token.getToken()); } FreeStyleBuild r2 = j.buildAndAssertSuccess(p2); try (ACLContext as = ACL.as(User.getById("bob", false))) { - DockerRegistryToken token = new DockerRegistryEndpoint("https://index.docker.io/v1/", globalCredentialsId).getToken(r2); - Assert.assertNull("Bob does not have Credentials.USE_ITEM and should not be able to use the credential", token); + DockerRegistryToken token = + new DockerRegistryEndpoint("https://index.docker.io/v1/", globalCredentialsId).getToken(r2); + assertNull(token, "Bob does not have Credentials.USE_ITEM and should not be able to use the credential"); } } - private void assertRegistry(String url, String repo) throws IOException { - assertEquals(url, DockerRegistryEndpoint.fromImageName(repo, null).getEffectiveUrl().toString()); + private static void assertRegistry(String url, String repo) throws IOException { + assertEquals( + url, + DockerRegistryEndpoint.fromImageName(repo, null) + .getEffectiveUrl() + .toString()); } - } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsBindingTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsBindingTest.java index dfd99a61..c4ed31e7 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsBindingTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsBindingTest.java @@ -24,14 +24,22 @@ package org.jenkinsci.plugins.docker.commons.credentials; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertNotNull; + +import com.cloudbees.plugins.credentials.CredentialsProvider; +import com.cloudbees.plugins.credentials.CredentialsScope; +import com.cloudbees.plugins.credentials.CredentialsStore; +import com.cloudbees.plugins.credentials.SystemCredentialsProvider; +import com.cloudbees.plugins.credentials.domains.Domain; +import hudson.FilePath; +import hudson.util.Secret; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Collections; - -import hudson.util.Secret; import org.apache.commons.io.IOUtils; -import org.jenkinsci.plugins.credentialsbinding.MultiBinding; import org.jenkinsci.plugins.credentialsbinding.impl.BindingStep; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; @@ -41,84 +49,77 @@ import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; -import org.junit.runners.model.Statement; import org.jvnet.hudson.test.BuildWatcher; -import org.jvnet.hudson.test.RestartableJenkinsRule; - -import com.cloudbees.plugins.credentials.CredentialsProvider; -import com.cloudbees.plugins.credentials.CredentialsScope; -import com.cloudbees.plugins.credentials.CredentialsStore; -import com.cloudbees.plugins.credentials.SystemCredentialsProvider; -import com.cloudbees.plugins.credentials.domains.Domain; -import com.cloudbees.plugins.credentials.domains.DomainSpecification; - -import hudson.FilePath; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertNotNull; +import org.jvnet.hudson.test.JenkinsSessionRule; public class DockerServerCredentialsBindingTest { @ClassRule public static BuildWatcher buildWatcher = new BuildWatcher(); + @Rule - public RestartableJenkinsRule story = new RestartableJenkinsRule(); + public JenkinsSessionRule story = new JenkinsSessionRule(); @Test - public void configRoundTrip() throws Exception { - story.addStep(new Statement() { - @SuppressWarnings("rawtypes") - @Override - public void evaluate() throws Throwable { - CredentialsStore store = CredentialsProvider.lookupStores(story.j.getInstance()).iterator().next(); - assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class)); - Domain domain = new Domain("docker", "A domain for docker credentials", - Collections. singletonList(new DockerServerDomainSpecification())); - DockerServerCredentials c = new DockerServerCredentials(CredentialsScope.GLOBAL, - "docker-client-cert", "desc", Secret.fromString("clientKey"), "clientCertificate", "serverCaCertificate"); - store.addDomain(domain, c); - BindingStep s = new StepConfigTester(story.j) - .configRoundTrip(new BindingStep(Collections. singletonList( - new DockerServerCredentialsBinding("DOCKER_CERT_PATH", "docker-client-cert")))); - story.j.assertEqualDataBoundBeans(s.getBindings(), Collections.singletonList( - new DockerServerCredentialsBinding("DOCKER_CERT_PATH", "docker-client-cert"))); - } + public void configRoundTrip() throws Throwable { + story.then(j -> { + CredentialsStore store = + CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); + assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class)); + Domain domain = new Domain( + "docker", + "A domain for docker credentials", + Collections.singletonList(new DockerServerDomainSpecification())); + DockerServerCredentials c = new DockerServerCredentials( + CredentialsScope.GLOBAL, + "docker-client-cert", + "desc", + Secret.fromString("clientKey"), + "clientCertificate", + "serverCaCertificate"); + store.addDomain(domain, c); + BindingStep s = new StepConfigTester(j) + .configRoundTrip(new BindingStep(Collections.singletonList( + new DockerServerCredentialsBinding("DOCKER_CERT_PATH", "docker-client-cert")))); + j.assertEqualDataBoundBeans( + s.getBindings(), + Collections.singletonList( + new DockerServerCredentialsBinding("DOCKER_CERT_PATH", "docker-client-cert"))); }); } @Test - public void basics() throws Exception { - story.addStep(new Statement() { - @Override - public void evaluate() throws Throwable { - DockerServerCredentials c = new DockerServerCredentials(CredentialsScope.GLOBAL, - "docker-client-cert", "desc", Secret.fromString("clientKey"), "clientCertificate", "serverCaCertificate"); - CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), c); - WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p"); - String pipelineScript = IOUtils.toString(getTestResourceInputStream("basics-Jenkinsfile"), StandardCharsets.UTF_8); - p.setDefinition(new CpsFlowDefinition(pipelineScript, true)); - WorkflowRun b = p.scheduleBuild2(0).waitForStart(); - SemaphoreStep.waitForStart("basics/1", b); - // copy some test scripts into the workspace - FilePath workspace = story.j.jenkins.getWorkspaceFor(p); - copyTestResourceIntoWorkspace(workspace, "basics-step1.bat", 0755); - copyTestResourceIntoWorkspace(workspace, "basics-step2.bat", 0755); - copyTestResourceIntoWorkspace(workspace, "basics-step1.sh", 0755); - copyTestResourceIntoWorkspace(workspace, "basics-step2.sh", 0755); - } + public void basics() throws Throwable { + story.then(j -> { + DockerServerCredentials c = new DockerServerCredentials( + CredentialsScope.GLOBAL, + "docker-client-cert", + "desc", + Secret.fromString("clientKey"), + "clientCertificate", + "serverCaCertificate"); + CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), c); + WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); + String pipelineScript = + IOUtils.toString(getTestResourceInputStream("basics-Jenkinsfile"), StandardCharsets.UTF_8); + p.setDefinition(new CpsFlowDefinition(pipelineScript, true)); + WorkflowRun b = p.scheduleBuild2(0).waitForStart(); + SemaphoreStep.waitForStart("basics/1", b); + // copy some test scripts into the workspace + FilePath workspace = j.jenkins.getWorkspaceFor(p); + copyTestResourceIntoWorkspace(workspace, "basics-step1.bat", 0755); + copyTestResourceIntoWorkspace(workspace, "basics-step2.bat", 0755); + copyTestResourceIntoWorkspace(workspace, "basics-step1.sh", 0755); + copyTestResourceIntoWorkspace(workspace, "basics-step2.sh", 0755); }); - story.addStep(new Statement() { - @Override - public void evaluate() throws Throwable { - WorkflowJob p = story.j.jenkins.getItemByFullName("p", WorkflowJob.class); - assertNotNull(p); - WorkflowRun b = p.getBuildByNumber(1); - assertNotNull(b); - SemaphoreStep.success("basics/1", null); - story.j.waitForCompletion(b); - story.j.assertBuildStatusSuccess(b); - } + story.then(j -> { + WorkflowJob p = j.jenkins.getItemByFullName("p", WorkflowJob.class); + assertNotNull(p); + WorkflowRun b = p.getBuildByNumber(1); + assertNotNull(b); + SemaphoreStep.success("basics/1", null); + j.waitForCompletion(b); + j.assertBuildStatusSuccess(b); }); } @@ -134,5 +135,4 @@ private FilePath copyTestResourceIntoWorkspace(FilePath workspace, String fileNa f.chmod(mask); return f; } - } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsHandlerTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsHandlerTest.java index 2fbd2029..78ff58d5 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsHandlerTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsHandlerTest.java @@ -24,10 +24,15 @@ package org.jenkinsci.plugins.docker.commons.credentials; +import static org.junit.Assert.assertNotNull; + import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.domains.Domain; import hudson.FilePath; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; @@ -36,56 +41,47 @@ import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; -import org.junit.runners.model.Statement; import org.jvnet.hudson.test.BuildWatcher; -import org.jvnet.hudson.test.RestartableJenkinsRule; - -import java.io.IOException; -import java.io.InputStream; - -import java.nio.charset.StandardCharsets; -import java.util.Collections; - - -import static org.junit.Assert.assertNotNull; +import org.jvnet.hudson.test.JenkinsSessionRule; public class DockerServerCredentialsHandlerTest { @ClassRule public static BuildWatcher buildWatcher = new BuildWatcher(); + @Rule - public RestartableJenkinsRule story = new RestartableJenkinsRule(); + public JenkinsSessionRule story = new JenkinsSessionRule(); @Test - public void basics() throws Exception { - story.addStep(new Statement() { - @Override - public void evaluate() throws Throwable { - DockerServerCredentials c = new DockerServerCredentials(CredentialsScope.GLOBAL, - "docker-client-cert", "desc", "clientKey", "clientCertificate", "serverCaCertificate"); - CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), c); - WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p"); - String pipelineScript = IOUtils.toString(getTestResourceInputStream("basics-Jenkinsfile"), StandardCharsets.UTF_8); - p.setDefinition(new CpsFlowDefinition(pipelineScript, true)); - WorkflowRun b = p.scheduleBuild2(0).waitForStart(); - SemaphoreStep.waitForStart("basics/1", b); - // copy some test scripts into the workspace - FilePath workspace = story.j.jenkins.getWorkspaceFor(p); - copyTestResourceIntoWorkspace(workspace, "basics-step1.bat", 0755); - copyTestResourceIntoWorkspace(workspace, "basics-step1.sh", 0755); - } + public void basics() throws Throwable { + story.then(j -> { + DockerServerCredentials c = new DockerServerCredentials( + CredentialsScope.GLOBAL, + "docker-client-cert", + "desc", + "clientKey", + "clientCertificate", + "serverCaCertificate"); + CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), c); + WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); + String pipelineScript = + IOUtils.toString(getTestResourceInputStream("basics-Jenkinsfile"), StandardCharsets.UTF_8); + p.setDefinition(new CpsFlowDefinition(pipelineScript, true)); + WorkflowRun b = p.scheduleBuild2(0).waitForStart(); + SemaphoreStep.waitForStart("basics/1", b); + // copy some test scripts into the workspace + FilePath workspace = j.jenkins.getWorkspaceFor(p); + copyTestResourceIntoWorkspace(workspace, "basics-step1.bat", 0755); + copyTestResourceIntoWorkspace(workspace, "basics-step1.sh", 0755); }); - story.addStep(new Statement() { - @Override - public void evaluate() throws Throwable { - WorkflowJob p = story.j.jenkins.getItemByFullName("p", WorkflowJob.class); - assertNotNull(p); - WorkflowRun b = p.getBuildByNumber(1); - assertNotNull(b); - SemaphoreStep.success("basics/1", null); - story.j.waitForCompletion(b); - story.j.assertBuildStatusSuccess(b); - } + story.then(j -> { + WorkflowJob p = j.jenkins.getItemByFullName("p", WorkflowJob.class); + assertNotNull(p); + WorkflowRun b = p.getBuildByNumber(1); + assertNotNull(b); + SemaphoreStep.success("basics/1", null); + j.waitForCompletion(b); + j.assertBuildStatusSuccess(b); }); } @@ -101,5 +97,4 @@ private FilePath copyTestResourceIntoWorkspace(FilePath workspace, String fileNa f.chmod(mask); return f; } - } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsTest.java index 7ea4b49b..9b552753 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerCredentialsTest.java @@ -23,6 +23,9 @@ */ package org.jenkinsci.plugins.docker.commons.credentials; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; + import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; @@ -30,70 +33,95 @@ import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.common.IdCredentials; import com.cloudbees.plugins.credentials.domains.Domain; -import com.cloudbees.plugins.credentials.domains.DomainSpecification; -import org.htmlunit.html.HtmlElement; -import org.htmlunit.html.HtmlForm; import hudson.security.ACL; import hudson.util.Secret; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsRule; -import org.xml.sax.SAXException; - import java.io.IOException; import java.util.Collections; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; +import org.htmlunit.html.HtmlElement; +import org.htmlunit.html.HtmlForm; +import org.junit.jupiter.api.Test; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +import org.xml.sax.SAXException; /** * @author Stephen Connolly */ -public class DockerServerCredentialsTest { - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class DockerServerCredentialsTest { @Test - public void configRoundTripEmpty() throws Exception { - CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); + void configRoundTripEmpty(JenkinsRule j) throws Exception { + CredentialsStore store = + CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class)); - Domain domain = new Domain("docker", "A domain for docker credentials", - Collections.singletonList(new DockerServerDomainSpecification())); - DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString(""), "", ""); + Domain domain = new Domain( + "docker", + "A domain for docker credentials", + Collections.singletonList(new DockerServerDomainSpecification())); + DockerServerCredentials credentials = + new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString(""), "", ""); store.addDomain(domain, credentials); - j.submit(j.createWebClient().goTo("credentials/store/system/domain/" + domain.getName() + "/credential/"+credentials.getId()+"/update") + j.submit(j.createWebClient() + .goTo("credentials/store/system/domain/" + domain.getName() + "/credential/" + credentials.getId() + + "/update") .getFormByName("update")); - - j.assertEqualDataBoundBeans(credentials, CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentialsInItemGroup(IdCredentials.class, j.getInstance(), - ACL.SYSTEM2, Collections.singletonList(new DockerServerDomainRequirement())), CredentialsMatchers.withId(credentials.getId()))); + + j.assertEqualDataBoundBeans( + credentials, + CredentialsMatchers.firstOrNull( + CredentialsProvider.lookupCredentialsInItemGroup( + IdCredentials.class, + j.getInstance(), + ACL.SYSTEM2, + Collections.singletonList(new DockerServerDomainRequirement())), + CredentialsMatchers.withId(credentials.getId()))); } - + @Test - public void configRoundTripData() throws Exception { - CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); + void configRoundTripData(JenkinsRule j) throws Exception { + CredentialsStore store = + CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class)); - Domain domain = new Domain("docker", "A domain for docker credentials", - Collections.singletonList(new DockerServerDomainSpecification())); - DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("a"), "b", "c"); + Domain domain = new Domain( + "docker", + "A domain for docker credentials", + Collections.singletonList(new DockerServerDomainSpecification())); + DockerServerCredentials credentials = + new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("a"), "b", "c"); store.addDomain(domain, credentials); - j.submit(j.createWebClient().goTo("credentials/store/system/domain/" + domain.getName() + "/credential/"+credentials.getId()+"/update") + j.submit(j.createWebClient() + .goTo("credentials/store/system/domain/" + domain.getName() + "/credential/" + credentials.getId() + + "/update") .getFormByName("update")); - - j.assertEqualDataBoundBeans(credentials, CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentialsInItemGroup(IdCredentials.class, j.getInstance(), - ACL.SYSTEM2, Collections.singletonList(new DockerServerDomainRequirement())), CredentialsMatchers.withId(credentials.getId()))); + + j.assertEqualDataBoundBeans( + credentials, + CredentialsMatchers.firstOrNull( + CredentialsProvider.lookupCredentialsInItemGroup( + IdCredentials.class, + j.getInstance(), + ACL.SYSTEM2, + Collections.singletonList(new DockerServerDomainRequirement())), + CredentialsMatchers.withId(credentials.getId()))); } @Test - public void configRoundTripUpdateCertificates() throws Exception { - CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); + void configRoundTripUpdateCertificates(JenkinsRule j) throws Exception { + CredentialsStore store = + CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class)); - Domain domain = new Domain("docker", "A domain for docker credentials", Collections.singletonList(new DockerServerDomainSpecification())); - DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("key"), "client-cert", "ca-cert"); + Domain domain = new Domain( + "docker", + "A domain for docker credentials", + Collections.singletonList(new DockerServerDomainSpecification())); + DockerServerCredentials credentials = new DockerServerCredentials( + CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("key"), "client-cert", "ca-cert"); store.addDomain(domain, credentials); - HtmlForm form = getUpdateForm(domain, credentials); + HtmlForm form = getUpdateForm(j, domain, credentials); ((HtmlElement) form.querySelector(".secret-update-btn")).click(); form.getTextAreaByName("_.clientKeySecret").setText("new key"); @@ -102,19 +130,30 @@ public void configRoundTripUpdateCertificates() throws Exception { j.submit(form); DockerServerCredentials expected = new DockerServerCredentials( - credentials.getScope(), credentials.getId(), credentials.getDescription(), - Secret.fromString("new key"), "new cert", "new ca cert"); - j.assertEqualDataBoundBeans(expected, findFirstWithId(credentials.getId())); + credentials.getScope(), + credentials.getId(), + credentials.getDescription(), + Secret.fromString("new key"), + "new cert", + "new ca cert"); + j.assertEqualDataBoundBeans(expected, findFirstWithId(j, credentials.getId())); } - private HtmlForm getUpdateForm(Domain domain, DockerServerCredentials credentials) throws IOException, SAXException { - return j.createWebClient().goTo("credentials/store/system/domain/" + domain.getName() + "/credential/" + credentials.getId() + "/update") + private static HtmlForm getUpdateForm(JenkinsRule j, Domain domain, DockerServerCredentials credentials) + throws IOException, SAXException { + return j.createWebClient() + .goTo("credentials/store/system/domain/" + domain.getName() + "/credential/" + credentials.getId() + + "/update") .getFormByName("update"); } - private IdCredentials findFirstWithId(String credentialsId) { + private static IdCredentials findFirstWithId(JenkinsRule j, String credentialsId) { return CredentialsMatchers.firstOrNull( - CredentialsProvider.lookupCredentialsInItemGroup(IdCredentials.class, j.getInstance(), ACL.SYSTEM2, Collections.singletonList(new DockerServerDomainRequirement())), + CredentialsProvider.lookupCredentialsInItemGroup( + IdCredentials.class, + j.getInstance(), + ACL.SYSTEM2, + Collections.singletonList(new DockerServerDomainRequirement())), CredentialsMatchers.withId(credentialsId)); } } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerDomainSpecificationTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerDomainSpecificationTest.java index 11b544bd..2bab8cea 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerDomainSpecificationTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerDomainSpecificationTest.java @@ -23,44 +23,45 @@ */ package org.jenkinsci.plugins.docker.commons.credentials; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; + import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.domains.Domain; -import com.cloudbees.plugins.credentials.domains.DomainSpecification; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsRule; - import java.util.Collections; import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; +import org.junit.jupiter.api.Test; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * @author Stephen Connolly */ -public class DockerServerDomainSpecificationTest { - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class DockerServerDomainSpecificationTest { @Test - public void configRoundTrip() throws Exception { - CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); + void configRoundTrip(JenkinsRule j) throws Exception { + CredentialsStore store = + CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class)); - Domain domain = new Domain("docker", "A domain for docker credentials", - Collections.singletonList(new DockerServerDomainSpecification())); + Domain domain = new Domain( + "docker", + "A domain for docker credentials", + Collections.singletonList(new DockerServerDomainSpecification())); store.addDomain(domain); - j.submit(j.createWebClient().goTo("credentials/store/system/domain/" + domain.getName() + "/configure") + j.submit(j.createWebClient() + .goTo("credentials/store/system/domain/" + domain.getName() + "/configure") .getFormByName("config")); - - j.assertEqualDataBoundBeans(domain, byName(store.getDomains(),domain.getName())); + + j.assertEqualDataBoundBeans(domain, byName(store.getDomains(), domain.getName())); } - + public Domain byName(List domains, String name) { - for (Domain d: domains) { + for (Domain d : domains) { if (name.equals(d.getName())) { return d; } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerEndpointTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerEndpointTest.java index 8d585a10..72737942 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerEndpointTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/DockerServerEndpointTest.java @@ -23,56 +23,56 @@ */ package org.jenkinsci.plugins.docker.commons.credentials; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; + import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.domains.Domain; -import com.cloudbees.plugins.credentials.domains.DomainSpecification; import hudson.FilePath; import hudson.Functions; import hudson.model.FreeStyleProject; import hudson.remoting.VirtualChannel; import hudson.slaves.DumbSlave; import hudson.util.Secret; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsRule; - import java.util.Collections; import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; +import org.junit.jupiter.api.Test; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * @author Stephen Connolly */ -public class DockerServerEndpointTest { - - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class DockerServerEndpointTest { @Test - public void smokes() throws Exception { + void smokes(JenkinsRule j) throws Exception { DumbSlave slave = j.createOnlineSlave(); VirtualChannel channel = slave.getChannel(); FreeStyleProject item = j.createFreeStyleProject(); - CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); + CredentialsStore store = + CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class)); - Domain domain = new Domain("docker", "A domain for docker credentials", - Collections.singletonList(new DockerServerDomainSpecification())); - DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("a"), "b", "c"); + Domain domain = new Domain( + "docker", + "A domain for docker credentials", + Collections.singletonList(new DockerServerDomainSpecification())); + DockerServerCredentials credentials = + new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("a"), "b", "c"); store.addDomain(domain, credentials); DockerServerEndpoint endpoint = new DockerServerEndpoint("tcp://localhost:2736", credentials.getId()); FilePath dotDocker = DockerServerEndpoint.dotDocker(channel); List dotDockerKids = dotDocker.list(); - int initialSize = dotDockerKids == null ? 0 : dotDockerKids.size(); + int initialSize = dotDockerKids.size(); KeyMaterialFactory factory = endpoint.newKeyMaterialFactory(item, channel); KeyMaterial keyMaterial = factory.materialize(); - FilePath path = null; + FilePath path; try { assertThat(keyMaterial.env().get("DOCKER_HOST", "missing"), is("tcp://localhost:2736")); assertThat(keyMaterial.env().get("DOCKER_TLS_VERIFY", "missing"), is("1")); @@ -92,6 +92,4 @@ public void smokes() throws Exception { assertThat(path.child("ca.pem").exists(), is(false)); assertThat(dotDocker.list().size(), is(initialSize)); } - - } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/ImageNameValidatorTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/ImageNameValidatorTest.java index 36f8304c..1062bb91 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/ImageNameValidatorTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/credentials/ImageNameValidatorTest.java @@ -1,19 +1,17 @@ package org.jenkinsci.plugins.docker.commons.credentials; -import hudson.util.FormValidation; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.Assert.*; +import hudson.util.FormValidation; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests various inputs to {@link ImageNameValidator#validateUserAndRepo(String)}. */ -@RunWith(Parameterized.class) -public class ImageNameValidatorTest { +class ImageNameValidatorTest { - @Parameterized.Parameters(name = "{index}:{0}") public static Object[][] data(){ + static Object[][] data() { return new Object[][] { {"jenkinsci/workflow-demo", FormValidation.Kind.OK}, {"docker:80/jenkinsci/workflow-demo", FormValidation.Kind.OK}, @@ -32,8 +30,8 @@ public class ImageNameValidatorTest { {"jenkinsci/workflow-demo@sha256:56930391cf0e1be83108422bbef43001650cfb75f64b3429928f0c5986fdb750", FormValidation.Kind.OK}, {"docker:80/jenkinsci/workflow-demo@sha256:56930391cf0e1be83108422bbef43001650cfb75f64b3429928f0c5986fdb750", FormValidation.Kind.OK}, {"docker:80/jenkinsci/workflow-demo:latest@sha256:56930391cf0e1be83108422bbef43001650cfb75f64b3429928f0c5986fdb750", FormValidation.Kind.OK}, - {"docker:80/jenkinsci/workflow-demo:latest@sha1:0123456789abcdef", FormValidation.Kind.OK}, - {"docker:80/jenkinsci/workflow-demo:latest@sha1:", FormValidation.Kind.ERROR}, + {"docker:80/jenkinsci/workflow-demo:latest@sha1:0123456789abcdef", FormValidation.Kind.OK}, + {"docker:80/jenkinsci/workflow-demo:latest@sha1:", FormValidation.Kind.ERROR}, {"docker:80/jenkinsci/workflow-demo@", FormValidation.Kind.ERROR}, {"docker:80/jenkinsci/workflow-demo:latest@", FormValidation.Kind.ERROR}, {":tag", FormValidation.Kind.ERROR}, @@ -62,17 +60,10 @@ public class ImageNameValidatorTest { }; } - private final String userAndRepo; - private final FormValidation.Kind expected; - - public ImageNameValidatorTest(final String userAndRepo, final FormValidation.Kind expected) { - this.userAndRepo = userAndRepo; - this.expected = expected; - } - - @Test - public void test() { + @ParameterizedTest(name = "{index}:{0}") + @MethodSource("data") + void test(String userAndRepo, FormValidation.Kind expected) { FormValidation res = ImageNameValidator.validateUserAndRepo(userAndRepo); - assertSame(userAndRepo + " : " + res.getMessage(), expected, res.kind); + assertSame(expected, res.kind, userAndRepo + " : " + res.getMessage()); } -} \ No newline at end of file +} diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/fingerprint/DockerFingerprintsTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/fingerprint/DockerFingerprintsTest.java index 3646b130..5c036d1b 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/fingerprint/DockerFingerprintsTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/fingerprint/DockerFingerprintsTest.java @@ -24,22 +24,25 @@ package org.jenkinsci.plugins.docker.commons.fingerprint; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class DockerFingerprintsTest { +class DockerFingerprintsTest { @Test - public void testGetFingerprintHashForId() { - assertEquals("598d0def97f180366008bcddbf0a4ed5", DockerFingerprints - .getFingerprintHash("598d0def97f180366008bcddbf0a4ed5267b35d0a876c0f867fc38c7adb041e3")); + void testGetFingerprintHashForId() { + assertEquals( + "598d0def97f180366008bcddbf0a4ed5", + DockerFingerprints.getFingerprintHash( + "598d0def97f180366008bcddbf0a4ed5267b35d0a876c0f867fc38c7adb041e3")); } @Test - public void testGetFingerprintHashForSha256() { - assertEquals("598d0def97f180366008bcddbf0a4ed5", DockerFingerprints - .getFingerprintHash("sha256:598d0def97f180366008bcddbf0a4ed5267b35d0a876c0f867fc38c7adb041e3")); + void testGetFingerprintHashForSha256() { + assertEquals( + "598d0def97f180366008bcddbf0a4ed5", + DockerFingerprints.getFingerprintHash( + "sha256:598d0def97f180366008bcddbf0a4ed5267b35d0a876c0f867fc38c7adb041e3")); } - } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/fingerprint/DockerRunFingerprintFacetTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/fingerprint/DockerRunFingerprintFacetTest.java index d76ab11e..562cf999 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/fingerprint/DockerRunFingerprintFacetTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/fingerprint/DockerRunFingerprintFacetTest.java @@ -23,48 +23,47 @@ */ package org.jenkinsci.plugins.docker.commons.fingerprint; +import static org.junit.jupiter.api.Assertions.*; + import hudson.model.Fingerprint; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsRule; - import java.util.Collections; +import org.junit.jupiter.api.Test; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * @author tom.fennelly@gmail.com */ -public class DockerRunFingerprintFacetTest { - - private static String IMAGE_ID = "0409d3ebf4f571d7dd2cf4b00f9d897f8af1d6d8a0f1ff791d173ba9891fd72f"; - - @Rule - public JenkinsRule rule = new JenkinsRule(); - +@WithJenkins +class DockerRunFingerprintFacetTest { + + private static final String IMAGE_ID = "0409d3ebf4f571d7dd2cf4b00f9d897f8af1d6d8a0f1ff791d173ba9891fd72f"; + @Test - public void test_readResolve() throws Exception { + void test_readResolve(JenkinsRule rule) throws Exception { FreeStyleProject p = rule.createFreeStyleProject("test"); FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); - - ContainerRecord r1 = new ContainerRecord("192.168.1.10", "cid", IMAGE_ID, "magic", System.currentTimeMillis(), Collections.emptyMap()); + + ContainerRecord r1 = new ContainerRecord( + "192.168.1.10", "cid", IMAGE_ID, "magic", System.currentTimeMillis(), Collections.emptyMap()); DockerFingerprints.addRunFacet(r1, b); Fingerprint fingerprint = DockerFingerprints.of(IMAGE_ID); - DockerRunFingerprintFacet facet = new DockerRunFingerprintFacet(fingerprint, System.currentTimeMillis(), IMAGE_ID); - ContainerRecord r2 = new ContainerRecord("192.168.1.10", "cid", null, "magic", System.currentTimeMillis(), Collections.emptyMap()); + DockerRunFingerprintFacet facet = + new DockerRunFingerprintFacet(fingerprint, System.currentTimeMillis(), IMAGE_ID); + ContainerRecord r2 = new ContainerRecord( + "192.168.1.10", "cid", null, "magic", System.currentTimeMillis(), Collections.emptyMap()); facet.add(r2); - - Assert.assertNull(r2.getImageId()); + + assertNull(r2.getImageId()); facet.readResolve(); - Assert.assertEquals(IMAGE_ID, r2.getImageId()); - + assertEquals(IMAGE_ID, r2.getImageId()); + // Check that actions have been automatically added DockerFingerprintAction fpAction = b.getAction(DockerFingerprintAction.class); - Assert.assertNotNull("DockerFingerprintAction should be added automatically", fpAction); - Assert.assertTrue("Docker image should be referred in the action", - fpAction.getImageIDs().contains(IMAGE_ID)); + assertNotNull(fpAction, "DockerFingerprintAction should be added automatically"); + assertTrue(fpAction.getImageIDs().contains(IMAGE_ID), "Docker image should be referred in the action"); } - } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/impl/HostOnlyRegistryKeyMaterialFactoryTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/impl/HostOnlyRegistryKeyMaterialFactoryTest.java index e6de1722..0048a318 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/impl/HostOnlyRegistryKeyMaterialFactoryTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/impl/HostOnlyRegistryKeyMaterialFactoryTest.java @@ -24,177 +24,161 @@ package org.jenkinsci.plugins.docker.commons.impl; -import static org.hamcrest.Matchers.arrayContaining; -import static org.hamcrest.Matchers.emptyArray; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import hudson.EnvVars; +import hudson.FilePath; +import hudson.Launcher; +import hudson.model.TaskListener; +import hudson.remoting.Callable; +import hudson.remoting.LocalChannel; +import hudson.remoting.VirtualChannel; import java.io.File; import java.io.IOException; import java.net.URL; - -import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.docker.commons.credentials.DockerRegistryEndpoint; -import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialContext; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory; import org.jenkinsci.plugins.docker.commons.tools.DockerTool; -import org.junit.Before; -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.jvnet.hudson.test.FakeLauncher; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.PretendSlave; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -import hudson.EnvVars; -import hudson.FilePath; -import hudson.Launcher; -import hudson.Launcher.ProcStarter; -import hudson.Proc; -import hudson.model.TaskListener; -import hudson.remoting.Callable; -import hudson.remoting.LocalChannel; -import hudson.remoting.VirtualChannel; +@WithJenkins +class HostOnlyRegistryKeyMaterialFactoryTest { -public class HostOnlyRegistryKeyMaterialFactoryTest { - - @Rule - public JenkinsRule j = new JenkinsRule(); - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; private KeyMaterialFactory factory; @Test - public void resolveRegistryDueToPodmanExecutable() throws Exception { - - // fake launcher for the docker login invocation - FakeLauncher faker = new FakeLauncher() { - @Override - public Proc onLaunch(final ProcStarter p) throws IOException { - return new FinishedProc(0); - } - }; - - PretendSlave slave = j.createPretendSlave(faker); - // VirtualChannel channel = slave.getChannel(); - // FreeStyleProject project = j.createFreeStyleProject(); - - TaskListener listener = TaskListener.NULL; - Launcher launcher = slave.createLauncher(listener); - launcher = new Launcher.DecoratedLauncher(launcher) { - @Override - public VirtualChannel getChannel() { - return new LocalChannel(null) { - @Override - public V call(final Callable callable) throws T { - // ugly as hell, but we need a way to mock fetching the home directory - return (V) new FilePath(tempFolder.getRoot()); - } - }; - } - }; - - URL endpoint = new DockerRegistryEndpoint(null, null).getEffectiveUrl(); - EnvVars env = new EnvVars(); - String dockerExecutable = "/usr/bin/podman"; - - factory = new RegistryKeyMaterialFactory("username", "password", endpoint, launcher, env, listener, - dockerExecutable).contextualize(new KeyMaterialContext(new FilePath(tempFolder.newFolder()))); - // act - String registry = ((RegistryKeyMaterialFactory)factory).registry(); - - // assert - assertEquals(registry, "index.docker.io"); + void resolveRegistryDueToPodmanExecutable(JenkinsRule j) throws Exception { + + // fake launcher for the docker login invocation + FakeLauncher faker = p -> new FakeLauncher.FinishedProc(0); + + PretendSlave slave = j.createPretendSlave(faker); + // VirtualChannel channel = slave.getChannel(); + // FreeStyleProject project = j.createFreeStyleProject(); + + TaskListener listener = TaskListener.NULL; + Launcher launcher = slave.createLauncher(listener); + launcher = new Launcher.DecoratedLauncher(launcher) { + @Override + public VirtualChannel getChannel() { + return new LocalChannel(null) { + @Override + public V call(final Callable callable) throws T { + // ugly as hell, but we need a way to mock fetching the home directory + return (V) new FilePath(tempFolder); + } + }; + } + }; + + URL endpoint = new DockerRegistryEndpoint(null, null).getEffectiveUrl(); + EnvVars env = new EnvVars(); + String dockerExecutable = "/usr/bin/podman"; + + factory = new RegistryKeyMaterialFactory( + "username", "password", endpoint, launcher, env, listener, dockerExecutable) + .contextualize(new KeyMaterialContext(new FilePath(newFolder(tempFolder, "junit")))); + // act + String registry = ((RegistryKeyMaterialFactory) factory).registry(); + + // assert + assertEquals("index.docker.io", registry); } - + @Test - public void resolveRegistryDueToENVSet() throws Exception { - - // fake launcher for the docker login invocation - FakeLauncher faker = new FakeLauncher() { - @Override - public Proc onLaunch(final ProcStarter p) throws IOException { - return new FinishedProc(0); - } - }; - - PretendSlave slave = j.createPretendSlave(faker); - // VirtualChannel channel = slave.getChannel(); - // FreeStyleProject project = j.createFreeStyleProject(); - - TaskListener listener = TaskListener.NULL; - Launcher launcher = slave.createLauncher(listener); - launcher = new Launcher.DecoratedLauncher(launcher) { - @Override - public VirtualChannel getChannel() { - return new LocalChannel(null) { - @Override - public V call(final Callable callable) throws T { - // ugly as hell, but we need a way to mock fetching the home directory - return (V) new FilePath(tempFolder.getRoot()); - } - }; - } - }; - - URL endpoint = new DockerRegistryEndpoint(null, null).getEffectiveUrl(); - EnvVars env = new EnvVars(); - env.put(RegistryKeyMaterialFactory.DOCKER_REGISTRY_HOST_ONLY, "true"); - String dockerExecutable = DockerTool.getExecutable(null, null, listener, env); - - factory = new RegistryKeyMaterialFactory("username", "password", endpoint, launcher, env, listener, - dockerExecutable).contextualize(new KeyMaterialContext(new FilePath(tempFolder.newFolder()))); - // act - String registry = ((RegistryKeyMaterialFactory)factory).registry(); - - // assert - assertEquals(registry, "index.docker.io"); + void resolveRegistryDueToENVSet(JenkinsRule j) throws Exception { + + // fake launcher for the docker login invocation + FakeLauncher faker = p -> new FakeLauncher.FinishedProc(0); + + PretendSlave slave = j.createPretendSlave(faker); + // VirtualChannel channel = slave.getChannel(); + // FreeStyleProject project = j.createFreeStyleProject(); + + TaskListener listener = TaskListener.NULL; + Launcher launcher = slave.createLauncher(listener); + launcher = new Launcher.DecoratedLauncher(launcher) { + @Override + public VirtualChannel getChannel() { + return new LocalChannel(null) { + @Override + public V call(final Callable callable) throws T { + // ugly as hell, but we need a way to mock fetching the home directory + return (V) new FilePath(tempFolder); + } + }; + } + }; + + URL endpoint = new DockerRegistryEndpoint(null, null).getEffectiveUrl(); + EnvVars env = new EnvVars(); + env.put(RegistryKeyMaterialFactory.DOCKER_REGISTRY_HOST_ONLY, "true"); + String dockerExecutable = DockerTool.getExecutable(null, null, listener, env); + + factory = new RegistryKeyMaterialFactory( + "username", "password", endpoint, launcher, env, listener, dockerExecutable) + .contextualize(new KeyMaterialContext(new FilePath(newFolder(tempFolder, "junit")))); + // act + String registry = ((RegistryKeyMaterialFactory) factory).registry(); + + // assert + assertEquals("index.docker.io", registry); } @Test - public void resolveRegistryDefault() throws Exception { - - // fake launcher for the docker login invocation - FakeLauncher faker = new FakeLauncher() { - @Override - public Proc onLaunch(final ProcStarter p) throws IOException { - return new FinishedProc(0); - } - }; - - PretendSlave slave = j.createPretendSlave(faker); - // VirtualChannel channel = slave.getChannel(); - // FreeStyleProject project = j.createFreeStyleProject(); - - TaskListener listener = TaskListener.NULL; - Launcher launcher = slave.createLauncher(listener); - launcher = new Launcher.DecoratedLauncher(launcher) { - @Override - public VirtualChannel getChannel() { - return new LocalChannel(null) { - @Override - public V call(final Callable callable) throws T { - // ugly as hell, but we need a way to mock fetching the home directory - return (V) new FilePath(tempFolder.getRoot()); - } - }; - } - }; - - URL endpoint = new DockerRegistryEndpoint(null, null).getEffectiveUrl(); - EnvVars env = new EnvVars(); - String dockerExecutable = DockerTool.getExecutable(null, null, listener, env); - - factory = new RegistryKeyMaterialFactory("username", "password", endpoint, launcher, env, listener, - dockerExecutable).contextualize(new KeyMaterialContext(new FilePath(tempFolder.newFolder()))); - // act - String registry = ((RegistryKeyMaterialFactory)factory).registry(); - - // assert - assertEquals(registry, "https://index.docker.io/v1/"); + void resolveRegistryDefault(JenkinsRule j) throws Exception { + + // fake launcher for the docker login invocation + FakeLauncher faker = p -> new FakeLauncher.FinishedProc(0); + + PretendSlave slave = j.createPretendSlave(faker); + // VirtualChannel channel = slave.getChannel(); + // FreeStyleProject project = j.createFreeStyleProject(); + + TaskListener listener = TaskListener.NULL; + Launcher launcher = slave.createLauncher(listener); + launcher = new Launcher.DecoratedLauncher(launcher) { + @Override + public VirtualChannel getChannel() { + return new LocalChannel(null) { + @Override + public V call(final Callable callable) throws T { + // ugly as hell, but we need a way to mock fetching the home directory + return (V) new FilePath(tempFolder); + } + }; + } + }; + + URL endpoint = new DockerRegistryEndpoint(null, null).getEffectiveUrl(); + EnvVars env = new EnvVars(); + String dockerExecutable = DockerTool.getExecutable(null, null, listener, env); + + factory = new RegistryKeyMaterialFactory( + "username", "password", endpoint, launcher, env, listener, dockerExecutable) + .contextualize(new KeyMaterialContext(new FilePath(newFolder(tempFolder, "junit")))); + // act + String registry = ((RegistryKeyMaterialFactory) factory).registry(); + + // assert + assertEquals("https://index.docker.io/v1/", registry); + } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; } } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/impl/RegistryKeyMaterialFactoryTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/impl/RegistryKeyMaterialFactoryTest.java index ea72b951..89534f7f 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/impl/RegistryKeyMaterialFactoryTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/impl/RegistryKeyMaterialFactoryTest.java @@ -27,210 +27,220 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.emptyArray; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; +import hudson.EnvVars; +import hudson.FilePath; +import hudson.Launcher; +import hudson.model.TaskListener; +import hudson.remoting.Callable; +import hudson.remoting.LocalChannel; +import hudson.remoting.VirtualChannel; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; - import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.docker.commons.credentials.DockerRegistryEndpoint; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialContext; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory; import org.jenkinsci.plugins.docker.commons.tools.DockerTool; -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.FakeLauncher; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.PretendSlave; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -import hudson.EnvVars; -import hudson.FilePath; -import hudson.Launcher; -import hudson.Launcher.ProcStarter; -import hudson.Proc; -import hudson.model.TaskListener; -import hudson.remoting.Callable; -import hudson.remoting.LocalChannel; -import hudson.remoting.VirtualChannel; - -public class RegistryKeyMaterialFactoryTest { +@WithJenkins +class RegistryKeyMaterialFactoryTest { - @Rule - public JenkinsRule j = new JenkinsRule(); - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; private KeyMaterialFactory factory; - @Before - public void setup() throws Exception { - // fake launcher for the docker login invocation - FakeLauncher faker = new FakeLauncher() { - @Override - public Proc onLaunch(final ProcStarter p) throws IOException { - return new FinishedProc(0); - } - }; - - PretendSlave slave = j.createPretendSlave(faker); - // VirtualChannel channel = slave.getChannel(); - // FreeStyleProject project = j.createFreeStyleProject(); - - TaskListener listener = TaskListener.NULL; - Launcher launcher = slave.createLauncher(listener); - launcher = new Launcher.DecoratedLauncher(launcher) { - @Override - public VirtualChannel getChannel() { - return new LocalChannel(null) { - @Override - public V call(final Callable callable) throws T { - // ugly as hell, but we need a way to mock fetching the home directory - return (V) new FilePath(tempFolder.getRoot()); - } - }; - } - }; - - URL endpoint = new DockerRegistryEndpoint(null, null).getEffectiveUrl(); - EnvVars env = new EnvVars(); - String dockerExecutable = DockerTool.getExecutable(null, null, listener, env); - - factory = new RegistryKeyMaterialFactory("username", "password", endpoint, launcher, env, listener, - dockerExecutable).contextualize(new KeyMaterialContext(new FilePath(tempFolder.newFolder()))); + @BeforeEach + void setup(JenkinsRule j) throws Exception { + // fake launcher for the docker login invocation + FakeLauncher faker = p -> new FakeLauncher.FinishedProc(0); + + PretendSlave slave = j.createPretendSlave(faker); + // VirtualChannel channel = slave.getChannel(); + // FreeStyleProject project = j.createFreeStyleProject(); + + TaskListener listener = TaskListener.NULL; + Launcher launcher = slave.createLauncher(listener); + launcher = new Launcher.DecoratedLauncher(launcher) { + @Override + public VirtualChannel getChannel() { + return new LocalChannel(null) { + @Override + public V call(final Callable callable) throws T { + // ugly as hell, but we need a way to mock fetching the home directory + return (V) new FilePath(tempFolder); + } + }; + } + }; + + URL endpoint = new DockerRegistryEndpoint(null, null).getEffectiveUrl(); + EnvVars env = new EnvVars(); + String dockerExecutable = DockerTool.getExecutable(null, null, listener, env); + + factory = new RegistryKeyMaterialFactory( + "username", "password", endpoint, launcher, env, listener, dockerExecutable) + .contextualize(new KeyMaterialContext(new FilePath(newFolder(tempFolder, "junit")))); } @Test - public void materialize_userConfigFileNotPresent_notCreated() throws Exception { - // act - KeyMaterial material = factory.materialize(); + void materialize_userConfigFileNotPresent_notCreated() throws Exception { + // act + KeyMaterial material = factory.materialize(); - // assert - String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); - assertNotNull(dockerCfgFolderPath); + // assert + String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); + assertNotNull(dockerCfgFolderPath); - File dockerCfgFolder = new File(dockerCfgFolderPath); - assertTrue(dockerCfgFolder.exists()); - assertThat(dockerCfgFolder.list(), emptyArray()); + File dockerCfgFolder = new File(dockerCfgFolderPath); + assertTrue(dockerCfgFolder.exists()); + assertThat(dockerCfgFolder.list(), emptyArray()); } @Test - public void materialize_userConfigFileBlank_notCreated() throws Exception { - // arrange - File cfgFile = new File(new File(tempFolder.getRoot(), ".docker"), "config.json"); - FileUtils.write(cfgFile, " ", Charset.defaultCharset()); + void materialize_userConfigFileBlank_notCreated() throws Exception { + // arrange + File cfgFile = new File(new File(tempFolder, ".docker"), "config.json"); + FileUtils.write(cfgFile, " ", Charset.defaultCharset()); - // act - KeyMaterial material = factory.materialize(); + // act + KeyMaterial material = factory.materialize(); - // assert - String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); - assertNotNull(dockerCfgFolderPath); + // assert + String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); + assertNotNull(dockerCfgFolderPath); - File dockerCfgFolder = new File(dockerCfgFolderPath); - assertTrue(dockerCfgFolder.exists()); - assertThat(dockerCfgFolder.list(), emptyArray()); + File dockerCfgFolder = new File(dockerCfgFolderPath); + assertTrue(dockerCfgFolder.exists()); + assertThat(dockerCfgFolder.list(), emptyArray()); } @Test - public void materialize_userConfigFileWithBrackets_createdEmpty() throws Exception { - // arrange - File cfgFile = new File(new File(tempFolder.getRoot(), ".docker"), "config.json"); - FileUtils.write(cfgFile, "{}", Charset.defaultCharset()); + void materialize_userConfigFileWithBrackets_createdEmpty() throws Exception { + // arrange + File cfgFile = new File(new File(tempFolder, ".docker"), "config.json"); + FileUtils.write(cfgFile, "{}", Charset.defaultCharset()); - // act - KeyMaterial material = factory.materialize(); + // act + KeyMaterial material = factory.materialize(); - // assert - String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); - assertNotNull(dockerCfgFolderPath); + // assert + String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); + assertNotNull(dockerCfgFolderPath); - File dockerCfgFolder = new File(dockerCfgFolderPath); - assertTrue(dockerCfgFolder.exists()); + File dockerCfgFolder = new File(dockerCfgFolderPath); + assertTrue(dockerCfgFolder.exists()); - String[] files = dockerCfgFolder.list(); - assertThat(files, arrayContaining("config.json")); + String[] files = dockerCfgFolder.list(); + assertThat(files, arrayContaining("config.json")); - File jsonFile = new File(dockerCfgFolder, "config.json"); - assertEquals("{}", FileUtils.readFileToString(jsonFile, Charset.defaultCharset())); + File jsonFile = new File(dockerCfgFolder, "config.json"); + assertEquals("{}", FileUtils.readFileToString(jsonFile, Charset.defaultCharset())); } @Test - public void materialize_userConfigFileWithAuths_createdEmpty() throws Exception { - // arrange - File cfgFile = new File(new File(tempFolder.getRoot(), ".docker"), "config.json"); - FileUtils.write(cfgFile, "{\"auths\": { \"localhost:5001\": { \"auth\": \"whatever\", \"email\": \"\"} }}", Charset.defaultCharset()); + void materialize_userConfigFileWithAuths_createdEmpty() throws Exception { + // arrange + File cfgFile = new File(new File(tempFolder, ".docker"), "config.json"); + FileUtils.write( + cfgFile, + "{\"auths\": { \"localhost:5001\": { \"auth\": \"whatever\", \"email\": \"\"} }}", + Charset.defaultCharset()); - // act - KeyMaterial material = factory.materialize(); + // act + KeyMaterial material = factory.materialize(); - // assert - String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); - assertNotNull(dockerCfgFolderPath); + // assert + String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); + assertNotNull(dockerCfgFolderPath); - File dockerCfgFolder = new File(dockerCfgFolderPath); - assertTrue(dockerCfgFolder.exists()); + File dockerCfgFolder = new File(dockerCfgFolderPath); + assertTrue(dockerCfgFolder.exists()); - String[] files = dockerCfgFolder.list(); - assertThat(files, arrayContaining("config.json")); + String[] files = dockerCfgFolder.list(); + assertThat(files, arrayContaining("config.json")); - File jsonFile = new File(dockerCfgFolder, "config.json"); - assertEquals("{}", FileUtils.readFileToString(jsonFile, Charset.defaultCharset())); + File jsonFile = new File(dockerCfgFolder, "config.json"); + assertEquals("{}", FileUtils.readFileToString(jsonFile, Charset.defaultCharset())); } @Test - public void materialize_userConfigFileWithAuthsAndProxies_createdWithProxies() throws Exception { - // arrange - File cfgFile = new File(new File(tempFolder.getRoot(), ".docker"), "config.json"); - FileUtils.write(cfgFile, "{" + "\"auths\": { \"localhost:5001\": { \"auth\": \"whatever\", \"email\": \"\"} }," - + "\"proxies\": { \"default\": { \"httpProxy\": \"proxy\", \"noProxy\": \"something\" } }" + "}", Charset.defaultCharset()); - - // act - KeyMaterial material = factory.materialize(); - - // assert - String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); - assertNotNull(dockerCfgFolderPath); - - File dockerCfgFolder = new File(dockerCfgFolderPath); - assertTrue(dockerCfgFolder.exists()); - - String[] files = dockerCfgFolder.list(); - assertThat(files, arrayContaining("config.json")); - - File jsonFile = new File(dockerCfgFolder, "config.json"); - assertEquals("{\"proxies\":{\"default\":{\"httpProxy\":\"proxy\",\"noProxy\":\"something\"}}}", - FileUtils.readFileToString(jsonFile, Charset.defaultCharset())); + void materialize_userConfigFileWithAuthsAndProxies_createdWithProxies() throws Exception { + // arrange + File cfgFile = new File(new File(tempFolder, ".docker"), "config.json"); + FileUtils.write( + cfgFile, + "{" + "\"auths\": { \"localhost:5001\": { \"auth\": \"whatever\", \"email\": \"\"} }," + + "\"proxies\": { \"default\": { \"httpProxy\": \"proxy\", \"noProxy\": \"something\" } }" + + "}", + Charset.defaultCharset()); + + // act + KeyMaterial material = factory.materialize(); + + // assert + String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); + assertNotNull(dockerCfgFolderPath); + + File dockerCfgFolder = new File(dockerCfgFolderPath); + assertTrue(dockerCfgFolder.exists()); + + String[] files = dockerCfgFolder.list(); + assertThat(files, arrayContaining("config.json")); + + File jsonFile = new File(dockerCfgFolder, "config.json"); + assertEquals( + "{\"proxies\":{\"default\":{\"httpProxy\":\"proxy\",\"noProxy\":\"something\"}}}", + FileUtils.readFileToString(jsonFile, Charset.defaultCharset())); } @Test - public void materialize_userConfigFileWithCredStoreAndHttpHeaders_createdWithHeaders() throws Exception { - // arrange - File cfgFile = new File(new File(tempFolder.getRoot(), ".docker"), "config.json"); - FileUtils.write(cfgFile, "{" + "\"credsStore\" : \"osxkeychain\", " - + "\"HttpHeaders\" : {\"User-Agent\" : \"Docker-Client\"}" + "}", Charset.defaultCharset()); - - // act - KeyMaterial material = factory.materialize(); - - // assert - String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); - assertNotNull(dockerCfgFolderPath); - - File dockerCfgFolder = new File(dockerCfgFolderPath); - assertTrue(dockerCfgFolder.exists()); - - String[] files = dockerCfgFolder.list(); - assertThat(files, arrayContaining("config.json")); - - File jsonFile = new File(dockerCfgFolder, "config.json"); - assertEquals("{\"HttpHeaders\":{\"User-Agent\":\"Docker-Client\"}}", FileUtils.readFileToString(jsonFile, Charset.defaultCharset())); + void materialize_userConfigFileWithCredStoreAndHttpHeaders_createdWithHeaders() throws Exception { + // arrange + File cfgFile = new File(new File(tempFolder, ".docker"), "config.json"); + FileUtils.write( + cfgFile, + "{" + "\"credsStore\" : \"osxkeychain\", " + "\"HttpHeaders\" : {\"User-Agent\" : \"Docker-Client\"}" + + "}", + Charset.defaultCharset()); + + // act + KeyMaterial material = factory.materialize(); + + // assert + String dockerCfgFolderPath = material.env().get("DOCKER_CONFIG", null); + assertNotNull(dockerCfgFolderPath); + + File dockerCfgFolder = new File(dockerCfgFolderPath); + assertTrue(dockerCfgFolder.exists()); + + String[] files = dockerCfgFolder.list(); + assertThat(files, arrayContaining("config.json")); + + File jsonFile = new File(dockerCfgFolder, "config.json"); + assertEquals( + "{\"HttpHeaders\":{\"User-Agent\":\"Docker-Client\"}}", + FileUtils.readFileToString(jsonFile, Charset.defaultCharset())); } + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/tools/DockerToolInstallerTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/tools/DockerToolInstallerTest.java index bf2201e0..d1b7ea97 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/tools/DockerToolInstallerTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/tools/DockerToolInstallerTest.java @@ -23,6 +23,12 @@ */ package org.jenkinsci.plugins.docker.commons.tools; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + import hudson.FilePath; import hudson.Functions; import hudson.console.PlainTextConsoleOutputStream; @@ -34,65 +40,92 @@ import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.io.output.TeeOutputStream; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.junit.Assume; -import org.junit.Rule; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class DockerToolInstallerTest { - - @Rule - public JenkinsRule r = new JenkinsRule(); +@WithJenkins +class DockerToolInstallerTest { @Issue({"JENKINS-48674"}) @WithoutJenkins @Test - public void testImageUrl() throws MalformedURLException { - assertEquals(new URL("https://get.docker.com/builds/Linux/x86_64/docker-1.10.0"), DockerToolInstaller.getDockerImageUrl("linux/x86_64", "1.10.0")); - assertEquals(new URL("https://get.docker.com/builds/Windows/x86_64/docker-1.10.0"), DockerToolInstaller.getDockerImageUrl("win/x86_64","1.10.0")); - assertEquals(new URL("https://get.docker.com/builds/Darwin/x86_64/docker-1.10.0"), DockerToolInstaller.getDockerImageUrl("mac/x86_64","1.10.0")); - assertEquals(new URL("https://get.docker.com/builds/Linux/x86_64/docker-17.05.0-ce"), DockerToolInstaller.getDockerImageUrl("linux/x86_64", "17.05.0-ce")); - assertEquals(new URL("https://get.docker.com/builds/Windows/x86_64/docker-17.05.0-ce"), DockerToolInstaller.getDockerImageUrl("win/x86_64","17.05.0-ce")); - assertEquals(new URL("https://get.docker.com/builds/Darwin/x86_64/docker-17.05.0-ce"), DockerToolInstaller.getDockerImageUrl("mac/x86_64","17.05.0-ce")); - assertEquals(new URL("https://get.docker.com/builds/Linux/x86_64/docker-latest"), DockerToolInstaller.getDockerImageUrl("linux/x86_64", "latest")); - assertEquals(new URL("https://get.docker.com/builds/Windows/x86_64/docker-latest"), DockerToolInstaller.getDockerImageUrl("win/x86_64","latest")); - assertEquals(new URL("https://get.docker.com/builds/Darwin/x86_64/docker-latest"), DockerToolInstaller.getDockerImageUrl("mac/x86_64","latest")); - assertEquals(new URL("https://download.docker.com/linux/static/stable/x86_64/docker-17.09.0-ce"), DockerToolInstaller.getDockerImageUrl("linux/x86_64", "17.09.0-ce")); - assertEquals(new URL("https://download.docker.com/win/static/stable/x86_64/docker-17.09.0-ce"), DockerToolInstaller.getDockerImageUrl("win/x86_64","17.09.0-ce")); - assertEquals(new URL("https://download.docker.com/mac/static/stable/x86_64/docker-17.09.0-ce"), DockerToolInstaller.getDockerImageUrl("mac/x86_64","17.09.0-ce")); - assertEquals(new URL("https://download.docker.com/linux/static/stable/x86_64/docker-20.10.6"), DockerToolInstaller.getDockerImageUrl("linux/x86_64", "20.10.6")); - assertEquals(new URL("https://download.docker.com/win/static/stable/x86_64/docker-20.10.6"), DockerToolInstaller.getDockerImageUrl("win/x86_64","20.10.6")); - assertEquals(new URL("https://download.docker.com/mac/static/stable/x86_64/docker-20.10.6"), DockerToolInstaller.getDockerImageUrl("mac/x86_64","20.10.6")); + void testImageUrl() throws MalformedURLException { + assertEquals( + new URL("https://get.docker.com/builds/Linux/x86_64/docker-1.10.0"), + DockerToolInstaller.getDockerImageUrl("linux/x86_64", "1.10.0")); + assertEquals( + new URL("https://get.docker.com/builds/Windows/x86_64/docker-1.10.0"), + DockerToolInstaller.getDockerImageUrl("win/x86_64", "1.10.0")); + assertEquals( + new URL("https://get.docker.com/builds/Darwin/x86_64/docker-1.10.0"), + DockerToolInstaller.getDockerImageUrl("mac/x86_64", "1.10.0")); + assertEquals( + new URL("https://get.docker.com/builds/Linux/x86_64/docker-17.05.0-ce"), + DockerToolInstaller.getDockerImageUrl("linux/x86_64", "17.05.0-ce")); + assertEquals( + new URL("https://get.docker.com/builds/Windows/x86_64/docker-17.05.0-ce"), + DockerToolInstaller.getDockerImageUrl("win/x86_64", "17.05.0-ce")); + assertEquals( + new URL("https://get.docker.com/builds/Darwin/x86_64/docker-17.05.0-ce"), + DockerToolInstaller.getDockerImageUrl("mac/x86_64", "17.05.0-ce")); + assertEquals( + new URL("https://get.docker.com/builds/Linux/x86_64/docker-latest"), + DockerToolInstaller.getDockerImageUrl("linux/x86_64", "latest")); + assertEquals( + new URL("https://get.docker.com/builds/Windows/x86_64/docker-latest"), + DockerToolInstaller.getDockerImageUrl("win/x86_64", "latest")); + assertEquals( + new URL("https://get.docker.com/builds/Darwin/x86_64/docker-latest"), + DockerToolInstaller.getDockerImageUrl("mac/x86_64", "latest")); + assertEquals( + new URL("https://download.docker.com/linux/static/stable/x86_64/docker-17.09.0-ce"), + DockerToolInstaller.getDockerImageUrl("linux/x86_64", "17.09.0-ce")); + assertEquals( + new URL("https://download.docker.com/win/static/stable/x86_64/docker-17.09.0-ce"), + DockerToolInstaller.getDockerImageUrl("win/x86_64", "17.09.0-ce")); + assertEquals( + new URL("https://download.docker.com/mac/static/stable/x86_64/docker-17.09.0-ce"), + DockerToolInstaller.getDockerImageUrl("mac/x86_64", "17.09.0-ce")); + assertEquals( + new URL("https://download.docker.com/linux/static/stable/x86_64/docker-20.10.6"), + DockerToolInstaller.getDockerImageUrl("linux/x86_64", "20.10.6")); + assertEquals( + new URL("https://download.docker.com/win/static/stable/x86_64/docker-20.10.6"), + DockerToolInstaller.getDockerImageUrl("win/x86_64", "20.10.6")); + assertEquals( + new URL("https://download.docker.com/mac/static/stable/x86_64/docker-20.10.6"), + DockerToolInstaller.getDockerImageUrl("mac/x86_64", "20.10.6")); } @Issue({"JENKINS-36082", "JENKINS-32790", "JENKINS-48674"}) @Test - public void smokes() throws Exception { - Assume.assumeFalse(Functions.isWindows()); + void smokes(JenkinsRule r) throws Exception { + Assumptions.assumeFalse(Functions.isWindows()); try { new URL("https://get.docker.com/").openStream().close(); new URL("https://download.docker.com/").openStream().close(); } catch (IOException x) { - Assume.assumeNoException("Cannot contact download sites, perhaps test machine is not online", x); + assumeTrue(false, "Cannot contact download sites, perhaps test machine is not online:" + x); } String[] testedVersions = {"20.10.6", "19.03.9"}; DockerTool[] installations = new DockerTool[testedVersions.length]; for (int i = 0; i < testedVersions.length; i++) { String v = testedVersions[i]; - installations[i] = new DockerTool(v, "", Collections.singletonList(new InstallSourceProperty(Collections.singletonList(new DockerToolInstaller("", v))))); + installations[i] = new DockerTool( + v, + "", + Collections.singletonList( + new InstallSourceProperty(Collections.singletonList(new DockerToolInstaller("", v))))); } r.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class).setInstallations(installations); DumbSlave slave = r.createOnlineSlave(); @@ -104,16 +137,20 @@ public void smokes() throws Exception { files.add(exe); files.add(toolDir.child(v + "/.timestamp")); } - assertThat("we do not have any extra files in here", toolDir.list("**"), arrayContainingInAnyOrder(files.toArray(new FilePath[files.size()]))); + assertThat( + "we do not have any extra files in here", + toolDir.list("**"), + arrayContainingInAnyOrder(files.toArray(new FilePath[0]))); } - private FilePath downloadDocker(DumbSlave slave, FilePath toolDir, String version) throws IOException, InterruptedException { + private static FilePath downloadDocker(DumbSlave slave, FilePath toolDir, String version) + throws IOException, InterruptedException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(baos, new PlainTextConsoleOutputStream(System.err)); - TaskListener l = new StreamTaskListener(tee); + TaskListener l = new StreamTaskListener(tee, StandardCharsets.UTF_8); ByteArrayOutputStream errStream = new ByteArrayOutputStream(); - FilePath exe = toolDir.child(version+"/bin/docker"); + FilePath exe = toolDir.child(version + "/bin/docker"); // Download for first time: assertEquals(exe.getRemote(), DockerTool.getExecutable(version, slave, l, null)); assertTrue(exe.exists()); @@ -122,10 +159,18 @@ private FilePath downloadDocker(DumbSlave slave, FilePath toolDir, String versio baos.reset(); assertEquals(exe.getRemote(), DockerTool.getExecutable(version, slave, l, null)); assertTrue(exe.exists()); - assertThat(baos.toString(), not(containsString(Messages.DockerToolInstaller_downloading_docker_client_(version)))); + assertThat( + baos.toString(), not(containsString(Messages.DockerToolInstaller_downloading_docker_client_(version)))); // Version check: baos.reset(); - if (slave.createLauncher(l).launch().cmds(exe.getRemote(), "version", "--format", "{{.Client.Version}}").quiet(true).stdout(tee).stderr(errStream).join() != 0) { + if (slave.createLauncher(l) + .launch() + .cmds(exe.getRemote(), "version", "--format", "{{.Client.Version}}") + .quiet(true) + .stdout(tee) + .stderr(errStream) + .join() + != 0) { /* Failure message should mention /var/run/docker.sock */ assertThat(errStream.toString(), containsString("/var/run/docker.sock")); } else { @@ -136,5 +181,4 @@ private FilePath downloadDocker(DumbSlave slave, FilePath toolDir, String versio } return exe; } - } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/tools/DockerToolTest.java b/src/test/java/org/jenkinsci/plugins/docker/commons/tools/DockerToolTest.java index 539d2eef..dfd6b93d 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/tools/DockerToolTest.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/tools/DockerToolTest.java @@ -24,31 +24,34 @@ package org.jenkinsci.plugins.docker.commons.tools; +import static org.junit.jupiter.api.Assertions.assertEquals; + import hudson.slaves.DumbSlave; import hudson.tools.ToolLocationNodeProperty; -import hudson.tools.ToolProperty; import hudson.util.StreamTaskListener; import java.util.Collections; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Rule; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class DockerToolTest { - - @Rule public JenkinsRule r = new JenkinsRule(); +@WithJenkins +class DockerToolTest { - @Test public void getExecutable() throws Exception { + @Test + void getExecutable(JenkinsRule r) throws Exception { assertEquals(DockerTool.COMMAND, DockerTool.getExecutable(null, null, null, null)); DockerTool.DescriptorImpl descriptor = r.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class); String name = "docker15"; - descriptor.setInstallations(new DockerTool(name, "/usr/local/docker15", Collections.>emptyList())); - // TODO r.jenkins.restart() does not reproduce need for get/setInstallations; use RestartableJenkinsRule in 1.567+ + descriptor.setInstallations(new DockerTool(name, "/usr/local/docker15", Collections.emptyList())); + // TODO r.jenkins.restart() does not reproduce need for get/setInstallations; use RestartableJenkinsRule in + // 1.567+ assertEquals("/usr/local/docker15/bin/docker", DockerTool.getExecutable(name, null, null, null)); DumbSlave slave = r.createOnlineSlave(); - slave.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation(descriptor, name, "/opt/docker"))); + slave.getNodeProperties() + .add(new ToolLocationNodeProperty( + new ToolLocationNodeProperty.ToolLocation(descriptor, name, "/opt/docker"))); assertEquals("/usr/local/docker15/bin/docker", DockerTool.getExecutable(name, null, null, null)); - assertEquals("/opt/docker/bin/docker", DockerTool.getExecutable(name, slave, StreamTaskListener.fromStderr(), null)); + assertEquals( + "/opt/docker/bin/docker", DockerTool.getExecutable(name, slave, StreamTaskListener.fromStderr(), null)); } - } diff --git a/src/test/java/org/jenkinsci/plugins/docker/commons/util/SampleDockerBuilder.java b/src/test/java/org/jenkinsci/plugins/docker/commons/util/SampleDockerBuilder.java index 53135174..60a2f18f 100644 --- a/src/test/java/org/jenkinsci/plugins/docker/commons/util/SampleDockerBuilder.java +++ b/src/test/java/org/jenkinsci/plugins/docker/commons/util/SampleDockerBuilder.java @@ -25,11 +25,6 @@ import edu.umd.cs.findbugs.annotations.NonNull; import hudson.EnvVars; -import org.jenkinsci.plugins.docker.commons.tools.DockerTool; -import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory; -import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial; -import org.jenkinsci.plugins.docker.commons.credentials.DockerServerEndpoint; -import org.jenkinsci.plugins.docker.commons.credentials.DockerRegistryEndpoint; import hudson.Extension; import hudson.Launcher; import hudson.Util; @@ -38,9 +33,13 @@ import hudson.model.BuildListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; -import org.kohsuke.stapler.DataBoundConstructor; - import java.io.IOException; +import org.jenkinsci.plugins.docker.commons.credentials.DockerRegistryEndpoint; +import org.jenkinsci.plugins.docker.commons.credentials.DockerServerEndpoint; +import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterial; +import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory; +import org.jenkinsci.plugins.docker.commons.tools.DockerTool; +import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; public class SampleDockerBuilder extends Builder { @@ -70,33 +69,42 @@ public String getToolName() { return toolName; } - @DataBoundSetter public void setToolName(String toolName) { + @DataBoundSetter + public void setToolName(String toolName) { this.toolName = Util.fixEmpty(toolName); } @Override - public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { + public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) + throws InterruptedException, IOException { EnvVars env = build.getEnvironment(listener); // prepare the credentials to talk to this docker and make it available for docker you'll be forking String dockerExecutable = DockerTool.getExecutable(toolName, build.getBuiltOn(), listener, env); - KeyMaterialFactory keyMaterialFactory = server.newKeyMaterialFactory(build).plus(registry.newKeyMaterialFactory(build.getParent(), build.getWorkspace(), launcher, env, listener, dockerExecutable)); + KeyMaterialFactory keyMaterialFactory = server.newKeyMaterialFactory(build) + .plus(registry.newKeyMaterialFactory( + build.getParent(), build.getWorkspace(), launcher, env, listener, dockerExecutable)); try (KeyMaterial key = keyMaterialFactory.materialize()) { // fork docker with appropriate environment to interact with this docker daemon - return launcher.launch().cmds(dockerExecutable, "info").envs(key.env()).join() == 0; + return launcher.launch() + .cmds(dockerExecutable, "info") + .envs(key.env()) + .join() + == 0; } } - @Extension public static class DescriptorImpl extends BuildStepDescriptor { + @Extension + public static class DescriptorImpl extends BuildStepDescriptor { @NonNull - @Override public String getDisplayName() { + @Override + public String getDisplayName() { return "Get Docker Info"; } - @Override public boolean isApplicable(Class jobType) { + @Override + public boolean isApplicable(Class jobType) { return true; } - } - }