diff --git a/pom.xml b/pom.xml index b82ba3e..20d682f 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.jenkins-ci.plugins plugin - 5.4 + 5.9 @@ -50,7 +50,7 @@ jenkinsci/${project.artifactId}-plugin 2.479 - ${jenkins.baseline}.1 + ${jenkins.baseline}.3 10.3.3 3.27.3 @@ -60,7 +60,7 @@ io.jenkins.tools.bom bom-${jenkins.baseline}.x - 3944.v1a_e4f8b_452db_ + 4545.v56392b_7ca_7b_a_ import pom diff --git a/src/test/java/jenkins/plugins/nodejs/CIBuilderHelper.java b/src/test/java/jenkins/plugins/nodejs/CIBuilderHelper.java index 85c68e3..406a5e2 100644 --- a/src/test/java/jenkins/plugins/nodejs/CIBuilderHelper.java +++ b/src/test/java/jenkins/plugins/nodejs/CIBuilderHelper.java @@ -34,7 +34,7 @@ /* package */ final class CIBuilderHelper { - public static interface Verifier { + public interface Verifier { void verify(AbstractBuild build, Launcher launcher, TaskListener listener) throws Exception; } @@ -64,7 +64,7 @@ private MockCommandInterpreterBuilder(String command, String nodeJSInstallationN } @Override - protected boolean internalPerform(AbstractBuild build, Launcher launcher, TaskListener listener) throws InterruptedException { + protected boolean internalPerform(AbstractBuild build, Launcher launcher, TaskListener listener) { if (verifier != null) { try { verifier.verify(build, launcher, listener); diff --git a/src/test/java/jenkins/plugins/nodejs/CredentialMaskingTest.java b/src/test/java/jenkins/plugins/nodejs/CredentialMaskingTest.java index 3c69fb9..06e6cad 100644 --- a/src/test/java/jenkins/plugins/nodejs/CredentialMaskingTest.java +++ b/src/test/java/jenkins/plugins/nodejs/CredentialMaskingTest.java @@ -24,6 +24,7 @@ package jenkins.plugins.nodejs; import java.io.File; +import java.io.IOException; import java.util.Collections; import java.util.List; @@ -32,12 +33,10 @@ import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.jvnet.hudson.test.BuildWatcher; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; @@ -53,20 +52,23 @@ import jenkins.plugins.nodejs.tools.NodeJSInstallation; import jenkins.plugins.nodejs.tools.NodeJSInstaller; import jenkins.plugins.nodejs.tools.Platform; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class CredentialMaskingTest { +@WithJenkins +class CredentialMaskingTest { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + private File temp; - @Rule - public BuildWatcher buildWatcher = new BuildWatcher(); + private static JenkinsRule r; - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } - @Before - public void setupConfigWithCredentials() throws Exception { + @BeforeEach + void setupConfigWithCredentials() throws Exception { UsernamePasswordCredentialsImpl credential = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "usercreds", "", "bot", "s3cr3t"); credential.setUsernameSecret(true); SystemCredentialsProvider.getInstance().getCredentials().add(credential); @@ -86,7 +88,7 @@ public void setupConfigWithCredentials() throws Exception { @Test @Issue("SECURITY-3196") - public void testNPMConfigFileWithConfigFileProviderBlock() throws Exception { + void testNPMConfigFileWithConfigFileProviderBlock() throws Exception { WorkflowJob p = r.createProject(WorkflowJob.class, "p1"); p.setDefinition(new CpsFlowDefinition( String.join("\n", @@ -125,10 +127,10 @@ public void testNPMConfigFileWithConfigFileProviderBlock() throws Exception { @Test @Issue("SECURITY-3196") - public void testNPMConfigFileWithNodejsBlock() throws Exception { + void testNPMConfigFileWithNodejsBlock() throws Exception { // fake enough of a nodejs install. Platform platform = Platform.current(); - File dir = temp.newFolder("node-js-dist"); + File dir = newFolder(temp, "node-js-dist"); File bin = new File(dir, platform.binFolder); bin.mkdir(); new File(bin, platform.nodeFileName).createNewFile(); @@ -172,4 +174,13 @@ public void testNPMConfigFileWithNodejsBlock() throws Exception { // stringcreds r.assertLogNotContains("sensitive", b1); } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/jenkins/plugins/nodejs/JCasCTest.java b/src/test/java/jenkins/plugins/nodejs/JCasCTest.java index 256eb93..2373ee7 100644 --- a/src/test/java/jenkins/plugins/nodejs/JCasCTest.java +++ b/src/test/java/jenkins/plugins/nodejs/JCasCTest.java @@ -31,15 +31,14 @@ import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.hamcrest.Matchers.is; import java.util.List; +import io.jenkins.plugins.casc.misc.junit.jupiter.AbstractRoundTripTest; import org.jenkinsci.lib.configprovider.model.Config; import org.jenkinsci.plugins.configfiles.ConfigFiles; -import org.junit.Assert; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import org.jvnet.hudson.test.JenkinsRule; import hudson.tools.BatchCommandInstaller; import hudson.tools.CommandInstaller; @@ -50,19 +49,18 @@ import hudson.tools.ToolPropertyDescriptor; import hudson.tools.ZipExtractionInstaller; import hudson.util.DescribableList; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; import jenkins.model.Jenkins; import jenkins.plugins.nodejs.configfiles.NPMConfig; import jenkins.plugins.nodejs.configfiles.NPMRegistry; import jenkins.plugins.nodejs.tools.NodeJSInstallation; import jenkins.plugins.nodejs.tools.NodeJSInstaller; -public class JCasCTest extends RoundTripAbstractTest { +class JCasCTest extends AbstractRoundTripTest { @Override - protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { - checkConfigFile(restartableJenkinsRule.j.jenkins); - checkInstallations(restartableJenkinsRule.j.jenkins); + protected void assertConfiguredAsExpected(JenkinsRule j, String s) { + checkConfigFile(j.jenkins); + checkInstallations(j.jenkins); } private void checkConfigFile(Jenkins j) { @@ -70,27 +68,27 @@ private void checkConfigFile(Jenkins j) { assertThat(config, instanceOf(NPMConfig.class)); NPMConfig npmConfig = (NPMConfig) config; - assertEquals("myComment", npmConfig.comment); - assertEquals("myContent", npmConfig.content); - assertEquals("myConfig", npmConfig.name); - assertEquals(true, npmConfig.isNpm9Format()); + assertThat(npmConfig.comment, equalTo("myComment")); + assertThat( npmConfig.content, equalTo("myContent")); + assertThat(npmConfig.name, equalTo("myConfig")); + assertThat(npmConfig.isNpm9Format(), is(true)); List registries = npmConfig.getRegistries(); - Assert.assertTrue(registries.size() == 1); + assertThat(registries, hasSize(1)); NPMRegistry registry = registries.get(0); - assertTrue(registry.isHasScopes()); - assertEquals("myScope", registry.getScopes()); - assertEquals("registryUrl", registry.getUrl()); + assertThat(registry.isHasScopes(), is(true)); + assertThat(registry.getScopes(), equalTo("myScope")); + assertThat(registry.getUrl(), equalTo("registryUrl")); } private void checkInstallations(Jenkins j) { - final ToolDescriptor descriptor = (ToolDescriptor) j.getDescriptor(NodeJSInstallation.class); + final ToolDescriptor descriptor = (ToolDescriptor) j.getDescriptor(NodeJSInstallation.class); final ToolInstallation[] installations = descriptor.getInstallations(); assertThat(installations, arrayWithSize(2)); ToolInstallation withInstaller = installations[0]; - assertEquals("myNode", withInstaller.getName()); + assertThat( withInstaller.getName(), equalTo("myNode")); final DescribableList, ToolPropertyDescriptor> properties = withInstaller.getProperties(); assertThat(properties, hasSize(1)); diff --git a/src/test/java/jenkins/plugins/nodejs/NodeJSBuildWrapperTest.java b/src/test/java/jenkins/plugins/nodejs/NodeJSBuildWrapperTest.java index 407fbd8..73ede50 100644 --- a/src/test/java/jenkins/plugins/nodejs/NodeJSBuildWrapperTest.java +++ b/src/test/java/jenkins/plugins/nodejs/NodeJSBuildWrapperTest.java @@ -23,7 +23,7 @@ */ package jenkins.plugins.nodejs; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.doReturn; @@ -33,15 +33,14 @@ import static org.mockito.Mockito.when; import java.io.File; +import java.io.IOException; import java.util.List; -import org.assertj.core.api.Assertions; import org.jenkinsci.lib.configprovider.model.Config; import org.jenkinsci.plugins.configfiles.GlobalConfigFiles; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; @@ -58,16 +57,22 @@ import jenkins.plugins.nodejs.configfiles.NPMRegistry; import jenkins.plugins.nodejs.tools.NodeJSInstallation; import jenkins.plugins.nodejs.tools.Platform; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class NodeJSBuildWrapperTest { +@WithJenkins +class NodeJSBuildWrapperTest { - @ClassRule - public static JenkinsRule j = new JenkinsRule(); - @Rule - public TemporaryFolder fileRule = new TemporaryFolder(); + private static JenkinsRule j; + @TempDir + private File fileRule; + + @BeforeAll + static void setUp(JenkinsRule rule) { + j = rule; + } @Test - public void test_calls_sequence_of_installer() throws Exception { + void test_calls_sequence_of_installer() throws Exception { FreeStyleProject job = j.createFreeStyleProject("free"); NodeJSInstallation installation = mockInstaller(); @@ -83,7 +88,7 @@ public void test_calls_sequence_of_installer() throws Exception { } @Test - public void test_creation_of_config() throws Exception { + void test_creation_of_config() throws Exception { FreeStyleProject job = j.createFreeStyleProject("free2"); final Config config = createSetting("my-config-id", "email=foo@acme.com", null); @@ -99,7 +104,7 @@ public void test_creation_of_config() throws Exception { } @Test - public void test_inject_path_variable() throws Exception { + void test_inject_path_variable() throws Exception { FreeStyleProject job = j.createFreeStyleProject("free3"); final Config config = createSetting("my-config-id", "", null); @@ -120,7 +125,7 @@ public void test_inject_path_variable() throws Exception { @Issue("JENKINS-45840") @Test - public void test_check_no_executable_in_installation_folder() throws Exception { + void test_check_no_executable_in_installation_folder() throws Exception { FreeStyleProject job = j.createFreeStyleProject("free4"); NodeJSInstallation installation = mockInstaller(); @@ -133,10 +138,10 @@ public void test_check_no_executable_in_installation_folder() throws Exception { } @Test - public void test_set_of_cache_location() throws Exception { + void test_set_of_cache_location() throws Exception { FreeStyleProject job = j.createFreeStyleProject("cache"); - final File cacheFolder = fileRule.newFolder(); + final File cacheFolder = newFolder(fileRule, "junit"); NodeJSBuildWrapper bw = mockWrapper(mockInstaller()); bw.setCacheLocationStrategy(new TestCacheLocationLocator(cacheFolder)); @@ -199,11 +204,22 @@ private PathVerifier(NodeJSInstallation installation) { @Override public void verify(EnvVars env) { String expectedValue = installation.getHome(); - assertEquals("Unexpected value for " + NodeJSConstants.ENVVAR_NODEJS_HOME, expectedValue, env.get(NodeJSConstants.ENVVAR_NODEJS_HOME)); - Assertions.assertThat(env.get("PATH")).contains(expectedValue); - // check that PATH is not exact the NodeJS home otherwise means PATH was overridden - Assertions.assertThat(env.get("PATH")).isNotEqualTo(expectedValue); // JENKINS-41947 + assertThat(env) + .as("Unexpected value for " + NodeJSConstants.ENVVAR_NODEJS_HOME).containsEntry(NodeJSConstants.ENVVAR_NODEJS_HOME, expectedValue); + assertThat(env.get("PATH")) + .contains(expectedValue) + // JENKINS-41947 check that PATH is not exact the NodeJS home otherwise means PATH was overridden + .isNotEqualTo(expectedValue); + } + } + + 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; } } \ No newline at end of file diff --git a/src/test/java/jenkins/plugins/nodejs/NodeJSCommandInterpreterTest.java b/src/test/java/jenkins/plugins/nodejs/NodeJSCommandInterpreterTest.java index 3f83870..1cb7488 100644 --- a/src/test/java/jenkins/plugins/nodejs/NodeJSCommandInterpreterTest.java +++ b/src/test/java/jenkins/plugins/nodejs/NodeJSCommandInterpreterTest.java @@ -23,10 +23,7 @@ */ package jenkins.plugins.nodejs; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.doCallRealMethod; @@ -38,54 +35,53 @@ import java.io.IOException; import java.util.List; -import org.assertj.core.api.Assertions; import org.jenkinsci.lib.configprovider.model.Config; import org.jenkinsci.plugins.configfiles.GlobalConfigFiles; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; -import hudson.model.AbstractBuild; import hudson.model.FreeStyleProject; import hudson.model.Node; import hudson.model.Result; import hudson.model.TaskListener; -import jenkins.plugins.nodejs.CIBuilderHelper.Verifier; import jenkins.plugins.nodejs.VerifyEnvVariableBuilder.EnvVarVerifier; import jenkins.plugins.nodejs.configfiles.NPMConfig; import jenkins.plugins.nodejs.configfiles.NPMRegistry; import jenkins.plugins.nodejs.tools.DetectionFailedException; import jenkins.plugins.nodejs.tools.NodeJSInstallation; import jenkins.plugins.nodejs.tools.Platform; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class NodeJSCommandInterpreterTest { +@WithJenkins +class NodeJSCommandInterpreterTest { - @ClassRule - public static JenkinsRule j = new JenkinsRule(); - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + private static JenkinsRule j; + @TempDir + private File folder; + + @BeforeAll + static void setUp(JenkinsRule rule) { + j = rule; + } @Issue("JENKINS-41947") @Test - public void test_inject_path_variable() throws Exception { + void test_inject_path_variable() throws Exception { NodeJSInstallation installation = mockInstaller(); - NodeJSCommandInterpreter builder = CIBuilderHelper.createMock("test_executable_value", installation, null, new CIBuilderHelper.Verifier() { - @Override - public void verify(AbstractBuild build, Launcher launcher, TaskListener listener) throws Exception { - assertFalse("No Environments", build.getEnvironments().isEmpty()); - - EnvVars env = build.getEnvironment(listener); - Assertions.assertThat(env.keySet()).contains(NodeJSConstants.ENVVAR_NODEJS_PATH, NodeJSConstants.ENVVAR_NODEJS_HOME); - assertEquals(getTestHome(), env.get(NodeJSConstants.ENVVAR_NODEJS_HOME)); - assertEquals(getTestHome(), env.get(NodeJSConstants.ENVVAR_NODE_HOME)); - assertEquals(getTestBin(), env.get(NodeJSConstants.ENVVAR_NODEJS_PATH)); - } + NodeJSCommandInterpreter builder = CIBuilderHelper.createMock("test_executable_value", installation, null, (build, launcher, listener) -> { + assertThat(build.getEnvironments()).as("No Environments").isNotEmpty(); + + EnvVars env = build.getEnvironment(listener); + assertThat(env) + .containsEntry(NodeJSConstants.ENVVAR_NODEJS_HOME, getTestHome()) + .containsEntry(NodeJSConstants.ENVVAR_NODE_HOME, getTestHome()) + .containsEntry(NodeJSConstants.ENVVAR_NODEJS_PATH, getTestBin()); }); FreeStyleProject job = j.createFreeStyleProject(); @@ -94,7 +90,7 @@ public void verify(AbstractBuild build, Launcher launcher, TaskListener li } @Test - public void test_executable_value() throws Exception { + void test_executable_value() throws Exception { NodeJSInstallation installation = mockInstaller(); NodeJSCommandInterpreter builder = CIBuilderHelper.createMock("test_executable_value", installation, null); @@ -102,27 +98,24 @@ public void test_executable_value() throws Exception { job.getBuildersList().add(builder); j.assertBuildStatusSuccess(job.scheduleBuild2(0)); - String[] buildCommandLine = builder.buildCommandLine(new FilePath(folder.newFile())); - assertEquals(buildCommandLine[0], getTestExecutable()); + String[] buildCommandLine = builder.buildCommandLine(new FilePath(File.createTempFile("junit", null, folder))); + assertThat(buildCommandLine[0]).isEqualTo(getTestExecutable()); } @Test - public void test_creation_of_config() throws Exception { + void test_creation_of_config() throws Exception { Config config = createSetting("my-config-id", "email=foo@acme.com", null); NodeJSInstallation installation = mockInstaller(); - NodeJSCommandInterpreter builder = CIBuilderHelper.createMock("test_creation_of_config", installation, config.id, new Verifier() { - @Override - public void verify(AbstractBuild build, Launcher launcher, TaskListener listener) throws Exception { - EnvVars env = build.getEnvironment(listener); - - String var = NodeJSConstants.NPM_USERCONFIG; - String value = env.get(var); - - assertTrue("variable " + var + " not set", env.containsKey(var)); - assertNotNull("empty value for environment variable " + var, value); - assertTrue("file of variable " + var + " does not exists or is not a file", new File(value).isFile()); - } + NodeJSCommandInterpreter builder = CIBuilderHelper.createMock("test_creation_of_config", installation, config.id, (build, launcher, listener) -> { + EnvVars env = build.getEnvironment(listener); + + String var = NodeJSConstants.NPM_USERCONFIG; + String value = env.get(var); + + assertThat(env.containsKey(var)).as("variable " + var + " not set").isTrue(); + assertThat(value).as("empty value for environment variable " + var).isNotNull(); + assertThat(new File(value).isFile()).as("file of variable " + var + " does not exists or is not a file").isTrue(); }); FreeStyleProject job = j.createFreeStyleProject(); @@ -131,7 +124,7 @@ public void verify(AbstractBuild build, Launcher launcher, TaskListener li } @Test - public void test_calls_sequence_of_installer() throws Exception { + void test_calls_sequence_of_installer() throws Exception { NodeJSInstallation installation = mockInstaller(); NodeJSCommandInterpreter builder = CIBuilderHelper.createMock("test_creation_of_config", installation, null); @@ -146,7 +139,7 @@ public void test_calls_sequence_of_installer() throws Exception { @Issue("JENKINS-45840") @Test - public void test_check_no_executable_in_installation_folder() throws Exception { + void test_check_no_executable_in_installation_folder() throws Exception { NodeJSInstallation installation = mockInstaller(); when(installation.getExecutable(any(Launcher.class))).thenReturn(null); @@ -158,8 +151,8 @@ public void test_check_no_executable_in_installation_folder() throws Exception { } @Test - public void test_set_of_cache_location() throws Exception { - final File cacheFolder = folder.newFolder(); + void test_set_of_cache_location() throws Exception { + final File cacheFolder = newFolder(folder, "junit"); NodeJSInstallation installation = mockInstaller(); NodeJSCommandInterpreter builder = CIBuilderHelper.createMock("test_creation_of_config", installation); @@ -202,4 +195,13 @@ private String getTestBin() throws DetectionFailedException { private String getTestHome() { return new File("/home", "nodejs").getAbsolutePath(); } + + 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; + } } \ No newline at end of file diff --git a/src/test/java/jenkins/plugins/nodejs/NodeJSSerialisationTest.java b/src/test/java/jenkins/plugins/nodejs/NodeJSSerialisationTest.java index 637e51f..ea7d918 100644 --- a/src/test/java/jenkins/plugins/nodejs/NodeJSSerialisationTest.java +++ b/src/test/java/jenkins/plugins/nodejs/NodeJSSerialisationTest.java @@ -23,24 +23,29 @@ */ package jenkins.plugins.nodejs; -import org.assertj.core.api.Assertions; -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.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; import hudson.model.FreeStyleProject; + import jenkins.plugins.nodejs.cache.DefaultCacheLocationLocator; import jenkins.plugins.nodejs.cache.PerJobCacheLocationLocator; -public class NodeJSSerialisationTest { +import static org.assertj.core.api.Assertions.assertThat; + +@WithJenkins +class NodeJSSerialisationTest { - @Rule - public JenkinsRule j = new JenkinsRule(); - @Rule - public TemporaryFolder fileRule = new TemporaryFolder(); + private JenkinsRule j; + + @BeforeEach + void setUp(JenkinsRule rule) { + j = rule; + } /** * Verify that the serialisation is backward compatible. @@ -48,14 +53,14 @@ public class NodeJSSerialisationTest { @LocalData @Test @Issue("JENKINS-57844") - public void test_serialisation_is_compatible_with_version_1_2_x_interpreter() throws Exception { + void test_serialisation_is_compatible_with_version_1_2_x_interpreter() { FreeStyleProject prj = j.jenkins.getAllItems(hudson.model.FreeStyleProject.class) // .stream() // .filter(p -> "test".equals(p.getName())) // .findFirst().get(); NodeJSCommandInterpreter step = prj.getBuildersList().get(NodeJSCommandInterpreter.class); - Assertions.assertThat(step.getCacheLocationStrategy()).isInstanceOf(DefaultCacheLocationLocator.class); + assertThat(step.getCacheLocationStrategy()).isInstanceOf(DefaultCacheLocationLocator.class); } /** @@ -64,14 +69,14 @@ public void test_serialisation_is_compatible_with_version_1_2_x_interpreter() th @LocalData @Test @Issue("JENKINS-58029") - public void test_reloading_job_configuration_contains_saved_cache_strategy_interpreter() throws Exception { + void test_reloading_job_configuration_contains_saved_cache_strategy_interpreter() { FreeStyleProject prj = j.jenkins.getAllItems(hudson.model.FreeStyleProject.class) // .stream() // .filter(p -> "test".equals(p.getName())) // .findFirst().get(); NodeJSCommandInterpreter step = prj.getBuildersList().get(NodeJSCommandInterpreter.class); - Assertions.assertThat(step.getCacheLocationStrategy()).isInstanceOf(PerJobCacheLocationLocator.class); + assertThat(step.getCacheLocationStrategy()).isInstanceOf(PerJobCacheLocationLocator.class); } /** @@ -80,14 +85,14 @@ public void test_reloading_job_configuration_contains_saved_cache_strategy_inter @LocalData @Test @Issue("JENKINS-57844") - public void test_serialisation_is_compatible_with_version_1_2_x_buildWrapper() throws Exception { + void test_serialisation_is_compatible_with_version_1_2_x_buildWrapper() { FreeStyleProject prj = j.jenkins.getAllItems(hudson.model.FreeStyleProject.class) // .stream() // .filter(p -> "test".equals(p.getName())) // .findFirst().get(); NodeJSBuildWrapper step = prj.getBuildWrappersList().get(NodeJSBuildWrapper.class); - Assertions.assertThat(step.getCacheLocationStrategy()).isInstanceOf(DefaultCacheLocationLocator.class); + assertThat(step.getCacheLocationStrategy()).isInstanceOf(DefaultCacheLocationLocator.class); } /** @@ -96,14 +101,14 @@ public void test_serialisation_is_compatible_with_version_1_2_x_buildWrapper() t @LocalData @Test @Issue("JENKINS-58029") - public void test_reloading_job_configuration_contains_saved_cache_strategy_buildWrapper() throws Exception { + void test_reloading_job_configuration_contains_saved_cache_strategy_buildWrapper() { FreeStyleProject prj = j.jenkins.getAllItems(hudson.model.FreeStyleProject.class) // .stream() // .filter(p -> "test".equals(p.getName())) // .findFirst().get(); NodeJSBuildWrapper step = prj.getBuildWrappersList().get(NodeJSBuildWrapper.class); - Assertions.assertThat(step.getCacheLocationStrategy()).isInstanceOf(PerJobCacheLocationLocator.class); + assertThat(step.getCacheLocationStrategy()).isInstanceOf(PerJobCacheLocationLocator.class); } } \ No newline at end of file diff --git a/src/test/java/jenkins/plugins/nodejs/NpmrcFileSupplyTest.java b/src/test/java/jenkins/plugins/nodejs/NpmrcFileSupplyTest.java index 9b95558..a888a0e 100644 --- a/src/test/java/jenkins/plugins/nodejs/NpmrcFileSupplyTest.java +++ b/src/test/java/jenkins/plugins/nodejs/NpmrcFileSupplyTest.java @@ -23,9 +23,6 @@ */ package jenkins.plugins.nodejs; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.io.File; import java.util.ArrayList; import java.util.Arrays; @@ -35,8 +32,8 @@ import org.jenkinsci.lib.configprovider.model.ConfigFile; import org.jenkinsci.lib.configprovider.model.ConfigFileManager; import org.jenkinsci.plugins.configfiles.GlobalConfigFiles; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import com.cloudbees.plugins.credentials.CredentialsScope; @@ -49,14 +46,22 @@ import jenkins.plugins.nodejs.configfiles.NPMConfig; import jenkins.plugins.nodejs.configfiles.NPMRegistry; import jenkins.plugins.nodejs.configfiles.Npmrc; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +import static org.assertj.core.api.Assertions.assertThat; -public class NpmrcFileSupplyTest { +@WithJenkins +class NpmrcFileSupplyTest { - @Rule - public JenkinsRule j = new JenkinsRule(); + private JenkinsRule j; + + @BeforeEach + void setUp(JenkinsRule rule) { + j = rule; + } @Test - public void test_supply_npmrc_with_registry() throws Exception { + void test_supply_npmrc_with_registry() throws Exception { StandardUsernameCredentials user = createUser("test-user-id", "myuser", "mypassword"); NPMRegistry privateRegistry = new NPMRegistry("https://private.organization.com/", user.getId(), null); NPMRegistry officalRegistry = new NPMRegistry("https://registry.npmjs.org/", null, "@user1 user2"); @@ -65,13 +70,13 @@ public void test_supply_npmrc_with_registry() throws Exception { FreeStyleBuild build = j.buildAndAssertSuccess(j.createFreeStyleProject()); - FilePath npmrcFile = ConfigFileManager.provisionConfigFile(new ConfigFile(config.id, null, true), null, build, build.getWorkspace(), j.createTaskListener(), new ArrayList(1)); - assertTrue(npmrcFile.exists()); - assertTrue(npmrcFile.length() > 0); + FilePath npmrcFile = ConfigFileManager.provisionConfigFile(new ConfigFile(config.id, null, true), null, build, build.getWorkspace(), j.createTaskListener(), new ArrayList<>(1)); + assertThat(npmrcFile.exists()).isTrue(); + assertThat(npmrcFile.length()).isGreaterThan(0); Npmrc npmrc = Npmrc.load(new File(npmrcFile.getRemote())); - assertTrue("Missing setting email", npmrc.contains("email")); - assertEquals("Unexpected value from settings email", "guest@example.com", npmrc.get("email")); + assertThat(npmrc.contains("email")).as("Missing setting email").isTrue(); + assertThat(npmrc.get("email")).as("Unexpected value from settings email").isEqualTo("guest@example.com"); } private StandardUsernameCredentials createUser(String id, String username, String password) throws FormException { diff --git a/src/test/java/jenkins/plugins/nodejs/SimpleNodeJSCommandInterpreterTest.java b/src/test/java/jenkins/plugins/nodejs/SimpleNodeJSCommandInterpreterTest.java index 1d44f80..f773343 100644 --- a/src/test/java/jenkins/plugins/nodejs/SimpleNodeJSCommandInterpreterTest.java +++ b/src/test/java/jenkins/plugins/nodejs/SimpleNodeJSCommandInterpreterTest.java @@ -25,22 +25,22 @@ import hudson.FilePath; import hudson.model.Descriptor; -import jenkins.plugins.nodejs.Messages; import jenkins.plugins.nodejs.tools.NodeJSInstallation; import hudson.tasks.Builder; -import hudson.tools.ToolProperty; -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.junit.jupiter.WithJenkins; +import java.io.File; import java.io.IOException; import java.util.Collections; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; -public class SimpleNodeJSCommandInterpreterTest { +@WithJenkins +class SimpleNodeJSCommandInterpreterTest { private static final String COMMAND = "var sys = require('sys'); sys.puts('build number: ' + process.env['BUILD_NUMBER']);"; @@ -48,49 +48,59 @@ public class SimpleNodeJSCommandInterpreterTest { private Descriptor descriptor; private NodeJSInstallation installation; - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + private File tempFolder; - @Before - public void setUp() { - installation = new NodeJSInstallation("11.0.0", "", Collections.>emptyList()); + @BeforeEach + void setUp() { + installation = new NodeJSInstallation("11.0.0", "", Collections.emptyList()); interpreter = new NodeJSCommandInterpreter(COMMAND, installation.getName(), null); descriptor = new NodeJSCommandInterpreter.NodeJsDescriptor(); } @Test - public void testGetContentsShouldGiveExpectedValue() { - assertEquals(COMMAND, interpreter.getCommand()); + void testGetContentsShouldGiveExpectedValue() { + assertThat(interpreter.getCommand()).isEqualTo(COMMAND); } @Test - public void testGetContentWithEmptyCommandShouldGiveExpectedValue() { - assertEquals("", new NodeJSCommandInterpreter("", installation.getName(), null).getCommand()); + void testGetContentWithEmptyCommandShouldGiveExpectedValue() { + assertThat(new NodeJSCommandInterpreter("", installation.getName(), null).getCommand()).isEmpty(); } @Test - public void testGetContentWithNullCommandShouldGiveExpectedValue() { - assertNull(new NodeJSCommandInterpreter(null, installation.getName(), null).getCommand()); + void testGetContentWithNullCommandShouldGiveExpectedValue() { + assertThat(new NodeJSCommandInterpreter(null, installation.getName(), null).getCommand()).isNull(); } @Test - public void testGetFileExtensionShouldGiveExpectedValue() throws IOException, InterruptedException { - assertEquals(true, interpreter.createScriptFile(new FilePath(tempFolder.newFolder())).getName().endsWith(".js")); + void testGetFileExtensionShouldGiveExpectedValue() throws IOException, InterruptedException { + assertThat(interpreter.createScriptFile(new FilePath(newFolder(tempFolder, "junit"))).getName()).endsWith(".js"); } @Test - public void testGetDescriptorShouldGiveExpectedValue() { - assertNotNull(descriptor); - assertTrue(descriptor instanceof Descriptor); + void testGetDescriptorShouldGiveExpectedValue() { + assertThat(descriptor) + .isNotNull() + .isInstanceOf(Descriptor.class); } @Test - public void testDescriptorGetDisplayNameShouldGiveExpectedValue() { - assertEquals(Messages.NodeJSCommandInterpreter_displayName(), descriptor.getDisplayName()); + void testDescriptorGetDisplayNameShouldGiveExpectedValue() { + assertThat(descriptor.getDisplayName()).isEqualTo(Messages.NodeJSCommandInterpreter_displayName()); } @Test - public void testDescriptorGetHelpFileShouldGiveExpectedValue() { - assertEquals("/plugin/nodejs/help.html", descriptor.getHelpFile()); + void testDescriptorGetHelpFileShouldGiveExpectedValue() { + assertThat(descriptor.getHelpFile()).isEqualTo("/plugin/nodejs/help.html"); + } + + 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; } } \ No newline at end of file diff --git a/src/test/java/jenkins/plugins/nodejs/TestCacheLocationLocator.java b/src/test/java/jenkins/plugins/nodejs/TestCacheLocationLocator.java index 5e8449e..064bb2c 100644 --- a/src/test/java/jenkins/plugins/nodejs/TestCacheLocationLocator.java +++ b/src/test/java/jenkins/plugins/nodejs/TestCacheLocationLocator.java @@ -31,7 +31,7 @@ public class TestCacheLocationLocator extends CacheLocationLocator { - private File location; + private final File location; public TestCacheLocationLocator(File location) { this.location = location; diff --git a/src/test/java/jenkins/plugins/nodejs/VerifyEnvVariableBuilder.java b/src/test/java/jenkins/plugins/nodejs/VerifyEnvVariableBuilder.java index 0739949..7c01b70 100644 --- a/src/test/java/jenkins/plugins/nodejs/VerifyEnvVariableBuilder.java +++ b/src/test/java/jenkins/plugins/nodejs/VerifyEnvVariableBuilder.java @@ -23,7 +23,6 @@ */ package jenkins.plugins.nodejs; -import static org.junit.Assert.*; import java.io.File; import java.io.IOException; @@ -34,6 +33,8 @@ import hudson.model.BuildListener; import hudson.tasks.Builder; +import static org.assertj.core.api.Assertions.assertThat; + abstract class VerifyEnvVariableBuilder extends Builder { @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { @@ -50,9 +51,9 @@ public void verify(EnvVars env) { String var = NodeJSConstants.NPM_USERCONFIG; String value = env.get(var); - assertTrue("variable " + var + " not set", env.containsKey(var)); - assertNotNull("empty value for environment variable " + var, value); - assertTrue("file of variable " + var + " does not exists or is not a file", new File(value).isFile()); + assertThat(env).as("variable " + var + " not set").containsKey(var); + assertThat(value).as("empty value for environment variable " + var).isNotNull(); + assertThat(new File(value)).as("file of variable " + var + " does not exists or is not a file").isFile(); } } @@ -68,10 +69,7 @@ public EnvVarVerifier(String name, String value) { @Override public void verify(EnvVars env) { - String envValue = env.get(name); - - assertTrue("variable " + name + " not set", env.containsKey(name)); - assertEquals(value, envValue); + assertThat(env).as("variable " + name + " not set").containsEntry(name, value); } } } \ No newline at end of file diff --git a/src/test/java/jenkins/plugins/nodejs/cache/CacheLocationLocatorTest.java b/src/test/java/jenkins/plugins/nodejs/cache/CacheLocationLocatorTest.java index 736f211..e4b1641 100644 --- a/src/test/java/jenkins/plugins/nodejs/cache/CacheLocationLocatorTest.java +++ b/src/test/java/jenkins/plugins/nodejs/cache/CacheLocationLocatorTest.java @@ -27,40 +27,42 @@ import hudson.model.Computer; import hudson.model.Executor; import hudson.model.Node; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.MockedStatic; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; -public class CacheLocationLocatorTest { +import java.io.File; +import java.io.IOException; - @Rule - public TemporaryFolder fileRule = new TemporaryFolder(); +class CacheLocationLocatorTest { + + @TempDir + private File fileRule; private FilePath workspace; - @Before - public void setup() throws Exception { - workspace = new FilePath(fileRule.newFolder()); + @BeforeEach + void setup() throws Exception { + workspace = new FilePath(newFolder(fileRule, "junit")); } @Test - public void test_default() { - Assert.assertNull("expect null location path", new DefaultCacheLocationLocator().locate(workspace)); + void test_default() { + assertThat(new DefaultCacheLocationLocator().locate(workspace)).as("expect null location path").isNull(); } @Test - public void test_per_job() throws Exception { - Assert.assertEquals("expect the same location path passes as input", workspace.child(".npm"), new PerJobCacheLocationLocator().locate(workspace)); + void test_per_job() { + assertThat(new PerJobCacheLocationLocator().locate(workspace)).as("expect the same location path passes as input").isEqualTo(workspace.child(".npm")); } @Test - public void test_per_executor() throws Exception { + void test_per_executor() throws Exception { FilePath wc = mock(FilePath.class); Executor executor = mock(Executor.class); int executorNumber = 7; @@ -72,12 +74,21 @@ public void test_per_executor() throws Exception { Computer computer = mock(Computer.class); Node node = mock(Node.class); when(computer.getNode()).thenReturn(node); - FilePath rootPath = new FilePath(fileRule.newFolder()); + FilePath rootPath = new FilePath(newFolder(fileRule, "junit")); when(node.getRootPath()).thenReturn(rootPath); when(wc.toComputer()).thenReturn(computer); FilePath expectedLocation = rootPath.child("npm-cache").child(String.valueOf(executorNumber)); - Assert.assertEquals("expect null location path", expectedLocation, new PerExecutorCacheLocationLocator().locate(wc)); + assertThat(new PerExecutorCacheLocationLocator().locate(wc)).as("expect null location path").isEqualTo(expectedLocation); + } + } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.exists() && !result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); } + return result; } } diff --git a/src/test/java/jenkins/plugins/nodejs/configfiles/NPMConfigTest.java b/src/test/java/jenkins/plugins/nodejs/configfiles/NPMConfigTest.java index 0fcfcae..f12bd89 100644 --- a/src/test/java/jenkins/plugins/nodejs/configfiles/NPMConfigTest.java +++ b/src/test/java/jenkins/plugins/nodejs/configfiles/NPMConfigTest.java @@ -23,32 +23,31 @@ */ package jenkins.plugins.nodejs.configfiles; -import static org.junit.Assert.assertNotNull; - -import org.assertj.core.api.Assertions; import org.jenkinsci.lib.configprovider.model.Config; -import org.junit.Rule; -import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import hudson.model.Descriptor; import jenkins.plugins.nodejs.configfiles.NPMConfig.NPMConfigProvider; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class NPMConfigTest { - - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class NPMConfigTest { @Test - public void test_load_template() { + void test_load_template(JenkinsRule j) { Descriptor descriptor = j.jenkins.getDescriptor(NPMConfig.class); - assertNotNull("NPMConfig descriptor not registered", descriptor); - Assertions.assertThat(descriptor).isInstanceOf(NPMConfigProvider.class).describedAs("Unexpected descriptor class"); + assertThat(descriptor) + .as("NPMConfig descriptor not registered").isNotNull() + .as("Unexpected descriptor class").isInstanceOf(NPMConfigProvider.class); NPMConfigProvider provider = (NPMConfigProvider) descriptor; Config config = provider.newConfig("testId"); - Assertions.assertThat(config).isInstanceOf(NPMConfig.class).describedAs("Unexpected config class"); - Assertions.assertThat(config.content).isNotBlank().describedAs("Expected the default template, instead got empty"); + assertThat(config).as("Unexpected config class").isInstanceOf(NPMConfig.class); + assertThat(config.content).as("Expected the default template, instead got empty").isNotBlank(); } } \ No newline at end of file diff --git a/src/test/java/jenkins/plugins/nodejs/configfiles/NPMConfigValidationTest.java b/src/test/java/jenkins/plugins/nodejs/configfiles/NPMConfigValidationTest.java index b060945..e2f08b1 100644 --- a/src/test/java/jenkins/plugins/nodejs/configfiles/NPMConfigValidationTest.java +++ b/src/test/java/jenkins/plugins/nodejs/configfiles/NPMConfigValidationTest.java @@ -23,54 +23,53 @@ */ package jenkins.plugins.nodejs.configfiles; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import java.util.Arrays; +import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class NPMConfigValidationTest { +class NPMConfigValidationTest { @Test - public void test_new_config() { + void test_new_config() { String id = "test_id"; NPMConfig config = new NPMConfig(id, "", "", "", null); - assertEquals(id, config.id); - assertNull(config.name); - assertNull(config.comment); - assertNull(config.content); - assertNotNull(config.getRegistries()); + assertThat(config.id).isEqualTo(id); + assertThat(config.name).isNull(); + assertThat(config.comment).isNull(); + assertThat(config.content).isNull(); + assertThat(config.getRegistries()).isNotNull(); } @Test - public void test_too_many_global_registries() throws Exception { + void test_too_many_global_registries() { NPMRegistry privateRegistry = new NPMRegistry("https://private.organization.com/", null, null); - NPMRegistry officalRegistry = new NPMRegistry("https://registry.npmjs.org/", null, null); + NPMRegistry officialRegistry = new NPMRegistry("https://registry.npmjs.org/", null, null); - NPMConfig config = new NPMConfig("too_many_registry", null, null, null, Arrays.asList(privateRegistry, officalRegistry)); + NPMConfig config = new NPMConfig("too_many_registry", null, null, null, Arrays.asList(privateRegistry, officialRegistry)); assertThatExceptionOfType(VerifyConfigProviderException.class) // - .isThrownBy(() -> config.doVerify()); + .isThrownBy(config::doVerify); } @Test - public void test_empty_URL() throws Exception { + void test_empty_URL() { NPMRegistry registry = new NPMRegistry("", null, null); - NPMConfig config = new NPMConfig("empty_URL", null, null, null, Arrays.asList(registry)); + NPMConfig config = new NPMConfig("empty_URL", null, null, null, List.of(registry)); assertThatExceptionOfType(VerifyConfigProviderException.class) // - .isThrownBy(() -> config.doVerify()); + .isThrownBy(config::doVerify); } @Test - public void test_no_exception_if_URL_has_variable() throws Exception { + void test_no_exception_if_URL_has_variable() throws Exception { NPMRegistry registry = new NPMRegistry("${URL}", null, null); - NPMConfig config = new NPMConfig("no_exception_if_URL_has_variable", null, null, null, Arrays.asList(registry)); + NPMConfig config = new NPMConfig("no_exception_if_URL_has_variable", null, null, null, List.of(registry)); config.doVerify(); } diff --git a/src/test/java/jenkins/plugins/nodejs/configfiles/NPMRegistryValidator2Test.java b/src/test/java/jenkins/plugins/nodejs/configfiles/NPMRegistryValidator2Test.java index 75439ca..4942916 100644 --- a/src/test/java/jenkins/plugins/nodejs/configfiles/NPMRegistryValidator2Test.java +++ b/src/test/java/jenkins/plugins/nodejs/configfiles/NPMRegistryValidator2Test.java @@ -23,20 +23,19 @@ */ package jenkins.plugins.nodejs.configfiles; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.assertj.core.api.Assertions; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import com.cloudbees.plugins.credentials.Credentials; @@ -51,36 +50,41 @@ import hudson.util.FormValidation; import hudson.util.FormValidation.Kind; import jenkins.plugins.nodejs.configfiles.NPMRegistry.DescriptorImpl; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * Test input form validation. * * @author Nikolas Falco */ -public class NPMRegistryValidator2Test { +@WithJenkins +class NPMRegistryValidator2Test { + private static JenkinsRule rule; - @ClassRule - public static JenkinsRule rule = new JenkinsRule(); + @BeforeAll + static void setUp(JenkinsRule r) { + rule = r; + } @Test - public void test_credentials_ok() throws Exception { + void test_credentials_ok() throws Exception { String credentialsId = "secret"; Credentials credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "", "user", "password"); Map> credentialsMap = new HashMap<>(); - credentialsMap.put(Domain.global(), Arrays.asList(credentials)); + credentialsMap.put(Domain.global(), List.of(credentials)); SystemCredentialsProvider.getInstance().setDomainCredentialsMap(credentialsMap); FreeStyleProject prj = mock(FreeStyleProject.class); when(prj.hasPermission(isA(Permission.class))).thenReturn(true); DescriptorImpl descriptor = mock(DescriptorImpl.class); - when(descriptor.doCheckCredentialsId(any(Item.class), (String) any(), anyString())).thenCallRealMethod(); + when(descriptor.doCheckCredentialsId(any(Item.class), any(), anyString())).thenCallRealMethod(); String serverURL = "http://acme.com"; FormValidation result = descriptor.doCheckCredentialsId(prj, credentialsId, serverURL); - Assertions.assertThat(result.kind).isEqualTo(Kind.OK); + assertThat(result.kind).isEqualTo(Kind.OK); } } diff --git a/src/test/java/jenkins/plugins/nodejs/configfiles/NPMRegistryValidatorTest.java b/src/test/java/jenkins/plugins/nodejs/configfiles/NPMRegistryValidatorTest.java index 7b8635d..e2fb2a0 100644 --- a/src/test/java/jenkins/plugins/nodejs/configfiles/NPMRegistryValidatorTest.java +++ b/src/test/java/jenkins/plugins/nodejs/configfiles/NPMRegistryValidatorTest.java @@ -23,15 +23,14 @@ */ package jenkins.plugins.nodejs.configfiles; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.assertj.core.api.Assertions; -import org.junit.Test; - +import org.junit.jupiter.api.Test; import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.security.Permission; @@ -45,117 +44,117 @@ * * @author Nikolas Falco */ -public class NPMRegistryValidatorTest { +class NPMRegistryValidatorTest { @Test - public void test_empty_scopes() throws Exception { + void test_empty_scopes() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckScopes(true, ""); - Assertions.assertThat(result.kind).isEqualTo(Kind.ERROR); - Assertions.assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_emptyScopes()); + assertThat(result.kind).isEqualTo(Kind.ERROR); + assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_emptyScopes()); } @Test - public void test_scopes_with_at_in_name() throws Exception { + void test_scopes_with_at_in_name() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckScopes(true, "@scope1"); - Assertions.assertThat(result.kind).isEqualTo(Kind.WARNING); - Assertions.assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_invalidCharInScopes()); + assertThat(result.kind).isEqualTo(Kind.WARNING); + assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_invalidCharInScopes()); } @Test - public void test_invalid_scopes() throws Exception { + void test_invalid_scopes() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckScopes(true, "@"); - Assertions.assertThat(result.kind).isEqualTo(Kind.ERROR); - Assertions.assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_invalidScopes()); + assertThat(result.kind).isEqualTo(Kind.ERROR); + assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_invalidScopes()); } @Test - public void test_scopes_ok() throws Exception { + void test_scopes_ok() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckScopes(true, "scope1 scope2 scope3"); - Assertions.assertThat(result.kind).isEqualTo(Kind.OK); + assertThat(result.kind).isEqualTo(Kind.OK); } @Test - public void test_empty_server_url() throws Exception { + void test_empty_server_url() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckUrl(""); - Assertions.assertThat(result.kind).isEqualTo(Kind.ERROR); - Assertions.assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_emptyRegistryURL()); + assertThat(result.kind).isEqualTo(Kind.ERROR); + assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_emptyRegistryURL()); } @Test - public void test_server_url_that_contains_variable() throws Exception { + void test_server_url_that_contains_variable() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckUrl("${REGISTRY_URL}/root"); - Assertions.assertThat(result.kind).isEqualTo(Kind.OK); + assertThat(result.kind).isEqualTo(Kind.OK); result = descriptor.doCheckUrl("http://${SERVER_NAME}/root"); - Assertions.assertThat(result.kind).isEqualTo(Kind.OK); + assertThat(result.kind).isEqualTo(Kind.OK); result = descriptor.doCheckUrl("http://acme.com/${CONTEXT_ROOT}"); - Assertions.assertThat(result.kind).isEqualTo(Kind.OK); + assertThat(result.kind).isEqualTo(Kind.OK); } @Test - public void test_empty_server_url_is_ok() throws Exception { + void test_empty_server_url_is_ok() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckUrl("http://acme.com"); - Assertions.assertThat(result.kind).isEqualTo(Kind.OK); + assertThat(result.kind).isEqualTo(Kind.OK); } @Test - public void test_server_url_invalid_protocol() throws Exception { + void test_server_url_invalid_protocol() { DescriptorImpl descriptor = new DescriptorImpl(); FormValidation result = descriptor.doCheckUrl("hpp://acme.com/root"); - Assertions.assertThat(result.kind).isEqualTo(Kind.ERROR); - Assertions.assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_invalidRegistryURL()); + assertThat(result.kind).isEqualTo(Kind.ERROR); + assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_invalidRegistryURL()); } @Test - public void test_invalid_credentials() throws Exception { + void test_invalid_credentials() { FreeStyleProject prj = mock(FreeStyleProject.class); when(prj.hasPermission(isA(Permission.class))).thenReturn(true); DescriptorImpl descriptor = mock(DescriptorImpl.class); - when(descriptor.doCheckCredentialsId(any(Item.class), (String) any(), anyString())).thenCallRealMethod(); + when(descriptor.doCheckCredentialsId(any(Item.class), any(), anyString())).thenCallRealMethod(); String credentialsId = "secret"; String serverURL = "http://acme.com"; FormValidation result = descriptor.doCheckCredentialsId(prj, credentialsId, serverURL); - Assertions.assertThat(result.kind).isEqualTo(Kind.ERROR); - Assertions.assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_invalidCredentialsId()); + assertThat(result.kind).isEqualTo(Kind.ERROR); + assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_invalidCredentialsId()); when(prj.hasPermission(isA(Permission.class))).thenReturn(false); result = descriptor.doCheckCredentialsId(prj, credentialsId, serverURL); - Assertions.assertThat(result.kind).isEqualTo(Kind.OK); + assertThat(result.kind).isEqualTo(Kind.OK); } @Test - public void test_empty_credentials() throws Exception { + void test_empty_credentials() { FreeStyleProject prj = mock(FreeStyleProject.class); when(prj.hasPermission(isA(Permission.class))).thenReturn(true); DescriptorImpl descriptor = mock(DescriptorImpl.class); - when(descriptor.doCheckCredentialsId(any(Item.class), (String) any(), anyString())).thenCallRealMethod(); + when(descriptor.doCheckCredentialsId(any(Item.class), any(), anyString())).thenCallRealMethod(); String serverURL = "http://acme.com"; FormValidation result = descriptor.doCheckCredentialsId(prj, "", serverURL); - Assertions.assertThat(result.kind).isEqualTo(Kind.WARNING); - Assertions.assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_emptyCredentialsId()); + assertThat(result.kind).isEqualTo(Kind.WARNING); + assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_emptyCredentialsId()); result = descriptor.doCheckCredentialsId(prj, null, serverURL); - Assertions.assertThat(result.kind).isEqualTo(Kind.WARNING); - Assertions.assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_emptyCredentialsId()); + assertThat(result.kind).isEqualTo(Kind.WARNING); + assertThat(result.getMessage()).isEqualTo(Messages.NPMRegistry_DescriptorImpl_emptyCredentialsId()); } } diff --git a/src/test/java/jenkins/plugins/nodejs/configfiles/NpmrcTest.java b/src/test/java/jenkins/plugins/nodejs/configfiles/NpmrcTest.java index 4ba4086..1804a6e 100644 --- a/src/test/java/jenkins/plugins/nodejs/configfiles/NpmrcTest.java +++ b/src/test/java/jenkins/plugins/nodejs/configfiles/NpmrcTest.java @@ -23,10 +23,6 @@ */ package jenkins.plugins.nodejs.configfiles; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -34,23 +30,24 @@ import java.util.List; import org.apache.commons.io.IOUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import static org.assertj.core.api.Assertions.assertThat; -public class NpmrcTest { +class NpmrcTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + private File folder; private File file; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { InputStream is = null; try { is = getClass().getResourceAsStream("npmrc.config"); - file = folder.newFile(".npmrc"); + file = File.createTempFile(".npmrc", null, folder); hudson.util.IOUtils.copy(is, file); } finally { IOUtils.closeQuietly(is); @@ -58,22 +55,21 @@ public void setUp() throws IOException { } @Test - public void testLoad() throws Exception { + void testLoad() throws Exception { Npmrc npmrc = Npmrc.load(file); - assertTrue(npmrc.contains("always-auth")); - assertEquals("true", npmrc.get("always-auth")); - assertEquals("\"/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/Node_6.x\"", - npmrc.get("prefix")); + assertThat(npmrc.contains("always-auth")).isTrue(); + assertThat(npmrc.get("always-auth")).isEqualTo("true"); + assertThat(npmrc.get("prefix")).isEqualTo("\"/var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/Node_6.x\""); } @Test - public void testAvoidParseError() throws Exception { + void testAvoidParseError() throws Exception { Npmrc npmrc = Npmrc.load(file); - assertFalse(npmrc.contains("browser")); + assertThat(npmrc.contains("browser")).isFalse(); } @Test - public void testSave() throws Exception { + void testSave() throws Exception { String testKey = "test"; String testValue = "value"; @@ -83,12 +79,12 @@ public void testSave() throws Exception { // reload content npmrc = Npmrc.load(file); - assertTrue(npmrc.contains(testKey)); - assertEquals(testValue, npmrc.get(testKey)); + assertThat(npmrc.contains(testKey)).isTrue(); + assertThat(npmrc.get(testKey)).isEqualTo(testValue); } @Test - public void testCommandAtLast() throws Exception { + void testCommandAtLast() throws Exception { String comment = "test comment"; Npmrc npmrc = Npmrc.load(file); @@ -97,7 +93,7 @@ public void testCommandAtLast() throws Exception { try (InputStream is = new FileInputStream(file)) { List lines = IOUtils.readLines(is, "UTF-8"); - assertEquals(';' + comment, lines.get(lines.size() - 1)); + assertThat(lines.get(lines.size() - 1)).isEqualTo(';' + comment); } } diff --git a/src/test/java/jenkins/plugins/nodejs/configfiles/RegistryHelperCredentialsTest.java b/src/test/java/jenkins/plugins/nodejs/configfiles/RegistryHelperCredentialsTest.java index b6cc9ff..3a928dd 100644 --- a/src/test/java/jenkins/plugins/nodejs/configfiles/RegistryHelperCredentialsTest.java +++ b/src/test/java/jenkins/plugins/nodejs/configfiles/RegistryHelperCredentialsTest.java @@ -28,10 +28,7 @@ import static jenkins.plugins.nodejs.NodeJSConstants.NPM_SETTINGS_PASSWORD; import static jenkins.plugins.nodejs.NodeJSConstants.NPM_SETTINGS_REGISTRY; import static jenkins.plugins.nodejs.NodeJSConstants.NPM_SETTINGS_USER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -43,11 +40,9 @@ import java.util.Map; import org.apache.commons.codec.binary.Base64; -import org.assertj.core.api.Assertions; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; @@ -55,13 +50,12 @@ import hudson.util.Secret; -@RunWith(Parameterized.class) -public class RegistryHelperCredentialsTest { +class RegistryHelperCredentialsTest { - @Parameters(name = "test registries: {0}") - public static Collection data() throws Exception { - Collection dataParameters = new ArrayList(); + private static StandardUsernameCredentials user; + @BeforeAll + static void setUp() throws Exception { user = mock(StandardUsernamePasswordCredentials.class); when(user.getId()).thenReturn("privateId"); when(user.getUsername()).thenReturn("myuser"); @@ -70,52 +64,47 @@ public static Collection data() throws Exception { c.setAccessible(true); Secret userSecret = c.newInstance("mypassword"); when(((StandardUsernamePasswordCredentials) user).getPassword()).thenReturn(userSecret); + } + + static Collection data() { + Collection dataParameters = new ArrayList<>(); NPMRegistry globalRegistry = new NPMRegistry("https://registry.npmjs.org", null, null); NPMRegistry proxyRegistry = new NPMRegistry("https://registry.proxy.com", user.getId(), null); - NPMRegistry scopedGlobalRegsitry = new NPMRegistry("https://registry.npmjs.org", null, "@user1 user2"); + NPMRegistry scopedGlobalRegistry = new NPMRegistry("https://registry.npmjs.org", null, "@user1 user2"); NPMRegistry organisationRegistry = new NPMRegistry("https://registry.acme.com", user.getId(), "scope1 scope2"); dataParameters.add(new Object[] { "global no auth", new NPMRegistry[] { globalRegistry }, false }); dataParameters.add(new Object[] { "proxy with auth", new NPMRegistry[] { proxyRegistry }, false }); - dataParameters.add(new Object[] { "global scoped no auth", new NPMRegistry[] { scopedGlobalRegsitry }, false }); + dataParameters.add(new Object[] { "global scoped no auth", new NPMRegistry[] { scopedGlobalRegistry }, false }); dataParameters.add(new Object[] { "organisation scoped with auth", new NPMRegistry[] { organisationRegistry }, false }); dataParameters.add(new Object[] { "organisation scoped with auth", new NPMRegistry[] { organisationRegistry }, true }); dataParameters.add(new Object[] { "mix of proxy + global scoped + scped organisation registries", - new NPMRegistry[] { proxyRegistry, scopedGlobalRegsitry, organisationRegistry }, true }); + new NPMRegistry[] { proxyRegistry, scopedGlobalRegistry, organisationRegistry }, true }); return dataParameters; } - private static StandardUsernameCredentials user; - private NPMRegistry[] registries; - private Map resolvedCredentials; - private boolean npm9Format; - - public RegistryHelperCredentialsTest(String testName, NPMRegistry[] registries, boolean npm9Format) { - this.registries = registries; - - resolvedCredentials = new HashMap<>(); + @ParameterizedTest(name = "test registries: {0}") + @MethodSource("data") + void test_registry_credentials(String testName, NPMRegistry[] registries, boolean npm9Format) { + Map resolvedCredentials = new HashMap<>(); for (NPMRegistry r : registries) { if (r.getCredentialsId() != null) { resolvedCredentials.put(r.getUrl(), user); } } - this.npm9Format = npm9Format; - } - @Test - public void test_registry_credentials() throws Exception { RegistryHelper helper = new RegistryHelper(Arrays.asList(registries)); String content = helper.fillRegistry("", resolvedCredentials, npm9Format); - assertNotNull(content); + assertThat(content).isNotNull(); Npmrc npmrc = new Npmrc(); npmrc.from(content); for (NPMRegistry registry : registries) { if (!registry.isHasScopes()) { - verifyGlobalRegistry(helper, registry, npmrc); + verifyGlobalRegistry(helper, registry, npmrc, npm9Format); } else { verifyScopedRegistry(helper, npmrc, registry); } @@ -132,48 +121,47 @@ private void verifyScopedRegistry(RegistryHelper helper, Npmrc npmrc, NPMRegistr String passwordKey = helper.compose(registryPrefix, NPM_SETTINGS_PASSWORD); for (String scope : registry.getScopesAsList()) { - assertFalse("Unexpected value for " + NPM_SETTINGS_AUTH, npmrc.contains(helper.compose(registryPrefix, NPM_SETTINGS_AUTH))); + assertThat(npmrc.contains(helper.compose(registryPrefix, NPM_SETTINGS_AUTH))).as("Unexpected value for " + NPM_SETTINGS_AUTH).isFalse(); if (registry.getCredentialsId() != null) { // test require authentication, by default is false - Assertions.assertThat(npmrc.contains(alwaysAuthKey)).isTrue() // - .describedAs("key %s not found", NPM_SETTINGS_ALWAYS_AUTH); - Assertions.assertThat(npmrc.getAsBoolean(alwaysAuthKey)).isTrue(); + assertThat(npmrc.contains(alwaysAuthKey)).as("key %s not found", NPM_SETTINGS_ALWAYS_AUTH).isTrue(); + assertThat(npmrc.getAsBoolean(alwaysAuthKey)).isTrue(); // test credentials fields - Assertions.assertThat(npmrc.get(usernameKey)).isEqualTo(user.getUsername()); + assertThat(npmrc.get(usernameKey)).isEqualTo(user.getUsername()); String password = npmrc.get(passwordKey); - Assertions.assertThat(password).isNotNull(); + assertThat(password).isNotNull(); password = new String(Base64.decodeBase64(password)); - Assertions.assertThat(password).isEqualTo("mypassword").describedAs("Invalid scoped password"); + assertThat(password).as("Invalid scoped password").isEqualTo("mypassword"); } scope = '@' + scope; String scopeKey = helper.compose(scope, NPM_SETTINGS_REGISTRY); // test registry URL entry - assertTrue("Miss registry entry for scope " + scope, npmrc.contains(scopeKey)); - assertEquals("Wrong registry URL for scope " + scope, registry.getUrl() + "/", npmrc.get(scopeKey)); + assertThat(npmrc.contains(scopeKey)).as("Miss registry entry for scope " + scope).isTrue(); + assertThat(npmrc.get(scopeKey)).as("Wrong registry URL for scope " + scope).isEqualTo(registry.getUrl() + "/"); } } - private void verifyGlobalRegistry(RegistryHelper helper, NPMRegistry registry, Npmrc npmrc) { + private void verifyGlobalRegistry(RegistryHelper helper, NPMRegistry registry, Npmrc npmrc, boolean npm9Format) { String registryPrefix = helper.calculatePrefix(registry.getUrl()); String alwaysAuthKey = npm9Format ? helper.compose(registryPrefix, NPM_SETTINGS_ALWAYS_AUTH) : NPM_SETTINGS_ALWAYS_AUTH; String authKey = npm9Format ? helper.compose(registryPrefix, NPM_SETTINGS_AUTH) : NPM_SETTINGS_AUTH; - Assertions.assertThat(npmrc.contains(alwaysAuthKey)).isEqualTo(registry.getCredentialsId() != null) // - .describedAs("Unexpected value for %s", alwaysAuthKey); + assertThat(npmrc.contains(alwaysAuthKey)).as("Unexpected value for %s", alwaysAuthKey).isEqualTo(registry.getCredentialsId() != null) // + ; if (registry.getCredentialsId() != null) { // test _auth String auth = npmrc.get(authKey); - assertNotNull("Unexpected value for " + NPM_SETTINGS_AUTH, npmrc); + assertThat(npmrc).as("Unexpected value for " + NPM_SETTINGS_AUTH).isNotNull(); auth = new String(Base64.decodeBase64(auth)); - Assertions.assertThat(auth).startsWith(user.getUsername()).endsWith("mypassword"); + assertThat(auth).startsWith(user.getUsername()).endsWith("mypassword"); } // test registry URL entry - Assertions.assertThat(npmrc.get(NPM_SETTINGS_REGISTRY)).isEqualTo(registry.getUrl()); + assertThat(npmrc.get(NPM_SETTINGS_REGISTRY)).isEqualTo(registry.getUrl()); } } diff --git a/src/test/java/jenkins/plugins/nodejs/configfiles/RegistryHelperTest.java b/src/test/java/jenkins/plugins/nodejs/configfiles/RegistryHelperTest.java index bf96d37..4049d5e 100644 --- a/src/test/java/jenkins/plugins/nodejs/configfiles/RegistryHelperTest.java +++ b/src/test/java/jenkins/plugins/nodejs/configfiles/RegistryHelperTest.java @@ -23,18 +23,16 @@ */ package jenkins.plugins.nodejs.configfiles; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Map; -import org.assertj.core.api.Assertions; import org.jenkinsci.plugins.plaincredentials.StringCredentials; import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import com.cloudbees.plugins.credentials.CredentialsProvider; @@ -47,17 +45,23 @@ import hudson.model.FreeStyleBuild; import hudson.util.Secret; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class RegistryHelperTest { +@WithJenkins +class RegistryHelperTest { - @ClassRule - public static JenkinsRule j = new JenkinsRule(); + private static JenkinsRule j; private StandardUsernameCredentials user; private StringCredentials token; - @Before - public void setUp() throws Exception { + @BeforeAll + static void setUp(JenkinsRule rule) { + j = rule; + } + + @BeforeEach + void setUp() throws Exception { user = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "privateId", "dummy desc", "myuser", "mypassword"); token = new StringCredentialsImpl(CredentialsScope.GLOBAL, "privateToken", "dummy desc", Secret.fromString("mysecret")); CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); @@ -66,35 +70,38 @@ public void setUp() throws Exception { } @Test - public void test_registry_credentials_resolution() throws Exception { + void test_registry_credentials_resolution() throws Exception { NPMRegistry privateRegistry = new NPMRegistry("https://private.organization.com/", user.getId(), null); - NPMRegistry officalRegistry = new NPMRegistry("https://registry.npmjs.org/", null, "@user1 user2"); + NPMRegistry officialRegistry = new NPMRegistry("https://registry.npmjs.org/", null, "@user1 user2"); FreeStyleBuild build = j.createFreeStyleProject().createExecutable(); - RegistryHelper helper = new RegistryHelper(Arrays.asList(privateRegistry, officalRegistry)); + RegistryHelper helper = new RegistryHelper(Arrays.asList(privateRegistry, officialRegistry)); Map resolvedCredentials = helper.resolveCredentials(build); - assertFalse(resolvedCredentials.isEmpty()); - assertEquals(1, resolvedCredentials.size()); - Assertions.assertThat(resolvedCredentials.keySet().contains(privateRegistry.getUrl())); - Assertions.assertThat(resolvedCredentials.get(privateRegistry.getUrl())).isEqualTo(user); + assertThat(resolvedCredentials) + .isNotEmpty() + .hasSize(1) + .containsKey(privateRegistry.getUrl()) + .containsEntry(privateRegistry.getUrl(), user); } @Test - public void test_registry_auth_token_credentials_resolution() throws Exception { + void test_registry_auth_token_credentials_resolution() throws Exception { NPMRegistry privateRegistry = new NPMRegistry("https://private.organization.com/", token.getId(), null); - NPMRegistry officalRegistry = new NPMRegistry("https://registry.npmjs.org/", token.getId(), "@user1 user2"); + NPMRegistry officialRegistry = new NPMRegistry("https://registry.npmjs.org/", token.getId(), "@user1 user2"); FreeStyleBuild build = j.createFreeStyleProject().createExecutable(); - RegistryHelper helper = new RegistryHelper(Arrays.asList(privateRegistry, officalRegistry)); + RegistryHelper helper = new RegistryHelper(Arrays.asList(privateRegistry, officialRegistry)); Map resolvedCredentials = helper.resolveCredentials(build); - assertFalse(resolvedCredentials.isEmpty()); - assertEquals(2, resolvedCredentials.size()); - Assertions.assertThat(resolvedCredentials.keySet().contains(privateRegistry.getUrl())); - Assertions.assertThat(resolvedCredentials.get(privateRegistry.getUrl())).isEqualTo(token); - Assertions.assertThat(resolvedCredentials.get(officalRegistry.getUrl())).isEqualTo(token); + assertThat(resolvedCredentials) + .isNotEmpty() + .hasSize(2) + .containsKey(privateRegistry.getUrl()) + .containsEntry(privateRegistry.getUrl(), token) + .containsKey(officialRegistry.getUrl()) + .containsEntry(officialRegistry.getUrl(), token); } } diff --git a/src/test/java/jenkins/plugins/nodejs/tools/CPUTest.java b/src/test/java/jenkins/plugins/nodejs/tools/CPUTest.java index 75e133a..d1085ba 100644 --- a/src/test/java/jenkins/plugins/nodejs/tools/CPUTest.java +++ b/src/test/java/jenkins/plugins/nodejs/tools/CPUTest.java @@ -23,20 +23,21 @@ */ package jenkins.plugins.nodejs.tools; -import org.assertj.core.api.Assertions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; -public class CPUTest { +import static org.assertj.core.api.Assertions.assertThat; + +class CPUTest { @Test @Issue("JENKINS-64311") - public void verify_aarch64() throws DetectionFailedException { + void verify_aarch64() throws DetectionFailedException { String systemProperty = "os.arch"; String current = System.setProperty(systemProperty, "aarch64"); try { - Assertions.assertThat(CPU.current()).isEqualTo(CPU.arm64); + assertThat(CPU.current()).isEqualTo(CPU.arm64); } finally { if (current != null) { System.setProperty(systemProperty, current); diff --git a/src/test/java/jenkins/plugins/nodejs/tools/InstallerPathResolversTest.java b/src/test/java/jenkins/plugins/nodejs/tools/InstallerPathResolversTest.java index 9b1daaa..d50c49a 100644 --- a/src/test/java/jenkins/plugins/nodejs/tools/InstallerPathResolversTest.java +++ b/src/test/java/jenkins/plugins/nodejs/tools/InstallerPathResolversTest.java @@ -23,7 +23,7 @@ */ package jenkins.plugins.nodejs.tools; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.io.InputStream; @@ -35,10 +35,8 @@ import java.util.TreeSet; import org.apache.commons.io.IOUtils; -import org.assertj.core.api.Assertions; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import com.google.common.base.Charsets; import com.google.common.io.Resources; @@ -47,25 +45,14 @@ import net.sf.json.JSONArray; import net.sf.json.JSONObject; -@RunWith(Parameterized.class) -public class InstallerPathResolversTest { +class InstallerPathResolversTest { private static Collection expectedURLs; - private DownloadFromUrlInstaller.Installable installable; - private final Platform platform; - private final CPU cpu; private final boolean testDownload = false; private final boolean showDownloadURL = false; - public InstallerPathResolversTest(DownloadFromUrlInstaller.Installable installable, Platform platform, CPU cpu, String testName) { - this.installable = installable; - this.platform = platform; - this.cpu = cpu; - } - - @Parameterized.Parameters(name = "{index}: {3}") - public static Collection data() throws Exception { - Collection testPossibleParams = new ArrayList(); + static Collection data() throws Exception { + Collection testPossibleParams = new ArrayList<>(); try (InputStream is = InstallerPathResolversTest.class.getResourceAsStream("expectedURLs.txt")) { expectedURLs = new TreeSet<>(IOUtils.readLines(is, StandardCharsets.UTF_8)); @@ -105,17 +92,18 @@ public static Collection data() throws Exception { return testPossibleParams; } - @Test - public void shouldNodeJSInstallerResolvedPathExist() throws IOException { - InstallerPathResolver installerPathResolver = InstallerPathResolver.Factory.findResolverFor(this.installable.id); + @ParameterizedTest(name = "{index}: {3}") + @MethodSource("data") + void shouldNodeJSInstallerResolvedPathExist(DownloadFromUrlInstaller.Installable installable, Platform platform, CPU cpu, String testName) throws Exception { + InstallerPathResolver installerPathResolver = InstallerPathResolver.Factory.findResolverFor(installable.id); try { - String path = installerPathResolver.resolvePathFor(installable.id, this.platform, this.cpu); + String path = installerPathResolver.resolvePathFor(installable.id, platform, cpu); URL url = new URL(installable.url + path); if (testDownload) { assertDownload(url); } else { - Assertions.assertThat(expectedURLs).contains(url.toString()); + assertThat(expectedURLs).contains(url.toString()); } if (showDownloadURL) { @@ -133,7 +121,9 @@ private void assertDownload(URL url) throws IOException { urlConnection.setConnectTimeout(2000); urlConnection.connect(); int code = urlConnection.getResponseCode(); - assertTrue(code >= 200 && code < 300); + assertThat(code) + .isGreaterThanOrEqualTo(200) + .isLessThan(300); } finally { if (urlConnection != null) { urlConnection.disconnect(); diff --git a/src/test/java/jenkins/plugins/nodejs/tools/MirrorNodeJSInstallerTest.java b/src/test/java/jenkins/plugins/nodejs/tools/MirrorNodeJSInstallerTest.java index 0da2cc1..019430b 100644 --- a/src/test/java/jenkins/plugins/nodejs/tools/MirrorNodeJSInstallerTest.java +++ b/src/test/java/jenkins/plugins/nodejs/tools/MirrorNodeJSInstallerTest.java @@ -23,6 +23,7 @@ */ package jenkins.plugins.nodejs.tools; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -30,15 +31,15 @@ import static org.mockito.Mockito.when; import java.io.IOException; -import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.assertj.core.api.Assertions; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.ArgumentCaptor; import com.cloudbees.plugins.credentials.Credentials; @@ -54,14 +55,14 @@ import hudson.tools.ToolInstallerDescriptor; import hudson.tools.DownloadFromUrlInstaller.Installable; -public class MirrorNodeJSInstallerTest { +@WithJenkins +class MirrorNodeJSInstallerTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; public static class MockMirrorNodeJSInstaller extends MirrorNodeJSInstaller { - private Installable installable; + private final Installable installable; public MockMirrorNodeJSInstaller(Installable installable, String mirrorURL) { super(installable.id, mirrorURL, null, 0); @@ -69,7 +70,7 @@ public MockMirrorNodeJSInstaller(Installable installable, String mirrorURL) { } @Override - public boolean isUpToDate(FilePath expectedLocation, Installable i) throws IOException, InterruptedException { + public boolean isUpToDate(FilePath expectedLocation, Installable i) { return true; } @@ -78,15 +79,21 @@ public boolean isUpToDate(FilePath expectedLocation, Installable i) throws IOExc public ToolInstallerDescriptor getDescriptor() { hudson.tools.DownloadFromUrlInstaller.DescriptorImpl descriptor = mock(hudson.tools.DownloadFromUrlInstaller.DescriptorImpl.class); try { - when(descriptor.getInstallables()).thenReturn((List) Arrays.asList(installable)); + when(descriptor.getInstallables()).thenReturn((List) Collections.singletonList(installable)); } catch (IOException e) { + // ignored } return descriptor; } } + @BeforeAll + static void setup(JenkinsRule rule) { + r = rule; + } + @Test - public void verify_mirror_url_replacing() throws Exception { + void verify_mirror_url_replacing() throws Exception { String installationId = "8.2.1"; String mirror = "http://npm.taobao.org/mirrors/node/"; @@ -104,11 +111,11 @@ public void verify_mirror_url_replacing() throws Exception { ArgumentCaptor captor = ArgumentCaptor.forClass(Installable.class); verify(installer).isUpToDate(any(FilePath.class), captor.capture()); - Assertions.assertThat(captor.getValue().url).startsWith("http://npm.taobao.org/mirrors/node/v8.2.1/node-v8.2.1"); + assertThat(captor.getValue().url).startsWith("http://npm.taobao.org/mirrors/node/v8.2.1/node-v8.2.1"); } @Test - public void verify_credentials_on_mirror_url() throws Exception { + void verify_credentials_on_mirror_url() throws Exception { String credentialsId = "secret"; String installationId = "8.2.1"; String mirror = "http://npm.taobao.org/mirrors/node/"; @@ -119,7 +126,7 @@ public void verify_credentials_on_mirror_url() throws Exception { Credentials credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "", "user", "password"); Map> credentialsMap = new HashMap<>(); - credentialsMap.put(Domain.global(), Arrays.asList(credentials)); + credentialsMap.put(Domain.global(), List.of(credentials)); SystemCredentialsProvider.getInstance().setDomainCredentialsMap(credentialsMap); MockMirrorNodeJSInstaller installer = spy(new MockMirrorNodeJSInstaller(installable, mirror)); @@ -133,7 +140,7 @@ public void verify_credentials_on_mirror_url() throws Exception { ArgumentCaptor captor = ArgumentCaptor.forClass(Installable.class); verify(installer).isUpToDate(any(FilePath.class), captor.capture()); - Assertions.assertThat(captor.getValue().url).startsWith("http://user:password@npm.taobao.org/mirrors/node/node-v8.2.1"); + assertThat(captor.getValue().url).startsWith("http://user:password@npm.taobao.org/mirrors/node/node-v8.2.1"); } } diff --git a/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallationMockitoTest.java b/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallationMockitoTest.java index 7a1b5b3..a16943e 100644 --- a/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallationMockitoTest.java +++ b/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallationMockitoTest.java @@ -24,8 +24,7 @@ package jenkins.plugins.nodejs.tools; import static jenkins.plugins.nodejs.NodeJSConstants.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.anyMap; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.never; @@ -34,21 +33,21 @@ import hudson.EnvVars; import hudson.Functions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; -public class NodeJSInstallationMockitoTest { +class NodeJSInstallationMockitoTest { /** * Ensure the use of {@link EnvVars#put(String, String)} instead * {@code EnvVars#override(String, String)} to respect the - * {@link ToolInstallation#buildEnvVars(EnvVars)) API documentation. + * {@link hudson.tools.ToolInstallation#buildEnvVars(EnvVars)) API documentation. *

* A lot stuff rely on that logic. */ @Issue("JENKINS-41947") @Test - public void test_installer_environment() throws Exception { + void test_installer_environment() { String nodeJSHome = "/home/nodejs"; String bin = nodeJSHome + "/bin"; @@ -59,10 +58,11 @@ public void test_installer_environment() throws Exception { verify(env, never()).override(anyString(), anyString()); verify(env, never()).overrideAll(anyMap()); - assertEquals("Unexpected value for " + ENVVAR_NODEJS_HOME, nodeJSHome, env.get(ENVVAR_NODEJS_HOME)); - assertEquals("Unexpected value for " + ENVVAR_NODE_HOME, nodeJSHome, env.get(ENVVAR_NODE_HOME)); - assertEquals("Unexpected value for " + ENVVAR_NODEJS_PATH, Functions.isWindows() ? nodeJSHome : bin, env.get(ENVVAR_NODEJS_PATH)); - assertNull("PATH variable should not appear in this environment", env.get("PATH")); + assertThat(env) + .as("Unexpected value for " + ENVVAR_NODEJS_HOME).containsEntry(ENVVAR_NODEJS_HOME, nodeJSHome) + .as("Unexpected value for " + ENVVAR_NODE_HOME).containsEntry(ENVVAR_NODE_HOME, nodeJSHome) + .as("Unexpected value for " + ENVVAR_NODEJS_PATH).containsEntry(ENVVAR_NODEJS_PATH, Functions.isWindows() ? nodeJSHome : bin) + .as("PATH variable should not appear in this environment").doesNotContainKey("PATH"); } } \ No newline at end of file diff --git a/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallationTest.java b/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallationTest.java index 8e00bf9..a26d798 100644 --- a/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallationTest.java +++ b/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallationTest.java @@ -36,37 +36,39 @@ import java.lang.reflect.Method; import jenkins.model.Jenkins; import jenkins.plugins.nodejs.tools.NodeJSInstallation.DescriptorImpl; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; import org.xml.sax.SAXException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; -public class NodeJSInstallationTest { +@WithJenkins +class NodeJSInstallationTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; + + @BeforeEach + void setUp(JenkinsRule rule) { + r = rule; + } /** - * Verify node executable is begin initialised correctly on a slave + * Verify node executable is being initialised correctly on a slave * node where {@link Computer#currentComputer()} is {@code null}. */ @Issue("JENKINS-42232") @Test - public void test_executable_resolved_on_slave_node() throws Exception { - assertNull(Computer.currentComputer()); + void test_executable_resolved_on_slave_node() throws Exception { + assertThat(Computer.currentComputer()).isNull(); NodeJSInstallation installation = new NodeJSInstallation("test_executable_resolved_on_slave_node", "/home/nodejs", null); Method method = installation.getClass().getDeclaredMethod("getPlatform"); method.setAccessible(true); Platform platform = (Platform) method.invoke(installation); - assertEquals(Platform.current(), platform); + assertThat(platform).isEqualTo(Platform.current()); } /** @@ -76,11 +78,11 @@ public void test_executable_resolved_on_slave_node() throws Exception { @LocalData @Test @Issue("JENKINS-41535") - public void test_load_at_startup() throws Exception { + void test_load_at_startup() throws Exception { File jenkinsHome = r.jenkins.getRootDir(); File installationsFile = new File(jenkinsHome, NodeJSInstallation.class.getName() + ".xml"); - assertTrue("NodeJS installations file has not been copied", installationsFile.exists()); + assertThat(installationsFile).as("NodeJS installations file has not been copied").exists(); verify(); } @@ -90,11 +92,11 @@ public void test_load_at_startup() throws Exception { */ @Test @Issue("JENKINS-41535") - public void test_persist_of_nodejs_installation() throws Exception { + void test_persist_of_nodejs_installation() throws Exception { File jenkinsHome = r.jenkins.getRootDir(); File installationsFile = new File(jenkinsHome, NodeJSInstallation.class.getName() + ".xml"); - assertFalse("NodeJS installations file already exists", installationsFile.exists()); + assertThat(installationsFile).as("NodeJS installations file already exists").doesNotExist(); HtmlPage p = getConfigurePage(); HtmlForm f = p.getFormByName("config"); @@ -105,7 +107,7 @@ public void test_persist_of_nodejs_installation() throws Exception { r.submit(f); verify(); - assertTrue("NodeJS installations file has not been saved", installationsFile.exists()); + assertThat(installationsFile).as("NodeJS installations file has not been saved").exists(); // another submission and verify it survives a roundtrip p = getConfigurePage(); @@ -122,15 +124,15 @@ private HtmlPage getConfigurePage() throws IOException, SAXException { private void verify() throws Exception { NodeJSInstallation[] l = r.get(DescriptorImpl.class).getInstallations(); - assertEquals(1, l.length); + assertThat(l).hasSize(1); r.assertEqualBeans(l[0], new NodeJSInstallation("myNode", "/tmp/foo", JenkinsRule.NO_PROPERTIES), "name,home"); // by default we should get the auto installer DescribableList, ToolPropertyDescriptor> props = l[0].getProperties(); - assertEquals(1, props.size()); + assertThat(props).hasSize(1); InstallSourceProperty isp = props.get(InstallSourceProperty.class); - assertEquals(1, isp.installers.size()); - assertNotNull(isp.installers.get(NodeJSInstaller.class)); + assertThat(isp.installers).hasSize(1); + assertThat(isp.installers.get(NodeJSInstaller.class)).isNotNull(); } } \ No newline at end of file diff --git a/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallerProxyTest.java b/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallerProxyTest.java index 5427149..2661e04 100644 --- a/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallerProxyTest.java +++ b/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallerProxyTest.java @@ -24,16 +24,12 @@ package jenkins.plugins.nodejs.tools; import java.lang.reflect.Method; -import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; -import org.assertj.core.api.Assertions; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; @@ -41,19 +37,14 @@ import hudson.ProxyConfiguration; import hudson.model.StreamBuildListener; import hudson.model.TaskListener; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -@RunWith(Parameterized.class) -public class NodeJSInstallerProxyTest { +import static org.assertj.core.api.Assertions.assertThat; - @Parameters(name = "proxy url = {0}") - public static String[][] data() throws MalformedURLException { - return new String[][] { { "http://proxy.example.org:8080", "*.npm.org\n\nregistry.npm.org" }, - { "http://user:password@proxy.example.org:8080", "*.npm.org\n\nregistry.npm.org" } - }; - } +@WithJenkins +class NodeJSInstallerProxyTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; private String host; private int port; @@ -61,14 +52,24 @@ public static String[][] data() throws MalformedURLException { private String password; private String expectedURL; private TaskListener log; - private String noProxy; - public NodeJSInstallerProxyTest(String url, String noProxy) throws Exception { + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } + + static String[][] data() { + return new String[][] { + { "http://proxy.example.org:8080", "*.npm.org\n\nregistry.npm.org" }, + { "http://user:password@proxy.example.org:8080", "*.npm.org\n\nregistry.npm.org" } + }; + } + + private void init(String url) throws Exception { URL proxyURL = new URL(url); this.log = new StreamBuildListener(System.out, Charset.defaultCharset()); this.expectedURL = url; - this.noProxy = noProxy; this.host = proxyURL.getHost(); this.port = proxyURL.getPort(); if (proxyURL.getUserInfo() != null) { @@ -79,8 +80,11 @@ public NodeJSInstallerProxyTest(String url, String noProxy) throws Exception { } @Issue("JENKINS-29266") - @Test - public void test_proxy_settings() throws Exception { + @ParameterizedTest(name = "proxy url = {0}") + @MethodSource("data") + void test_proxy_settings(String url, String noProxy) throws Exception { + init(url); + r.getInstance().proxy = new ProxyConfiguration(host, port, username, password); NodeJSInstaller installer = new NodeJSInstaller("test-id", "grunt", NodeJSInstaller.DEFAULT_NPM_PACKAGES_REFRESH_HOURS); @@ -89,14 +93,17 @@ public void test_proxy_settings() throws Exception { method.setAccessible(true); method.invoke(installer, env, log); - Assertions.assertThat(env.keySet()).contains("HTTP_PROXY", "HTTPS_PROXY"); - Assertions.assertThat(env.get("HTTP_PROXY")).isEqualTo(expectedURL); - Assertions.assertThat(env.get("HTTPS_PROXY")).isEqualTo(expectedURL); - Assertions.assertThat(env.keySet()).doesNotContain("NO_PROXY"); + assertThat(env) + .containsEntry("HTTP_PROXY", expectedURL) + .containsEntry("HTTPS_PROXY", expectedURL) + .doesNotContainKey("NO_PROXY"); } - @Test - public void test_no_proxy_settings() throws Exception { + @ParameterizedTest(name = "proxy url = {0}") + @MethodSource("data") + void test_no_proxy_settings(String url, String noProxy) throws Exception { + init(url); + r.getInstance().proxy = new ProxyConfiguration(host, port, username, password, noProxy); NodeJSInstaller installer = new NodeJSInstaller("test-id", "grunt", NodeJSInstaller.DEFAULT_NPM_PACKAGES_REFRESH_HOURS); @@ -105,8 +112,8 @@ public void test_no_proxy_settings() throws Exception { method.setAccessible(true); method.invoke(installer, env, log); - Assertions.assertThat(env.keySet()).contains("HTTP_PROXY", "HTTPS_PROXY"); - Assertions.assertThat(env.get("NO_PROXY")).isEqualTo("*.npm.org,registry.npm.org"); + assertThat(env).containsKeys("HTTP_PROXY", "HTTPS_PROXY") + .containsEntry("NO_PROXY", "*.npm.org,registry.npm.org"); } } \ No newline at end of file diff --git a/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallerTest.java b/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallerTest.java index e9ca745..2e1a1bb 100644 --- a/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallerTest.java +++ b/src/test/java/jenkins/plugins/nodejs/tools/NodeJSInstallerTest.java @@ -23,6 +23,7 @@ */ package jenkins.plugins.nodejs.tools; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; @@ -45,10 +46,8 @@ import org.apache.tools.tar.TarInputStream; import org.apache.tools.tar.TarOutputStream; import org.assertj.core.api.AssertDelegateTarget; -import org.assertj.core.api.Assertions; -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.Issue; import org.mockito.MockedStatic; @@ -59,18 +58,18 @@ import hudson.tools.DownloadFromUrlInstaller.Installable; import hudson.util.StreamTaskListener; -public class NodeJSInstallerTest { +class NodeJSInstallerTest { private static class TarFileAssert implements AssertDelegateTarget { - private File file; + private final File file; public TarFileAssert(File file) { this.file = file; } void hasEntry(String path) throws IOException { - Assertions.assertThat(file).exists(); + assertThat(file).exists(); try (TarInputStream zf = new TarInputStream(new GZIPInputStream(new FileInputStream(file)))) { TarEntry entry; while ((entry = zf.getNextEntry()) != null) { @@ -78,16 +77,16 @@ void hasEntry(String path) throws IOException { break; } } - Assertions.assertThat(entry).as("Entry " + path + " not found.").isNotNull(); + assertThat(entry).as("Entry " + path + " not found.").isNotNull(); } } } - @Rule - public TemporaryFolder fileRule = new TemporaryFolder(); + @TempDir + private File fileRule; @SuppressWarnings("deprecation") - private TaskListener taskListener = new StreamTaskListener(new NullPrintStream()); + private final TaskListener taskListener = new StreamTaskListener(new NullPrintStream()); /** * Verify that the installer skip install of global package also if @@ -100,13 +99,13 @@ void hasEntry(String path) throws IOException { */ @Issue("JENKINS-41876") @Test - public void test_skip_install_global_packages_when_empty() throws Exception { - File cache = new File(fileRule.getRoot(), "test.tar.gz"); + void test_skip_install_global_packages_when_empty() throws Exception { + File cache = new File(fileRule, "test.tar.gz"); IOUtils.copy(getClass().getResource("test.tar.gz"), cache); String expectedPackages = " "; int expectedRefreshHours = NodeJSInstaller.DEFAULT_NPM_PACKAGES_REFRESH_HOURS; Node currentNode = mock(Node.class); - when(currentNode.getRootPath()).thenReturn(new FilePath(fileRule.newFolder())); + when(currentNode.getRootPath()).thenReturn(new FilePath(newFolder(fileRule, "junit"))); // create partial mock NodeJSInstaller installer = new NodeJSInstaller("test-id", expectedPackages, expectedRefreshHours); @@ -115,7 +114,7 @@ public void test_skip_install_global_packages_when_empty() throws Exception { // use Mockito to set up your expectation doReturn(cache).when(spy).getLocalCacheFile(any(), any()); Installable installable = new Installable(); - installable.url = fileRule.newFile().toURI().toString(); + installable.url = File.createTempFile("junit", null, fileRule).toURI().toString(); doReturn(installable).when(spy).getInstallable(); when(spy.getNpmPackages()).thenReturn(expectedPackages); @@ -132,13 +131,13 @@ public void test_skip_install_global_packages_when_empty() throws Exception { } @Test - public void verify_cache_is_build() throws Exception { - File cache = new File(fileRule.getRoot(), "test.tar.gz"); + void verify_cache_is_build() throws Exception { + File cache = new File(fileRule, "test.tar.gz"); IOUtils.copy(getClass().getResource("test.tar.gz"), cache); String expectedPackages = " "; int expectedRefreshHours = NodeJSInstaller.DEFAULT_NPM_PACKAGES_REFRESH_HOURS; Node currentNode = mock(Node.class); - when(currentNode.getRootPath()).thenReturn(new FilePath(fileRule.newFolder())); + when(currentNode.getRootPath()).thenReturn(new FilePath(newFolder(fileRule, "junit"))); // create partial mock NodeJSInstaller installer = new NodeJSInstaller("test-id", expectedPackages, expectedRefreshHours); @@ -147,7 +146,7 @@ public void verify_cache_is_build() throws Exception { // use Mockito to set up your expectation doReturn(cache).when(spy).getLocalCacheFile(any(), any()); Installable installable = new Installable(); - File downloadURL = fileRule.newFile("nodejs.tar.gz"); + File downloadURL = File.createTempFile("nodejs.tar.gz", null, fileRule); fillArchive(downloadURL, "nodejs/bin/npm.sh", "echo \"hello\"".getBytes()); installable.url = downloadURL.toURI().toString(); doReturn(installable).when(spy).getInstallable(); @@ -162,27 +161,27 @@ public void verify_cache_is_build() throws Exception { // execute test spy.performInstallation(toolInstallation, currentNode, taskListener); - Assertions.assertThat(new TarFileAssert(cache)).hasEntry("bin/npm.sh"); + assertThat(new TarFileAssert(cache)).hasEntry("bin/npm.sh"); } } @Test - public void test_cache_archive_is_used() throws Exception { + void test_cache_archive_is_used() throws Exception { String expectedPackages = " "; int expectedRefreshHours = NodeJSInstaller.DEFAULT_NPM_PACKAGES_REFRESH_HOURS; Node currentNode = mock(Node.class); - when(currentNode.getRootPath()).thenReturn(new FilePath(fileRule.newFolder())); + when(currentNode.getRootPath()).thenReturn(new FilePath(newFolder(fileRule, "junit"))); // create partial mock NodeJSInstaller installer = new NodeJSInstaller("test-id", expectedPackages, expectedRefreshHours); NodeJSInstaller spy = spy(installer); // use Mockito to set up your expectation - File cache = fileRule.newFile(); + File cache = File.createTempFile("junit", null, fileRule); fillArchive(cache, "nodejs.txt", "test".getBytes()); doReturn(cache).when(spy).getLocalCacheFile(any(), any()); Installable installable = new Installable(); - installable.url = fileRule.newFile().toURI().toString(); + installable.url = File.createTempFile("junit", null, fileRule).toURI().toString(); doReturn(installable).when(spy).getInstallable(); when(spy.getNpmPackages()).thenReturn(expectedPackages); @@ -195,7 +194,7 @@ public void test_cache_archive_is_used() throws Exception { // execute test FilePath expected = spy.performInstallation(toolInstallation, currentNode, taskListener); - Assertions.assertThat(expected.list("nodejs.txt")).isNotEmpty(); + assertThat(expected.list("nodejs.txt")).isNotEmpty(); } } @@ -211,23 +210,23 @@ private void fillArchive(File file, String fileEntry, byte[] content) throws IOE @Issue("JENKINS-56895") @Test - public void verify_global_packages_are_refreshed_also_if_nodejs_installation_is_uptodate() throws Exception { + void verify_global_packages_are_refreshed_also_if_nodejs_installation_is_uptodate() throws Exception { String expectedPackages = "npm@6.7.0"; int expectedRefreshHours = NodeJSInstaller.DEFAULT_NPM_PACKAGES_REFRESH_HOURS; Node currentNode = mock(Node.class); - when(currentNode.getRootPath()).thenReturn(new FilePath(fileRule.newFolder())); + when(currentNode.getRootPath()).thenReturn(new FilePath(newFolder(fileRule, "junit"))); // create partial mock NodeJSInstaller installer = new NodeJSInstaller("test-id", expectedPackages, expectedRefreshHours) { @Override public Installable getInstallable() throws IOException { Installable installable = new Installable(); - installable.url = fileRule.newFile().toURI().toString(); + installable.url = File.createTempFile("junit", null, fileRule).toURI().toString(); return installable; } @Override - protected boolean isUpToDate(FilePath expectedLocation, Installable i) throws IOException, InterruptedException { + protected boolean isUpToDate(FilePath expectedLocation, Installable i) { return true; } }; @@ -245,4 +244,13 @@ protected boolean isUpToDate(FilePath expectedLocation, Installable i) throws IO verify(spy).refreshGlobalPackages(any(Node.class), any(TaskListener.class), any(FilePath.class)); } + 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; + } + } \ No newline at end of file diff --git a/src/test/java/jenkins/plugins/nodejs/tools/ToolsUtilsTest.java b/src/test/java/jenkins/plugins/nodejs/tools/ToolsUtilsTest.java index a80fb64..53fe63f 100644 --- a/src/test/java/jenkins/plugins/nodejs/tools/ToolsUtilsTest.java +++ b/src/test/java/jenkins/plugins/nodejs/tools/ToolsUtilsTest.java @@ -23,64 +23,64 @@ */ package jenkins.plugins.nodejs.tools; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; import hudson.model.Node; -import org.assertj.core.api.Assertions; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; -public class ToolsUtilsTest { +class ToolsUtilsTest { private MockedStatic staticCpu; - @Before - public void setup() { + @BeforeEach + void setup() { CPU[] cpuValues = CPU.values(); staticCpu = mockStatic(CPU.class); staticCpu.when(CPU::values).thenReturn(cpuValues); } - @After - public void tearDown() { + @AfterEach + void tearDown() { staticCpu.close(); } @Test - public void nodejs_supports_32bit_64bit_on_windows_linux_mac() throws Exception { + void nodejs_supports_32bit_64bit_on_windows_linux_mac() throws Exception { Node currentNode = mock(Node.class); - + when(CPU.of(currentNode)).thenReturn(CPU.amd64); CPU cpu = ToolsUtils.getCPU(currentNode, true); - Assertions.assertThat(cpu).isEqualTo(CPU.i386); + assertThat(cpu).isEqualTo(CPU.i386); cpu = ToolsUtils.getCPU(currentNode); - Assertions.assertThat(cpu).isEqualTo(CPU.amd64); + assertThat(cpu).isEqualTo(CPU.amd64); } - @Test(expected = DetectionFailedException.class) - public void nodejs_doesn_t_supports_32bit_on_armv64() throws Exception { + @Test + void nodejs_doesn_t_supports_32bit_on_armv64() throws Exception { Node currentNode = mock(Node.class); - when(CPU.of(currentNode)).thenReturn(CPU.arm64); - ToolsUtils.getCPU(currentNode, true); + assertThatThrownBy(() -> ToolsUtils.getCPU(currentNode, true)).isInstanceOf(DetectionFailedException.class); } @Test - public void nodejs_supports_32bit_on_armv6_armv7() throws Exception { + void nodejs_supports_32bit_on_armv6_armv7() throws Exception { Node currentNode = mock(Node.class); when(CPU.of(currentNode)).thenReturn(CPU.armv7l); CPU cpu = ToolsUtils.getCPU(currentNode, true); - Assertions.assertThat(cpu).isEqualTo(CPU.armv7l); + assertThat(cpu).isEqualTo(CPU.armv7l); when(CPU.of(currentNode)).thenReturn(CPU.armv6l); cpu = ToolsUtils.getCPU(currentNode, true); - Assertions.assertThat(cpu).isEqualTo(CPU.armv6l); + assertThat(cpu).isEqualTo(CPU.armv6l); } } \ No newline at end of file