From edfb7f7a5a050e574a237dbb1865c2fcb996a14b Mon Sep 17 00:00:00 2001 From: strangelookingnerd <49242855+strangelookingnerd@users.noreply.github.com> Date: Tue, 9 Sep 2025 13:12:04 +0200 Subject: [PATCH] Migrate tests to JUnit5 * Migrate annotations and imports * Migrate assertions * Remove public visibility for test classes and methods * Minor code cleanup --- pom.xml | 3 +- .../folder/ChildNameGeneratorAltTest.java | 39 ++--- .../folder/ChildNameGeneratorRecTest.java | 32 ++-- .../folder/ChildNameGeneratorTest.java | 35 ++-- .../folder/ConfigurationAsCodeTest.java | 13 +- .../folder/FolderSystemPropertyTest.java | 38 +++-- .../hudson/plugins/folder/FolderTest.java | 145 ++++++++++------- .../folder/computed/ComputedFolder2Test.java | 25 ++- .../folder/computed/ComputedFolderTest.java | 152 +++++++----------- .../computed/EventOutputStreamsTest.java | 23 ++- .../computed/PeriodicFolderTriggerTest.java | 25 +-- ...tleComputationQueueTaskDispatcherTest.java | 42 +++-- .../AbstractFolderConfigurationTest.java | 36 +++-- .../health/NamedChildHealthMetricTest.java | 29 ++-- .../FolderCredentialsProviderTest.java | 39 +++-- .../folder/relocate/StandardHandlerTest.java | 35 ++-- .../views/DefaultFolderViewHolderTest.java | 23 ++- 17 files changed, 392 insertions(+), 342 deletions(-) diff --git a/pom.xml b/pom.xml index 13e47789..fc4b9941 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.jenkins-ci.plugins plugin - 5.18 + 5.25 @@ -26,6 +26,7 @@ ${jenkins.baseline}.1 false 5.2 + false diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorAltTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorAltTest.java index b4921caf..233f9c38 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorAltTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorAltTest.java @@ -53,10 +53,10 @@ import java.util.TreeSet; import edu.umd.cs.findbugs.annotations.NonNull; import net.sf.json.JSONObject; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsSessionRule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension; import org.kohsuke.stapler.StaplerRequest2; import static com.cloudbees.hudson.plugins.folder.ChildNameGeneratorTest.asJavaStrings; @@ -65,18 +65,18 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; /** * Tests {@link ChildNameGenerator} using a generator that leaves the {@link Item#getName()} unmodified but mangles * the directory. */ -public class ChildNameGeneratorAltTest { +class ChildNameGeneratorAltTest { - @Rule - public JenkinsSessionRule r = new JenkinsSessionRule(); + @RegisterExtension + private final JenkinsSessionExtension extension = new JenkinsSessionExtension(); /** * Given: a computed folder @@ -84,8 +84,8 @@ public class ChildNameGeneratorAltTest { * Then: mangling gets applied */ @Test - public void createdFromScratch() throws Throwable { - r.then(j -> { + void createdFromScratch() throws Throwable { + extension.then(j -> { ComputedFolderImpl instance = j.createProject(ComputedFolderImpl.class, "instance"); instance.assertItemNames(0); instance.recompute(Result.SUCCESS); @@ -103,7 +103,7 @@ public void createdFromScratch() throws Throwable { instance.recompute(Result.SUCCESS); checkComputedFolder(instance, 2); }); - r.then(j -> { + extension.then(j -> { TopLevelItem i = j.jenkins.getItem("instance"); assertThat("Item loaded from disk", i, instanceOf(ComputedFolderImpl.class)); ComputedFolderImpl instance = (ComputedFolderImpl) i; @@ -120,12 +120,12 @@ public void createdFromScratch() throws Throwable { // Check child items identity is preserved assertThat("Items are the same", items, is(newItems)); for (int k = 0; k < items.size(); k++) { - assertSame("Individual items must be the same", items.get(k), newItems.get(k)); + assertSame(items.get(k), newItems.get(k), "Individual items must be the same"); } }); } - private void checkComputedFolder(ComputedFolderImpl instance, int round) throws IOException { + private void checkComputedFolder(ComputedFolderImpl instance, int round) { boolean windows = false; for (FreeStyleProject p : instance.getItems()) { if ("leanbh cu\u0301ig".equals(p.getName())) { @@ -230,7 +230,7 @@ private void checkComputedFolder(ComputedFolderImpl instance, int round) throws } } - private void checkChild(ComputedFolderImpl instance, String idealName) throws IOException { + private void checkChild(ComputedFolderImpl instance, String idealName) { String encodedName = encode(idealName); FreeStyleProject item = instance.getItem(encodedName); assertThat("We have an item for name " + idealName, item, notNullValue()); @@ -238,12 +238,12 @@ private void checkChild(ComputedFolderImpl instance, String idealName) throws IO item.getRootDir().getName(), is(mangle(idealName))); } - public static String encode(String s) { + private static String encode(String s) { // We force every name to NFD to ensure that the test works irrespective of what the filesystem does return Normalizer.normalize(s, Normalizer.Form.NFD); } - public static String mangle(String s) { + private static String mangle(String s) { // We force every name to NFD to ensure that the test works irrespective of what the filesystem does s = Normalizer.normalize(s, Normalizer.Form.NFD); String hash = Util.getDigestOf(s); @@ -440,7 +440,7 @@ public String recompute(Result result) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); computation.writeWholeLogTo(baos); String log = baos.toString(); - assertEquals(log, result, computation.getResult()); + assertEquals(result, computation.getResult(), log); return log; } @@ -474,6 +474,7 @@ public void assertItemDirs(int round, String... names) { assertThat(actual, is(new TreeSet<>(Arrays.asList(names)))); } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends AbstractFolderDescriptor { @@ -484,6 +485,7 @@ public TopLevelItem newInstance(ItemGroup parent, String name) { return new ComputedFolderImpl(parent, name); } + @NonNull @Override public ChildNameGenerator, I> childNameGenerator() { return (ChildNameGenerator, I>) GENERATOR; @@ -533,6 +535,7 @@ public JobProperty reconfigure(StaplerRequest2 req, JSONObject form) { return this; } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends JobPropertyDescriptor { @Override @@ -586,6 +589,4 @@ public String dirNameFromLegacy(@NonNull F parent, return mangle(Normalizer.normalize(legacyDirName, Normalizer.Form.NFD)); } } - - } diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorRecTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorRecTest.java index 0543461b..8604f2dc 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorRecTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorRecTest.java @@ -51,10 +51,10 @@ import java.util.Set; import java.util.TreeSet; import net.sf.json.JSONObject; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsSessionRule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension; import org.kohsuke.stapler.StaplerRequest2; import static com.cloudbees.hudson.plugins.folder.ChildNameGeneratorAltTest.windowsFFS; @@ -63,17 +63,17 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests {@link ChildNameGenerator} using a generator where the previous implementation of the computed folder used a * name encoding algorithm and the new one has switched to {@link ChildNameGenerator}. We want to ensure that the * name gets decoded from the legacy name and fixed to the correct name while the directory name gets mangled. */ -public class ChildNameGeneratorRecTest { +class ChildNameGeneratorRecTest { - @Rule - public JenkinsSessionRule r = new JenkinsSessionRule(); + @RegisterExtension + private final JenkinsSessionExtension extension = new JenkinsSessionExtension(); /** * Given: a computed folder @@ -81,8 +81,8 @@ public class ChildNameGeneratorRecTest { * Then: mangling gets applied */ @Test - public void createdFromScratch() throws Throwable { - r.then(j -> { + void createdFromScratch() throws Throwable { + extension.then(j -> { ComputedFolderImpl instance = j.createProject(ComputedFolderImpl.class, "instance"); instance.assertItemNames(0); instance.recompute(Result.SUCCESS); @@ -100,7 +100,7 @@ public void createdFromScratch() throws Throwable { instance.recompute(Result.SUCCESS); checkComputedFolder(instance, 2); }); - r.then(j -> { + extension.then(j -> { TopLevelItem i = j.jenkins.getItem("instance"); assertThat("Item loaded from disk", i, instanceOf(ComputedFolderImpl.class)); ComputedFolderImpl instance = (ComputedFolderImpl) i; @@ -115,7 +115,7 @@ public void createdFromScratch() throws Throwable { }); } - private void checkComputedFolder(ComputedFolderImpl instance, int round) throws IOException { + private void checkComputedFolder(ComputedFolderImpl instance, int round) { // because these were previously encoded with rawEncode we can recover exactly instance.assertItemNames(round, "child-one", @@ -161,7 +161,7 @@ private void checkComputedFolder(ComputedFolderImpl instance, int round) throws } } - private void checkChild(ComputedFolderImpl instance, String idealName) throws IOException { + private void checkChild(ComputedFolderImpl instance, String idealName) { String encodedName = encode(idealName); FreeStyleProject item = instance.getItem(encodedName); assertThat("We have an item for name " + idealName, item, notNullValue()); @@ -169,11 +169,11 @@ private void checkChild(ComputedFolderImpl instance, String idealName) throws IO item.getRootDir().getName(), is(mangle(idealName))); } - public static String encode(String s) { + private static String encode(String s) { return s; } - public static String mangle(String s) { + private static String mangle(String s) { String hash = Util.getDigestOf(s); String base = Normalizer.normalize(s, Normalizer.Form.NFD).toLowerCase(Locale.ENGLISH); StringBuilder buf = new StringBuilder(32); @@ -368,7 +368,7 @@ public String recompute(Result result) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); computation.writeWholeLogTo(baos); String log = baos.toString(); - assertEquals(log, result, computation.getResult()); + assertEquals(result, computation.getResult(), log); return log; } @@ -409,6 +409,7 @@ public TopLevelItem newInstance(ItemGroup parent, String name) { return new ComputedFolderImpl(parent, name); } + @NonNull @Override public ChildNameGenerator, I> childNameGenerator() { return (ChildNameGenerator, I>) GENERATOR; @@ -434,6 +435,7 @@ public JobProperty reconfigure(StaplerRequest2 req, JSONObject form) { return this; } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends JobPropertyDescriptor { @Override diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorTest.java index 30db732b..8fb86d1a 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/ChildNameGeneratorTest.java @@ -53,10 +53,10 @@ import java.util.TreeSet; import edu.umd.cs.findbugs.annotations.NonNull; import net.sf.json.JSONObject; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsSessionRule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension; import org.kohsuke.stapler.StaplerRequest2; import static com.cloudbees.hudson.plugins.folder.ChildNameGeneratorAltTest.windowsFFS; @@ -65,7 +65,7 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests {@link ChildNameGenerator} using a generator that modifies both the {@link Item#getName()} and the directory. @@ -89,14 +89,14 @@ *
  • niƱo ocho (Spanish, supposed to be "child eight" round-tripped through Google translate gives * "eight boy") demonstrates a name that has a NFC chacacter with a different NFD encoding
  • * - * + *

    * Aside: Here's what happens when you round-trip through Google * Translate "Cold, apricot, relaxing satisfaction!" */ -public class ChildNameGeneratorTest { +class ChildNameGeneratorTest { - @Rule - public JenkinsSessionRule r = new JenkinsSessionRule(); + @RegisterExtension + private final JenkinsSessionExtension extension = new JenkinsSessionExtension(); /** * Given: a computed folder @@ -104,8 +104,8 @@ public class ChildNameGeneratorTest { * Then: mangling gets applied */ @Test - public void createdFromScratch() throws Throwable { - r.then(j -> { + void createdFromScratch() throws Throwable { + extension.then(j -> { ComputedFolderImpl instance = j.createProject(ComputedFolderImpl.class, "instance"); instance.assertItemNames(0); instance.recompute(Result.SUCCESS); @@ -123,7 +123,7 @@ public void createdFromScratch() throws Throwable { instance.recompute(Result.SUCCESS); checkComputedFolder(instance, 2, Normalizer.Form.NFC); }); - r.then(j -> { + extension.then(j -> { TopLevelItem i = j.jenkins.getItem("instance"); assertThat("Item loaded from disk", i, instanceOf(ComputedFolderImpl.class)); ComputedFolderImpl instance = (ComputedFolderImpl) i; @@ -261,7 +261,7 @@ private void checkComputedFolder(ComputedFolderImpl instance, int round, Normali } } - private void checkChild(ComputedFolderImpl instance, String idealName) throws IOException { + private void checkChild(ComputedFolderImpl instance, String idealName) { String encodedName = encode(idealName); FreeStyleProject item = instance.getItem(encodedName); assertThat("We have an item for name " + idealName, item, notNullValue()); @@ -278,12 +278,12 @@ private void checkChild(ComputedFolderImpl instance, String idealName) throws IO } } - public static String encode(String s) { + private static String encode(String s) { // we want to test that the name can be different from the on-disk name return "$$"+Normalizer.normalize(s, Normalizer.Form.NFD); } - public static String mangle(String s) { + private static String mangle(String s) { String hash = Util.getDigestOf(s); String base = Normalizer.normalize(s, Normalizer.Form.NFD).toLowerCase(Locale.ENGLISH); StringBuilder buf = new StringBuilder(32); @@ -479,7 +479,7 @@ public String recompute(Result result) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); computation.writeWholeLogTo(baos); String log = baos.toString(); - assertEquals(log, result, computation.getResult()); + assertEquals(result, computation.getResult(), log); return log; } @@ -513,6 +513,7 @@ public void assertItemDirs(int round, String... names) { assertThat(actual, is(new TreeSet<>(Arrays.asList(names)))); } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends AbstractFolderDescriptor { @@ -523,13 +524,12 @@ public TopLevelItem newInstance(ItemGroup parent, String name) { return new ComputedFolderImpl(parent, name); } + @NonNull @Override public ChildNameGenerator, I> childNameGenerator() { return (ChildNameGenerator, I>) GENERATOR; } - } - } public static class NameProperty extends JobProperty { @@ -548,6 +548,7 @@ public JobProperty reconfigure(StaplerRequest2 req, JSONObject form) { return this; } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends JobPropertyDescriptor { @Override diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/ConfigurationAsCodeTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/ConfigurationAsCodeTest.java index 497a1b73..b7dc02f9 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/ConfigurationAsCodeTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/ConfigurationAsCodeTest.java @@ -3,17 +3,19 @@ import com.cloudbees.hudson.plugins.folder.config.AbstractFolderConfiguration; import com.cloudbees.hudson.plugins.folder.health.FolderHealthMetric; import com.cloudbees.hudson.plugins.folder.health.WorstChildHealthMetric; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import io.jenkins.plugins.casc.misc.junit.jupiter.AbstractRoundTripTest; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; -public class ConfigurationAsCodeTest extends RoundTripAbstractTest { +@WithJenkins +class ConfigurationAsCodeTest extends AbstractRoundTripTest { @Override protected String stringInLogExpected() { @@ -21,12 +23,11 @@ protected String stringInLogExpected() { } @Override - protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { + protected void assertConfiguredAsExpected(JenkinsRule rule, String s) { List healthMetrics = AbstractFolderConfiguration.get().getHealthMetrics(); assertThat(healthMetrics, hasSize(1)); assertThat(healthMetrics.get(0), instanceOf(WorstChildHealthMetric.class)); WorstChildHealthMetric worstChildHealthMetric = (WorstChildHealthMetric) healthMetrics.get(0); assertFalse(worstChildHealthMetric.isRecursive()); } - } diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/FolderSystemPropertyTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/FolderSystemPropertyTest.java index 625233f9..3d3ce518 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/FolderSystemPropertyTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/FolderSystemPropertyTest.java @@ -32,28 +32,33 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class FolderSystemPropertyTest { +@WithJenkins +class FolderSystemPropertyTest { - @Rule - public JenkinsRule j = new JenkinsRule(); + private static final String HEALTH_METRIC_PROPERTY = System.getProperty(AbstractFolderConfiguration.class.getName() + ".ADD_HEALTH_METRICS"); - private static String HEALTH_METRIC_PROPERTY; + private JenkinsRule r; - @BeforeClass - public static void enableHealthMetrics() { - HEALTH_METRIC_PROPERTY = System.getProperty(AbstractFolderConfiguration.class.getName() + ".ADD_HEALTH_METRICS"); + @BeforeAll + static void beforeAll() { System.setProperty(AbstractFolderConfiguration.class.getName() + ".ADD_HEALTH_METRICS", "true"); } - @AfterClass - public static void disableHealthMetrics() { + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } + + @AfterAll + static void afterAll() { // Put back the previous value before the test was executed if (HEALTH_METRIC_PROPERTY != null) { System.setProperty(AbstractFolderConfiguration.class.getName() + ".ADD_HEALTH_METRICS", HEALTH_METRIC_PROPERTY); @@ -64,20 +69,19 @@ public static void disableHealthMetrics() { @Issue("JENKINS-63836") @Test - public void shouldHaveHealthMetricConfiguredGloballyOnSystemProperty() throws Exception { + void shouldHaveHealthMetricConfiguredGloballyOnSystemProperty() throws Exception { assertThat("if used .ADD_HEALTH_METRICS system property, global configuration should have all folder health metrics", AbstractFolderConfiguration.get().getHealthMetrics(), hasSize((int) FolderHealthMetricDescriptor.all().stream().filter(d -> d.createDefault() != null).count())); - Folder folder = j.jenkins.createProject(Folder.class, "myFolder"); + Folder folder = r.jenkins.createProject(Folder.class, "myFolder"); DescribableList healthMetrics = folder.getHealthMetrics(); assertThat("a new created folder should have all the folder health metrics configured globally", healthMetrics.toList(), containsInAnyOrder(AbstractFolderConfiguration.get().getHealthMetrics().toArray())); AbstractFolderConfiguration.get().setHealthMetrics(null); - folder = j.jenkins.createProject(Folder.class, "myFolder2"); + folder = r.jenkins.createProject(Folder.class, "myFolder2"); healthMetrics = folder.getHealthMetrics(); assertThat("a new created folder should have all the folder health metrics configured globally", healthMetrics, iterableWithSize(0)); } - } diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/FolderTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/FolderTest.java index a2c8cd47..bba15794 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/FolderTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/FolderTest.java @@ -73,23 +73,17 @@ import jenkins.model.Jenkins; import jenkins.model.RenameAction; import jenkins.util.Timer; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.jvnet.hudson.test.junit.jupiter.BuildWatcherExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.springframework.security.access.AccessDeniedException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.BuildWatcher; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; @@ -97,15 +91,25 @@ import org.jvnet.hudson.test.TestExtension; import org.jvnet.hudson.test.recipes.LocalData; -public class FolderTest { +@WithJenkins +class FolderTest { + + @SuppressWarnings("unused") + @RegisterExtension + private static final BuildWatcherExtension BUILD_WATCHER = new BuildWatcherExtension(); - @Rule public JenkinsRule r = new JenkinsRule(); - @ClassRule public static BuildWatcher bw = new BuildWatcher(); + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } /** * Tests rename operation. */ - @Test public void rename() throws Exception { + @Test + void rename() throws Exception { Folder f = createFolder(); f.setDescription("Some view"); @@ -126,7 +130,8 @@ public class FolderTest { assertSame(r.jenkins.getItem("newName"),f); } - @Test public void renameProgrammatically() throws Exception { + @Test + void renameProgrammatically() throws Exception { Folder f = createFolder(); var folderFullName = f.getFullName(); FreeStyleProject fsProject = new FreeStyleProject(f, "p1"); @@ -142,7 +147,8 @@ public class FolderTest { assertEquals("newName/newP1", itemAfterRename.getFullName()); } - @Test public void configRoundtrip() throws Exception { + @Test + void configRoundtrip() throws Exception { Folder f = createFolder(); r.configRoundtrip(f); } @@ -150,7 +156,8 @@ public class FolderTest { /** * Makes sure the child can be deleted. */ - @Test public void deleteChild() throws Exception { + @Test + void deleteChild() throws Exception { Folder f = createFolder(); FreeStyleProject child = f.createProject(FreeStyleProject.class, "foo"); assertEquals(1,f.getItems().size()); @@ -162,7 +169,8 @@ public class FolderTest { /** * Tests the path resolution of "foo" (relative) vs "/foo" (absolute) */ - @Test public void copyJob() throws Exception { + @Test + void copyJob() throws Exception { /* - foo - folder @@ -184,7 +192,6 @@ public class FolderTest { // "/foo" should copy "top" copyViaHttp(f, wc, "/foo", "uvw"); assertEquals("top",((Job)f.getItem("uvw")).getDescription()); - } private void copyViaHttp(Folder f, JenkinsRule.WebClient wc, String fromName, String toName) throws Exception { @@ -192,15 +199,16 @@ private void copyViaHttp(Folder f, JenkinsRule.WebClient wc, String fromName, St r.jenkins.setCrumbIssuer(null); URL apiURL = new URL( - r.jenkins.getRootUrl().toString() + "/" + f.getUrl().toString() + "createItem?mode=copy&from=" + URLEncoder.encode(fromName, StandardCharsets.UTF_8) + "&name=" + URLEncoder.encode(toName, StandardCharsets.UTF_8)); + r.jenkins.getRootUrl() + "/" + f.getUrl() + "createItem?mode=copy&from=" + URLEncoder.encode(fromName, StandardCharsets.UTF_8) + "&name=" + URLEncoder.encode(toName, StandardCharsets.UTF_8)); WebRequest request = new WebRequest(apiURL, HttpMethod.POST); request.setEncodingType(null); - assertEquals("Copy Job request has failed", 200, r.createWebClient() - .getPage(request).getWebResponse().getStatusCode()); + assertEquals(200, r.createWebClient() + .getPage(request).getWebResponse().getStatusCode(), "Copy Job request has failed"); } - @Test public void itemName() throws IOException { + @Test + void itemName() throws IOException { Folder f = createFolder(); var foo = f.createProject(FreeStyleProject.class, "foo"); assertEquals("foo", f.getItemName(foo.getRootDir(), foo)); @@ -209,32 +217,38 @@ private void copyViaHttp(Folder f, JenkinsRule.WebClient wc, String fromName, St /** * When copying a folder, its contents need to be recursively copied. */ - @Test public void copy() throws Exception { + @Test + void copy() throws Exception { Folder f = createFolder(); FreeStyleProject c1 = f.createProject(FreeStyleProject.class, "child1"); Folder c2 = f.createProject(Folder.class, "nested"); FreeStyleProject c21 = c2.createProject(FreeStyleProject.class,"child2"); Folder f2 = r.jenkins.copy(f, "fcopy"); - assertTrue(f2.getItem("child1") instanceof FreeStyleProject); + assertInstanceOf(FreeStyleProject.class, f2.getItem("child1")); Folder n = (Folder)f2.getItem("nested"); - assertTrue(n.getItem("child2") instanceof FreeStyleProject); + assertInstanceOf(FreeStyleProject.class, n.getItem("child2")); } @Issue("JENKINS-34939") - @Test public void delete() throws Exception { + @Test + void delete() throws Exception { Folder d1 = r.jenkins.createProject(Folder.class, "d1"); d1.createProject(FreeStyleProject.class, "p1"); d1.createProject(FreeStyleProject.class, "p2"); d1.createProject(Folder.class, "d2").createProject(FreeStyleProject.class, "p4"); d1.delete(); - assertEquals("AbstractFolder.items is sorted by name so we can predict deletion order", - "{d1=[d1], d1/d2=[d1, d1/d2, d1/p1, d1/p2], d1/d2/p4=[d1, d1/d2, d1/d2/p4, d1/p1, d1/p2], d1/p1=[d1, d1/p1, d1/p2], d1/p2=[d1, d1/p2]}", - DeleteListener.whatRemainedWhenDeleted.toString()); + assertEquals("{d1=[d1], d1/d2=[d1, d1/d2, d1/p1, d1/p2], d1/d2/p4=[d1, d1/d2, d1/d2/p4, d1/p1, d1/p2], d1/p1=[d1, d1/p1, d1/p2], d1/p2=[d1, d1/p2]}", + DeleteListener.whatRemainedWhenDeleted.toString(), + "AbstractFolder.items is sorted by name so we can predict deletion order"); } - @TestExtension("delete") public static class DeleteListener extends ItemListener { + + @TestExtension("delete") + public static class DeleteListener extends ItemListener { static Map> whatRemainedWhenDeleted = new TreeMap<>(); - @Override public void onDeleted(Item item) { + + @Override + public void onDeleted(Item item) { try { // Access metadata from another thread. whatRemainedWhenDeleted.put(item.getFullName(), Timer.get().submit(() -> { @@ -255,7 +269,7 @@ private void copyViaHttp(Folder f, JenkinsRule.WebClient wc, String fromName, St @Issue("JENKINS-35160") @Test - public void interruptOnDelete() throws Exception { + void interruptOnDelete() throws Exception { // adapted from JobTest in core r.jenkins.setNumExecutors(2); Queue.getInstance().maintain(); @@ -277,14 +291,15 @@ public void interruptOnDelete() throws Exception { /** * This is more of a test of the core, but make sure the triggers resolve between ourselves. */ - @Test public void trigger() throws Exception { + @Test + void trigger() throws Exception { Folder f = createFolder(); FreeStyleProject a = f.createProject(FreeStyleProject.class, "a"); FreeStyleProject b = f.createProject(FreeStyleProject.class, "b"); a.getPublishersList().add(new BuildTrigger("b",false)); FreeStyleBuild a1 = r.assertBuildStatusSuccess(a.scheduleBuild2(0)); - for (int i=0; i<10 && b.getLastBuild()==null; i++) { + for (int i = 0; i < 10 && b.getLastBuild() == null; i++) { Thread.sleep(100); } // make sue that a build of B happens @@ -293,7 +308,8 @@ public void interruptOnDelete() throws Exception { /** * Makes sure that there's no JavaScript error in the new view page. */ - @Test public void newViewPage() throws Exception { + @Test + void newViewPage() throws Exception { Folder f = createFolder(); HtmlPage p = r.createWebClient().getPage(f, "newView"); HtmlForm fm = p.getFormByName("createItem"); @@ -311,7 +327,8 @@ public void interruptOnDelete() throws Exception { * correctly comes back. */ @LocalData - @Test public void dataCompatibility() throws Exception { + @Test + void dataCompatibility() { Folder f = (Folder) r.jenkins.getItem("foo"); ListView pv = (ListView)f.getPrimaryView(); assertEquals(2,pv.getColumns().size()); @@ -322,7 +339,8 @@ public void interruptOnDelete() throws Exception { assertTrue(2(Arrays.asList(middleJob, bottomJob)), new HashSet<>(items)); } - @Test public void reloadJenkinsAndFindBuildInProgress() throws Exception { + @Test + void reloadJenkinsAndFindBuildInProgress() throws Exception { Folder f1 = r.jenkins.createProject(Folder.class, "f"); FreeStyleProject p1 = f1.createProject(FreeStyleProject.class, "test1"); @@ -365,7 +384,8 @@ public void interruptOnDelete() throws Exception { p1b2.getExecutor().interrupt(); // kill the executor } - @Test public void discoverPermission() throws Exception { + @Test + void discoverPermission() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); final Folder d = r.jenkins.createProject(Folder.class, "d"); final FreeStyleProject p1 = d.createProject(FreeStyleProject.class, "p1"); @@ -383,24 +403,21 @@ public void interruptOnDelete() throws Exception { try (var context = ACL.as2(User.getById("alice", true).impersonate2())) { assertEquals(Collections.singletonList(p1), d.getItems()); assertEquals(p1, d.getItem("p1")); - try { - d.getItem("p2"); - fail("should have been told p2 exists"); - } catch (AccessDeniedException x) { - // correct - } + assertThrows(AccessDeniedException.class, () -> d.getItem("p2"), "should have been told p2 exists"); } } - @Test public void addAction() throws Exception { + @Test + void addAction() throws Exception { Folder f = createFolder(); WhoAmI a = new WhoAmI(); f.addAction(a); assertNotNull(f.getAction(WhoAmI.class)); } - + @Issue("JENKINS-32487") - @Test public void shouldAssignPropertyOwnerOnCreationAndReload() throws Exception { + @Test + void shouldAssignPropertyOwnerOnCreationAndReload() throws Exception { Folder folder = r.jenkins.createProject(Folder.class, "myFolder"); ProjectMatrixAuthorizationStrategy as = new ProjectMatrixAuthorizationStrategy(); // Need to do this to avoid JENKINS-9774 @@ -417,9 +434,10 @@ public void interruptOnDelete() throws Exception { Folder reloadedFolder = r.jenkins.getItemByFullName("myFolder", Folder.class); assertPropertyOwner("After reload", reloadedFolder, FolderCredentialsProvider.FolderCredentialsProperty.class); } - + @Issue("JENKINS-32359") - @Test public void shouldProperlyPersistFolderPropertiesOnMultipleReloads() throws Exception { + @Test + void shouldProperlyPersistFolderPropertiesOnMultipleReloads() throws Exception { Folder folder = r.jenkins.createProject(Folder.class, "myFolder"); // We add a stub property to generate the persisted list @@ -453,7 +471,8 @@ public void interruptOnDelete() throws Exception { } @Issue("JENKINS-52164") - @Test public void renameLinksShouldBeValid() throws Exception { + @Test + void renameLinksShouldBeValid() throws Exception { FreeStyleProject project1 = r.createFreeStyleProject(); Folder folder1 = createFolder(); FreeStyleProject project2 = folder1.createProject(FreeStyleProject.class, "project2"); @@ -469,7 +488,8 @@ public void interruptOnDelete() throws Exception { } @Issue("JENKINS-63836") - @Test public void shouldNotHaveHealthMetricConfiguredGloballyOnCreation() throws Exception { + @Test + void shouldNotHaveHealthMetricConfiguredGloballyOnCreation() throws Exception { assertThat("by default, global configuration should not have any health metrics", AbstractFolderConfiguration.get().getHealthMetrics(), hasSize(0)); @@ -485,7 +505,8 @@ public void interruptOnDelete() throws Exception { healthMetrics, hasSize(0)); } - @Test public void visibleItems() throws IOException, InterruptedException { + @Test + void visibleItems() throws IOException, InterruptedException { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.READ).everywhere().toEveryone(). @@ -505,7 +526,8 @@ public void interruptOnDelete() throws Exception { assertFalse(f.hasVisibleItems()); } - @Test public void getItemsPredicate() throws IOException { + @Test + void getItemsPredicate() throws IOException { final Folder d = r.jenkins.createProject(Folder.class, "d"); final FreeStyleProject p1 = d.createProject(FreeStyleProject.class, "p1"); final FreeStyleProject p2 = d.createProject(FreeStyleProject.class, "p2"); @@ -542,7 +564,8 @@ private HtmlAnchor findRenameAnchor(AbstractItem item) throws Exception { } @Issue("SECURITY-3105") - @Test public void doCreateView() throws Exception { + @Test + void doCreateView() throws Exception { Folder f = createFolder(); String folderURL = f.getUrl() + "createView?mode=copy&name=NewView&from=All"; // Create a web client with the option to not throw exceptions on failing status codes - this allows us to catch the status code instead of the test crashing @@ -553,7 +576,8 @@ private HtmlAnchor findRenameAnchor(AbstractItem item) throws Exception { } @Issue("SECURITY-3106") - @Test public void doCreateItem() throws Exception { + @Test + void doCreateItem() throws Exception { Folder f = createFolder(); String folderURL = f.getUrl() + "createItem?mode=copy&name=NewFolder&from=" + f.getName(); // Create a web client with the option to not throw exceptions on failing status codes - this allows us to catch the status code instead of the test crashing @@ -562,5 +586,4 @@ private HtmlAnchor findRenameAnchor(AbstractItem item) throws Exception { // The request sent is using a GET instead of POST request which is not allowed assertEquals(405, webClient.goTo(folderURL).getWebResponse().getStatusCode()); } - } diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ComputedFolder2Test.java b/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ComputedFolder2Test.java index 7be5eb07..701c785c 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ComputedFolder2Test.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ComputedFolder2Test.java @@ -37,29 +37,29 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.Issue; -import org.jvnet.hudson.test.JenkinsSessionRule; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.JenkinsSessionExtension; -public class ComputedFolder2Test { +class ComputedFolder2Test { - @Rule - public JenkinsSessionRule rr = new JenkinsSessionRule(); + @RegisterExtension + private final JenkinsSessionExtension extension = new JenkinsSessionExtension(); @Issue("JENKINS-42593") @Test - public void eventAfterRestart() throws Throwable { - rr.then(j -> { + void eventAfterRestart() throws Throwable { + extension.then(j -> { EventableFolder d = j.createProject(EventableFolder.class, "d"); d.add("one"); String log = ComputedFolderTest.doRecompute(d, Result.SUCCESS); assertThat(log, d.getItems(), hasSize(equalTo(1))); }); - rr.then(j -> { + extension.then(j -> { EventableFolder d = j.jenkins.getItemByFullName("d", EventableFolder.class); assertNotNull(d); assertThat(d.getItems(), hasSize(equalTo(1))); @@ -69,7 +69,6 @@ public void eventAfterRestart() throws Throwable { }); } - @SuppressWarnings({"unchecked", "rawtypes"}) public static final class EventableFolder extends ComputedFolder { private final List kids = new ArrayList<>(); @@ -115,6 +114,7 @@ public void add(String kid) throws IOException, InterruptedException { } } + @SuppressWarnings("unused") @TestExtension("eventAfterRestart") public static final class DescriptorImpl extends AbstractFolderDescriptor { @@ -122,9 +122,6 @@ public static final class DescriptorImpl extends AbstractFolderDescriptor { public TopLevelItem newInstance(ItemGroup parent, String name) { return new EventableFolder(parent, name); } - } - } - } diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ComputedFolderTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ComputedFolderTest.java index 4adc81ac..6e7249dc 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ComputedFolderTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ComputedFolderTest.java @@ -30,12 +30,7 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import com.cloudbees.hudson.plugins.folder.AbstractFolderDescriptor; import com.cloudbees.hudson.plugins.folder.Folder; @@ -94,24 +89,29 @@ import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.SleepBuilder; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.stapler.StaplerRequest2; import org.kohsuke.stapler.StaplerResponse2; -public class ComputedFolderTest { +@WithJenkins +class ComputedFolderTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } @Issue("JENKINS-32179") @Test - public void duplicateEntries() throws Exception { + void duplicateEntries() throws Exception { SampleComputedFolder d = r.jenkins.createProject(SampleComputedFolder.class, "d"); d.recompute(Result.SUCCESS); d.assertItemNames(1); @@ -121,11 +121,9 @@ public void duplicateEntries() throws Exception { assertEquals("[A, B, C]", d.created.toString()); // ComputedFolder page opens correctly - try { + assertDoesNotThrow(() -> { r.createWebClient().getPage(d); - } catch (Exception ex) { - Assert.fail("ComputedFolder cannot be opened: " + ex.getMessage()); - } + }, "ComputedFolder cannot be opened: "); d.recompute(Result.SUCCESS); d.assertItemNames(3, "A", "B", "C"); @@ -148,7 +146,7 @@ public void duplicateEntries() throws Exception { } @Test - public void disableOrphans() throws Exception { + void disableOrphans() throws Exception { SampleComputedFolder d = r.jenkins.createProject(SampleComputedFolder.class, "d"); d.setOrphanedItemStrategy(new DefaultOrphanedItemStrategy(true, "-1", "1")); d.recompute(Result.SUCCESS); @@ -170,7 +168,7 @@ public void disableOrphans() throws Exception { } @Test - public void disableFolder() throws Exception { + void disableFolder() throws Exception { SampleComputedFolder d = r.jenkins.createProject(SampleComputedFolder.class, "d"); d.recompute(Result.SUCCESS); d.assertItemNames(1); @@ -193,7 +191,7 @@ public void disableFolder() throws Exception { } @Test - public void roundTrip() throws Exception { + void roundTrip() throws Exception { SampleComputedFolder d = r.jenkins.createProject(SampleComputedFolder.class, "d"); d.makeDisabled(true); d = r.configRoundtrip(d); @@ -202,30 +200,26 @@ public void roundTrip() throws Exception { @Issue("JENKINS-42680") @Test - public void foldersAsChildren() throws Exception { + void foldersAsChildren() throws Exception { final SampleComputedFolderWithFoldersAsChildren d = r.jenkins.createProject(SampleComputedFolderWithFoldersAsChildren.class, "d"); d.recompute(Result.SUCCESS); d.kids.add("A"); d.recompute(Result.SUCCESS); // Folder page opens correctly - try { + assertDoesNotThrow(() -> { Folder a = d.getItems().iterator().next(); r.createWebClient().getPage(a); - } catch (Exception ex) { - Assert.fail("Folder inside ComputedFolder cannot be opened: " + ex.getMessage()); - } + }, "Folder inside ComputedFolder cannot be opened: "); // ComputerFolder page does no open - try { + assertDoesNotThrow(() -> { r.createWebClient().getPage(d); - } catch (Exception ex) { - Assert.fail("ComputedFolder cannot be opened: " + ex.getMessage()); - } + }, "ComputedFolder cannot be opened: "); } @Test - public void abortException() throws Exception { + void abortException() throws Exception { SampleComputedFolder d = r.jenkins.createProject(SampleComputedFolder.class, "d"); d.setDisplayName("My Folder"); d.kids.addAll(Arrays.asList("A", "B")); @@ -236,13 +230,13 @@ public void abortException() throws Exception { // Despite its name, AbortException is intended to be FAILURE, not ABORTED which would be InterruptedException. String log = d.recompute(Result.FAILURE); d.assertItemNames(2, "A", "B"); - assertTrue(log, log.contains("not adding Z")); - assertFalse(log, log.contains(SampleComputedFolder.class.getName())); + assertTrue(log.contains("not adding Z"), log); + assertFalse(log.contains(SampleComputedFolder.class.getName()), log); } @Issue("JENKINS-25240") @Test - public void runningBuild() throws Exception { + void runningBuild() throws Exception { SampleComputedFolder d = r.jenkins.createProject(SampleComputedFolder.class, "d"); d.kids.addAll(Arrays.asList("A", "B")); d.recompute(Result.SUCCESS); @@ -274,7 +268,7 @@ public void runningBuild() throws Exception { @Issue("JENKINS-60677") @Test - public void runningBuildWithAbortBuildsOption() throws Exception { + void runningBuildWithAbortBuildsOption() throws Exception { SampleComputedFolder folder = r.jenkins.createProject(SampleComputedFolder.class, "d"); DefaultOrphanedItemStrategy strategy = new DefaultOrphanedItemStrategy(true, -1, -1); strategy.setAbortBuilds(true); @@ -294,7 +288,7 @@ public void runningBuildWithAbortBuildsOption() throws Exception { r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(bBuild)); InterruptedBuildAction interruptedBuildAction = bBuild.getAction(InterruptedBuildAction.class); CauseOfInterruption causeOfInterruption = interruptedBuildAction.getCauses().stream().findFirst().orElseThrow(NoSuchElementException::new); - assertTrue(causeOfInterruption instanceof OrphanedParent); + assertInstanceOf(OrphanedParent.class, causeOfInterruption); } folder.recompute(Result.SUCCESS); folder.assertItemNames(3, "A"); @@ -311,7 +305,7 @@ public void runningBuildWithAbortBuildsOption() throws Exception { @Issue("JENKINS-60677") @Test - public void runningWorkflowJobBuildWithAbortBuildsOption() throws Exception { + void runningWorkflowJobBuildWithAbortBuildsOption() throws Exception { SampleComputedFolderWithWorkflowJobAsChildren folder = r.jenkins.createProject(SampleComputedFolderWithWorkflowJobAsChildren.class, "d"); DefaultOrphanedItemStrategy strategy = new DefaultOrphanedItemStrategy(true, -1, -1); strategy.setAbortBuilds(true); @@ -332,13 +326,13 @@ public void runningWorkflowJobBuildWithAbortBuildsOption() throws Exception { r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(build)); InterruptedBuildAction interruptedBuildAction = build.getAction(InterruptedBuildAction.class); CauseOfInterruption causeOfInterruption = interruptedBuildAction.getCauses().stream().findFirst().orElseThrow(NoSuchElementException::new); - assertTrue(causeOfInterruption instanceof OrphanedParent); + assertInstanceOf(OrphanedParent.class, causeOfInterruption); } } @Issue("JENKINS-60677") @Test - public void pendingBuildWithAbortBuildsOption() throws Exception { + void pendingBuildWithAbortBuildsOption() throws Exception { SampleComputedFolder folder = r.jenkins.createProject(SampleComputedFolder.class, "d"); DefaultOrphanedItemStrategy strategy = new DefaultOrphanedItemStrategy(true, -1, -1); strategy.setAbortBuilds(true); @@ -358,29 +352,24 @@ public void pendingBuildWithAbortBuildsOption() throws Exception { folder.recompute(Result.SUCCESS); folder.assertItemNames(2); - try { - pendingBuild.getFuture().get(); - fail("Cancellation exception was expected"); - } catch (CancellationException e) { - // As expected - } + assertThrows(CancellationException.class, () -> pendingBuild.getFuture().get()); } @Test - public void notAddChildren() throws Exception { + void notAddChildren() throws Exception { JenkinsRule.WebClient client = r.createWebClient(); SampleComputedFolder s = r.jenkins.createProject(SampleComputedFolder.class, "s"); - assertEquals(client.getPage(s).getByXPath("//a[contains(text(), \"New Item\")]").size(), 0); + assertEquals(0, client.getPage(s).getByXPath("//a[contains(text(), \"New Item\")]").size()); s.kids.add("A"); s.recompute(Result.SUCCESS); - assertEquals(client.getPage(s).getByXPath("//a[contains(text(), \"New Item\")]").size(), 0); + assertEquals(0, client.getPage(s).getByXPath("//a[contains(text(), \"New Item\")]").size()); } @Test - public void runByTrigger() throws Exception { + void runByTrigger() throws Exception { SampleComputedFolder s = r.jenkins.createProject(SampleComputedFolder.class, "s"); s.assertItemNames(0); @@ -396,7 +385,7 @@ public void runByTrigger() throws Exception { /** Verify that running branch projects are not deleted even after an organization folder reindex. */ @Issue("JENKINS-25240") @Test - public void runningBuildMeta() throws Exception { + void runningBuildMeta() throws Exception { SecondOrderComputedFolder org = r.jenkins.createProject(SecondOrderComputedFolder.class, "org"); org.metakids.add(Arrays.asList("A", "B")); org.metakids.add(Arrays.asList("C", "D")); @@ -413,7 +402,7 @@ public void runningBuildMeta() throws Exception { } @Test - public void viewHolderRestrictions() throws Exception { + void viewHolderRestrictions() throws Exception { LockedDownSampleComputedFolder org = r.jenkins.createProject(LockedDownSampleComputedFolder.class, "org"); // initial setup is correct assertThat(org.getViews().size(), is(2)); @@ -451,7 +440,7 @@ public void viewHolderRestrictions() throws Exception { } @Test - public void recomputationSuppression() throws Exception { + void recomputationSuppression() throws Exception { final VariableRecomputationComputedFolder org = r.jenkins.createProject(VariableRecomputationComputedFolder.class, "org"); // no recalculateAfterSubmitted calls means we recalculate @@ -476,11 +465,10 @@ public void recomputationSuppression() throws Exception { r.configRoundtrip(org); r.waitUntilNoActivity(); assertThat(org.round, is(round)); - } @Test - public void recomputationSuppressionMulti() throws Exception { + void recomputationSuppressionMulti() throws Exception { final VariableRecomputationComputedFolder org = r.jenkins.createProject(VariableRecomputationComputedFolder.class, "org"); @@ -530,7 +518,7 @@ public void recomputationSuppressionMulti() throws Exception { } @Test - public void triggersRoundtrip() throws Exception { + void triggersRoundtrip() throws Exception { SampleComputedFolder s = r.jenkins.createProject(SampleComputedFolder.class, "s"); s.addTrigger(new PeriodicFolderTrigger("30m")); SampleComputedFolder s2 = r.configRoundtrip(s); @@ -538,11 +526,10 @@ public void triggersRoundtrip() throws Exception { assertThat(trigger, notNullValue()); assertThat(trigger, instanceOf(PeriodicFolderTrigger.class)); assertThat(((PeriodicFolderTrigger)trigger).getInterval(), is("30m")); - } @Test - public void cleanTriggers() throws Exception { + void cleanTriggers() throws Exception { SampleComputedFolder s = r.jenkins.createProject(SampleComputedFolder.class, "s"); s.addTrigger(new PeriodicFolderTrigger("30m")); @@ -555,7 +542,7 @@ public void cleanTriggers() throws Exception { @Test @Issue("JENKINS-42511") - public void concurrentEvents() throws Exception { + void concurrentEvents() throws Exception { CoordinatedComputedFolder d = r.jenkins.createProject(CoordinatedComputedFolder.class, "d"); d.kids.addAll(Arrays.asList("A", "B")); QueueTaskFuture future = d.scheduleBuild2(0).getFuture(); @@ -580,7 +567,7 @@ public void concurrentEvents() throws Exception { @Test @Issue("JENKINS-35112") - public void deleteWhileComputing() throws Exception { + void deleteWhileComputing() throws Exception { CoordinatedComputedFolder d = r.jenkins.createProject(CoordinatedComputedFolder.class, "d"); d.kids.addAll(Arrays.asList("A", "B")); QueueTaskFuture future = d.scheduleBuild2(0).getFuture(); @@ -593,17 +580,14 @@ public void deleteWhileComputing() throws Exception { } @Test - public void renameWhileComputing() throws Exception { + void renameWhileComputing() throws Exception { CoordinatedComputedFolder d = r.jenkins.createProject(CoordinatedComputedFolder.class, "d"); d.kids.addAll(Arrays.asList("A", "B")); QueueTaskFuture future = d.scheduleBuild2(0).getFuture(); future.waitForStart(); - try { - d.checkRename("d2"); - fail("Should be blocked while computation is in progress"); - } catch (Failure f) { - assertThat(f.getMessage(), is(Messages.ComputedFolder_ComputationInProgress())); - } + Failure f = assertThrows(Failure.class, () -> d.checkRename("d2"), "Should be blocked while computation is in progress"); + assertThat(f.getMessage(), is(Messages.ComputedFolder_ComputationInProgress())); + d.onKid("B"); future.get(); waitUntilNoActivityIgnoringThreadDeathUpTo(10000); @@ -611,7 +595,7 @@ public void renameWhileComputing() throws Exception { } @Test - public void failAllDeletedOnes() throws Exception { + void failAllDeletedOnes() throws Exception { OneUndeletableChildComputedFolder d = r.jenkins.createProject(OneUndeletableChildComputedFolder.class, "d"); d.kids.addAll(Arrays.asList("A", "B")); d.recompute(Result.SUCCESS); @@ -627,9 +611,9 @@ public void failAllDeletedOnes() throws Exception { @Issue("JENKINS-73930") @Test - public void disabledWarningFromUiViews() throws Exception { + void disabledWarningFromUiViews() throws Exception { LockedDownSampleComputedFolder folder = r.jenkins.createProject(LockedDownSampleComputedFolder.class, "d"); - assertFalse("by default, a folder is disabled", folder.isDisabled()); + assertFalse(folder.isDisabled(), "by default, a folder is disabled"); for(View view : folder.getViews()){ assertNull(r.createWebClient().goTo(view.getViewUrl()).getElementById("disabled-message")); } @@ -715,7 +699,6 @@ public boolean isSomethingHappeningIgnoringThreadDeath() { return false; } - @SuppressWarnings({"unchecked", "rawtypes"}) public static class SampleComputedFolder extends ComputedFolder { List kids = new ArrayList<>(); @@ -756,7 +739,6 @@ protected void computeChildren(ChildObserver observer, TaskLis observer.completed(kid); } } - } @Override @@ -783,6 +765,7 @@ void assertItemNames(int round, String... names) { assertEquals(new TreeSet<>(Arrays.asList(names)).toString(), actual.toString()); } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends AbstractFolderDescriptor { @@ -790,12 +773,9 @@ public static class DescriptorImpl extends AbstractFolderDescriptor { public TopLevelItem newInstance(ItemGroup parent, String name) { return new SampleComputedFolder(parent, name); } - } - } - @SuppressWarnings({"unchecked", "rawtypes"}) public static class SampleComputedFolderWithWorkflowJobAsChildren extends ComputedFolder { List kids = new ArrayList<>(); @@ -830,7 +810,6 @@ protected void computeChildren(ChildObserver observer, TaskListener observer.completed(kid); } } - } String recompute(Result result) throws Exception { @@ -846,6 +825,7 @@ void assertItemNames(int round, String... names) { assertEquals(new TreeSet<>(Arrays.asList(names)).toString(), actual.toString()); } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends AbstractFolderDescriptor { @@ -853,11 +833,9 @@ public static class DescriptorImpl extends AbstractFolderDescriptor { public TopLevelItem newInstance(ItemGroup parent, String name) { return new SampleComputedFolderWithWorkflowJobAsChildren(parent, name); } - } } - @SuppressWarnings({"unchecked", "rawtypes"}) public static class SampleComputedFolderWithFoldersAsChildren extends ComputedFolder { List kids = new ArrayList<>(); @@ -892,13 +870,13 @@ protected void computeChildren(ChildObserver observer, TaskListener list observer.completed(kid); } } - } String recompute(Result result) throws Exception { return doRecompute(this, result); } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends AbstractFolderDescriptor { @@ -906,9 +884,7 @@ public static class DescriptorImpl extends AbstractFolderDescriptor { public TopLevelItem newInstance(ItemGroup parent, String name) { return new SampleComputedFolderWithFoldersAsChildren(parent, name); } - } - } public static class LockedDownSampleComputedFolder extends SampleComputedFolder { @@ -922,6 +898,7 @@ protected AbstractFolderViewHolder newFolderViewHolder() { return new FixedViewHolder(this); } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends AbstractFolderDescriptor { @@ -1006,6 +983,7 @@ protected void submit(StaplerRequest2 req, StaplerResponse2 rsp) } } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends AbstractFolderDescriptor { @@ -1013,13 +991,12 @@ public static class DescriptorImpl extends AbstractFolderDescriptor { public TopLevelItem newInstance(ItemGroup parent, String name) { return new VariableRecomputationComputedFolder(parent, name); } - } } static String doRecompute(ComputedFolder d, Result result) throws Exception { if (d.isDisabled()) { - assertEquals("Folder " + d.getFullName() + " is disabled", result, Result.NOT_BUILT); + assertEquals(Result.NOT_BUILT, result, "Folder " + d.getFullName() + " is disabled"); return "DISABLED"; } d.scheduleBuild2(0).getFuture().get(); @@ -1027,11 +1004,10 @@ static String doRecompute(ComputedFolder d, Result result) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); computation.writeWholeLogTo(baos); String log = baos.toString(); - assertEquals(log, result, computation.getResult()); + assertEquals(result, computation.getResult(), log); return log; } - @SuppressWarnings({"unchecked", "rawtypes"}) public static class SecondOrderComputedFolder extends ComputedFolder { List> metakids = new ArrayList<>(); @@ -1063,7 +1039,6 @@ protected void computeChildren(ChildObserver observer, Tas observer.completed(childName); } } - } String assertItemNames(String... names) throws Exception { @@ -1078,6 +1053,7 @@ String assertItemNames(String... names) throws Exception { return log; } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends AbstractFolderDescriptor { @@ -1085,9 +1061,7 @@ public static class DescriptorImpl extends AbstractFolderDescriptor { public TopLevelItem newInstance(ItemGroup parent, String name) { return new SecondOrderComputedFolder(parent, name); } - } - } public static class CoordinatedComputedFolder extends ComputedFolder { @@ -1199,6 +1173,7 @@ void assertItemNames(int round, String... names) { assertEquals(new TreeSet<>(Arrays.asList(names)).toString(), actual.toString()); } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends AbstractFolderDescriptor { @@ -1257,7 +1232,6 @@ public void delete() throws IOException, InterruptedException { observer.completed(kid); } } - } String recompute(Result result) throws Exception { @@ -1273,6 +1247,7 @@ void assertItemNames(int round, String... names) { assertEquals(new TreeSet<>(Arrays.asList(names)).toString(), actual.toString()); } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends AbstractFolderDescriptor { @@ -1280,9 +1255,6 @@ public static class DescriptorImpl extends AbstractFolderDescriptor { public TopLevelItem newInstance(ItemGroup parent, String name) { return new OneUndeletableChildComputedFolder(parent, name); } - } - } - } diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/computed/EventOutputStreamsTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/computed/EventOutputStreamsTest.java index 9a35c00f..81fb0bae 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/computed/EventOutputStreamsTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/computed/EventOutputStreamsTest.java @@ -36,36 +36,35 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.apache.commons.text.StringEscapeUtils; -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 static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; -public class EventOutputStreamsTest { +class EventOutputStreamsTest { - @Rule - public TemporaryFolder work = new TemporaryFolder(); + @TempDir + private File work; @Test - public void given_everyoneFlushing_when_twoThreads_then_outputCorrect() throws Exception { + void given_everyoneFlushing_when_twoThreads_then_outputCorrect() throws Exception { test(true, true); } @Test - public void given_nobodyFlushing_when_twoThreads_then_outputCorrect() throws Exception { + void given_nobodyFlushing_when_twoThreads_then_outputCorrect() throws Exception { test(false, false); } @Test - public void given_oneFlushing_when_twoThreads_then_outputCorrect() throws Exception { + void given_oneFlushing_when_twoThreads_then_outputCorrect() throws Exception { test(true, false); } - public void test(final boolean aFlush, final boolean bFlush) throws Exception { - final File file = work.newFile(); + private void test(final boolean aFlush, final boolean bFlush) throws Exception { + final File file = File.createTempFile("junit", null, work); final EventOutputStreams instance = new EventOutputStreams(new EventOutputStreams.OutputFile() { @NonNull @Override diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/computed/PeriodicFolderTriggerTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/computed/PeriodicFolderTriggerTest.java index 4e8308ed..8c4d1b78 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/computed/PeriodicFolderTriggerTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/computed/PeriodicFolderTriggerTest.java @@ -25,18 +25,25 @@ package com.cloudbees.hudson.plugins.folder.computed; import hudson.util.ListBoxModel; -import org.junit.Test; -import static org.junit.Assert.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; -public class PeriodicFolderTriggerTest { +import java.util.List; - @Issue("JENKINS-33006") - @Test - public void interval() throws Exception { - for (ListBoxModel.Option option : new PeriodicFolderTrigger.DescriptorImpl().doFillIntervalItems()) { - assertEquals("correctly round-trip " + option.name, option.value, new PeriodicFolderTrigger(option.value).getInterval()); - } +class PeriodicFolderTriggerTest { + + static List options() { + return new PeriodicFolderTrigger.DescriptorImpl().doFillIntervalItems(); } + @Issue("JENKINS-33006") + @ParameterizedTest + @MethodSource("options") + void interval(ListBoxModel.Option option) { + assertEquals(option.value, new PeriodicFolderTrigger(option.value).getInterval(), "correctly round-trip " + option.name); + } } diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ThrottleComputationQueueTaskDispatcherTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ThrottleComputationQueueTaskDispatcherTest.java index 0289875b..297987ab 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ThrottleComputationQueueTaskDispatcherTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/computed/ThrottleComputationQueueTaskDispatcherTest.java @@ -17,31 +17,39 @@ import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; -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.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@WithJenkins +class ThrottleComputationQueueTaskDispatcherTest { -public class ThrottleComputationQueueTaskDispatcherTest { private static final Logger LOGGER = Logger.getLogger(ThrottleComputationQueueTaskDispatcherTest.class.getName()); - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; + + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; + } @Test - public void acceptOne() throws Exception { + void acceptOne() throws Exception { SlowComputedFolder d = r.jenkins.createProject(SlowComputedFolder.class, "acceptOne"); d.recompute(Result.SUCCESS); } @Test - public void acceptLimit() throws Exception { + void acceptLimit() throws Exception { SlowComputedFolder[] d = new SlowComputedFolder[ThrottleComputationQueueTaskDispatcher.LIMIT]; Queue.Item[] q = new Queue.Item[ThrottleComputationQueueTaskDispatcher.LIMIT]; QueueTaskFuture[] f = new QueueTaskFuture[ThrottleComputationQueueTaskDispatcher.LIMIT]; @@ -91,12 +99,12 @@ public void acceptLimit() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); computation.writeWholeLogTo(baos); String log = baos.toString(); - assertEquals(log, Result.SUCCESS, computation.getResult()); + assertEquals(Result.SUCCESS, computation.getResult(), log); } } @Test - public void blockOneAboveLimit() throws Exception { + void blockOneAboveLimit() throws Exception { SlowComputedFolder[] d = new SlowComputedFolder[ThrottleComputationQueueTaskDispatcher.LIMIT + 1]; Queue.Item[] q = new Queue.Item[ThrottleComputationQueueTaskDispatcher.LIMIT + 1]; QueueTaskFuture[] f = new QueueTaskFuture[ThrottleComputationQueueTaskDispatcher.LIMIT + 1]; @@ -149,12 +157,12 @@ public void blockOneAboveLimit() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); computation.writeWholeLogTo(baos); String log = baos.toString(); - assertEquals(log, Result.SUCCESS, computation.getResult()); + assertEquals(Result.SUCCESS, computation.getResult(), log); } } @Test - public void blockManyAboveLimit() throws Exception { + void blockManyAboveLimit() throws Exception { // The queue could pick them up in any random order, so we need to leave at least one slot free in the // second set in order to ensure that the first set can complete (even eventually) once we release // it's finished latch, hence 2*LIMIT-1 and not 2*LIMIT. If we used 2*LIMIT then every so @@ -253,13 +261,13 @@ public void blockManyAboveLimit() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); computation.writeWholeLogTo(baos); String log = baos.toString(); - assertEquals(log, Result.SUCCESS, computation.getResult()); + assertEquals(Result.SUCCESS, computation.getResult(), log); } } - static String doRecompute(ComputedFolder d, Result result) throws Exception { + private static String doRecompute(ComputedFolder d, Result result) throws Exception { if (d.isDisabled()) { - assertEquals("Folder " + d.getFullName() + " is disabled", result, Result.NOT_BUILT); + assertEquals(Result.NOT_BUILT, result, "Folder " + d.getFullName() + " is disabled"); return "DISABLED"; } d.scheduleBuild2(0).getFuture().get(); @@ -267,7 +275,7 @@ static String doRecompute(ComputedFolder d, Result result) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); computation.writeWholeLogTo(baos); String log = baos.toString(); - assertEquals(log, result, computation.getResult()); + assertEquals(result, computation.getResult(), log); return log; } @@ -304,6 +312,7 @@ String recompute(Result result) throws Exception { return doRecompute(this, result); } + @SuppressWarnings("unused") @TestExtension public static class DescriptorImpl extends AbstractFolderDescriptor { @@ -311,7 +320,6 @@ public static class DescriptorImpl extends AbstractFolderDescriptor { public TopLevelItem newInstance(ItemGroup parent, String name) { return new SlowComputedFolder(parent, name); } - } } } diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/config/AbstractFolderConfigurationTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/config/AbstractFolderConfigurationTest.java index d7ce0a60..28f324f0 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/config/AbstractFolderConfigurationTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/config/AbstractFolderConfigurationTest.java @@ -1,7 +1,6 @@ package com.cloudbees.hudson.plugins.folder.config; import com.cloudbees.hudson.plugins.folder.health.FolderHealthMetric; -import com.cloudbees.hudson.plugins.folder.health.FolderHealthMetricDescriptor; import com.cloudbees.hudson.plugins.folder.health.WorstChildHealthMetric; import org.htmlunit.html.HtmlElement; import org.htmlunit.html.HtmlForm; @@ -9,46 +8,50 @@ import hudson.init.InitMilestone; import hudson.init.Initializer; import jenkins.model.Jenkins; -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.LoggerRule; +import org.jvnet.hudson.test.LogRecorder; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; -import java.util.stream.Collectors; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.hasSize; -public class AbstractFolderConfigurationTest { +@WithJenkins +class AbstractFolderConfigurationTest { private static final String GUICE_INITIALIZATION_MESSAGE = "Failed to instantiate Key[type=" + AbstractFolderConfiguration.class.getName() + ", annotation=[none]];"; - - @Rule - public JenkinsRule r = new JenkinsRule(); - @Rule - public LoggerRule logging = new LoggerRule().record(ExtensionFinder.GuiceFinder.class, Level.INFO).capture(100); + private final LogRecorder logging = new LogRecorder().record(ExtensionFinder.GuiceFinder.class, Level.INFO).capture(100); + + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } @Test @Issue("JENKINS-60393") - public void testInitialization() { + void testInitialization() { assertThat("AbstractFolderConfiguration should not cause circular dependency on startup", logging.getRecords().stream() .filter(lr -> lr.getLevel().intValue() == Level.WARNING.intValue()) .filter(lr -> lr.getMessage().contains(GUICE_INITIALIZATION_MESSAGE)) .map(lr -> lr.getSourceClassName() + "." + lr.getSourceMethodName() + ": " + lr.getMessage()) - .collect(Collectors.toList()), + .toList(), emptyIterable()); } @Test - public void healthMetricsAppearsInConfiguredGlobally() throws Exception { + void healthMetricsAppearsInConfiguredGlobally() throws Exception { HtmlForm cfg = r.createWebClient().goTo("configure").getFormByName("config"); assertThat("adding metrics from Global Configuration", AbstractFolderConfiguration.get().getHealthMetrics(), hasSize(cfg.getElementsByAttribute("div", "suffix", "healthMetrics").size())); @@ -56,7 +59,7 @@ public void healthMetricsAppearsInConfiguredGlobally() throws Exception { @Issue("JENKINS-60393") @Test - public void shouldBeAbleToRemoveHealthMetricConfiguredGlobally() throws Exception { + void shouldBeAbleToRemoveHealthMetricConfiguredGlobally() throws Exception { List healthMetrics = new ArrayList<>(1); healthMetrics.add(new WorstChildHealthMetric(true)); AbstractFolderConfiguration.get().setHealthMetrics(healthMetrics); @@ -71,9 +74,10 @@ public void shouldBeAbleToRemoveHealthMetricConfiguredGlobally() throws Exceptio } /** - * A initializer that can produce circular dependency if AbstractFolderConfiguration is not properly initialized + * An initializer that can produce circular dependency if AbstractFolderConfiguration is not properly initialized * on startup. */ + @SuppressWarnings("unused") public static class TestInitialization { @Initializer(before = InitMilestone.JOB_LOADED, after = InitMilestone.PLUGINS_STARTED) diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/health/NamedChildHealthMetricTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/health/NamedChildHealthMetricTest.java index da4e62f4..1d41386c 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/health/NamedChildHealthMetricTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/health/NamedChildHealthMetricTest.java @@ -29,22 +29,28 @@ import java.util.List; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import com.cloudbees.hudson.plugins.folder.Folder; import hudson.model.HealthReport; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class NamedChildHealthMetricTest { +@WithJenkins +class NamedChildHealthMetricTest { - @Rule - public JenkinsRule j = new JenkinsRule(); + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } @Test - public void childExists() throws Exception { - Folder folder = j.jenkins.createProject(Folder.class, "myFolder"); + void childExists() throws Exception { + Folder folder = r.jenkins.createProject(Folder.class, "myFolder"); folder.createProject(Folder.class, "mySubFolder"); folder.getHealthMetrics().add(new NamedChildHealthMetric("mySubFolder")); @@ -53,8 +59,8 @@ public void childExists() throws Exception { } @Test - public void childDoesNotExist() throws Exception { - Folder folder = j.jenkins.createProject(Folder.class, "myFolder"); + void childDoesNotExist() throws Exception { + Folder folder = r.jenkins.createProject(Folder.class, "myFolder"); folder.createProject(Folder.class, "mySubFolder"); folder.getHealthMetrics().add(new NamedChildHealthMetric("doesnotexist")); @@ -63,8 +69,8 @@ public void childDoesNotExist() throws Exception { } @Test - public void nestedChild() throws Exception { - Folder folder = j.jenkins.createProject(Folder.class, "myFolder"); + void nestedChild() throws Exception { + Folder folder = r.jenkins.createProject(Folder.class, "myFolder"); Folder subFolder = folder.createProject(Folder.class, "mySubFolder"); subFolder.createProject(Folder.class, "nestedFolder"); folder.getHealthMetrics().add(new NamedChildHealthMetric("mySubFolder/nestedFolder")); @@ -72,5 +78,4 @@ public void nestedChild() throws Exception { List reports = folder.getBuildHealthReports(); assertThat("report should not contain report for nested child", reports, hasSize(0)); } - } diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/properties/FolderCredentialsProviderTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/properties/FolderCredentialsProviderTest.java index d87fd077..0cfda3cc 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/properties/FolderCredentialsProviderTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/properties/FolderCredentialsProviderTest.java @@ -52,34 +52,40 @@ import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.hamcrest.StringDescription; -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.MockAuthorizationStrategy; import org.jvnet.hudson.test.MockQueueItemAuthenticator; import org.jvnet.hudson.test.TestBuilder; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class FolderCredentialsProviderTest { +@WithJenkins +class FolderCredentialsProviderTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } @Test - public void foldersHaveTheirOwnStore() throws Exception { + void foldersHaveTheirOwnStore() throws Exception { Folder f = createFolder(); CredentialsStore folderStore = getFolderStore(f); assertThat(folderStore, notNullValue()); } @Test - public void credentialsAvailableAtFolderScope() throws Exception { + void credentialsAvailableAtFolderScope() throws Exception { Folder f = createFolder(); List asGroup = CredentialsProvider.lookupCredentialsInItemGroup(StandardUsernamePasswordCredentials.class, f, @@ -103,7 +109,7 @@ public void credentialsAvailableAtFolderScope() throws Exception { } @Test - public void credentialsListableAtFolderScope() throws Exception { + void credentialsListableAtFolderScope() throws Exception { Folder f = createFolder(); ListBoxModel asGroup = CredentialsProvider.listCredentialsInItemGroup(StandardUsernamePasswordCredentials.class, f, @@ -130,7 +136,7 @@ public void credentialsListableAtFolderScope() throws Exception { } @Test - public void given_folderCredential_when_builtAsSystem_then_credentialFound() throws Exception { + void given_folderCredential_when_builtAsSystem_then_credentialFound() throws Exception { Folder f = createFolder(); CredentialsStore folderStore = getFolderStore(f); folderStore.addCredentials(Domain.global(), @@ -142,7 +148,7 @@ public void given_folderCredential_when_builtAsSystem_then_credentialFound() thr } @Test - public void given_folderCredential_when_builtAsUserWithUseItem_then_credentialFound() throws Exception { + void given_folderCredential_when_builtAsUserWithUseItem_then_credentialFound() throws Exception { Folder f = createFolder(); CredentialsStore folderStore = getFolderStore(f); folderStore.addCredentials(Domain.global(), @@ -168,7 +174,7 @@ public void given_folderCredential_when_builtAsUserWithUseItem_then_credentialFo } @Test - public void given_folderCredential_when_builtAsUserWithoutUseItem_then_credentialNotFound() throws Exception { + void given_folderCredential_when_builtAsUserWithoutUseItem_then_credentialNotFound() throws Exception { Folder f = createFolder(); CredentialsStore folderStore = getFolderStore(f); folderStore.addCredentials(Domain.global(), @@ -193,7 +199,7 @@ public void given_folderCredential_when_builtAsUserWithoutUseItem_then_credentia } @Test - public void given_folderAndSystemCredentials_when_builtAsUserWithUseItem_then_folderCredentialFound() throws Exception { + void given_folderAndSystemCredentials_when_builtAsUserWithUseItem_then_folderCredentialFound() throws Exception { SystemCredentialsProvider.getInstance().getCredentials().add( new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "foo-manchu", "You don't want me", "bar", "fly") ); @@ -230,7 +236,7 @@ public void given_folderAndSystemCredentials_when_builtAsUserWithUseItem_then_fo } @Test - public void given_nestedFolderAndSystemCredentials_when_builtAsUserWithUseItem_then_folderCredentialFound() throws Exception { + void given_nestedFolderAndSystemCredentials_when_builtAsUserWithUseItem_then_folderCredentialFound() throws Exception { SystemCredentialsProvider.getInstance().getCredentials().add( new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "foo-manchu", "You don't want me", "bar", "fly") ); @@ -272,7 +278,7 @@ public void given_nestedFolderAndSystemCredentials_when_builtAsUserWithUseItem_t @Test @Issue("SECURITY-3252") - public void cannotUpdateCredentialsId() throws Exception { + void cannotUpdateCredentialsId() throws Exception { UsernamePasswordCredentialsImpl cred1 = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "cred1", "Cred 1", "foo", "bar"); UsernamePasswordCredentialsImpl cred2 = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "cred2", "Cred 2", "fee", "baz"); Folder f = createFolder(); @@ -312,7 +318,7 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen } else { StringDescription description = new StringDescription(); matcher.describeMismatch(credentials, description); - listener.getLogger().println(description.toString()); + listener.getLogger().println(description); return false; } } @@ -337,5 +343,4 @@ private CredentialsStore getFolderStore(Folder f) { private Folder createFolder() throws IOException { return r.jenkins.createProject(Folder.class, "folder" + r.jenkins.getItems().size()); } - } diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/relocate/StandardHandlerTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/relocate/StandardHandlerTest.java index de7b3abd..ed357283 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/relocate/StandardHandlerTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/relocate/StandardHandlerTest.java @@ -32,17 +32,27 @@ import hudson.security.ACLContext; import java.util.Arrays; import jenkins.model.Jenkins; -import static org.junit.Assert.*; -import org.junit.Rule; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +@WithJenkins +class StandardHandlerTest { -public class StandardHandlerTest { + private JenkinsRule r; - @Rule public JenkinsRule r = new JenkinsRule(); + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } - @Test public void getDestinations() throws Exception { + @Test + void getDestinations() throws Exception { Folder d1 = r.jenkins.createProject(Folder.class, "d1"); // where we start FreeStyleProject j = d1.createProject(FreeStyleProject.class, "j"); final Folder d2 = r.jenkins.createProject(Folder.class, "d2"); // where we could go @@ -60,7 +70,8 @@ public class StandardHandlerTest { } } - @Test public void getDestinationsUsingSubfolders() throws Exception { + @Test + void getDestinationsUsingSubfolders() throws Exception { Folder d1 = r.jenkins.createProject(Folder.class, "d1"); Folder d11 = d1.createProject(Folder.class, "d11"); FreeStyleProject j = d1.createProject(FreeStyleProject.class, "j"); @@ -74,7 +85,8 @@ public class StandardHandlerTest { assertNotEquals(d11, new StandardHandler().validDestinations(d11)); } - @Test public void getDestinationsUsingItemsWithSameName() throws Exception { + @Test + void getDestinationsUsingItemsWithSameName() throws Exception { Folder d1 = r.jenkins.createProject(Folder.class, "d1"); Folder d11 = d1.createProject(Folder.class, "d11"); FreeStyleProject j = d1.createProject(FreeStyleProject.class, "j"); @@ -90,7 +102,8 @@ public class StandardHandlerTest { assertNotEquals(Arrays.asList(d11, d3), new StandardHandler().validDestinations(d11)); } - @Test public void getDestinationsUsingItemsWithSameNameOnRootContext() throws Exception { + @Test + void getDestinationsUsingItemsWithSameNameOnRootContext() throws Exception { FreeStyleProject j = r.jenkins.createProject(FreeStyleProject.class, "j"); Folder d1 = r.jenkins.createProject(Folder.class, "d1"); Folder d11 = d1.createProject(Folder.class, "d11"); @@ -106,7 +119,8 @@ public class StandardHandlerTest { assertNotEquals(d3, new StandardHandler().validDestinations(d11)); } - @Test public void getDestinationsMovingAParentFolderInToTheTree() throws Exception { + @Test + void getDestinationsMovingAParentFolderInToTheTree() throws Exception { Folder d1 = r.jenkins.createProject(Folder.class, "d1"); Folder d11 = d1.createProject(Folder.class, "d2"); Folder d12 = d11.createProject(Folder.class, "d3"); @@ -115,5 +129,4 @@ public class StandardHandlerTest { assertEquals(Arrays.asList(r.jenkins, d4), new StandardHandler().validDestinations(d1)); assertNotEquals(Arrays.asList(d11, d12), new StandardHandler().validDestinations(d1)); } - } diff --git a/src/test/java/com/cloudbees/hudson/plugins/folder/views/DefaultFolderViewHolderTest.java b/src/test/java/com/cloudbees/hudson/plugins/folder/views/DefaultFolderViewHolderTest.java index 1e99c433..e9cef73f 100644 --- a/src/test/java/com/cloudbees/hudson/plugins/folder/views/DefaultFolderViewHolderTest.java +++ b/src/test/java/com/cloudbees/hudson/plugins/folder/views/DefaultFolderViewHolderTest.java @@ -28,27 +28,34 @@ import hudson.diagnosis.OldDataMonitor; import hudson.model.AdministrativeMonitor; import hudson.model.AllView; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Rule; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; -public class DefaultFolderViewHolderTest { +@WithJenkins +class DefaultFolderViewHolderTest { + + private JenkinsRule r; - @Rule - public JenkinsRule r = new JenkinsRule(); + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } @Issue("JENKINS-47416") @LocalData @Test - public void oldData() throws Exception { + void oldData() { Folder d = r.jenkins.getItemByFullName("d", Folder.class); assertEquals(AllView.DEFAULT_VIEW_NAME, d.getPrimaryView().getViewName()); for (OldDataMonitor.VersionRange problem : AdministrativeMonitor.all().get(OldDataMonitor.class).getData().values()) { fail(problem.extra); } } - }