diff --git a/pom.xml b/pom.xml index 699ee718..d3f3d5a2 100644 --- a/pom.xml +++ b/pom.xml @@ -82,7 +82,7 @@ org.mockito - mockito-core + mockito-junit-jupiter test diff --git a/src/test/java/hudson/matrix/AxisDescriptorTest.java b/src/test/java/hudson/matrix/AxisDescriptorTest.java index c048e8ff..f58eb0f4 100644 --- a/src/test/java/hudson/matrix/AxisDescriptorTest.java +++ b/src/test/java/hudson/matrix/AxisDescriptorTest.java @@ -23,17 +23,17 @@ */ package hudson.matrix; -import static org.junit.Assert.*; import hudson.util.FormValidation; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AxisDescriptorTest { +class AxisDescriptorTest { - TextAxis.DescriptorImpl descriptor = new TextAxis.DescriptorImpl(); + private final TextAxis.DescriptorImpl descriptor = new TextAxis.DescriptorImpl(); @Test - public void combinationNameSpecialChars() { + void combinationNameSpecialChars() { assertEquals( FormValidation.Kind.ERROR, descriptor.doCheckName("a=b").kind @@ -51,7 +51,7 @@ public void combinationNameSpecialChars() { } @Test - public void combinationValueSpecialChars() { + void combinationValueSpecialChars() { assertEquals( FormValidation.Kind.OK, descriptor.checkValue("a=b").kind diff --git a/src/test/java/hudson/matrix/AxisTest.java b/src/test/java/hudson/matrix/AxisTest.java index 8400eabc..218a6357 100644 --- a/src/test/java/hudson/matrix/AxisTest.java +++ b/src/test/java/hudson/matrix/AxisTest.java @@ -27,7 +27,6 @@ import hudson.Util; import hudson.model.JDK; import hudson.util.VersionNumber; -import java.util.List; import jenkins.model.Jenkins; import org.hamcrest.collection.IsEmptyCollection; import org.htmlunit.HttpMethod; @@ -37,32 +36,34 @@ import org.htmlunit.html.HtmlInput; import org.htmlunit.html.HtmlPage; import org.htmlunit.xml.XmlPage; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.WebClient; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.xml.sax.SAXException; import java.io.IOException; import java.net.URL; +import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AxisTest { +@WithJenkins +class AxisTest { - public @Rule JenkinsRule j = new JenkinsRule(); + private JenkinsRule j; private MatrixProject p; private WebClient wc; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + j = rule; wc = j.createWebClient(); p = j.createProject(MatrixProject.class); @@ -72,7 +73,7 @@ public void setUp() throws Exception { } @Test - public void submitEmptyAxisName() throws Exception { + void submitEmptyAxisName() throws Exception { wc.getOptions().setThrowExceptionOnFailingStatusCode(false); final String expectedMsg = "Matrix axis name '' is invalid: Axis name can not be empty"; @@ -82,7 +83,7 @@ public void submitEmptyAxisName() throws Exception { } @Test - public void submitInvalidAxisName() throws Exception { + void submitInvalidAxisName() throws Exception { wc.getOptions().setThrowExceptionOnFailingStatusCode(false); String expectedMsg = "Matrix axis name 'a,b' is invalid: ‘,’ is an unsafe character"; @@ -110,7 +111,7 @@ private void setName(HtmlForm form, String value) { } @Test - public void submitInvalidAxisValue() throws Exception { + void submitInvalidAxisValue() throws Exception { wc.getOptions().setThrowExceptionOnFailingStatusCode(false); HtmlForm form = addAxis("User-defined Axis"); @@ -125,23 +126,24 @@ public void submitInvalidAxisValue() throws Exception { } @Test - public void emptyAxisValueListResultInNoConfigurations() throws Exception { + void emptyAxisValueListResultInNoConfigurations() throws Exception { emptyValue("User-defined Axis"); emptyValue("Agents"); emptyValue("Label expression"); emptyValue("JDK"); MatrixBuild build = j.buildAndAssertSuccess(p); - assertThat(build.getRuns(), new IsEmptyCollection()); - assertThat(p.getItems(), new IsEmptyCollection()); + assertThat(build.getRuns(), new IsEmptyCollection<>()); + assertThat(p.getItems(), new IsEmptyCollection<>()); for (Axis axis : p.getAxes()) { assertEquals("", axis.getValueString()); } } - @Test @Issue("SECURITY-3289") - public void testHaxorNameFromConfigXml() throws IOException, SAXException { + @Test + @Issue("SECURITY-3289") + void testHaxorNameFromConfigXml() throws IOException, SAXException { p.getAxes().add(new TextAxis("CHANGEME", p.getName())); p.save(); XmlPage xmlPage = wc.goToXml(p.getUrl() + "config.xml"); @@ -189,7 +191,7 @@ private HtmlPage emptyValue(String axis) throws Exception { return ret; } - private void assertFailedWith(String expected, HtmlPage res) { + private static void assertFailedWith(String expected, HtmlPage res) { String actual = res.getWebResponse().getContentAsString(); assertThat(actual, res.getWebResponse().getStatusCode(), equalTo(400)); @@ -210,7 +212,7 @@ private HtmlForm addAxis(String axis) throws Exception { return form; } - private void waitForInput(HtmlForm form) throws InterruptedException { + private static void waitForInput(HtmlForm form) throws InterruptedException { int numberInputs = form.getInputsByName("_.name").size(); int initialInputs = numberInputs; int tries = 18; // 18 * 17 == 306 diff --git a/src/test/java/hudson/matrix/CombinationFilterUsingBuildParamsTest.java b/src/test/java/hudson/matrix/CombinationFilterUsingBuildParamsTest.java index 2b1cb732..506a9bbf 100644 --- a/src/test/java/hudson/matrix/CombinationFilterUsingBuildParamsTest.java +++ b/src/test/java/hudson/matrix/CombinationFilterUsingBuildParamsTest.java @@ -23,13 +23,6 @@ */ package hudson.matrix; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import hudson.ExtensionList; import hudson.matrix.MatrixBuild.MatrixBuildExecution; import hudson.matrix.listeners.MatrixBuildListener; @@ -39,54 +32,64 @@ import hudson.model.Result; import hudson.model.Run; import hudson.model.StringParameterValue; +import org.apache.commons.io.output.ByteArrayOutputStream; +import org.jenkinsci.plugins.scriptsecurity.sandbox.Whitelist; +import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.BlanketWhitelist; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.jvnet.hudson.test.Issue; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.verification.VerificationMode; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import org.apache.commons.io.output.ByteArrayOutputStream; -import org.jenkinsci.plugins.scriptsecurity.sandbox.Whitelist; -import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.BlanketWhitelist; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.jvnet.hudson.test.Issue; -import org.mockito.Mock; -import org.mockito.MockedStatic; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.verification.VerificationMode; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * Make sure that the combination filter schedules correct builds in correct order * * @author ogondza */ -@Ignore("TODO ScriptApproval.get fails with NPE in ExtensionList.lookup(RootAction.class).get(ScriptApproval.class)") -public class CombinationFilterUsingBuildParamsTest { +@Disabled("TODO ScriptApproval.get fails with NPE in ExtensionList.lookup(RootAction.class).get(ScriptApproval.class)") +@ExtendWith(MockitoExtension.class) +class CombinationFilterUsingBuildParamsTest { /** * Execute releases: experimental, stable, beta, devel - * - * x s b d + *

+ * x s b d * 0.1 * 0.9 * * * * - * 1 * * * - * 2 * * - * 3 * + * 1 * * * + * 2 * * + * 3 * */ private static final String filter = String.format( - "(%s) || (%s) || (%s)", - "RELEASE == 'stable' && VERSION == '1'", - "RELEASE == 'beta' && VERSION >= '1' && VERSION <= '2'", - "RELEASE == 'devel' && VERSION >= '1' && VERSION <= '3'" - ); + "(%s) || (%s) || (%s)", + "RELEASE == 'stable' && VERSION == '1'", + "RELEASE == 'beta' && VERSION >= '1' && VERSION <= '2'", + "RELEASE == 'devel' && VERSION >= '1' && VERSION <= '3'" + ); private static final String touchstoneFilter = "VERSION == '0.9'"; @@ -94,24 +97,26 @@ public class CombinationFilterUsingBuildParamsTest { "stable", "beta", "devel", "experimental" ); - private final Map confs = new HashMap(); - private final MatrixExecutionStrategy strategy = new DefaultMatrixExecutionStrategyImpl ( + private final Map confs = new HashMap<>(); + private final MatrixExecutionStrategy strategy = new DefaultMatrixExecutionStrategyImpl( true, touchstoneFilter, Result.SUCCESS, new NoopMatrixConfigurationSorter() ); private MatrixProject project; - @Mock private MatrixBuildExecution execution; - @Mock private MatrixBuild build; - @Mock private MatrixRun run; - @Mock private BuildListener listener; - - @Mock private ExtensionList extensions; - - @Before - public void setUp() throws Exception { - - MockitoAnnotations.openMocks(this); - + @Mock + private MatrixBuildExecution execution; + @Mock + private MatrixBuild build; + @Mock + private MatrixRun run; + @Mock + private BuildListener listener; + + @Mock + private ExtensionList extensions; + + @BeforeEach + void setUp() { usingDummyJenkins(); usingNoListeners(); usingDummyProject(); @@ -120,8 +125,7 @@ public void setUp() throws Exception { } @Test - public void testCombinationFilterV01() throws InterruptedException, IOException { - + void testCombinationFilterV01() throws InterruptedException, IOException { givenTheVersionIs("0.1"); strategy.run(execution); @@ -133,8 +137,7 @@ public void testCombinationFilterV01() throws InterruptedException, IOException } @Test - public void testCombinationFilterV09() throws InterruptedException, IOException { - + void testCombinationFilterV09() throws InterruptedException, IOException { givenTheVersionIs("0.9"); strategy.run(execution); @@ -146,8 +149,7 @@ public void testCombinationFilterV09() throws InterruptedException, IOException } @Test - public void testCombinationFilterV1() throws InterruptedException, IOException { - + void testCombinationFilterV1() throws InterruptedException, IOException { givenTheVersionIs("1"); strategy.run(execution); @@ -159,8 +161,7 @@ public void testCombinationFilterV1() throws InterruptedException, IOException { } @Test - public void testCombinationFilterV2() throws InterruptedException, IOException { - + void testCombinationFilterV2() throws InterruptedException, IOException { givenTheVersionIs("2"); strategy.run(execution); @@ -172,8 +173,7 @@ public void testCombinationFilterV2() throws InterruptedException, IOException { } @Test - public void testCombinationFilterV3() throws InterruptedException, IOException { - + void testCombinationFilterV3() throws InterruptedException, IOException { givenTheVersionIs("3"); strategy.run(execution); @@ -186,12 +186,11 @@ public void testCombinationFilterV3() throws InterruptedException, IOException { @Test @Issue("JENKINS-7285") - public void reproduceTouchstoneRegression () throws InterruptedException, IOException { - + void reproduceTouchstoneRegression() throws InterruptedException, IOException { givenTheVersionIs("3"); // No touchstone - MatrixExecutionStrategy myStrategy = new DefaultMatrixExecutionStrategyImpl ( + MatrixExecutionStrategy myStrategy = new DefaultMatrixExecutionStrategyImpl( true, null, Result.SUCCESS, new NoopMatrixConfigurationSorter() ); @@ -204,7 +203,6 @@ true, null, Result.SUCCESS, new NoopMatrixConfigurationSorter() } private void usingDummyProject() { - project = Mockito.mock(MatrixProject.class); Mockito.when(build.getParent()).thenReturn(project); @@ -216,7 +214,6 @@ private void usingDummyProject() { } private void usingDummyExecution() { - when(execution.getProject()).thenReturn(project); when(execution.getBuild()).thenReturn(build); when(execution.getListener()).thenReturn(listener); @@ -237,8 +234,8 @@ private void usingDummyJenkins() { } } - private void usingNoListeners() throws Exception { - when(extensions.iterator()).thenReturn(new ArrayList().iterator()); + private void usingNoListeners() { + when(extensions.iterator()).thenReturn(Collections.emptyIterator()); try (MockedStatic mocked = Mockito.mockStatic(MatrixBuildListener.class)) { mocked.when(MatrixBuildListener::all).thenReturn(extensions); when(MatrixBuildListener.buildConfiguration(any(MatrixBuild.class), any(MatrixConfiguration.class))).thenCallRealMethod(); @@ -246,19 +243,16 @@ private void usingNoListeners() throws Exception { } private void withReleaseAxis(final List releases) { - - for(final String release: releases) { - - confs.put(release, getConfiguration("RELEASE=" + release)); + for (final String release : releases) { + confs.put(release, getConfiguration("RELEASE=" + release)); } when(execution.getActiveConfigurations()).thenReturn( - new HashSet(confs.values()) + new HashSet<>(confs.values()) ); } - private MatrixConfiguration getConfiguration (final String axis) { - + private MatrixConfiguration getConfiguration(final String axis) { final MatrixConfiguration conf = mock(MatrixConfiguration.class); when(conf.getParent()).thenReturn(project); when(conf.getCombination()).thenReturn(Combination.fromString(axis)); @@ -270,23 +264,20 @@ private MatrixConfiguration getConfiguration (final String axis) { } private void givenTheVersionIs(final String version) { - final ParametersAction parametersAction = new ParametersAction( new StringParameterValue("VERSION", version) ); when(build.getAction(ParametersAction.class)) - .thenReturn(parametersAction) + .thenReturn(parametersAction) ; } private void wasBuilt(final MatrixConfiguration conf) { - wasBuildTimes(conf, times(1)); } private void wasNotBuilt(final MatrixConfiguration conf) { - wasBuildTimes(conf, never()); } diff --git a/src/test/java/hudson/matrix/CombinationTest.java b/src/test/java/hudson/matrix/CombinationTest.java index b96f5fcc..93de975e 100644 --- a/src/test/java/hudson/matrix/CombinationTest.java +++ b/src/test/java/hudson/matrix/CombinationTest.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,64 +23,65 @@ */ package hudson.matrix; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; - import groovy.lang.GroovyRuntimeException; +import org.junit.jupiter.api.Test; +import org.jvnet.hudson.test.Issue; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.Issue; -import org.jvnet.hudson.test.JenkinsRule; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Kohsuke Kawaguchi */ -public class CombinationTest { - - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class CombinationTest { - AxisList axes = new AxisList( - new Axis("a","X","x"), - new Axis("b","Y","y")); + private final AxisList axes = new AxisList( + new Axis("a", "X", "x"), + new Axis("b", "Y", "y")); @Test - public void testEval() { - Map r = new HashMap(); - r.put("a","X"); - r.put("b",new String("Y")); // make sure this 'Y' is not the same object as literal "Y". + void testEval(JenkinsRule j) { + Map r = new HashMap<>(); + r.put("a", "X"); + r.put("b", new String("Y")); // make sure this 'Y' is not the same object as literal "Y". Combination c = new Combination(r); - r.put("a","x"); + r.put("a", "x"); Combination d = new Combination(r); assertTrue(eval(c, null)); - assertTrue(eval(c," ")); - assertTrue(eval(c,"true")); - assertTrue(eval(c,"a=='X'")); - assertTrue(eval(c,"b=='Y'")); - assertTrue(eval(c,"(a=='something').implies(b=='other')")); - assertTrue(eval(c,"index%2==0")^eval(d,"index%2==0")); - assertTrue(eval(c,"index%2==1")^eval(d,"index%2==1")); + assertTrue(eval(c, " ")); + assertTrue(eval(c, "true")); + assertTrue(eval(c, "a=='X'")); + assertTrue(eval(c, "b=='Y'")); + assertTrue(eval(c, "(a=='something').implies(b=='other')")); + assertTrue(eval(c, "index%2==0") ^ eval(d, "index%2==0")); + assertTrue(eval(c, "index%2==1") ^ eval(d, "index%2==1")); } @Issue("SECURITY-1339") @Test - public void testSandboxConstructors() { - Combination c = new Combination(Collections.emptyMap()); + void testSandboxConstructors(JenkinsRule j) { + Combination c = new Combination(Collections.emptyMap()); GroovyRuntimeException e = assertThrows(GroovyRuntimeException.class, () -> - eval(c, "class DoNotRunConstructor {\n" + - " static void main(String[] args) {}\n" + - " DoNotRunConstructor() {\n" + - " assert jenkins.model.Jenkins.instance.createProject(hudson.model.FreeStyleProject, 'should-not-exist')\n" + - " }\n" + - "}\n")); + eval(c, """ + class DoNotRunConstructor { + static void main(String[] args) {} + DoNotRunConstructor() { + assert jenkins.model.Jenkins.instance.createProject(hudson.model.FreeStyleProject, 'should-not-exist') + } + } + """)); assertNull(j.jenkins.getItem("should-not-exist")); assertThat(e.getMessage(), containsString("staticMethod jenkins.model.Jenkins getInstance")); } diff --git a/src/test/java/hudson/matrix/LabelExpAxisTest.java b/src/test/java/hudson/matrix/LabelExpAxisTest.java index 56fbd4d4..ed888fde 100644 --- a/src/test/java/hudson/matrix/LabelExpAxisTest.java +++ b/src/test/java/hudson/matrix/LabelExpAxisTest.java @@ -23,23 +23,22 @@ */ package hudson.matrix; -import static org.junit.Assert.*; import hudson.matrix.LabelExpAxis.DescriptorImpl; import hudson.util.FormValidation; - -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class LabelExpAxisTest { +import static org.junit.jupiter.api.Assertions.assertEquals; - @Rule public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class LabelExpAxisTest { @Test - public void test() throws Exception { + void test(JenkinsRule j) throws Exception { j.jenkins.setLabelString("aaaa bbbb"); - MatrixProject project = j.createProject(MatrixProject.class,"project"); + MatrixProject project = j.createProject(MatrixProject.class, "project"); DescriptorImpl descriptor = new LabelExpAxis.DescriptorImpl(); assertEquals(FormValidation.Kind.ERROR, descriptor.doCheckLabelExpr(project, "").kind); diff --git a/src/test/java/hudson/matrix/MatrixChildParametersActionTest.java b/src/test/java/hudson/matrix/MatrixChildParametersActionTest.java index 29e1dd5d..9e63c0a9 100644 --- a/src/test/java/hudson/matrix/MatrixChildParametersActionTest.java +++ b/src/test/java/hudson/matrix/MatrixChildParametersActionTest.java @@ -1,34 +1,36 @@ package hudson.matrix; -import hudson.model.*; -import org.junit.Rule; -import org.junit.Test; +import hudson.model.ParameterValue; +import hudson.model.ParametersAction; +import hudson.model.ParametersDefinitionProperty; +import hudson.model.StringParameterDefinition; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; /** * Created by lvotypko on 4/4/17. */ -public class MatrixChildParametersActionTest { - - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class MatrixChildParametersActionTest { @Test - public void testLoadingParameters() throws Exception { + void testLoadingParameters(JenkinsRule j) throws Exception { MatrixProject project = j.createProject(MatrixProject.class, "project"); StringParameterDefinition def1 = new StringParameterDefinition("definition1", "value1", "description"); StringParameterDefinition def2 = new StringParameterDefinition("definition2", "value2", "description"); - ParametersDefinitionProperty prop = new ParametersDefinitionProperty(def1,def2); + ParametersDefinitionProperty prop = new ParametersDefinitionProperty(def1, def2); project.addProperty(prop); AxisList axes = new AxisList( - new Axis("a","axis1","axis2")); + new Axis("a", "axis1", "axis2")); project.setAxes(axes); project.save(); j.buildAndAssertSuccess(project); MatrixBuild build = project.getLastBuild(); - assertEquals("Two configuration should have been build.",2, build.getRuns().size()); + assertEquals(2, build.getRuns().size(), "Two configuration should have been build."); checkReferencesForParameters(build); //reloading @@ -38,16 +40,16 @@ public void testLoadingParameters() throws Exception { checkReferencesForParameters(build); } - private void checkReferencesForParameters(MatrixBuild build) { + private static void checkReferencesForParameters(MatrixBuild build) { ParametersAction action = build.getAction(ParametersAction.class); ParameterValue definition1 = action.getParameter("definition1"); ParameterValue definition2 = action.getParameter("definition2"); - for(MatrixRun run : build.getExactRuns()){ + for (MatrixRun run : build.getExactRuns()) { ParametersAction matrichChildParameters = run.getAction(ParametersAction.class); ParameterValue definition1Child = matrichChildParameters.getParameter("definition1"); ParameterValue definition2Child = matrichChildParameters.getParameter("definition2"); - assertSame("Parameters shoud be references to parameters of parent build.", definition1Child, definition1); - assertSame("Parameters shoud be references to parameters of parent build.", definition2Child, definition2); + assertSame(definition1Child, definition1, "Parameters shoud be references to parameters of parent build."); + assertSame(definition2Child, definition2, "Parameters shoud be references to parameters of parent build."); } } } diff --git a/src/test/java/hudson/matrix/MatrixConfigurationSorterTest.java b/src/test/java/hudson/matrix/MatrixConfigurationSorterTest.java index 42282c78..bbf4a377 100644 --- a/src/test/java/hudson/matrix/MatrixConfigurationSorterTest.java +++ b/src/test/java/hudson/matrix/MatrixConfigurationSorterTest.java @@ -1,47 +1,47 @@ package hudson.matrix; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertNotSame; import hudson.model.Item; -import hudson.util.FormValidation; - -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.stapler.DataBoundConstructor; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * @author Kohsuke Kawaguchi */ -public class MatrixConfigurationSorterTest { +@WithJenkins +class MatrixConfigurationSorterTest { - @Rule public JenkinsRule j = new JenkinsRule(); - - @Test public void testConfigRoundtrip() throws Exception { + @Test + void testConfigRoundtrip(JenkinsRule j) throws Exception { MatrixProject p = j.createProject(MatrixProject.class); - j.configRoundtrip((Item)p); - j.assertEqualDataBoundBeans(new NoopMatrixConfigurationSorter(),strategy(p).getSorter()); + j.configRoundtrip((Item) p); + j.assertEqualDataBoundBeans(new NoopMatrixConfigurationSorter(), strategy(p).getSorter()); SorterImpl before = new SorterImpl(); strategy(p).setSorter(before); strategy(p).setRunSequentially(true); - j.configRoundtrip((Item)p); + j.configRoundtrip((Item) p); MatrixConfigurationSorter after = strategy(p).getSorter(); - assertNotSame(before,after); - assertSame(before.getClass(),after.getClass()); + assertNotSame(before, after); + assertSame(before.getClass(), after.getClass()); } - private DefaultMatrixExecutionStrategyImpl strategy(MatrixProject p) { + private static DefaultMatrixExecutionStrategyImpl strategy(MatrixProject p) { return (DefaultMatrixExecutionStrategyImpl) p.getExecutionStrategy(); } public static class SorterImpl extends MatrixConfigurationSorter { @DataBoundConstructor - public SorterImpl() {} + public SorterImpl() { + } @Override - public void validate(MatrixProject p) throws FormValidation { + public void validate(MatrixProject p) { } public int compare(MatrixConfiguration o1, MatrixConfiguration o2) { diff --git a/src/test/java/hudson/matrix/MatrixConfigurationTest.java b/src/test/java/hudson/matrix/MatrixConfigurationTest.java index f0bfabfb..1b189fa2 100644 --- a/src/test/java/hudson/matrix/MatrixConfigurationTest.java +++ b/src/test/java/hudson/matrix/MatrixConfigurationTest.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c), Red Hat, Inc. - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,52 +23,50 @@ */ package hudson.matrix; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; - import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; +import org.htmlunit.html.HtmlPage; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.WebClient; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -import org.htmlunit.html.HtmlPage; +import java.util.Arrays; +import java.util.Collection; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@WithJenkins +class MatrixConfigurationTest { -public class MatrixConfigurationTest { - - @Rule public JenkinsRule r = new JenkinsRule(); - @Test - public void testDelete() throws Exception{ + void testDelete(JenkinsRule r) throws Exception { MatrixProject project = r.createProject(MatrixProject.class); AxisList axes = new AxisList( - new Axis("a","active1","active2", "unactive")); + new Axis("a", "active1", "active2", "unactive")); project.setAxes(axes); project.setCombinationFilter("a!=\"unactive\""); MatrixConfiguration toDelete = project.getItem("a=unactive"); toDelete.delete(); - assertFalse("Configuration should be deleted for disk", toDelete.getRootDir().exists()); - assertNull("Configuration should be deleted from parent matrix project", project.getItem(toDelete.getCombination())); + assertFalse(toDelete.getRootDir().exists(), "Configuration should be deleted for disk"); + assertNull(project.getItem(toDelete.getCombination()), "Configuration should be deleted from parent matrix project"); MatrixConfiguration notDelete = project.getItem("a=active1"); notDelete.delete(); - assertTrue("Active configuration should not be deleted for disk", notDelete.getRootDir().exists()); - assertNotNull("Active configuration should not be deleted from parent matrix project", project.getItem(notDelete.getCombination())); - assertFalse("Active configuration should not be disabled,", notDelete.isDisabled()); + assertTrue(notDelete.getRootDir().exists(), "Active configuration should not be deleted for disk"); + assertNotNull(project.getItem(notDelete.getCombination()), "Active configuration should not be deleted from parent matrix project"); + assertFalse(notDelete.isDisabled(), "Active configuration should not be disabled,"); } - - @Test @Issue("JENKINS-32423") - public void doNotServeConfigurePage() throws Exception { + + @Test + @Issue("JENKINS-32423") + void doNotServeConfigurePage(JenkinsRule r) throws Exception { MatrixProject p = r.createProject(MatrixProject.class); p.setAxes(new AxisList(new Axis("a", "b"))); @@ -77,11 +75,11 @@ public void doNotServeConfigurePage() throws Exception { wc.getOptions().setPrintContentOnFailingStatusCode(false); HtmlPage page = wc.getPage(p.getItem("a=b"), "configure"); - assertEquals("Page should not exist", 404, page.getWebResponse().getStatusCode()); + assertEquals(404, page.getWebResponse().getStatusCode(), "Page should not exist"); } @Test - public void labelAxis() throws Exception { + void labelAxis(JenkinsRule r) throws Exception { LabelAxis label = new LabelAxis("label", Arrays.asList("a", "b")); LabelExpAxis expr = new LabelExpAxis("expr", Arrays.asList("a||b", "a&&b")); @@ -93,17 +91,17 @@ public void labelAxis() throws Exception { combinedP.setAxes(new AxisList(expr, label)); Collection lc = labelP.getItems(); - assertThat(lc, Matchers.iterableWithSize(2)); + assertThat(lc, Matchers.iterableWithSize(2)); assertEquals("a", labelP.getItem("label=a").getAssignedLabel().toString()); assertEquals("b", labelP.getItem("label=b").getAssignedLabel().toString()); Collection ec = exprP.getItems(); - assertThat(ec, Matchers.iterableWithSize(2)); + assertThat(ec, Matchers.iterableWithSize(2)); assertEquals("a||b", exprP.getItem("expr=a||b").getAssignedLabel().toString()); assertEquals("a&&b", exprP.getItem("expr=a&&b").getAssignedLabel().toString()); Collection cc = combinedP.getItems(); - assertThat(cc, Matchers.iterableWithSize(4)); + assertThat(cc, Matchers.iterableWithSize(4)); assertEquals("a&&b&&a", combinedP.getItem("expr=a&&b,label=a").getAssignedLabel().toString()); assertEquals("a&&b&&b", combinedP.getItem("expr=a&&b,label=b").getAssignedLabel().toString()); assertEquals("a||b&&a", combinedP.getItem("expr=a||b,label=a").getAssignedLabel().toString()); @@ -112,16 +110,16 @@ public void labelAxis() throws Exception { @Test @Issue("JENKINS-37292") - public void nextBuildNumber() throws Exception { + void nextBuildNumber(JenkinsRule r) throws Exception { MatrixProject p = r.createProject(MatrixProject.class); p.setAxes(new AxisList(new Axis("a", "b"))); - p.getItems().forEach( mc -> { - int size = (int)mc.getBuilds().stream().count(); + p.getItems().forEach(mc -> { + int size = mc.getBuilds().size(); assertThat(mc.getNextBuildNumber(), is(greaterThan(size))); }); r.buildAndAssertSuccess(p); - p.getItems().forEach( mc -> { - int size = (int)mc.getBuilds().stream().count(); + p.getItems().forEach(mc -> { + int size = mc.getBuilds().size(); assertThat(mc.getNextBuildNumber(), is(greaterThan(size))); }); } diff --git a/src/test/java/hudson/matrix/MatrixProjectCustomWorkspaceTest.java b/src/test/java/hudson/matrix/MatrixProjectCustomWorkspaceTest.java index 620e24fd..0065454c 100644 --- a/src/test/java/hudson/matrix/MatrixProjectCustomWorkspaceTest.java +++ b/src/test/java/hudson/matrix/MatrixProjectCustomWorkspaceTest.java @@ -1,77 +1,75 @@ package hudson.matrix; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; import hudson.FilePath; - -import java.util.concurrent.CountDownLatch; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.jvnet.hudson.test.JenkinsRule; -import org.jvnet.hudson.test.TestBuilder; - -import hudson.model.AbstractBuild; import hudson.Launcher; +import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.queue.QueueTaskFuture; +import jenkins.model.Jenkins; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.TestBuilder; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CountDownLatch; -import jenkins.model.Jenkins; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; /** * Tests the custom workspace support in {@link MatrixProject}. - * + *

* To validate the lease behaviour, use concurrent builds to run two builds and make sure they get * same/different workspaces. * * @author Kohsuke Kawaguchi */ -public class MatrixProjectCustomWorkspaceTest { +@WithJenkins +class MatrixProjectCustomWorkspaceTest { private static final String S = File.separator; - @Rule public JenkinsRule j = new JenkinsRule(); - @Rule public TemporaryFolder tmp = new TemporaryFolder(); + @TempDir + private File tmp; @Test - public void customWorkspaceForParentAndChild() throws Exception { + void customWorkspaceForParentAndChild(JenkinsRule j) throws Exception { MatrixProject p = j.createProject(MatrixProject.class); - File dir = tmp.newFolder(); + File dir = newFolder(tmp, "junit"); p.setCustomWorkspace(dir.getPath()); p.setChildCustomWorkspace("xyz"); j.configRoundtrip(p); - configureCustomWorkspaceConcurrentBuild(p); + configureCustomWorkspaceConcurrentBuild(j, p); // all concurrent builds should build on the same one workspace - for (MatrixBuild b : runTwoConcurrentBuilds(p)) { + for (MatrixBuild b : runTwoConcurrentBuilds(j, p)) { assertEquals(dir.getPath(), b.getWorkspace().getRemote()); for (MatrixRun r : b.getRuns()) { - assertEquals(new File(dir,"xyz").getPath(), r.getWorkspace().getRemote()); + assertEquals(new File(dir, "xyz").getPath(), r.getWorkspace().getRemote()); } } } @Test - public void customWorkspaceForParent() throws Exception { + void customWorkspaceForParent(JenkinsRule j) throws Exception { MatrixProject p = j.createProject(MatrixProject.class); - File dir = tmp.newFolder(); + File dir = newFolder(tmp, "junit"); p.setCustomWorkspace(dir.getPath()); p.setChildCustomWorkspace(null); j.configRoundtrip(p); - configureCustomWorkspaceConcurrentBuild(p); + configureCustomWorkspaceConcurrentBuild(j, p); - List bs = runTwoConcurrentBuilds(p); + List bs = runTwoConcurrentBuilds(j, p); // all parent builds share the same workspace for (MatrixBuild b : bs) { @@ -83,23 +81,23 @@ public void customWorkspaceForParent() throws Exception { } // but foo=1 #1 and foo=2 #1 shouldn't. for (int i = 0; i < 2; i++) { - assertFalse(bs.get(i).getRuns().get(0).getWorkspace().equals(bs.get(i).getRuns().get(1).getWorkspace())); + assertNotEquals(bs.get(i).getRuns().get(0).getWorkspace(), bs.get(i).getRuns().get(1).getWorkspace()); } } @Test - public void customWorkspaceForChild() throws Exception { + void customWorkspaceForChild(JenkinsRule j) throws Exception { MatrixProject p = j.createProject(MatrixProject.class); p.setCustomWorkspace(null); p.setChildCustomWorkspace("."); j.configRoundtrip(p); - configureCustomWorkspaceConcurrentBuild(p); + configureCustomWorkspaceConcurrentBuild(j, p); - List bs = runTwoConcurrentBuilds(p); + List bs = runTwoConcurrentBuilds(j, p); // each parent gets different directory - assertFalse(bs.get(0).getWorkspace().equals(bs.get(1).getWorkspace())); + assertNotEquals(bs.get(0).getWorkspace(), bs.get(1).getWorkspace()); // but all #1 builds should get the same workspace for (MatrixBuild b : bs) { for (int i = 0; i < 2; i++) { @@ -112,34 +110,34 @@ public void customWorkspaceForChild() throws Exception { * Test the case where neither has custom workspace */ @Test - public void noCustomWorkspace() throws Exception { + void noCustomWorkspace(JenkinsRule j) throws Exception { MatrixProject p = j.createProject(MatrixProject.class); p.setCustomWorkspace(null); p.setChildCustomWorkspace(null); j.configRoundtrip(p); - configureCustomWorkspaceConcurrentBuild(p); + configureCustomWorkspaceConcurrentBuild(j, p); - List bs = runTwoConcurrentBuilds(p); + List bs = runTwoConcurrentBuilds(j, p); // each parent gets different directory - assertFalse(bs.get(0).getWorkspace().equals(bs.get(1).getWorkspace())); + assertNotEquals(bs.get(0).getWorkspace(), bs.get(1).getWorkspace()); // and every sub-build gets a different directory for (MatrixBuild b : bs) { FilePath x = b.getRuns().get(0).getWorkspace(); FilePath y = b.getRuns().get(1).getWorkspace(); FilePath z = b.getWorkspace(); - - assertFalse(x.equals(y)); - assertFalse(y.equals(z)); - assertFalse(z.equals(x)); + + assertNotEquals(x, y); + assertNotEquals(y, z); + assertNotEquals(z, x); } } /** * Configures MatrixProject such that two builds run concurrently. */ - private void configureCustomWorkspaceConcurrentBuild(MatrixProject p) throws Exception { + private void configureCustomWorkspaceConcurrentBuild(JenkinsRule j, MatrixProject p) throws Exception { // needs sufficient parallel execution capability j.jenkins.setNumExecutors(10); Method m = Jenkins.class.getDeclaredMethod("updateComputerList"); // TODO is this really necessary? @@ -151,7 +149,8 @@ private void configureCustomWorkspaceConcurrentBuild(MatrixProject p) throws Exc final CountDownLatch latch = new CountDownLatch(4); p.getBuildersList().add(new TestBuilder() { - @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { + @Override + public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) { latch.countDown(); try { latch.await(); @@ -165,20 +164,20 @@ private void configureCustomWorkspaceConcurrentBuild(MatrixProject p) throws Exc /** * Runs two concurrent builds and return their results. */ - private List runTwoConcurrentBuilds(MatrixProject p) throws Exception { + private static List runTwoConcurrentBuilds(JenkinsRule j, MatrixProject p) throws Exception { QueueTaskFuture f1 = p.scheduleBuild2(0); // get one going f1.waitForStart(); QueueTaskFuture f2 = p.scheduleBuild2(0); - List bs = new ArrayList(); + List bs = new ArrayList<>(); bs.add(j.assertBuildStatusSuccess(f1.get())); bs.add(j.assertBuildStatusSuccess(f2.get())); return bs; } @Test - public void useCombinationInWorkspaceName() throws Exception { + void useCombinationInWorkspaceName(JenkinsRule j) throws Exception { MatrixProject p = j.jenkins.createProject(MatrixProject.class, "defaultName"); p.setAxes(new AxisList(new TextAxis("AXIS", "VALUE"))); @@ -189,7 +188,7 @@ public void useCombinationInWorkspaceName() throws Exception { } @Test - public void useShortWorkspaceNameGlobally() throws Exception { + void useShortWorkspaceNameGlobally(JenkinsRule j) throws Exception { MatrixConfiguration.useShortWorkspaceName = true; MatrixProject p = j.jenkins.createProject(MatrixProject.class, "shortName"); @@ -209,14 +208,14 @@ public void useShortWorkspaceNameGlobally() throws Exception { } @Test - public void useShortWorkspaceNamePerProject() throws Exception { + void useShortWorkspaceNamePerProject(JenkinsRule j) throws Exception { MatrixProject p = j.jenkins.createProject(MatrixProject.class, "shortName"); p.setAxes(new AxisList(new TextAxis("AXIS", "VALUE"))); p.scheduleBuild2(0).get(); MatrixRun build = p.getItem("AXIS=VALUE").getLastBuild(); - assertThat(build.getWorkspace().getRemote(), containsString(S + "workspace" + S + "shortName" + S + "AXIS" + S + "VALUE")); + assertThat(build.getWorkspace().getRemote(), containsString(S + "workspace" + S + "shortName" + S + "AXIS" + S + "VALUE")); p.setChildCustomWorkspace("${SHORT_COMBINATION}"); @@ -225,4 +224,13 @@ public void useShortWorkspaceNamePerProject() throws Exception { assertThat(build.getWorkspace().getRemote(), containsString(S + "workspace" + S + "shortName" + S + build.getParent().getDigestName())); } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/hudson/matrix/MatrixProjectDependencyTest.java b/src/test/java/hudson/matrix/MatrixProjectDependencyTest.java index 32985161..ee033f85 100644 --- a/src/test/java/hudson/matrix/MatrixProjectDependencyTest.java +++ b/src/test/java/hudson/matrix/MatrixProjectDependencyTest.java @@ -1,47 +1,46 @@ package hudson.matrix; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsRule; - import hudson.model.AbstractProject; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; import hudson.tasks.BuildTrigger; import hudson.util.RunList; +import org.junit.jupiter.api.Test; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Stefan Wolf */ -public class MatrixProjectDependencyTest { - - @Rule public JenkinsRule j = new JenkinsRule(); - - /** - * Checks if the MatrixProject adds and Triggers downstream Projects via - * the DependencyGraph - */ - @Test public void matrixProjectTriggersDependencies() throws Exception { - MatrixProject matrixProject = j.createProject(MatrixProject.class); - FreeStyleProject freestyleProject = j.createFreeStyleProject(); - matrixProject.getPublishersList().add(new BuildTrigger(freestyleProject.getName(), false)); - - j.jenkins.rebuildDependencyGraph(); - - j.buildAndAssertSuccess(matrixProject); - j.waitUntilNoActivity(); - - RunList builds = freestyleProject.getBuilds(); - assertEquals("There should only be one FreestyleBuild", 1, builds.size()); - FreeStyleBuild build = builds.iterator().next(); - assertEquals(Result.SUCCESS, build.getResult()); - List downstream = j.jenkins.getDependencyGraph().getDownstream(matrixProject); - assertTrue(downstream.contains(freestyleProject)); - } +@WithJenkins +class MatrixProjectDependencyTest { + + /** + * Checks if the MatrixProject adds and Triggers downstream Projects via + * the DependencyGraph + */ + @Test + void matrixProjectTriggersDependencies(JenkinsRule j) throws Exception { + MatrixProject matrixProject = j.createProject(MatrixProject.class); + FreeStyleProject freestyleProject = j.createFreeStyleProject(); + matrixProject.getPublishersList().add(new BuildTrigger(freestyleProject.getName(), false)); + + j.jenkins.rebuildDependencyGraph(); + + j.buildAndAssertSuccess(matrixProject); + j.waitUntilNoActivity(); + + RunList builds = freestyleProject.getBuilds(); + assertEquals(1, builds.size(), "There should only be one FreestyleBuild"); + FreeStyleBuild build = builds.iterator().next(); + assertEquals(Result.SUCCESS, build.getResult()); + List downstream = j.jenkins.getDependencyGraph().getDownstream(matrixProject); + assertTrue(downstream.contains(freestyleProject)); + } } diff --git a/src/test/java/hudson/matrix/MatrixProjectTest.java b/src/test/java/hudson/matrix/MatrixProjectTest.java index 6c711466..7efd1cac 100644 --- a/src/test/java/hudson/matrix/MatrixProjectTest.java +++ b/src/test/java/hudson/matrix/MatrixProjectTest.java @@ -23,106 +23,113 @@ */ package hudson.matrix; -import org.htmlunit.html.HtmlPage; +import hudson.FilePath; +import hudson.Functions; +import hudson.Launcher; import hudson.cli.CLICommandInvoker; import hudson.cli.DeleteBuildsCommand; +import hudson.model.AbstractBuild; +import hudson.model.BuildListener; import hudson.model.Cause; +import hudson.model.FileParameterDefinition; +import hudson.model.FileParameterValue; +import hudson.model.JDK; +import hudson.model.ParameterDefinition; +import hudson.model.ParameterValue; +import hudson.model.ParametersAction; +import hudson.model.ParametersDefinitionProperty; import hudson.model.Result; +import hudson.model.Slave; +import hudson.model.StringParameterDefinition; +import hudson.model.StringParameterValue; +import hudson.model.queue.QueueTaskFuture; import hudson.slaves.DumbSlave; import hudson.slaves.RetentionStrategy; import hudson.tasks.Ant; import hudson.tasks.ArtifactArchiver; +import hudson.tasks.BatchFile; import hudson.tasks.Fingerprinter; import hudson.tasks.LogRotator; import hudson.tasks.Maven; import hudson.tasks.Shell; -import hudson.tasks.BatchFile; - -import org.jvnet.hudson.test.Email; -import org.jvnet.hudson.test.SingleFileSCM; -import org.jvnet.hudson.test.ToolInstallations; -import org.jvnet.hudson.test.UnstableBuilder; -import org.jvnet.hudson.test.recipes.LocalData; - +import hudson.util.OneShotEvent; +import jenkins.model.Jenkins; +import org.htmlunit.html.HtmlPage; import org.htmlunit.html.HtmlTable; import org.htmlunit.html.HtmlTableCell; import org.htmlunit.html.HtmlTableRow; -import hudson.FilePath; - +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.rules.TemporaryFolder; +import org.jvnet.hudson.test.Email; import org.jvnet.hudson.test.Issue; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.SingleFileSCM; import org.jvnet.hudson.test.TestBuilder; +import org.jvnet.hudson.test.ToolInstallations; +import org.jvnet.hudson.test.UnstableBuilder; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +import org.jvnet.hudson.test.recipes.LocalData; -import hudson.model.AbstractBuild; -import hudson.Launcher; -import hudson.model.BuildListener; -import hudson.util.OneShotEvent; - +import java.io.File; import java.io.IOException; +import java.lang.reflect.Method; import java.nio.charset.Charset; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import hudson.model.JDK; -import hudson.model.Slave; -import hudson.Functions; -import hudson.model.ParametersDefinitionProperty; -import hudson.model.FileParameterDefinition; -import hudson.model.ParametersAction; -import hudson.model.FileParameterValue; -import hudson.model.StringParameterDefinition; -import hudson.model.StringParameterValue; - -import java.util.List; import java.util.ArrayList; - - -import java.util.concurrent.CountDownLatch; - -import static hudson.model.Node.Mode.EXCLUSIVE; -import hudson.model.ParameterDefinition; -import hudson.model.ParameterValue; -import hudson.model.queue.QueueTaskFuture; -import java.io.File; -import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; -import jenkins.model.Jenkins; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import static hudson.model.Node.Mode.EXCLUSIVE; import static org.awaitility.Awaitility.await; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.*; -import static org.junit.Assume.assumeFalse; -import org.junit.Ignore; - -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsRule; -import org.junit.rules.TemporaryFolder; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeFalse; /** - * - * * @author Kohsuke Kawaguchi */ -public class MatrixProjectTest { +@WithJenkins +class MatrixProjectTest { + + private JenkinsRule j; - @Rule public JenkinsRule j = new JenkinsRule(); - @Rule public TemporaryFolder tmp = new TemporaryFolder(); + @TempDir + private File tmp; + + @BeforeEach + void setUp(JenkinsRule rule) { + j = rule; + } /** * Tests that axes are available as build variables in the Ant builds. */ @Test - public void testBuildAxisInAnt() throws Exception { + void testBuildAxisInAnt() throws Exception { MatrixProject p = createMatrixProject(); - Ant.AntInstallation ant = ToolInstallations.configureDefaultAnt(tmp); + TemporaryFolder folder = new TemporaryFolder(tmp); + folder.create(); + Ant.AntInstallation ant = ToolInstallations.configureDefaultAnt(folder); p.getBuildersList().add(new Ant("-Dprop=${db} test", ant.getName(), null, null, null)); // we need a dummy build script that echos back our property @@ -130,37 +137,37 @@ public void testBuildAxisInAnt() throws Exception { MatrixBuild build = p.scheduleBuild2(0, new Cause.UserIdCause()).get(); List runs = build.getRuns(); - assertEquals(4,runs.size()); + assertEquals(4, runs.size()); for (MatrixRun run : runs) { j.assertBuildStatus(Result.SUCCESS, run); String expectedDb = run.getParent().getCombination().get("db"); - j.assertLogContains("assertion "+expectedDb+"="+expectedDb, run); + j.assertLogContains("assertion " + expectedDb + "=" + expectedDb, run); } } /** * Tests that axes are available as build variables in the Maven builds. */ - @Ignore("TODO failing on CI: http://repo1.maven.org/maven2") + @Disabled("TODO failing on CI: http://repo1.maven.org/maven2") @Test - public void testBuildAxisInMaven() throws Exception { - assumeFalse("TODO seems to have problems with variable substitution", Functions.isWindows()); + void testBuildAxisInMaven() throws Exception { + assumeFalse(Functions.isWindows(), "TODO seems to have problems with variable substitution"); MatrixProject p = createMatrixProject(); Maven.MavenInstallation maven = ToolInstallations.configureDefaultMaven(); p.getBuildersList().add(new Maven("-Dprop=${db} validate", maven.getName())); // we need a dummy build script that echos back our property - p.setScm(new SingleFileSCM("pom.xml",getClass().getResource("echo-property.pom"))); + p.setScm(new SingleFileSCM("pom.xml", getClass().getResource("echo-property.pom"))); MatrixBuild build = p.scheduleBuild2(0).get(); List runs = build.getRuns(); - assertEquals(4,runs.size()); + assertEquals(4, runs.size()); for (MatrixRun run : runs) { j.assertBuildStatus(Result.SUCCESS, run); String expectedDb = run.getParent().getCombination().get("db"); String log = run.getLog(); System.out.println(log); - j.assertLogContains("assertion "+expectedDb+"="+expectedDb, run); + j.assertLogContains("assertion " + expectedDb + "=" + expectedDb, run); // also make sure that the variables are expanded at the command line level. assertFalse(log.contains("-Dprop=${db}")); } @@ -170,7 +177,7 @@ public void testBuildAxisInMaven() throws Exception { * Test that configuration filters work */ @Test - public void testConfigurationFilter() throws Exception { + void testConfigurationFilter() throws Exception { MatrixProject p = createMatrixProject(); p.setCombinationFilter("db==\"mysql\""); MatrixBuild build = p.scheduleBuild2(0).get(); @@ -181,7 +188,7 @@ public void testConfigurationFilter() throws Exception { * Test that touch stone builds work */ @Test - public void testTouchStone() throws Exception { + void testTouchStone() throws Exception { MatrixProject p = createMatrixProject(); p.setTouchStoneCombinationFilter("db==\"mysql\""); p.setTouchStoneResultCondition(Result.SUCCESS); @@ -193,13 +200,13 @@ public void testTouchStone() throws Exception { assertEquals(2, build.getExactRuns().size()); } - protected MatrixProject createMatrixProject() throws IOException { + private MatrixProject createMatrixProject() throws IOException { MatrixProject p = j.createProject(MatrixProject.class); // set up 2x2 matrix AxisList axes = new AxisList(); - axes.add(new TextAxis("db","mysql","oracle")); - axes.add(new TextAxis("direction","north","south")); + axes.add(new TextAxis("db", "mysql", "oracle")); + axes.add(new TextAxis("direction", "north", "south")); p.setAxes(axes); return p; @@ -210,24 +217,24 @@ protected MatrixProject createMatrixProject() throws IOException { */ @Email("http://www.nabble.com/1.286-version-and-fingerprints-option-broken-.-td22236618.html") @Test - public void testFingerprinting() throws Exception { + void testFingerprinting() throws Exception { MatrixProject p = createMatrixProject(); - if (Functions.isWindows()) - p.getBuildersList().add(new BatchFile("echo \"\" > p")); - else - p.getBuildersList().add(new Shell("touch p")); - + if (Functions.isWindows()) { + p.getBuildersList().add(new BatchFile("echo \"\" > p")); + } else { + p.getBuildersList().add(new Shell("touch p")); + } p.getPublishersList().add(new ArtifactArchiver("p")); p.getPublishersList().add(new Fingerprinter("")); j.buildAndAssertSuccess(p); } - void assertRectangleTable(MatrixProject p) throws Exception { + private void assertRectangleTable(MatrixProject p) throws Exception { HtmlPage html = j.createWebClient().getPage(p); HtmlTable table = html.getFirstByXPath("id('matrix')/table"); // remember cells that are extended from rows above. - Map rowSpans = new HashMap(); + Map rowSpans = new HashMap<>(); Integer masterWidth = null; for (HtmlTableRow r : table.getRows()) { int width = 0; @@ -245,12 +252,11 @@ void assertRectangleTable(MatrixProject p) throws Exception { for (HtmlTableCell c : r.getCells()) { int rowSpan = c.getRowSpan(); - Integer val = rowSpans.get(rowSpan); - rowSpans.put(rowSpan, (val != null ? val : 0) + c.getColumnSpan()); + rowSpans.compute(rowSpan, (k, val) -> (val != null ? val : 0) + c.getColumnSpan()); } // shift rowSpans by one - Map nrs = new HashMap(); - for (Map.Entry entry : rowSpans.entrySet()) { + Map nrs = new HashMap<>(); + for (Map.Entry entry : rowSpans.entrySet()) { if (entry.getKey() > 1) { nrs.put(entry.getKey() - 1, entry.getValue()); } @@ -261,11 +267,11 @@ void assertRectangleTable(MatrixProject p) throws Exception { @Issue("JENKINS-4245") @Test - public void testLayout1() throws Exception { + void testLayout1() throws Exception { // 5*5*5*5*5 matrix MatrixProject p = createMatrixProject(); - List axes = new ArrayList(); - for (String name : new String[] {"a", "b", "c", "d", "e"}) { + List axes = new ArrayList<>(); + for (String name : new String[]{"a", "b", "c", "d", "e"}) { axes.add(new TextAxis(name, "1", "2", "3", "4")); } p.setAxes(new AxisList(axes)); @@ -274,12 +280,12 @@ public void testLayout1() throws Exception { @Issue("JENKINS-4245") @Test - public void testLayout2() throws Exception { + void testLayout2() throws Exception { // 2*3*4*5*6 matrix MatrixProject p = createMatrixProject(); - List axes = new ArrayList(); + List axes = new ArrayList<>(); for (int i = 2; i <= 6; i++) { - List vals = new ArrayList(); + List vals = new ArrayList<>(); for (int j = 1; j <= i; j++) { vals.add(Integer.toString(j)); } @@ -293,23 +299,23 @@ public void testLayout2() throws Exception { * Makes sure that the configuration correctly roundtrips. */ @Test - public void testConfigRoundtrip() throws Exception { + void testConfigRoundtrip() throws Exception { j.jenkins.getJDKs().addAll(Arrays.asList( - new JDK("jdk1.7","somewhere"), - new JDK("jdk1.6","here"), - new JDK("jdk1.5","there"))); + new JDK("jdk1.7", "somewhere"), + new JDK("jdk1.6", "here"), + new JDK("jdk1.5", "there"))); Slave[] slaves = {j.createSlave(), j.createSlave(), j.createSlave()}; MatrixProject p = createMatrixProject(); p.getAxes().add(new JDKAxis(Arrays.asList("jdk1.6", "jdk1.5"))); p.getAxes().add(new LabelAxis("label1", Arrays.asList(slaves[0].getNodeName(), slaves[1].getNodeName()))); - p.getAxes().add(new LabelAxis("label2", Arrays.asList(slaves[2].getNodeName()))); // make sure single value handling works OK + p.getAxes().add(new LabelAxis("label2", List.of(slaves[2].getNodeName()))); // make sure single value handling works OK AxisList o = new AxisList(p.getAxes()); j.configRoundtrip(p); AxisList n = p.getAxes(); - assertEquals(o.size(),n.size()); + assertEquals(o.size(), n.size()); for (int i = 0; i < o.size(); i++) { Axis oi = o.get(i); Axis ni = n.get(i); @@ -318,7 +324,6 @@ public void testConfigRoundtrip() throws Exception { assertEquals(oi.getValues(), ni.getValues()); } - DefaultMatrixExecutionStrategyImpl before = new DefaultMatrixExecutionStrategyImpl(true, "foo", Result.UNSTABLE, null); p.setExecutionStrategy(before); j.configRoundtrip(p); @@ -331,7 +336,7 @@ public void testConfigRoundtrip() throws Exception { } @Test - public void testLabelAxes() throws Exception { + void testLabelAxes() throws Exception { MatrixProject p = createMatrixProject(); Slave[] slaves = {j.createSlave(), j.createSlave(), j.createSlave(), j.createSlave()}; @@ -352,16 +357,17 @@ public void testLabelAxes() throws Exception { */ @Issue("JENKINS-4873") @Test - public void testQuietDownDeadlock() throws Exception { + void testQuietDownDeadlock() throws Exception { MatrixProject p = createMatrixProject(); - p.setAxes(new AxisList(new TextAxis("foo","1","2"))); + p.setAxes(new AxisList(new TextAxis("foo", "1", "2"))); p.setRunSequentially(true); // so that we can put the 2nd one in the queue final OneShotEvent firstStarted = new OneShotEvent(); final OneShotEvent buildCanProceed = new OneShotEvent(); p.getBuildersList().add(new TestBuilder() { - @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { + @Override + public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException { firstStarted.signal(); buildCanProceed.block(); return true; @@ -376,22 +382,22 @@ public void testQuietDownDeadlock() throws Exception { buildCanProceed.signal(); // make sure foo=2 still completes. use time out to avoid hang - j.assertBuildStatusSuccess(f.get(10,TimeUnit.SECONDS)); + j.assertBuildStatusSuccess(f.get(10, TimeUnit.SECONDS)); // MatrixProject scheduled after the quiet down shouldn't start try { Future g = p.scheduleBuild2(0); - g.get(3,TimeUnit.SECONDS); + g.get(3, TimeUnit.SECONDS); fail(); } catch (TimeoutException e) { // expected - } + } } @Issue("JENKINS-9009") @Test - public void testTrickyNodeName() throws Exception { - List names = new ArrayList(); + void testTrickyNodeName() throws Exception { + List names = new ArrayList<>(); names.add(j.createSlave("Sean's Workstation", null).getNodeName()); names.add(j.createSlave("John\"s Workstation", null).getNodeName()); MatrixProject p = createMatrixProject(); @@ -399,43 +405,43 @@ public void testTrickyNodeName() throws Exception { j.configRoundtrip(p); LabelAxis a = (LabelAxis) p.getAxes().find("label"); - assertEquals(new HashSet(a.getValues()), new HashSet(names)); + assertEquals(new HashSet<>(a.getValues()), new HashSet<>(names)); } @Issue("JENKINS-10108") @Test - public void testTwoFileParams() throws Exception { + void testTwoFileParams() throws Exception { MatrixProject p = createMatrixProject(); - p.setAxes(new AxisList(new TextAxis("foo","1","2","3","4"))); + p.setAxes(new AxisList(new TextAxis("foo", "1", "2", "3", "4"))); p.addProperty(new ParametersDefinitionProperty( - new FileParameterDefinition("a.txt",""), - new FileParameterDefinition("b.txt","") + new FileParameterDefinition("a.txt", ""), + new FileParameterDefinition("b.txt", "") )); - File dir = tmp.getRoot(); - List params = new ArrayList(); - for (final String n : new String[] {"aaa", "bbb"}) { + File dir = tmp; + List params = new ArrayList<>(); + for (final String n : new String[]{"aaa", "bbb"}) { params.add(new FileParameterValue(n + ".txt", File.createTempFile(n, "", dir), n)); } - QueueTaskFuture f = p.scheduleBuild2(0,new Cause.UserIdCause(),new ParametersAction(params)); - - j.assertBuildStatusSuccess(f.get(10,TimeUnit.SECONDS)); + QueueTaskFuture f = p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction(params)); + + j.assertBuildStatusSuccess(f.get(10, TimeUnit.SECONDS)); } @Issue("JENKINS-34758") @Test - public void testParametersAsEnvOnChildren() throws Exception { + void testParametersAsEnvOnChildren() throws Exception { assumeFalse(Functions.isWindows()); MatrixProject p = createMatrixProject(); - p.setAxes(new AxisList(new TextAxis("foo","1"))); + p.setAxes(new AxisList(new TextAxis("foo", "1"))); p.addProperty(new ParametersDefinitionProperty( - new StringParameterDefinition("MY_PARAM","") + new StringParameterDefinition("MY_PARAM", "") )); // must fail if $MY_PARAM or $foo are not defined in children p.getBuildersList().add(new Shell("set -eux; echo $MY_PARAM; echo $foo")); - List params = new ArrayList(); + List params = new ArrayList<>(); params.add(new StringParameterValue("MY_PARAM", "value1")); QueueTaskFuture f = p.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction(params)); @@ -447,27 +453,28 @@ public void testParametersAsEnvOnChildren() throws Exception { * that each gets its own unique workspace. */ @Test - public void testConcurrentBuild() throws Exception { + void testConcurrentBuild() throws Exception { j.jenkins.setNumExecutors(10); Method m = Jenkins.class.getDeclaredMethod("updateComputerList"); // TODO is this really necessary? m.setAccessible(true); m.invoke(j.jenkins); MatrixProject p = createMatrixProject(); - p.setAxes(new AxisList(new TextAxis("foo","1","2"))); + p.setAxes(new AxisList(new TextAxis("foo", "1", "2"))); p.setConcurrentBuild(true); final CountDownLatch latch = new CountDownLatch(4); - final Set dirs = Collections.synchronizedSet(new HashSet()); - + final Set dirs = Collections.synchronizedSet(new HashSet<>()); + p.getBuildersList().add(new TestBuilder() { - @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { + @Override + public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { dirs.add(build.getWorkspace().getRemote()); FilePath marker = build.getWorkspace().child("file"); String name = build.getFullDisplayName(); marker.write(name, Charset.defaultCharset().name()); latch.countDown(); latch.await(); - assertEquals(name,marker.readToString()); + assertEquals(name, marker.readToString()); return true; } }); @@ -493,31 +500,30 @@ public void testConcurrentBuild() throws Exception { assertEquals(4, dirs.size()); } - /** * Test that Actions are passed to configurations */ @Test - public void testParameterActions() throws Exception { + void testParameterActions() throws Exception { MatrixProject p = createMatrixProject(); ParametersDefinitionProperty pdp = new ParametersDefinitionProperty( - new StringParameterDefinition("PARAM_A","default_a"), - new StringParameterDefinition("PARAM_B","default_b") + new StringParameterDefinition("PARAM_A", "default_a"), + new StringParameterDefinition("PARAM_B", "default_b") ); p.addProperty(pdp); - List values = new ArrayList(); + List values = new ArrayList<>(); for (ParameterDefinition def : pdp.getParameterDefinitions()) { values.add(def.getDefaultParameterValue()); } ParametersAction pa = new ParametersAction(values); - MatrixBuild build = p.scheduleBuild2(0,new Cause.UserIdCause(), pa).get(); + MatrixBuild build = p.scheduleBuild2(0, new Cause.UserIdCause(), pa).get(); assertEquals(4, build.getRuns().size()); - for(MatrixRun run : build.getRuns()) { + for (MatrixRun run : build.getRuns()) { ParametersAction pa1 = run.getAction(ParametersAction.class); assertNotNull(pa1); assertNotNull(pa1.getParameter("PARAM_A")); @@ -528,7 +534,7 @@ public void testParameterActions() throws Exception { @Issue("JENKINS-15271") @LocalData @Test - public void testUpgrade() throws Exception { + void testUpgrade() { MatrixProject p = j.jenkins.getItemByFullName("x", MatrixProject.class); assertNotNull(p); MatrixExecutionStrategy executionStrategy = p.getExecutionStrategy(); @@ -541,7 +547,8 @@ public void testUpgrade() throws Exception { } @Issue("JENKINS-17337") - @Test public void reload() throws Exception { + @Test + void reload() throws Exception { MatrixProject p = j.createProject(MatrixProject.class); AxisList axes = new AxisList(); axes.add(new TextAxis("p", "only")); @@ -559,14 +566,14 @@ public void testUpgrade() throws Exception { /** * Given a small controller and a big exclusive agent, the fair scheduling would prefer running the flyweight job * in the agent. But if the scheduler honors the EXCLUSIVE flag, then we should see it built on the controller. - * + *

* Since there's a chance that the fair scheduling just so happens to pick up the controller by chance, * we try multiple jobs to reduce the chance of that happening. */ @Issue("JENKINS-5076") @Test - public void dontRunOnExclusiveSlave() throws Exception { - List projects = new ArrayList(); + void dontRunOnExclusiveSlave() throws Exception { + List projects = new ArrayList<>(); for (int i = 0; i <= 10; i++) { MatrixProject m = j.createProject(MatrixProject.class); AxisList axes = new AxisList(); @@ -574,19 +581,17 @@ public void dontRunOnExclusiveSlave() throws Exception { m.setAxes(axes); projects.add(m); } - - tmp.create(); DumbSlave s = new DumbSlave( "big", "this is a big slave", - tmp.getRoot().getPath(), + tmp.getPath(), "20", EXCLUSIVE, "", j.createComputerLauncher(null), RetentionStrategy.NOOP, - new ArrayList()); - j.jenkins.addNode(s); + new ArrayList<>()); + j.jenkins.addNode(s); s.toComputer().connect(false).get(); // connect this guy @@ -596,8 +601,9 @@ public void dontRunOnExclusiveSlave() throws Exception { } } - @Test @Issue("JENKINS-13554") - public void deletedLockedParentBuild() throws Exception { + @Test + @Issue("JENKINS-13554") + void deletedLockedParentBuild() throws Exception { MatrixProject p = j.jenkins.createProject(MatrixProject.class, "project"); p.setAxes(new AxisList(new TextAxis("AXIS", "1", "2"))); MatrixBuild codeDelete = p.scheduleBuild2(0).get(); @@ -623,8 +629,9 @@ public void deletedLockedParentBuild() throws Exception { assertEquals(1, p.getBuilds().size()); } - @Test @Issue("JENKINS-13554") - public void deletedLockedChildrenBuild() throws Exception { + @Test + @Issue("JENKINS-13554") + void deletedLockedChildrenBuild() throws Exception { MatrixProject p = j.jenkins.createProject(MatrixProject.class, "project"); p.setAxes(new AxisList(new TextAxis("AXIS", "1", "2"))); p.scheduleBuild2(0).get(); @@ -638,11 +645,11 @@ public void deletedLockedChildrenBuild() throws Exception { assertEquals(3, p.getBuilds().size()); assertEquals(2, c.getBuilds().size()); - assertNull("build #1 should not be locked", p.getBuildByNumber(2).getWhyKeepLog()); - assertNotNull("build #1 should have delete message", p.getBuildByNumber(2).getDeleteMessage()); + assertNull(p.getBuildByNumber(2).getWhyKeepLog(), "build #1 should not be locked"); + assertNotNull(p.getBuildByNumber(2).getDeleteMessage(), "build #1 should have delete message"); - assertNull("configuration run #1 should not be locked", c.getBuildByNumber(2).getWhyKeepLog()); - assertNotNull("configuration run #1 should have delete message", c.getBuildByNumber(2).getDeleteMessage()); + assertNull(c.getBuildByNumber(2).getWhyKeepLog(), "configuration run #1 should not be locked"); + assertNotNull(c.getBuildByNumber(2).getDeleteMessage(), "configuration run #1 should have delete message"); // UI delete JenkinsRule.WebClient wc = j.createWebClient(); @@ -658,8 +665,9 @@ public void deletedLockedChildrenBuild() throws Exception { assertEquals(0, c.getBuilds().size()); } - @Test @Issue("JENKINS-13554") - public void discardBuilds() throws Exception { + @Test + @Issue("JENKINS-13554") + void discardBuilds() throws Exception { MatrixProject p = j.jenkins.createProject(MatrixProject.class, "discarder"); p.setAxes(new AxisList(new TextAxis("AXIS", "VALUE"))); @@ -676,7 +684,7 @@ public void discardBuilds() throws Exception { } @Test - public void discardArtifacts() throws Exception { + void discardArtifacts() throws Exception { MatrixProject p = j.jenkins.createProject(MatrixProject.class, "discarder"); p.setAxes(new AxisList(new TextAxis("AXIS", "VALUE"))); @@ -684,7 +692,8 @@ public void discardArtifacts() throws Exception { p.setBuildDiscarder(new LogRotator("", "", "", "1")); p.getBuildersList().add(new TestBuilder() { - @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { + @Override + public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { build.getWorkspace().child("artifact.zip").write("content", "UTF-8"); return true; } @@ -700,8 +709,9 @@ public void discardArtifacts() throws Exception { await().until(last::getArtifacts, hasSize(1)); } - @Test @Issue("JENKINS-13554") - public void deleteBuildWithChildrenOverCLI() throws Exception { + @Test + @Issue("JENKINS-13554") + void deleteBuildWithChildrenOverCLI() throws Exception { MatrixProject p = j.jenkins.createProject(MatrixProject.class, "project"); p.setAxes(new AxisList(new TextAxis("AXIS", "VALUE"))); p.scheduleBuild2(0).get(); diff --git a/src/test/java/hudson/matrix/MatrixRunTest.java b/src/test/java/hudson/matrix/MatrixRunTest.java index 9dc92bf2..76252cc9 100644 --- a/src/test/java/hudson/matrix/MatrixRunTest.java +++ b/src/test/java/hudson/matrix/MatrixRunTest.java @@ -26,23 +26,25 @@ import jenkins.model.CauseOfInterruption; import jenkins.model.InterruptedBuildAction; -import static org.junit.Assert.*; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; -public class MatrixRunTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; - @Rule public JenkinsRule r = new JenkinsRule(); +@WithJenkins +class MatrixRunTest { /** * Unmarshall a matrix build.xml result. */ @LocalData @Issue("JENKINS-10903") - @Test public void unmarshalRunMatrix() { + @Test + void unmarshalRunMatrix(JenkinsRule r) { MatrixRun result = r.jenkins.getItemByFullName("p/x=1", MatrixConfiguration.class).getBuildByNumber(1); assertNotNull(result); InterruptedBuildAction action = result.getAction(InterruptedBuildAction.class); @@ -50,8 +52,7 @@ public class MatrixRunTest { assertNotNull(action.getCauses()); assertEquals(1, action.getCauses().size()); CauseOfInterruption.UserInterruption cause = - (CauseOfInterruption.UserInterruption) action.getCauses().get(0); + (CauseOfInterruption.UserInterruption) action.getCauses().get(0); assertNotNull(cause); } - } diff --git a/src/test/java/hudson/matrix/MatrixTest.java b/src/test/java/hudson/matrix/MatrixTest.java index b18f6465..ada19d02 100644 --- a/src/test/java/hudson/matrix/MatrixTest.java +++ b/src/test/java/hudson/matrix/MatrixTest.java @@ -1,18 +1,18 @@ /* * The MIT License - * + * * Copyright (c) 2010-2011, Alan Harder - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,61 +23,56 @@ */ package hudson.matrix; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertArrayEquals; - +import hudson.Functions; import hudson.matrix.helper.DynamicTestAxis; - import hudson.model.Item; import hudson.model.queue.QueueTaskFuture; import hudson.security.AuthorizationMatrixProperty; import hudson.security.ProjectMatrixAuthorizationStrategy; - -import java.util.Arrays; -import java.util.Collections; - import org.acegisecurity.context.SecurityContextHolder; - import org.htmlunit.xml.XmlPage; - -import hudson.Functions; - -import java.io.IOException; -import java.util.Set; - import org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException; import org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Alan Harder */ -public class MatrixTest { - - @Rule public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class MatrixTest { /** * Test that spaces are encoded as %20 for project name, axis name and axis value. */ - @Test public void spaceInUrl() { + @Test + void spaceInUrl(JenkinsRule j) { MatrixProject mp = new MatrixProject("matrix test"); MatrixConfiguration mc = new MatrixConfiguration(mp, Combination.fromString("foo bar=baz bat")); assertEquals("job/matrix%20test/", mp.getUrl()); assertEquals("job/matrix%20test/foo%20bar=baz%20bat/", mc.getUrl()); } - + /** * Test that project level permissions apply to child configurations as well. */ @Issue("JENKINS-9293") - @Test public void configurationACL() throws Exception { + @Test + void configurationACL(JenkinsRule j) throws Exception { j.jenkins.setAuthorizationStrategy(new ProjectMatrixAuthorizationStrategy()); MatrixProject mp = j.createProject(MatrixProject.class); mp.setAxes(new AxisList(new Axis("foo", "a", "b"))); @@ -91,7 +86,8 @@ public class MatrixTest { assertTrue(mc.getACL().hasPermission(Item.READ)); } - @Test public void api() throws Exception { + @Test + void api(JenkinsRule j) throws Exception { MatrixProject project = j.createProject(MatrixProject.class); project.setAxes(new AxisList( new Axis("FOO", "abc", "def"), @@ -101,7 +97,8 @@ public class MatrixTest { } @Issue("JENKINS-27162") - @Test public void completedLogging() throws Exception { + @Test + void completedLogging(JenkinsRule j) throws Exception { MatrixProject project = j.createProject(MatrixProject.class); project.setAxes(new AxisList( new Axis("axis", "a", "b") @@ -116,7 +113,8 @@ public class MatrixTest { } @Issue("SECURITY-125") - @Test public void combinationFilterSecurity() throws Exception { + @Test + void combinationFilterSecurity(JenkinsRule j) throws Exception { MatrixProject project = j.createProject(MatrixProject.class); String combinationFilter = "jenkins.model.Jenkins.getInstance().setSystemMessage('hacked')"; expectRejection(project, combinationFilter, "staticMethod jenkins.model.Jenkins getInstance"); @@ -124,15 +122,16 @@ public class MatrixTest { expectRejection(project, combinationFilter, "method jenkins.model.Jenkins setSystemMessage java.lang.String"); assertNull(j.jenkins.getSystemMessage()); project.setCombinationFilter(combinationFilter); - assertEquals("you asked for it", "hacked", j.jenkins.getSystemMessage()); + assertEquals("hacked", j.jenkins.getSystemMessage(), "you asked for it"); } + private static void expectRejection(MatrixProject project, String combinationFilter, String signature) throws IOException { ScriptApproval scriptApproval = ScriptApproval.get(); assertEquals(Collections.emptySet(), scriptApproval.getPendingSignatures()); try { project.setCombinationFilter(combinationFilter); } catch (RejectedAccessException x) { - assertEquals(Functions.printThrowable(x), signature, x.getSignature()); + assertEquals(signature, x.getSignature(), Functions.printThrowable(x)); } Set pendingSignatures = scriptApproval.getPendingSignatures(); assertEquals(1, pendingSignatures.size()); @@ -141,9 +140,9 @@ private static void expectRejection(MatrixProject project, String combinationFil assertEquals(Collections.emptySet(), scriptApproval.getPendingSignatures()); } - @Issue("JENKINS-34389") - @Test public void axisValuesChanged() throws Exception { + @Test + void axisValuesChanged(JenkinsRule j) throws Exception { // create project with dynamic axis MatrixProject project = j.createProject(MatrixProject.class); project.setAxes(new AxisList( diff --git a/src/test/java/hudson/matrix/RestartingRestoreTest.java b/src/test/java/hudson/matrix/RestartingRestoreTest.java index 84ebb0e9..fb611041 100644 --- a/src/test/java/hudson/matrix/RestartingRestoreTest.java +++ b/src/test/java/hudson/matrix/RestartingRestoreTest.java @@ -26,14 +26,12 @@ import hudson.matrix.MatrixConfiguration.ParentBuildAction; import hudson.model.Label; import hudson.model.ParametersDefinitionProperty; -import hudson.model.Queue; import hudson.model.Result; import hudson.model.StringParameterDefinition; import org.hamcrest.Matchers; import org.hamcrest.core.AnyOf; import org.junit.Rule; import org.junit.Test; -import org.junit.runners.model.Statement; import org.jvnet.hudson.test.JenkinsSessionRule; import java.util.Arrays; @@ -104,7 +102,7 @@ private void resumeBuildAfterRestart() throws Throwable { assertTrue(parent.isBuilding()); Thread.sleep(1000); - assertThat(j.jenkins.getQueue().getItems(), Matchers.arrayWithSize(4)); + assertThat(j.jenkins.getQueue().getItems(), Matchers.arrayWithSize(4)); }); sessions.then(j -> { Thread.sleep(10000); // If the jobs is loaded too soon, its builds are never loaded. @@ -120,11 +118,11 @@ private void resumeBuildAfterRestart() throws Throwable { j.createOnlineSlave(Label.get("bar")); j.waitUntilNoActivity(); - assertThat(p1.getExactRuns(), Matchers.iterableWithSize(2)); + assertThat(p1.getExactRuns(), Matchers.iterableWithSize(2)); for (MatrixRun run : p1.getExactRuns()) { j.assertBuildStatus(Result.SUCCESS, run); } - assertThat(p2.getExactRuns(), Matchers.iterableWithSize(2)); + assertThat(p2.getExactRuns(), Matchers.iterableWithSize(2)); for (MatrixRun run : p2.getExactRuns()) { j.assertBuildStatus(Result.SUCCESS, run); }