diff --git a/pom.xml b/pom.xml index d071e51b..6a5baf8f 100644 --- a/pom.xml +++ b/pom.xml @@ -111,12 +111,6 @@ mockito-core test - - pl.pragmatists - JUnitParams - 1.1.1 - test - org.jenkins-ci.plugins scm-api @@ -139,11 +133,6 @@ tests test - - org.jenkins-ci.plugins - junit - test - diff --git a/src/test/java/integration/BrandingTest.java b/src/test/java/integration/BrandingTest.java index 5265f172..28025d7c 100644 --- a/src/test/java/integration/BrandingTest.java +++ b/src/test/java/integration/BrandingTest.java @@ -25,8 +25,6 @@ package integration; -import org.htmlunit.html.HtmlAnchor; -import org.htmlunit.html.HtmlPage; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.model.Action; @@ -42,11 +40,6 @@ import hudson.views.WeatherColumn; import integration.harness.BasicMultiBranchProject; import integration.harness.BasicMultiBranchProjectFactory; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; import jenkins.branch.Branch; import jenkins.branch.BranchIndexingCause; import jenkins.branch.BranchSource; @@ -65,11 +58,20 @@ import jenkins.scm.impl.mock.MockSCMNavigator; import jenkins.scm.impl.mock.MockSCMSource; import jenkins.scm.impl.mock.MockSCMSourceEvent; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.htmlunit.html.HtmlAnchor; +import org.htmlunit.html.HtmlPage; +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; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; @@ -82,24 +84,29 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -public class BrandingTest { +@WithJenkins +class BrandingTest { /** * All tests in this class only create items and do not affect other global configuration, thus we trade test * execution time for the restriction on only touching items. */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } - @Before - public void cleanOutAllItems() throws Exception { + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void given_multibranch_when_noSourcesDefined_then_noSourceBrandingPresent() throws Exception { + void given_multibranch_when_noSourcesDefined_then_noSourceBrandingPresent() throws Exception { try (MockSCMController c = MockSCMController.create()) { BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); prj.setCriteria(null); @@ -108,7 +115,7 @@ public void given_multibranch_when_noSourcesDefined_then_noSourceBrandingPresent } @Test - public void given_multibranch_when_sourceDefined_then_sourceBrandingPresentAfterIndexing() + void given_multibranch_when_sourceDefined_then_sourceBrandingPresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -123,7 +130,7 @@ public void given_multibranch_when_sourceDefined_then_sourceBrandingPresentAfter } @Test - public void given_multibranch_when_sourceDefined_then_sourceBrandingPresentAfterSourceEvent() + void given_multibranch_when_sourceDefined_then_sourceBrandingPresentAfterSourceEvent() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -138,7 +145,7 @@ public void given_multibranch_when_sourceDefined_then_sourceBrandingPresentAfter } @Test - public void given_multibranch_when_branches_then_branchBrandingPresent() + void given_multibranch_when_branches_then_branchBrandingPresent() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -152,7 +159,7 @@ public void given_multibranch_when_branches_then_branchBrandingPresent() } @Test - public void given_multibranch_when_branches_then_runBrandingPresent() + void given_multibranch_when_branches_then_runBrandingPresent() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -169,7 +176,7 @@ public void given_multibranch_when_branches_then_runBrandingPresent() @Test @Issue("JENKINS-48090") - public void given_multibranch_when_runBrandingIncludesAdditionalCauses_then_causesMerged() throws Exception { + void given_multibranch_when_runBrandingIncludesAdditionalCauses_then_causesMerged() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -188,7 +195,7 @@ public void given_multibranch_when_runBrandingIncludesAdditionalCauses_then_caus } @Test - public void given_orgFolder_when_noNavigatorsDefined_then_noNavigatorBrandingPresent() throws Exception { + void given_orgFolder_when_noNavigatorsDefined_then_noNavigatorBrandingPresent() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); assertThat(prj.getAction(MockSCMLink.class), nullValue()); @@ -196,7 +203,7 @@ public void given_orgFolder_when_noNavigatorsDefined_then_noNavigatorBrandingPre } @Test - public void given_multibranch_when_sourceHasNonSafeNames_then_branchDisplayNameNotMangled() throws Exception { + void given_multibranch_when_sourceHasNonSafeNames_then_branchDisplayNameNotMangled() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "."); @@ -258,7 +265,7 @@ public void given_multibranch_when_sourceHasNonSafeNames_then_branchDisplayNameN } @Test - public void given_multibranch_when_sourceHasI18nNames_then_branchDisplayNameNotMangled() throws Exception { + void given_multibranch_when_sourceHasI18nNames_then_branchDisplayNameNotMangled() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo","特征/新"); @@ -347,7 +354,7 @@ public void given_multibranch_when_sourceHasI18nNames_then_branchDisplayNameNotM } @Test - public void given_orgFolder_when_navigatorDefined_then_navigatorBrandingPresentAfterIndexing() + void given_orgFolder_when_navigatorDefined_then_navigatorBrandingPresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -362,7 +369,7 @@ public void given_orgFolder_when_navigatorDefined_then_navigatorBrandingPresentA } @Test - public void given_orgFolderWithI18nRepos_when_indexing_then_repoNamesEncoded() + void given_orgFolderWithI18nRepos_when_indexing_then_repoNamesEncoded() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("England"); @@ -437,7 +444,7 @@ public void given_orgFolderWithI18nRepos_when_indexing_then_repoNamesEncoded() } @Test - public void given_orgFolderWithNonSafeRepos_when_indexing_then_repoNamesEncoded() + void given_orgFolderWithNonSafeRepos_when_indexing_then_repoNamesEncoded() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("a?"); @@ -482,7 +489,7 @@ public void given_orgFolderWithNonSafeRepos_when_indexing_then_repoNamesEncoded( } @Test - public void given_orgFolder_when_navigatorDefined_then_sourceBrandingPresentAfterIndexing() + void given_orgFolder_when_navigatorDefined_then_sourceBrandingPresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -497,7 +504,7 @@ public void given_orgFolder_when_navigatorDefined_then_sourceBrandingPresentAfte } @Test - public void given_orgFolder_when_navigatorDefined_then_branchBrandingPresentAfterIndexing() + void given_orgFolder_when_navigatorDefined_then_branchBrandingPresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -513,7 +520,7 @@ public void given_orgFolder_when_navigatorDefined_then_branchBrandingPresentAfte } @Test - public void given_orgFolder_when_navigatorDefined_then_revisionBrandingPresentAfterIndexing() + void given_orgFolder_when_navigatorDefined_then_revisionBrandingPresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -529,7 +536,7 @@ public void given_orgFolder_when_navigatorDefined_then_revisionBrandingPresentAf } @Test - public void given_multibranch_when_decoratedSourceDefined_then_descriptionPresentAfterIndexing() + void given_multibranch_when_decoratedSourceDefined_then_descriptionPresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -545,7 +552,7 @@ public void given_multibranch_when_decoratedSourceDefined_then_descriptionPresen } @Test - public void given_multibranch_when_decoratedSourceDefined_then_displayNamePresentAfterIndexing() + void given_multibranch_when_decoratedSourceDefined_then_displayNamePresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -564,7 +571,7 @@ public void given_multibranch_when_decoratedSourceDefined_then_displayNamePresen } @Test - public void given_orgFolder_when_decoratedSourceDefined_then_descriptionLinkPresentAfterIndexing() + void given_orgFolder_when_decoratedSourceDefined_then_descriptionLinkPresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -588,7 +595,7 @@ public void given_orgFolder_when_decoratedSourceDefined_then_descriptionLinkPres } @Test - public void given_multibranch_when_decoratedSourceDefined_then_folderIconPresentAfterIndexing() + void given_multibranch_when_decoratedSourceDefined_then_folderIconPresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -604,7 +611,7 @@ public void given_multibranch_when_decoratedSourceDefined_then_folderIconPresent } @Test - public void given_orgFolder_when_decoratedOrganizationDefined_then_folderIconPresentAfterIndexing() + void given_orgFolder_when_decoratedOrganizationDefined_then_folderIconPresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -620,7 +627,7 @@ public void given_orgFolder_when_decoratedOrganizationDefined_then_folderIconPre } @Test - public void given_orgFolder_when_decoratedOrganizationDefined_then_displayNamePresentAfterIndexing() + void given_orgFolder_when_decoratedOrganizationDefined_then_displayNamePresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -636,7 +643,7 @@ public void given_orgFolder_when_decoratedOrganizationDefined_then_displayNamePr } @Test - public void given_orgFolder_when_decoratedOrganizationDefined_then_descriptionLinkPresentAfterIndexing() + void given_orgFolder_when_decoratedOrganizationDefined_then_descriptionLinkPresentAfterIndexing() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); diff --git a/src/test/java/integration/CategorizationTest.java b/src/test/java/integration/CategorizationTest.java index eb4a8f88..44a20dc9 100644 --- a/src/test/java/integration/CategorizationTest.java +++ b/src/test/java/integration/CategorizationTest.java @@ -39,10 +39,11 @@ import jenkins.scm.impl.mock.MockSCMDiscoverChangeRequests; import jenkins.scm.impl.mock.MockSCMDiscoverTags; import jenkins.scm.impl.mock.MockSCMSource; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; @@ -54,24 +55,29 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -public class CategorizationTest { +@WithJenkins +class CategorizationTest { /** * All tests in this class only create items and do not affect other global configuration, thus we trade test * execution time for the restriction on only touching items. */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; - @Before - public void cleanOutAllItems() throws Exception { + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } + + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void given_multibranch_when_noSourcesDefined_then_welcomeViewPresent() throws Exception { + void given_multibranch_when_noSourcesDefined_then_welcomeViewPresent() throws Exception { try (MockSCMController c = MockSCMController.create()) { BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); prj.setCriteria(null); @@ -82,7 +88,7 @@ public void given_multibranch_when_noSourcesDefined_then_welcomeViewPresent() th } @Test - public void given_multibranch_when_atLeastOneSourceDefinedButNoItems_then_welcomeViewPresent() + void given_multibranch_when_atLeastOneSourceDefinedButNoItems_then_welcomeViewPresent() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -96,7 +102,7 @@ public void given_multibranch_when_atLeastOneSourceDefinedButNoItems_then_welcom } @Test - public void given_multibranch_when_onlyUncategorizedCategory_then_onlyUncategorizedViewPresent() throws Exception { + void given_multibranch_when_onlyUncategorizedCategory_then_onlyUncategorizedViewPresent() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createTag("foo", "master", "master-1.0"); @@ -122,7 +128,7 @@ public void given_multibranch_when_onlyUncategorizedCategory_then_onlyUncategori } @Test - public void given_multibranch_when_changeRequestsWanted_then_onlyUncategorizedAndChangeRequetsViewsPresent() + void given_multibranch_when_changeRequestsWanted_then_onlyUncategorizedAndChangeRequetsViewsPresent() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -156,7 +162,7 @@ public void given_multibranch_when_changeRequestsWanted_then_onlyUncategorizedAn } @Test - public void given_multibranch_when_tagsWanted_then_onlyUncategorizedAndTagsViewsPresent() + void given_multibranch_when_tagsWanted_then_onlyUncategorizedAndTagsViewsPresent() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -190,7 +196,7 @@ public void given_multibranch_when_tagsWanted_then_onlyUncategorizedAndTagsViews } @Test - public void given_multibranch_when_noBranchesWanted_then_uncategorizedViewPresentButEmpty() + void given_multibranch_when_noBranchesWanted_then_uncategorizedViewPresentButEmpty() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -229,7 +235,7 @@ public void given_multibranch_when_noBranchesWanted_then_uncategorizedViewPresen } @Test - public void given_multibranch_when_wantsEverything_then_hasEverything() + void given_multibranch_when_wantsEverything_then_hasEverything() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); diff --git a/src/test/java/integration/EnvironmentTest.java b/src/test/java/integration/EnvironmentTest.java index a8b536b8..ef9162cf 100644 --- a/src/test/java/integration/EnvironmentTest.java +++ b/src/test/java/integration/EnvironmentTest.java @@ -38,10 +38,11 @@ import jenkins.scm.impl.mock.MockSCMDiscoverChangeRequests; import jenkins.scm.impl.mock.MockSCMDiscoverTags; import jenkins.scm.impl.mock.MockSCMSource; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; @@ -49,24 +50,29 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.nullValue; -public class EnvironmentTest { +@WithJenkins +class EnvironmentTest { /** * All tests in this class only create items and do not affect other global configuration, thus we trade test * execution time for the restriction on only touching items. */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; - @Before - public void cleanOutAllItems() throws Exception { + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } + + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void given_multibranch_when_buildingABranch_then_environmentContainsBranchName() throws Exception { + void given_multibranch_when_buildingABranch_then_environmentContainsBranchName() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -83,7 +89,7 @@ public void given_multibranch_when_buildingABranch_then_environmentContainsBranc } @Test - public void given_multibranch_when_buildingAChangeRequest_then_environmentContainsBranchName() throws Exception { + void given_multibranch_when_buildingAChangeRequest_then_environmentContainsBranchName() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); Integer crNum = c.openChangeRequest("foo", "master"); @@ -102,7 +108,7 @@ public void given_multibranch_when_buildingAChangeRequest_then_environmentContai } @Test - public void given_multibranch_when_buildingAChangeRequest_then_environmentContainsChangeDetails() throws Exception { + void given_multibranch_when_buildingAChangeRequest_then_environmentContainsChangeDetails() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); Integer crNum = c.openChangeRequest("foo", "master"); @@ -121,7 +127,7 @@ public void given_multibranch_when_buildingAChangeRequest_then_environmentContai containsString("CHANGE_URL=http://changes.example.com/" + crNum), anyOf( containsString("CHANGE_TITLE='Change request #" + crNum + "'"), // unix - containsString("CHANGE_TITLE=Change request #" + crNum + "") // win + containsString("CHANGE_TITLE=Change request #" + crNum) // win ), containsString("CHANGE_AUTHOR=bob"), anyOf( @@ -135,7 +141,7 @@ public void given_multibranch_when_buildingAChangeRequest_then_environmentContai } @Test - public void given_multibranch_when_buildingATag_then_environmentContainsTagName() throws Exception { + void given_multibranch_when_buildingATag_then_environmentContainsTagName() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createTag("foo", "master", "release"); diff --git a/src/test/java/integration/EventsTest.java b/src/test/java/integration/EventsTest.java index 26943f65..13a20505 100644 --- a/src/test/java/integration/EventsTest.java +++ b/src/test/java/integration/EventsTest.java @@ -43,21 +43,6 @@ import integration.harness.BasicMultiBranchProject; import integration.harness.BasicMultiBranchProjectFactory; import integration.harness.BasicSCMSourceCriteria; -import java.io.IOException; -import java.lang.management.ThreadInfo; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; import jenkins.branch.Branch; import jenkins.branch.BranchBuildStrategy; import jenkins.branch.BranchBuildStrategyDescriptor; @@ -93,12 +78,30 @@ import jenkins.scm.impl.mock.MockSCMSourceSaveListener; import jenkins.scm.impl.trait.WildcardSCMSourceFilterTrait; import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +import java.io.IOException; +import java.lang.management.ThreadInfo; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; @@ -113,13 +116,14 @@ 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.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assume.assumeThat; -import org.junit.Ignore; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; -public class EventsTest { +@WithJenkins +class EventsTest { /** * A branch name that contains a slash @@ -130,7 +134,7 @@ public class EventsTest { */ private static final String SLASHY_JOB_NAME = "feature%2Fux-1"; /** - * A branch name with unicode characters that have a two canonical forms (Korean for New Features). + * A branch name with unicode characters that have two canonical forms (Korean for New Features). * There are two normalize forms: {@code "\uc0c8\ub85c\uc6b4 \ud2b9\uc9d5"} and * {@code "\u1109\u1162\u1105\u1169\u110b\u116e\u11ab \u1110\u1173\u11a8\u110c\u1175\u11bc"} */ @@ -139,18 +143,21 @@ public class EventsTest { * The encoded name of {@link #I18N_BRANCH_NAME}, see {@link NameEncoder#encode(String)} */ private static final String I18N_JOB_NAME = "\uc0c8\ub85c\uc6b4 \ud2b9\uc9d5"; + /** * All tests in this class only create items and do not affect other global configuration, thus we trade test * execution time for the restriction on only touching items. */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); - static { + private static JenkinsRule r; + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; r.timeout = 600; } - @Before - public void cleanOutAllItems() throws Exception { + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } @@ -169,7 +176,7 @@ public void cleanOutAllItems() throws Exception { } @Test - public void given_multibranch_when_inspectingProjectFactory_then_ProjectTypeCorrectlyInferred() throws Exception { + void given_multibranch_when_inspectingProjectFactory_then_ProjectTypeCorrectlyInferred() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -178,7 +185,7 @@ public void given_multibranch_when_inspectingProjectFactory_then_ProjectTypeCorr } @Test - public void given_multibranch_when_inspectingProject_then_ProjectTypeCorrectlyInferred() throws Exception { + void given_multibranch_when_inspectingProject_then_ProjectTypeCorrectlyInferred() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -187,7 +194,7 @@ public void given_multibranch_when_inspectingProject_then_ProjectTypeCorrectlyIn } @Test - public void given_multibranch_when_noSources_then_noBranchProjects() throws Exception { + void given_multibranch_when_noSources_then_noBranchProjects() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -198,7 +205,7 @@ public void given_multibranch_when_noSources_then_noBranchProjects() throws Exce } @Test - public void given_multibranch_when_addingCriteriaWithoutSources_then_noBranchProjects() throws Exception { + void given_multibranch_when_addingCriteriaWithoutSources_then_noBranchProjects() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -215,7 +222,7 @@ public void given_multibranch_when_addingCriteriaWithoutSources_then_noBranchPro } @Test - public void given_multibranch_when_addingSources_then_noIndexingIsTriggered() throws Exception { + void given_multibranch_when_addingSources_then_noIndexingIsTriggered() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -228,7 +235,7 @@ public void given_multibranch_when_addingSources_then_noIndexingIsTriggered() th } @Test - public void given_multibranchWithSources_when_indexing_then_branchesAreFoundAndBuilt() throws Exception { + void given_multibranchWithSources_when_indexing_then_branchesAreFoundAndBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -248,7 +255,7 @@ public void given_multibranchWithSources_when_indexing_then_branchesAreFoundAndB @Test @Issue("JENKINS-41255") - public void given_multibranchWithSource_when_replacingSource_then_noBuildStorm() throws Exception { + void given_multibranchWithSource_when_replacingSource_then_noBuildStorm() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -277,7 +284,7 @@ public void given_multibranchWithSource_when_replacingSource_then_noBuildStorm() @Test @Issue("JENKINS-41255") - public void given_multibranchWithSources_when_replacingSources_then_noBuildStorm() throws Exception { + void given_multibranchWithSources_when_replacingSources_then_noBuildStorm() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); Integer id = c.openChangeRequest("foo", "master"); @@ -334,7 +341,7 @@ public void given_multibranchWithSources_when_replacingSources_then_noBuildStorm } @Test - public void given_multibranchWithSourcesWantingBranchesOnly_when_indexing_then_onlyBranchesAreFoundAndBuilt() + void given_multibranchWithSourcesWantingBranchesOnly_when_indexing_then_onlyBranchesAreFoundAndBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -362,7 +369,7 @@ public void given_multibranchWithSourcesWantingBranchesOnly_when_indexing_then_o } @Test - public void given_multibranchWithSourcesWantingTagsOnly_when_indexing_then_onlyTagsAreFoundAndBuilt() + void given_multibranchWithSourcesWantingTagsOnly_when_indexing_then_onlyTagsAreFoundAndBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -389,8 +396,7 @@ public void given_multibranchWithSourcesWantingTagsOnly_when_indexing_then_onlyT } @Test - public void - given_multibranchWithSourcesWantingChangeRequestsOnly_when_indexing_then_onlyChangeRequestsAreFoundAndBuilt() + void given_multibranchWithSourcesWantingChangeRequestsOnly_when_indexing_then_onlyChangeRequestsAreFoundAndBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -418,8 +424,7 @@ public void given_multibranchWithSourcesWantingTagsOnly_when_indexing_then_onlyT } @Test - public void - given_multibranchWithUntrustedChangeRequestBuildStrategy_when_indexing_then_onlyTrustedChangeRequestsAreFoundAndBuilt() + void given_multibranchWithUntrustedChangeRequestBuildStrategy_when_indexing_then_onlyTrustedChangeRequestsAreFoundAndBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo", MockRepositoryFlags.TRUST_AWARE); @@ -452,7 +457,7 @@ public void given_multibranchWithSourcesWantingTagsOnly_when_indexing_then_onlyT } @Test - public void given_multibranchWithMergeableChangeRequests_when_indexing_then_mergableChangeRequestsBuilt() + void given_multibranchWithMergeableChangeRequests_when_indexing_then_mergableChangeRequestsBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -492,7 +497,7 @@ public void given_multibranchWithMergeableChangeRequests_when_indexing_then_merg } @Test - public void given_multibranchWithMergeableChangeRequests_when_reindexing_then_mergableChangeRequestsRebuilt() + void given_multibranchWithMergeableChangeRequests_when_reindexing_then_mergableChangeRequestsRebuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -505,25 +510,23 @@ public void given_multibranchWithMergeableChangeRequests_when_reindexing_then_me prj.getSourcesList().add(new BranchSource(source)); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); - assumeThat("We now have projects", - prj.getItems(), not(Matchers.empty())); + assumeFalse(prj.getItems().isEmpty(), "We now have projects"); FreeStyleProject master = prj.getItem("master"); - assumeThat("We have no master branch", master, nullValue()); + assumeTrue(master == null, "We have no master branch"); FreeStyleProject tag = prj.getItem("master-1.0"); - assumeThat("We have no master-1.0 tag", tag, nullValue()); + assumeTrue(tag == null, "We have no master-1.0 tag"); FreeStyleProject cr = prj.getItem("CR-" + crNum); - assumeThat("We have no plan CR", cr, nullValue()); + assumeTrue(cr == null, "We have no plan CR"); FreeStyleProject crMerge = prj.getItem("CR-" + crNum+"-merge"); - assumeThat("We now have the merge change request", crMerge, notNullValue()); + assumeTrue(crMerge != null, "We now have the merge change request"); FreeStyleProject crHead = prj.getItem("CR-" + crNum+"-head"); - assumeThat("We now have the head change request", crHead, notNullValue()); - assumeThat("We have change requests but no tags or branches", - prj.getItems(), containsInAnyOrder(crMerge, crHead)); + assumeTrue(crHead != null, "We now have the head change request"); + assumeTrue(prj.getItems().containsAll(List.of(crMerge, crHead)), "We have change requests but no tags or branches"); r.waitUntilNoActivity(); - assumeThat("The merge change request was built", crMerge.getLastBuild(), notNullValue()); - assumeThat("The merge change request was built", crMerge.getLastBuild().getNumber(), is(1)); - assumeThat("The head change request was built", crHead.getLastBuild(), notNullValue()); - assumeThat("The head change request was built", crHead.getLastBuild().getNumber(), is(1)); + assumeTrue(crMerge.getLastBuild() != null, "The merge change request was built"); + assumeTrue(crMerge.getLastBuild().getNumber() == 1, "The merge change request was built"); + assumeTrue(crHead.getLastBuild() != null, "The head change request was built"); + assumeTrue(crHead.getLastBuild().getNumber() == 1, "The head change request was built"); c.addFile("foo", "master", "change the target", "file.txt", new byte[]{0}); prj.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); @@ -546,7 +549,7 @@ public void given_multibranchWithMergeableChangeRequests_when_reindexing_then_me } @Test - public void given_multibranchWithSourcesWantingBranchesAndTags_when_indexing_then_branchesAndTagsAreFoundAndBuilt() + void given_multibranchWithSourcesWantingBranchesAndTags_when_indexing_then_branchesAndTagsAreFoundAndBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -575,7 +578,7 @@ public void given_multibranchWithSourcesWantingBranchesAndTags_when_indexing_the } @Test - public void given_indexedMultibranch_when_indexingFails_then_previouslyIndexedBranchesAreNotDeleted() + void given_indexedMultibranch_when_indexingFails_then_previouslyIndexedBranchesAreNotDeleted() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -611,7 +614,7 @@ public void check(@CheckForNull String repository, @CheckForNull String branchOr } @Test - public void given_multibranchWithSourcesWantingEverything_when_indexing_then_everythingIsFoundAndBuilt() + void given_multibranchWithSourcesWantingEverything_when_indexing_then_everythingIsFoundAndBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { @@ -660,7 +663,7 @@ public static class DescriptorImpl extends BranchBuildStrategyDescriptor { } @Test - public void given_multibranchWithSourcesWantingEverythingAndBuildingTags_when_indexing_then_everythingIsFoundAndBuiltEvenTags() + void given_multibranchWithSourcesWantingEverythingAndBuildingTags_when_indexing_then_everythingIsFoundAndBuiltEvenTags() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -734,7 +737,7 @@ public static class DescriptorImpl extends BranchBuildStrategyDescriptor { } @Test - public void given_multibranchWithSourcesWantingEverythingAndBuildingCRs_when_indexing_then_everythingIsFoundAndOnlyCRsBuilt() + void given_multibranchWithSourcesWantingEverythingAndBuildingCRs_when_indexing_then_everythingIsFoundAndOnlyCRsBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -768,7 +771,7 @@ public void given_multibranchWithSourcesWantingEverythingAndBuildingCRs_when_ind @Issue("JENKINS-54052") @Test - public void given_multibranchWithSources_when_zero_quiet_period_then_two_runs() throws Exception { + void given_multibranchWithSources_when_zero_quiet_period_then_two_runs() throws Exception { int savedQuietPeriod = BasicBranchProjectFactory.quietPeriodSeconds; try (MockSCMController c = MockSCMController.create()) { BasicBranchProjectFactory.quietPeriodSeconds = 0; @@ -781,7 +784,7 @@ public void given_multibranchWithSources_when_zero_quiet_period_then_two_runs() @Issue("JENKINS-54052") @Test - public void given_multibranchWithSources_when_system_quiet_period_then_one_run() throws Exception { + void given_multibranchWithSources_when_system_quiet_period_then_one_run() throws Exception { int savedQuietPeriod = BasicBranchProjectFactory.quietPeriodSeconds; try (MockSCMController c = MockSCMController.create()) { BasicBranchProjectFactory.quietPeriodSeconds = -1; @@ -816,7 +819,7 @@ private FreeStyleProject runMultipleScansOnChangedMaster(MockSCMController c) th } @Test - public void given_multibranchWithSources_when_matchingEvent_then_branchesAreFoundAndBuilt() throws Exception { + void given_multibranchWithSources_when_matchingEvent_then_branchesAreFoundAndBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -834,7 +837,7 @@ public void given_multibranchWithSources_when_matchingEvent_then_branchesAreFoun } @Test - public void given_multibranchWithSlashySources_when_matchingEvent_then_branchesAreFoundAndBuilt() throws Exception { + void given_multibranchWithSlashySources_when_matchingEvent_then_branchesAreFoundAndBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", SLASHY_BRANCH_NAME); @@ -856,7 +859,7 @@ public void given_multibranchWithSlashySources_when_matchingEvent_then_branchesA } @Test - public void given_multibranchWithI18nSources_when_matchingEvent_then_branchesAreFoundAndBuilt() throws Exception { + void given_multibranchWithI18nSources_when_matchingEvent_then_branchesAreFoundAndBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", I18N_BRANCH_NAME); @@ -878,7 +881,7 @@ public void given_multibranchWithI18nSources_when_matchingEvent_then_branchesAre } @Test - public void given_multibranchWithSources_when_matchingEventWithMatchingRevision_then_branchesAreBuilt() throws Exception { + void given_multibranchWithSources_when_matchingEventWithMatchingRevision_then_branchesAreBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -897,7 +900,7 @@ public void given_multibranchWithSources_when_matchingEventWithMatchingRevision_ } @Test - public void given_multibranchWithSlashySources_when_matchingEventWithMatchingRevision_then_branchesAreBuilt() throws Exception { + void given_multibranchWithSlashySources_when_matchingEventWithMatchingRevision_then_branchesAreBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", SLASHY_BRANCH_NAME); @@ -920,7 +923,7 @@ public void given_multibranchWithSlashySources_when_matchingEventWithMatchingRev } @Test - public void given_multibranchWithI18nSources_when_matchingEventWithMatchingRevision_then_branchesAreBuilt() throws Exception { + void given_multibranchWithI18nSources_when_matchingEventWithMatchingRevision_then_branchesAreBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", I18N_BRANCH_NAME); @@ -943,7 +946,7 @@ public void given_multibranchWithI18nSources_when_matchingEventWithMatchingRevis } @Test - public void given_multibranchWithSources_when_matchingEventWithMatchingPreviousRevision_then_branchesAreNotBuilt() throws Exception { + void given_multibranchWithSources_when_matchingEventWithMatchingPreviousRevision_then_branchesAreNotBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -962,7 +965,7 @@ public void given_multibranchWithSources_when_matchingEventWithMatchingPreviousR } @Test - public void given_multibranchWithSlashySources_when_matchingEventWithMatchingPreviousRevision_then_branchesAreNotBuilt() throws Exception { + void given_multibranchWithSlashySources_when_matchingEventWithMatchingPreviousRevision_then_branchesAreNotBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", SLASHY_BRANCH_NAME); @@ -983,7 +986,7 @@ public void given_multibranchWithSlashySources_when_matchingEventWithMatchingPre } @Test - public void given_multibranchWithI18nSources_when_matchingEventWithMatchingPreviousRevision_then_branchesAreNotBuilt() throws Exception { + void given_multibranchWithI18nSources_when_matchingEventWithMatchingPreviousRevision_then_branchesAreNotBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", I18N_BRANCH_NAME); @@ -1004,7 +1007,7 @@ public void given_multibranchWithI18nSources_when_matchingEventWithMatchingPrevi } @Test - public void given_multibranchWithSources_when_createEventForExistingBranch_then_eventIgnored() throws Exception { + void given_multibranchWithSources_when_createEventForExistingBranch_then_eventIgnored() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -1029,7 +1032,7 @@ public void given_multibranchWithSources_when_createEventForExistingBranch_then_ @Test @Issue("JENKINS-42511") - public void given_multibranchWithSources_when_createEventWhileIndexing_then_onlyOneBuildCreated() throws Exception { + void given_multibranchWithSources_when_createEventWhileIndexing_then_onlyOneBuildCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -1096,8 +1099,7 @@ public static class DescriptorImpl extends BranchBuildStrategyDescriptor { @Test @Issue("JENKINS-47308") - public void - given_multibranchWithRevisionSpecificStrategy_when_indexing_then_everythingIsFoundButMagicRevisionOnlyBuilt() + void given_multibranchWithRevisionSpecificStrategy_when_indexing_then_everythingIsFoundButMagicRevisionOnlyBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -1149,8 +1151,7 @@ public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head @NonNull SCMRevision currRevision, SCMRevision lastBuiltRevision, SCMRevision lastSeenRevision, @NonNull TaskListener listener) { - if (currRevision instanceof ChangeRequestSCMRevision) { - ChangeRequestSCMRevision currCR = (ChangeRequestSCMRevision) currRevision; + if (currRevision instanceof ChangeRequestSCMRevision currCR) { if (lastBuiltRevision instanceof ChangeRequestSCMRevision) { // if we have a previous, only build if the change is affecting the head not the target return !currCR.equivalent((ChangeRequestSCMRevision) lastBuiltRevision); @@ -1171,8 +1172,7 @@ public static class DescriptorImpl extends BranchBuildStrategyDescriptor { @Test @Issue("JENKINS-48535") - public void - given_multibranchWithIgnoreTargetChangesStrategy_when_reindexing_then_onlyCRsWithHeadChangesRebuilt() + void given_multibranchWithIgnoreTargetChangesStrategy_when_reindexing_then_onlyCRsWithHeadChangesRebuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -1310,7 +1310,7 @@ public boolean isSomethingHappeningIgnoringThreadDeath() { } @Test - public void given_multibranchWithSources_when_nonMatchingEvent_then_branchesAreNotFoundAndBuilt() throws Exception { + void given_multibranchWithSources_when_nonMatchingEvent_then_branchesAreNotFoundAndBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -1325,7 +1325,7 @@ public void given_multibranchWithSources_when_nonMatchingEvent_then_branchesAreN } @Test - public void given_multibranchWithSources_when_branchChangeEvent_then_branchFromEventIsRebuilt() throws Exception { + void given_multibranchWithSources_when_branchChangeEvent_then_branchFromEventIsRebuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "feature"); @@ -1365,7 +1365,7 @@ public void given_multibranchWithSources_when_branchChangeEvent_then_branchFromE } @Test - public void given_multibranchWithSources_when_lateBranchChangeEvent_then_branchIsNotRebuilt() throws Exception { + void given_multibranchWithSources_when_lateBranchChangeEvent_then_branchIsNotRebuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "feature"); @@ -1406,7 +1406,7 @@ public void given_multibranchWithSources_when_lateBranchChangeEvent_then_branchI } @Test - public void given_multibranchWithSourcesAndTwoBranches_when_indexing_then_deadBranchIsDeleted() throws Exception { + void given_multibranchWithSourcesAndTwoBranches_when_indexing_then_deadBranchIsDeleted() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "feature"); @@ -1433,8 +1433,7 @@ public void given_multibranchWithSourcesAndTwoBranches_when_indexing_then_deadBr } @Test - public void - given_multibranchWithSourcesAndSomeRetentionOfDeadBranches_when_indexing_then_oldestDeadBranchIsDeleted() + void given_multibranchWithSourcesAndSomeRetentionOfDeadBranches_when_indexing_then_oldestDeadBranchIsDeleted() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -1499,7 +1498,7 @@ public void given_multibranchWithSourcesAndTwoBranches_when_indexing_then_deadBr } @Test - public void given_multibranchWithSourcesAndTwoBranches_when_eventForBranchRemoval_then_branchIsDisabled() + void given_multibranchWithSourcesAndTwoBranches_when_eventForBranchRemoval_then_branchIsDisabled() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -1528,7 +1527,7 @@ public void given_multibranchWithSourcesAndTwoBranches_when_eventForBranchRemova } @Test - public void given_multibranchWithSourcesAndOneDeadBranches_when_indexing_then_branchIsDeleted() throws Exception { + void given_multibranchWithSourcesAndOneDeadBranches_when_indexing_then_branchIsDeleted() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "feature"); @@ -1558,7 +1557,7 @@ public void given_multibranchWithSourcesAndOneDeadBranches_when_indexing_then_br } @Test - public void given_multibranchWithSourcesAndCriteria_when_indexingAndNoMatchingBranches_then_noProjectsCreated() + void given_multibranchWithSourcesAndCriteria_when_indexingAndNoMatchingBranches_then_noProjectsCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -1574,8 +1573,7 @@ public void given_multibranchWithSourcesAndCriteria_when_indexingAndNoMatchingBr } @Test - public void - given_multibranchWithSourcesCriteriaAndNoMatchingBranches_when_eventDoesntAddMatch_then_noProjectsCreated() + void given_multibranchWithSourcesCriteriaAndNoMatchingBranches_when_eventDoesntAddMatch_then_noProjectsCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -1596,7 +1594,7 @@ public void given_multibranchWithSourcesAndCriteria_when_indexingAndNoMatchingBr } @Test - public void given_multibranchWithSourcesCriteriaAndNoMatchingBranches_when_eventAddsMatch_then_projectsCreated() + void given_multibranchWithSourcesCriteriaAndNoMatchingBranches_when_eventAddsMatch_then_projectsCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -1617,7 +1615,7 @@ public void given_multibranchWithSourcesCriteriaAndNoMatchingBranches_when_event } @Test - public void given_multibranchWithSourcesCriteriaAndMatchingBranches_when_eventAddsMatch_then_projectsCreated() + void given_multibranchWithSourcesCriteriaAndMatchingBranches_when_eventAddsMatch_then_projectsCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -1653,7 +1651,7 @@ public void given_multibranchWithSourcesCriteriaAndMatchingBranches_when_eventAd } @Test - public void given_multibranch_when_eventStorm_then_projectsCreated() + void given_multibranch_when_eventStorm_then_projectsCreated() throws Exception { List branchNames = Arrays.asList( // top 20 names for boys and girls 2016 in case you are wondering "Sophia", "Jackson", "Emma", "Aiden", "Olivia", "Lucas", "Ava", "Liam", "Mia", "Noah", "Isabella", @@ -1696,7 +1694,7 @@ public void given_multibranch_when_eventStorm_then_projectsCreated() } @Test - public void given_multibranch_when_eventStorm_then_eventsConcurrent() + void given_multibranch_when_eventStorm_then_eventsConcurrent() throws Exception { List branchNames = Arrays.asList( // top 20 names for boys and girls 2016 in case you are wondering "Sophia", "Jackson", "Emma", "Aiden", "Olivia", "Lucas", "Ava", "Liam", "Mia", "Noah", "Isabella", @@ -1756,9 +1754,9 @@ public void apply() throws InterruptedException { assertThat("More than one event processed concurrently", maxInflight.get(), greaterThan(1)); } - @Ignore("TODO passes locally, but on CI often (and on Windows, always?) fails; seems to be a ClosedByInterruptException") + @Disabled("TODO passes locally, but on CI often (and on Windows, always?) fails; seems to be a ClosedByInterruptException") @Test - public void given_multibranch_when_oneEventBlocking_then_otherEventsProcessed() throws Exception { + void given_multibranch_when_oneEventBlocking_then_otherEventsProcessed() throws Exception { List branchNames = Arrays.asList( // top 20 names for boys and girls 2016 in case you are wondering "Sophia", "Jackson", "Emma", "Aiden", "Olivia", "Lucas", "Ava", "Liam", "Mia", "Noah", "Isabella", "Ethan", "Riley", "Mason", "Aria", "Caden", "Zoe", "Oliver", "Charlotte", "Elijah", "Lily", "Grayson", @@ -1839,7 +1837,7 @@ public void check(@CheckForNull String repository, @CheckForNull String branchOr } @Test - public void given_multibranchWithSourcesCriteriaAndMatchingBranches_when_eventRemoveMatch_then_projectsDisables() + void given_multibranchWithSourcesCriteriaAndMatchingBranches_when_eventRemoveMatch_then_projectsDisables() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -1871,7 +1869,7 @@ public void given_multibranchWithSourcesCriteriaAndMatchingBranches_when_eventRe } @Test - public void given_orgFolder_when_noRepos_then_scanCreatesNoProjects() throws Exception { + void given_orgFolder_when_noRepos_then_scanCreatesNoProjects() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -1890,7 +1888,7 @@ public void given_orgFolder_when_noRepos_then_scanCreatesNoProjects() throws Exc } @Test - public void given_orgFolder_when_noMatchingRepos_then_scanCreatesNoProjects() throws Exception { + void given_orgFolder_when_noMatchingRepos_then_scanCreatesNoProjects() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -1909,7 +1907,7 @@ public void given_orgFolder_when_noMatchingRepos_then_scanCreatesNoProjects() th } @Test - public void given_orgFolder_when_someReposMatch_then_scanCreatesMatchingProjects() throws Exception { + void given_orgFolder_when_someReposMatch_then_scanCreatesMatchingProjects() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -1935,7 +1933,7 @@ public void given_orgFolder_when_someReposMatch_then_scanCreatesMatchingProjects @Issue("JENKINS-48536") @Test - public void given_orgFolder_when_someReposMatch_then_scanFiresSCMSourceAfterSave() throws Exception { + void given_orgFolder_when_someReposMatch_then_scanFiresSCMSourceAfterSave() throws Exception { final ConcurrentMap saved = new ConcurrentHashMap<>(); try (MockSCMController c = MockSCMController.create().withSaveListener(new MockSCMSourceSaveListener() { @Override @@ -1968,7 +1966,7 @@ public void afterSave(MockSCMSource source) { } @Test - public void given_orgFolderWithFilteringTrait_when_someReposMatch_then_scanCreatesMatchingProjects() throws Exception { + void given_orgFolderWithFilteringTrait_when_someReposMatch_then_scanCreatesMatchingProjects() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches(), @@ -1998,7 +1996,7 @@ public void given_orgFolderWithFilteringTrait_when_someReposMatch_then_scanCreat @Test @Issue("JENKINS-42000") - public void given_orgFolder_when_navigatorIoErrorScanning_then_scanRecordedAsFailure() throws Exception { + void given_orgFolder_when_navigatorIoErrorScanning_then_scanRecordedAsFailure() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2052,7 +2050,7 @@ public void check(@CheckForNull String repository, @CheckForNull String branchOr @Test @Issue("JENKINS-42000") - public void given_orgFolder_when_sourceIoErrorScanning_then_scanRecordedAsFailure() throws Exception { + void given_orgFolder_when_sourceIoErrorScanning_then_scanRecordedAsFailure() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2104,7 +2102,7 @@ public void check(@CheckForNull String repository, @CheckForNull String branchOr } @Test - public void given_orgFolder_when_someReposMatch_then_eventCreatesMatchingProject() throws Exception { + void given_orgFolder_when_someReposMatch_then_eventCreatesMatchingProject() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2126,7 +2124,7 @@ public void given_orgFolder_when_someReposMatch_then_eventCreatesMatchingProject } @Test - public void given_orgFolder_when_someSlashyReposMatch_then_eventCreatesMatchingProject() throws Exception { + void given_orgFolder_when_someSlashyReposMatch_then_eventCreatesMatchingProject() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2152,7 +2150,7 @@ public void given_orgFolder_when_someSlashyReposMatch_then_eventCreatesMatchingP } @Test - public void given_orgFolder_when_someI18nReposMatch_then_eventCreatesMatchingProject() throws Exception { + void given_orgFolder_when_someI18nReposMatch_then_eventCreatesMatchingProject() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2178,7 +2176,7 @@ public void given_orgFolder_when_someI18nReposMatch_then_eventCreatesMatchingPro } @Test - public void given_orgFolder_when_someReposMatch_then_eventsAreValidated() throws Exception { + void given_orgFolder_when_someReposMatch_then_eventsAreValidated() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2200,7 +2198,7 @@ public void given_orgFolder_when_someReposMatch_then_eventsAreValidated() throws } @Test - public void given_orgFolder_when_eventUpdatesABranchToAMatch_then_projectIsCreated() throws Exception { + void given_orgFolder_when_eventUpdatesABranchToAMatch_then_projectIsCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2222,7 +2220,7 @@ public void given_orgFolder_when_eventUpdatesABranchToAMatch_then_projectIsCreat @Test @Issue("JENKINS-48214") - public void given_orgFolderWithOnlyDeactivatedChildren_when_eventUpdatesABranchToRestoreAMatch_then_projectIsRestored() throws Exception { + void given_orgFolderWithOnlyDeactivatedChildren_when_eventUpdatesABranchToRestoreAMatch_then_projectIsRestored() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2269,7 +2267,7 @@ public void given_orgFolderWithOnlyDeactivatedChildren_when_eventUpdatesABranchT } @Test - public void given_orgFolder_when_eventCreatesABranchWithAMatch_then_projectIsCreated() throws Exception { + void given_orgFolder_when_eventCreatesABranchWithAMatch_then_projectIsCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2292,7 +2290,7 @@ public void given_orgFolder_when_eventCreatesABranchWithAMatch_then_projectIsCre } @Test - public void given_orgFolder_when_eventCreatesASlashyBranchWithAMatch_then_projectIsCreated() throws Exception { + void given_orgFolder_when_eventCreatesASlashyBranchWithAMatch_then_projectIsCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2315,7 +2313,7 @@ public void given_orgFolder_when_eventCreatesASlashyBranchWithAMatch_then_projec } @Test - public void given_orgFolder_when_eventCreatesAI18nBranchWithAMatch_then_projectIsCreated() throws Exception { + void given_orgFolder_when_eventCreatesAI18nBranchWithAMatch_then_projectIsCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2338,7 +2336,7 @@ public void given_orgFolder_when_eventCreatesAI18nBranchWithAMatch_then_projectI } @Test - public void given_orgFolder_when_eventCreatesARepoWithAMatch_then_projectIsCreated() throws Exception { + void given_orgFolder_when_eventCreatesARepoWithAMatch_then_projectIsCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2361,7 +2359,7 @@ public void given_orgFolder_when_eventCreatesARepoWithAMatch_then_projectIsCreat } @Test - public void given_orgFolder_when_eventTouchesADifferentBranchInAnUndiscoveredRepoWithAMatch_then_noProjectIsCreated() throws Exception { + void given_orgFolder_when_eventTouchesADifferentBranchInAnUndiscoveredRepoWithAMatch_then_noProjectIsCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2388,7 +2386,7 @@ public void given_orgFolder_when_eventTouchesADifferentBranchInAnUndiscoveredRep } @Test - public void given_orgFolder_when_eventCreatesARepoWithoutAMatch_then_noProjectIsCreated() throws Exception { + void given_orgFolder_when_eventCreatesARepoWithoutAMatch_then_noProjectIsCreated() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -2406,7 +2404,7 @@ public void given_orgFolder_when_eventCreatesARepoWithoutAMatch_then_noProjectIs } @Test - public void given_multibranch_when_sourcesManipulatedProgrammatically_then_configureTriggersIndex() + void given_multibranch_when_sourcesManipulatedProgrammatically_then_configureTriggersIndex() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -2428,7 +2426,7 @@ public void given_multibranch_when_sourcesManipulatedProgrammatically_then_confi } @Test - public void given_multibranchWithSourcesAndDeadBranch_when_eventForBranchResurrection_then_branchIsBuilt() + void given_multibranchWithSourcesAndDeadBranch_when_eventForBranchResurrection_then_branchIsBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -2462,7 +2460,7 @@ public void given_multibranchWithSourcesAndDeadBranch_when_eventForBranchResurre } @Test - public void given_multibranchWithSourcesCriteriaAndDeadBranch_when_eventForBranchResurrection_then_branchIsBuilt() + void given_multibranchWithSourcesCriteriaAndDeadBranch_when_eventForBranchResurrection_then_branchIsBuilt() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -2494,7 +2492,7 @@ public void given_multibranchWithSourcesCriteriaAndDeadBranch_when_eventForBranc } @Test - public void given_multibranchWith2Sources_when_eventForBranchOnHigherSource_then_branchTakeover() + void given_multibranchWith2Sources_when_eventForBranchOnHigherSource_then_branchTakeover() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -2533,7 +2531,7 @@ public void given_multibranchWith2Sources_when_eventForBranchOnHigherSource_then } @Test - public void given_multibranchWith2Sources_when_eventForBranchOnLowerSource_then_eventIgnored() + void given_multibranchWith2Sources_when_eventForBranchOnLowerSource_then_eventIgnored() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -2572,7 +2570,7 @@ public void given_multibranchWith2Sources_when_eventForBranchOnLowerSource_then_ } @Test - public void given_multibranchWith2Sources_when_eventForBranchOnHigherSourceOpensTakeover_then_branchDeadUntilLowerEvent() + void given_multibranchWith2Sources_when_eventForBranchOnHigherSourceOpensTakeover_then_branchDeadUntilLowerEvent() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -2617,7 +2615,7 @@ public void given_multibranchWith2Sources_when_eventForBranchOnHigherSourceOpens } @Test - public void given_multibranchWith2SourcesAndCriteria_when_firstSourceDoesntHaveBranchAndSecondSourceHasMatch_then_branchPresent() + void given_multibranchWith2SourcesAndCriteria_when_firstSourceDoesntHaveBranchAndSecondSourceHasMatch_then_branchPresent() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -2650,7 +2648,7 @@ public void given_multibranchWith2SourcesAndCriteria_when_firstSourceDoesntHaveB } @Test - public void given_multibranchWith2SourcesAndCriteria_when_firstSourceHasBranchWithoutMatchAndSecondSourceHasMatch_then_branchFromSecondSource() + void given_multibranchWith2SourcesAndCriteria_when_firstSourceHasBranchWithoutMatchAndSecondSourceHasMatch_then_branchFromSecondSource() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -2684,7 +2682,7 @@ public void given_multibranchWith2SourcesAndCriteria_when_firstSourceHasBranchWi } @Test - public void given_multibranchWith2SourcesAndCriteria_when_eventForBranchOnHigherSource_then_branchTakeover() + void given_multibranchWith2SourcesAndCriteria_when_eventForBranchOnHigherSource_then_branchTakeover() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -2725,7 +2723,7 @@ public void given_multibranchWith2SourcesAndCriteria_when_eventForBranchOnHigher } @Test - public void given_multibranchWith2SourcesAndCriteria_when_eventForBranchOnLowerSource_then_eventIgnored() + void given_multibranchWith2SourcesAndCriteria_when_eventForBranchOnLowerSource_then_eventIgnored() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -2767,7 +2765,7 @@ public void given_multibranchWith2SourcesAndCriteria_when_eventForBranchOnLowerS } @Test - public void given_multibranchWith2SourcesAndCriteria_when_eventForBranchOnHigherSourceOpensTakeover_then_branchDeadUntilLowerEvent() + void given_multibranchWith2SourcesAndCriteria_when_eventForBranchOnHigherSourceOpensTakeover_then_branchDeadUntilLowerEvent() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -2814,7 +2812,7 @@ public void given_multibranchWith2SourcesAndCriteria_when_eventForBranchOnHigher } @Test - public void given_multibranch_when_not_build_is_skipped_then_lastSeenRevision_is_equal_to_lastBuiltRevision() throws Exception { + void given_multibranch_when_not_build_is_skipped_then_lastSeenRevision_is_equal_to_lastBuiltRevision() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "my-project"); @@ -2835,7 +2833,7 @@ public void given_multibranch_when_not_build_is_skipped_then_lastSeenRevision_is } @Test - public void given_multibranch_when_first_build_is_skipped_then_lastSeenRevision_is_different_to_lastBuiltRevision() throws Exception { + void given_multibranch_when_first_build_is_skipped_then_lastSeenRevision_is_different_to_lastBuiltRevision() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "my-project"); @@ -2880,7 +2878,7 @@ public static class DescriptorImpl extends BranchBuildStrategyDescriptor { } @Test - public void given_multibranch_when__build_is_skipped_then_lastBuiltRevision_is_null() throws Exception { + void given_multibranch_when__build_is_skipped_then_lastBuiltRevision_is_null() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "my-project"); diff --git a/src/test/java/integration/MigrationTest.java b/src/test/java/integration/MigrationTest.java index c2108fce..4edd5a95 100644 --- a/src/test/java/integration/MigrationTest.java +++ b/src/test/java/integration/MigrationTest.java @@ -28,12 +28,6 @@ import hudson.model.Job; import hudson.model.TopLevelItem; import integration.harness.BasicMultiBranchProjectFactory; -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; import jenkins.branch.MultiBranchProject; import jenkins.branch.OrganizationFolder; import jenkins.scm.impl.mock.MockSCMController; @@ -47,6 +41,15 @@ import org.junit.Test; import org.jvnet.hudson.test.JenkinsSessionRule; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.instanceOf; @@ -58,7 +61,7 @@ public class MigrationTest { private static MockSCMController c; @Rule - public JenkinsSessionRule r = new JenkinsSessionRule(); + public JenkinsSessionRule story = new JenkinsSessionRule(); @BeforeClass public static void setupSCM() throws IOException { @@ -87,54 +90,54 @@ public static void closeSCM() { @Test public void createdFromScratch() throws Throwable { - r.then(j -> { - OrganizationFolder foo = j.createProject(OrganizationFolder.class, "foo"); - foo.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); - foo.getProjectFactories() - .replaceBy(Collections.singletonList(new BasicMultiBranchProjectFactory(null))); - foo.scheduleBuild2(0).getFuture().get(); - j.waitUntilNoActivity(); - assertDataMigrated(foo); + story.then(j -> { + OrganizationFolder foo = j.createProject(OrganizationFolder.class, "foo"); + foo.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); + foo.getProjectFactories() + .replaceBy(Collections.singletonList(new BasicMultiBranchProjectFactory(null))); + foo.scheduleBuild2(0).getFuture().get(); + j.waitUntilNoActivity(); + assertDataMigrated(foo); }); - r.then(j -> { - TopLevelItem foo = j.jenkins.getItem("foo"); - assertDataMigrated(foo); + story.then(j -> { + TopLevelItem foo = j.jenkins.getItem("foo"); + assertDataMigrated(foo); }); } @Test public void createdFromScratch_full_reload() throws Throwable { - r.then(j -> { - OrganizationFolder foo = j.createProject(OrganizationFolder.class, "foo"); - foo.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); - foo.getProjectFactories() - .replaceBy(Collections.singletonList(new BasicMultiBranchProjectFactory(null))); - foo.scheduleBuild2(0).getFuture().get(); - j.waitUntilNoActivity(); - j.jenkins.reload(); - assertDataMigrated(foo); + story.then(j -> { + OrganizationFolder foo = j.createProject(OrganizationFolder.class, "foo"); + foo.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); + foo.getProjectFactories() + .replaceBy(Collections.singletonList(new BasicMultiBranchProjectFactory(null))); + foo.scheduleBuild2(0).getFuture().get(); + j.waitUntilNoActivity(); + j.jenkins.reload(); + assertDataMigrated(foo); }); - r.then(j -> { - TopLevelItem foo = j.jenkins.getItem("foo"); - assertDataMigrated(foo); + story.then(j -> { + TopLevelItem foo = j.jenkins.getItem("foo"); + assertDataMigrated(foo); }); } @Test public void createdFromScratch_folder_reload() throws Throwable { - r.then(j -> { - OrganizationFolder foo = j.createProject(OrganizationFolder.class, "foo"); - foo.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); - foo.getProjectFactories() - .replaceBy(Collections.singletonList(new BasicMultiBranchProjectFactory(null))); - foo.scheduleBuild2(0).getFuture().get(); - j.waitUntilNoActivity(); - foo.doReload(); - assertDataMigrated(foo); + story.then(j -> { + OrganizationFolder foo = j.createProject(OrganizationFolder.class, "foo"); + foo.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); + foo.getProjectFactories() + .replaceBy(Collections.singletonList(new BasicMultiBranchProjectFactory(null))); + foo.scheduleBuild2(0).getFuture().get(); + j.waitUntilNoActivity(); + foo.doReload(); + assertDataMigrated(foo); }); - r.then(j -> { - TopLevelItem foo = j.jenkins.getItem("foo"); - assertDataMigrated(foo); + story.then(j -> { + TopLevelItem foo = j.jenkins.getItem("foo"); + assertDataMigrated(foo); }); } diff --git a/src/test/java/integration/ScmApiTest.java b/src/test/java/integration/ScmApiTest.java index 6f590bcd..bce5f480 100644 --- a/src/test/java/integration/ScmApiTest.java +++ b/src/test/java/integration/ScmApiTest.java @@ -30,7 +30,6 @@ import integration.harness.BasicMultiBranchProject; import integration.harness.BasicMultiBranchProjectFactory; import integration.harness.BasicSCMSourceCriteria; -import java.util.Collections; import jenkins.branch.BranchSource; import jenkins.branch.OrganizationFolder; import jenkins.scm.api.SCMHead; @@ -45,33 +44,41 @@ import jenkins.scm.impl.mock.MockSCMRevision; import jenkins.scm.impl.mock.MockSCMSource; import jenkins.scm.impl.mock.MockTagSCMHead; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +import java.util.Collections; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -public class ScmApiTest { +@WithJenkins +class ScmApiTest { /** * All tests in this class only create items and do not affect other global configuration, thus we trade test * execution time for the restriction on only touching items. */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } - @Before - public void cleanOutAllItems() throws Exception { + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void given_multibranchJob_when_scmHeadHeadByItemFindHead_then_headReturned() throws Exception { + void given_multibranchJob_when_scmHeadHeadByItemFindHead_then_headReturned() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); long timestamp = c.createTag("foo", "master", "1.0"); @@ -91,7 +98,7 @@ public void given_multibranchJob_when_scmHeadHeadByItemFindHead_then_headReturne } @Test - public void given_multibranch_when_scmHeadHeadByItemFindHead_then_noHeadReturned() throws Exception { + void given_multibranch_when_scmHeadHeadByItemFindHead_then_noHeadReturned() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createTag("foo", "master", "1.0"); @@ -107,7 +114,7 @@ public void given_multibranch_when_scmHeadHeadByItemFindHead_then_noHeadReturned } @Test - public void given_orgFolder_when_scmHeadHeadByItemFindHead_then_noHeadReturned() throws Exception { + void given_orgFolder_when_scmHeadHeadByItemFindHead_then_noHeadReturned() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); @@ -121,7 +128,7 @@ public void given_orgFolder_when_scmHeadHeadByItemFindHead_then_noHeadReturned() } @Test - public void given_freestyle_when_scmHeadHeadByItemFindHead_then_noHeadReturned() throws Exception { + void given_freestyle_when_scmHeadHeadByItemFindHead_then_noHeadReturned() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); FreeStyleProject prj = r.createFreeStyleProject(); diff --git a/src/test/java/integration/UpdatingFromXmlTest.java b/src/test/java/integration/UpdatingFromXmlTest.java index 538049a3..4a21e276 100644 --- a/src/test/java/integration/UpdatingFromXmlTest.java +++ b/src/test/java/integration/UpdatingFromXmlTest.java @@ -5,49 +5,55 @@ import jenkins.scm.impl.mock.MockSCMController; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.ReaderInputStream; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import java.io.StringReader; import java.nio.charset.StandardCharsets; -import static junit.framework.TestCase.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; -public class UpdatingFromXmlTest { +@WithJenkins +class UpdatingFromXmlTest { /** * All tests in this class only create items and do not affect other global configuration, thus we trade test * execution time for the restriction on only touching items. */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; - @Before - public void cleanOutAllItems() throws Exception { + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } + + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void given_multibranch_when_createFromXml_then_hasItems() throws Exception { + void given_multibranch_when_createFromXml_then_hasItems() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.cloneBranch("foo", "master", "feature"); c.addFile("foo", "feature", "add new feature", "FEATURE", "new".getBytes()); String configXml = IOUtils.toString(getClass().getResourceAsStream("UpdatingFromXmlTest/config.xml"), StandardCharsets.UTF_8).replace("fixme", c.getId()); - BasicMultiBranchProject prj = (BasicMultiBranchProject) r.jenkins.createProjectFromXML("foo", new ReaderInputStream(new StringReader(configXml), StandardCharsets.UTF_8)); + BasicMultiBranchProject prj = (BasicMultiBranchProject) r.jenkins.createProjectFromXML("foo", ReaderInputStream.builder().setReader(new StringReader(configXml)).setCharset(StandardCharsets.UTF_8).get()); r.waitUntilNoActivity(); - assertTrue(prj.getItems().size() > 0); + assertFalse(prj.getItems().isEmpty()); } } @Test - public void given_multibranch_when_updateFromXml_then_hasItems() throws Exception { + void given_multibranch_when_updateFromXml_then_hasItems() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.cloneBranch("foo", "master", "feature"); @@ -56,7 +62,7 @@ public void given_multibranch_when_updateFromXml_then_hasItems() throws Exceptio BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); prj.updateByXml((Source) new StreamSource(new StringReader(configXml))); r.waitUntilNoActivity(); - assertTrue(prj.getItems().size() > 0); + assertFalse(prj.getItems().isEmpty()); } } diff --git a/src/test/java/integration/UpdatingFromXmlWithDisabledFlagTest.java b/src/test/java/integration/UpdatingFromXmlWithDisabledFlagTest.java index c2a711dc..b01026d3 100644 --- a/src/test/java/integration/UpdatingFromXmlWithDisabledFlagTest.java +++ b/src/test/java/integration/UpdatingFromXmlWithDisabledFlagTest.java @@ -5,54 +5,67 @@ import jenkins.scm.impl.mock.MockSCMController; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.ReaderInputStream; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.Rule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; -import org.jvnet.hudson.test.FlagRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import java.io.StringReader; import java.nio.charset.StandardCharsets; -import static junit.framework.TestCase.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class UpdatingFromXmlWithDisabledFlagTest { +@WithJenkins +class UpdatingFromXmlWithDisabledFlagTest { + + private String fireSCMSourceBuildsAfterSave; /** * All tests in this class only create items and do not affect other global configuration, thus we trade test * execution time for the restriction on only touching items. */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } - @Rule - public FlagRule flagRule = FlagRule.systemProperty("jenkins.branch.MultiBranchProject.fireSCMSourceBuildsAfterSave", "false"); + @BeforeEach + void setUp() throws Exception { + fireSCMSourceBuildsAfterSave = System.setProperty("jenkins.branch.MultiBranchProject.fireSCMSourceBuildsAfterSave", "false"); - @Before - public void cleanOutAllItems() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } + @AfterEach + void tearDown() { + if (fireSCMSourceBuildsAfterSave != null) { + System.setProperty("jenkins.branch.MultiBranchProject.fireSCMSourceBuildsAfterSave", fireSCMSourceBuildsAfterSave); + } + } + @Test - public void given_multibranch_when_createFromXml_is_disabled_then_hasNoItems() throws Exception { + void given_multibranch_when_createFromXml_is_disabled_then_hasNoItems() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.cloneBranch("foo", "master", "feature"); c.addFile("foo", "feature", "add new feature", "FEATURE", "new".getBytes()); String configXml = IOUtils.toString(getClass().getResourceAsStream("UpdatingFromXmlTest/config.xml"), StandardCharsets.UTF_8).replace("fixme", c.getId()); - BasicMultiBranchProject prj = (BasicMultiBranchProject) r.jenkins.createProjectFromXML("foo", new ReaderInputStream(new StringReader(configXml), StandardCharsets.UTF_8)); + BasicMultiBranchProject prj = (BasicMultiBranchProject) r.jenkins.createProjectFromXML("foo", ReaderInputStream.builder().setReader(new StringReader(configXml)).setCharset(StandardCharsets.UTF_8).get()); r.waitUntilNoActivity(); assertTrue(prj.getItems().isEmpty()); } } @Test - public void given_multibranch_when_updateFromXml_is_disabled_then_hasNoItems() throws Exception { + void given_multibranch_when_updateFromXml_is_disabled_then_hasNoItems() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.cloneBranch("foo", "master", "feature"); diff --git a/src/test/java/jenkins/branch/BranchCategoryFilterTest.java b/src/test/java/jenkins/branch/BranchCategoryFilterTest.java index d223f1f8..229fe80e 100644 --- a/src/test/java/jenkins/branch/BranchCategoryFilterTest.java +++ b/src/test/java/jenkins/branch/BranchCategoryFilterTest.java @@ -25,17 +25,13 @@ package jenkins.branch; +import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.ItemGroup; import hudson.model.Job; import hudson.model.Run; import hudson.model.TopLevelItem; import hudson.model.View; import hudson.scm.SCM; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import edu.umd.cs.findbugs.annotations.NonNull; import jenkins.scm.api.SCMHeadCategory; import jenkins.scm.api.SCMSource; import jenkins.scm.api.SCMSourceDescriptor; @@ -45,19 +41,24 @@ import jenkins.scm.impl.mock.MockSCMHead; import jenkins.scm.impl.mock.MockTagSCMHead; import org.hamcrest.Matchers; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; -import org.junit.Ignore; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class BranchCategoryFilterTest { +class BranchCategoryFilterTest { - @Ignore("TODO fails in Mockito 5; SCMSource.getCategories is empty") + @Disabled("TODO fails in Mockito 5; SCMSource.getCategories is empty") @Test - public void filter_uncategorizedCategory() throws Exception { + void filter_uncategorizedCategory() { MultiBranchProject owner = mock(MultiBranchProject.class); View filteringView = mock(View.class); when(filteringView.getOwner()).thenReturn(owner); @@ -112,7 +113,7 @@ public void filter_uncategorizedCategory() throws Exception { } @Test - public void filter_specificCategory() throws Exception { + void filter_specificCategory() { MultiBranchProject owner = mock(MultiBranchProject.class); View filteringView = mock(View.class); when(filteringView.getOwner()).thenReturn(owner); diff --git a/src/test/java/jenkins/branch/BranchNameContributorTest.java b/src/test/java/jenkins/branch/BranchNameContributorTest.java index 5870927d..f55efd86 100644 --- a/src/test/java/jenkins/branch/BranchNameContributorTest.java +++ b/src/test/java/jenkins/branch/BranchNameContributorTest.java @@ -30,9 +30,6 @@ import hudson.model.TopLevelItem; import hudson.util.LogTaskListener; import integration.harness.BasicMultiBranchProject; -import java.util.Collections; -import java.util.logging.Level; -import java.util.logging.Logger; import jenkins.scm.impl.mock.MockChangeRequestFlags; import jenkins.scm.impl.mock.MockRepositoryFlags; import jenkins.scm.impl.mock.MockSCMController; @@ -40,10 +37,15 @@ import jenkins.scm.impl.mock.MockSCMDiscoverChangeRequests; import jenkins.scm.impl.mock.MockSCMDiscoverTags; import jenkins.scm.impl.mock.MockSCMSource; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +import java.util.Collections; +import java.util.logging.Level; +import java.util.logging.Logger; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; @@ -52,24 +54,30 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -public class BranchNameContributorTest { +@WithJenkins +class BranchNameContributorTest { private static final Logger LOGGER = Logger.getLogger(BranchNameContributorTest.class.getName()); + /** * All tests in this class only create items and do not affect other global configuration, thus we trade test * execution time for the restriction on only touching items. */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } - @Before - public void cleanOutAllItems() throws Exception { + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void buildEnvironmentFor() throws Exception { + void buildEnvironmentFor() throws Exception { BranchNameContributor instance = r.jenkins.getExtensionList(EnvironmentContributor.class).get(BranchNameContributor.class); assertThat("The extension is registered", instance, notNullValue()); diff --git a/src/test/java/jenkins/branch/BranchTest.java b/src/test/java/jenkins/branch/BranchTest.java index 39a278b1..5d6a3d7f 100644 --- a/src/test/java/jenkins/branch/BranchTest.java +++ b/src/test/java/jenkins/branch/BranchTest.java @@ -26,31 +26,33 @@ import hudson.model.Action; import hudson.model.Items; import hudson.scm.NullSCM; -import java.util.Collections; import jenkins.scm.impl.NullSCMSource; import jenkins.scm.impl.mock.MockSCMHead; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import java.util.Collections; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -public class BranchTest { +class BranchTest { @Test - public void given_livePre2Branch_when_deserialized_then_objectInvariantsCorrect() throws Exception { + void given_livePre2Branch_when_deserialized_then_objectInvariantsCorrect() { Branch b = (Branch) Items.XSTREAM2 - .fromXML("\n" - + " any-id\n" - + " \n" - + " quicker\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " "); + .fromXML(""" + + any-id + + quicker + + + + + + """); assertThat(b.getName(), is("quicker")); assertThat(b.getHead(), instanceOf(MockSCMHead.class)); assertThat(b.getActions(), is(Collections.emptyList())); @@ -60,18 +62,19 @@ public void given_livePre2Branch_when_deserialized_then_objectInvariantsCorrect( } @Test - public void given_deadPre2Branch_when_deserialized_then_objectInvariantsCorrect() throws Exception { + void given_deadPre2Branch_when_deserialized_then_objectInvariantsCorrect() { Branch b = (Branch) Items.XSTREAM2 - .fromXML("\n" - + " ::NullSCMSource::\n" - + " \n" - + " quicker\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " "); + .fromXML(""" + + ::NullSCMSource:: + + quicker + + + + + + """); assertThat(b.getName(), is("quicker")); assertThat(b.getHead(), instanceOf(MockSCMHead.class)); assertThat(b.getActions(), is(Collections.emptyList())); diff --git a/src/test/java/jenkins/branch/BuildRetentionBranchPropertyTest.java b/src/test/java/jenkins/branch/BuildRetentionBranchPropertyTest.java index 6014a7b4..99ec5f80 100644 --- a/src/test/java/jenkins/branch/BuildRetentionBranchPropertyTest.java +++ b/src/test/java/jenkins/branch/BuildRetentionBranchPropertyTest.java @@ -29,33 +29,44 @@ import hudson.model.ItemGroup; import hudson.model.Job; import hudson.tasks.LogRotator; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + import java.io.IOException; -import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertTrue; -import org.junit.ClassRule; -import org.jvnet.hudson.test.JenkinsRule; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class BuildRetentionBranchPropertyTest { +@WithJenkins +class BuildRetentionBranchPropertyTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + /** + * All tests in this class only create items and do not affect other global configuration, thus we trade test + * execution time for the restriction on only touching items. + */ + private static JenkinsRule r; + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } @Test - public void decoratesStandardJobByFieldReflectionAccess() throws Exception { + void decoratesStandardJobByFieldReflectionAccess() { BuildRetentionBranchProperty instance = new BuildRetentionBranchProperty(new LogRotator(5, 5, 5, 5)); Job job = new FreeStyleProject(mock(ItemGroup.class), "foo"); assertThat(instance.jobDecorator((Class) Job.class).project(job).getBuildDiscarder(), is(instance.getBuildDiscarder())); } @Test - public void decoratesNonStandardJobBySetter() throws Exception { + void decoratesNonStandardJobBySetter() throws Exception { BuildRetentionBranchProperty instance = new BuildRetentionBranchProperty(new LogRotator(5, 5, 5, 5)); Job job = mock(Job.class); when(job.getBuildDiscarder()).thenReturn(new LogRotator(0, 0, 0, 0)); @@ -64,13 +75,12 @@ public void decoratesNonStandardJobBySetter() throws Exception { } @Test - public void decoratesIsBestEffort() throws Exception { + void decoratesIsBestEffort() throws Exception { BuildRetentionBranchProperty instance = new BuildRetentionBranchProperty(new LogRotator(5, 5, 5, 5)); Job job = mock(Job.class); when(job.getBuildDiscarder()).thenReturn(new LogRotator(0, 0, 0, 0)); doThrow(new IOException("boom")).when(job).setBuildDiscarder(new LogRotator(5, 5, 5, 5)); - instance.jobDecorator((Class) Job.class).project(job); - assertTrue("The IOException was caught and ignored", true); + assertDoesNotThrow(() -> instance.jobDecorator((Class) Job.class).project(job)); verify(job).setBuildDiscarder(instance.getBuildDiscarder()); } } diff --git a/src/test/java/jenkins/branch/MultiBranchProjectTest.java b/src/test/java/jenkins/branch/MultiBranchProjectTest.java index 771ae2b2..b37ad34e 100644 --- a/src/test/java/jenkins/branch/MultiBranchProjectTest.java +++ b/src/test/java/jenkins/branch/MultiBranchProjectTest.java @@ -1,17 +1,17 @@ package jenkins.branch; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; /** * @author Stephen Connolly */ -public class MultiBranchProjectTest { +class MultiBranchProjectTest { @Test - public void smokes() { + void smokes() { assertThat(MultiBranchProject.rawDecode("Hello world"), is("Hello world")); assertThat(MultiBranchProject.rawDecode("Hello+world"), is("Hello+world")); assertThat(MultiBranchProject.rawDecode("origin/production"), is("origin/production")); diff --git a/src/test/java/jenkins/branch/MultibranchImplementationTest.java b/src/test/java/jenkins/branch/MultibranchImplementationTest.java index 712af036..fd83c9bc 100644 --- a/src/test/java/jenkins/branch/MultibranchImplementationTest.java +++ b/src/test/java/jenkins/branch/MultibranchImplementationTest.java @@ -24,26 +24,31 @@ package jenkins.branch; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsRule; -import org.jvnet.hudson.test.TestExtension; - import hudson.model.Item; import hudson.model.listeners.ItemListener; import jenkins.branch.harness.MultiBranchImpl; import jenkins.scm.api.SCMSourceOwner; +import org.junit.jupiter.api.BeforeEach; +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; + +@WithJenkins +class MultibranchImplementationTest { -public class MultibranchImplementationTest { + private static Exception check = null; - @Rule - public JenkinsRule j = new JenkinsRule(); + private JenkinsRule r; - public static Exception check = null; + @BeforeEach + void setUp(JenkinsRule rule) { + r = rule; + } @Test - public void createMultiBranchProjectWithListenerTest() throws Exception { - j.jenkins.createProject(MultiBranchImpl.class, "test"); + void createMultiBranchProjectWithListenerTest() throws Exception { + r.jenkins.createProject(MultiBranchImpl.class, "test"); if (check != null) { throw check; } diff --git a/src/test/java/jenkins/branch/NameEncoderTest.java b/src/test/java/jenkins/branch/NameEncoderTest.java index f1d92b89..73f544fb 100644 --- a/src/test/java/jenkins/branch/NameEncoderTest.java +++ b/src/test/java/jenkins/branch/NameEncoderTest.java @@ -24,15 +24,15 @@ package jenkins.branch; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -public class NameEncoderTest { +class NameEncoderTest { @Test - public void smokes() throws Exception { + void smokes() { assertRoundTrip("test"); assertRoundTrip("."); assertRoundTrip(".."); @@ -42,7 +42,7 @@ public void smokes() throws Exception { } @Test - public void safeNames() { + void safeNames() { assertRoundTrip("foo"); assertRoundTrip("foo-bar"); assertRoundTrip("foo bar"); @@ -51,7 +51,7 @@ public void safeNames() { } @Test - public void reservedNames() { + void reservedNames() { assertRoundTrip("."); assertRoundTrip(".."); assertRoundTrip("con"); @@ -79,7 +79,7 @@ public void reservedNames() { } @Test - public void slashNames() { + void slashNames() { assertRoundTrip("foo/bar"); assertRoundTrip("foo/bar/fu manchu"); assertRoundTrip("foo/bar/fu manchu/1"); @@ -101,7 +101,7 @@ public void slashNames() { } @Test - public void longNames() { + void longNames() { assertRoundTrip("cafebabedeadbeefcafebabedeadbeef"); assertRoundTrip("cafebabedeadbeefcafebabedeadbeefcafebabedeadbeef"); assertRoundTrip("cafebabedeadbeefcafebabeDeadbeefcafebabedeadbeef"); @@ -110,7 +110,7 @@ public void longNames() { } @Test - public void nonSafeNames() { + void nonSafeNames() { assertRoundTrip("Is maith liom criospaí"); assertRoundTrip("Ich liebe Fußball"); assertRoundTrip("我喜欢披萨"); @@ -122,14 +122,14 @@ public void nonSafeNames() { } @Test - public void spain() { + void spain() { assertRoundTrip("Espana"); assertRoundTrip("España"); assertRoundTrip("Espa\u006e\u0303a"); } @Test - public void ireland() { + void ireland() { assertRoundTrip("Eireann"); assertRoundTrip("Éireann"); assertRoundTrip("E\u0301ireann"); diff --git a/src/test/java/jenkins/branch/NameManglerTest.java b/src/test/java/jenkins/branch/NameManglerTest.java index 12458e7a..c18afb54 100644 --- a/src/test/java/jenkins/branch/NameManglerTest.java +++ b/src/test/java/jenkins/branch/NameManglerTest.java @@ -23,15 +23,15 @@ */ package jenkins.branch; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -public class NameManglerTest { +class NameManglerTest { @Test - public void safeNames() { + void safeNames() { assertThat(NameMangler.apply("foo"), is("foo")); assertThat(NameMangler.apply("foo-bar"), is("foo-bar")); assertThat(NameMangler.apply("foo bar"), is("foo-bar.074vf0")); @@ -40,7 +40,7 @@ public void safeNames() { } @Test - public void reservedNames() { + void reservedNames() { assertThat(NameMangler.apply("."), is("0-.tkvgu3")); assertThat(NameMangler.apply(".."), is("0--.mpdh40")); assertThat(NameMangler.apply("con"), is("con.lkb1gc")); @@ -68,7 +68,7 @@ public void reservedNames() { } @Test - public void slashNames() { + void slashNames() { assertThat(NameMangler.apply("foo/bar"), is("foo-bar.nj9av9")); assertThat(NameMangler.apply("foo/bar/fu manchu"), is("foo-bar-fu-manchu.k630nd")); assertThat(NameMangler.apply("foo/bar/fu manchu/1"), is("foo-bar-fu-manchu-1.vgnr4j")); @@ -90,7 +90,7 @@ public void slashNames() { } @Test - public void longNames() { + void longNames() { assertThat(NameMangler.apply("cafebabedeadbeefcafebabedeadbeef"), is("cafebabedeadbeefcafebabedeadbeef")); assertThat(NameMangler.apply("cafebabedeadbeefcafebabedeadbeefcafebabedeadbeef"), is("cafebabed.98h82o58mhfo.edeadbeef")); assertThat(NameMangler.apply("cafebabedeadbeefcafebabeDeadbeefcafebabedeadbeef"), is("cafebabed.a67pve49oi0n.edeadbeef")); @@ -99,7 +99,7 @@ public void longNames() { } @Test - public void nonSafeNames() { + void nonSafeNames() { assertThat(NameMangler.apply("Is maith liom criospaí"), is("Is-maith-liom-criospa_ed.0g5uh9")); assertThat(NameMangler.apply("Ich liebe Fußball"), is("Ich-liebe-Fu_dfball.fp53tq")); assertThat(NameMangler.apply("我喜欢披萨"), is("0_62_11_55_9.f9c1g4._62_ab_84_28")); @@ -111,13 +111,14 @@ public void nonSafeNames() { } @Test - public void spain() { + void spain() { assertThat(NameMangler.apply("Espana"), is("Espana")); assertThat(NameMangler.apply("España"), is("Espa_f1a.9jabqu")); assertThat(NameMangler.apply("Espa\u006e\u0303a"), is("Espan_03_03a.eqqe01")); } + @Test - public void ireland() { + void ireland() { assertThat(NameMangler.apply("Eireann"), is("Eireann")); assertThat(NameMangler.apply("Éireann"), is("0_c9ireann.giuvlt")); assertThat(NameMangler.apply("E\u0301ireann"), is("E_03_01ireann.0qtq11")); diff --git a/src/test/java/jenkins/branch/NamedExceptionsBranchPropertyStrategyTest.java b/src/test/java/jenkins/branch/NamedExceptionsBranchPropertyStrategyTest.java index 2e51252a..746bfcdb 100644 --- a/src/test/java/jenkins/branch/NamedExceptionsBranchPropertyStrategyTest.java +++ b/src/test/java/jenkins/branch/NamedExceptionsBranchPropertyStrategyTest.java @@ -1,6 +1,6 @@ package jenkins.branch; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static jenkins.branch.NamedExceptionsBranchPropertyStrategy.Named.isMatch; import static org.hamcrest.MatcherAssert.assertThat; @@ -9,9 +9,10 @@ /** * @author Stephen Connolly */ -public class NamedExceptionsBranchPropertyStrategyTest { +class NamedExceptionsBranchPropertyStrategyTest { + @Test - public void examplesFromHelpText() throws Exception { + void examplesFromHelpText() { // "production" matches one and only one branch assertThat(isMatch("production", "production"), is(true)); assertThat(isMatch("Production", "production"), is(true)); diff --git a/src/test/java/jenkins/branch/NoTriggerBranchPropertyTest.java b/src/test/java/jenkins/branch/NoTriggerBranchPropertyTest.java index 31623b38..ff3279c4 100644 --- a/src/test/java/jenkins/branch/NoTriggerBranchPropertyTest.java +++ b/src/test/java/jenkins/branch/NoTriggerBranchPropertyTest.java @@ -23,25 +23,16 @@ */ package jenkins.branch; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - import com.cloudbees.hudson.plugins.folder.computed.ComputedFolder; import com.cloudbees.hudson.plugins.folder.computed.FolderComputation; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.queue.QueueTaskFuture; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.nio.charset.StandardCharsets; -import java.util.Collections; import jenkins.branch.harness.MultiBranchImpl; import jenkins.plugins.git.GitSCMSource; import jenkins.plugins.git.GitSampleRepoRule; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import jenkins.plugins.git.traits.BranchDiscoveryTrait; import jenkins.scm.api.SCMEvent; import jenkins.scm.api.SCMEvents; @@ -53,21 +44,39 @@ import jenkins.scm.impl.mock.MockSCMSource; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.ReaderInputStream; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class NoTriggerBranchPropertyTest { +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.util.Collections; - @Rule - public JenkinsRule r = new JenkinsRule(); - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@WithJenkins +@WithGitSampleRepo +class NoTriggerBranchPropertyTest { + + private JenkinsRule r; + private GitSampleRepoRule sampleRepo; + + @BeforeEach + void setUp(JenkinsRule rule, GitSampleRepoRule repo) { + r = rule; + sampleRepo = repo; + } @Issue("JENKINS-32396") @Test - public void smokes() throws Exception { + void smokes() throws Exception { sampleRepo.init(); sampleRepo.git("checkout", "-b", "newfeature"); sampleRepo.write("stuff", "content"); @@ -113,7 +122,7 @@ public void smokes() throws Exception { assertEquals(1, release.getNextBuildNumber()); assertEquals(3, newfeature.getNextBuildNumber()); QueueTaskFuture releaseBuild = release.scheduleBuild2(0); - assertNotNull("was able to schedule a manual build of the release branch", releaseBuild); + assertNotNull(releaseBuild, "was able to schedule a manual build of the release branch"); assertEquals(1, releaseBuild.get().getNumber()); assertEquals(2, release.getNextBuildNumber()); } @@ -127,7 +136,7 @@ static void showComputation(@NonNull ComputedFolder d) throws Exception { @Issue("JENKINS-63673") @Test - public void suppressNothing() throws Exception { + void suppressNothing() throws Exception { try (MockSCMController controller = MockSCMController.create()) { ProjectWrapper project = createProject(controller, NoTriggerMultiBranchQueueDecisionHandler.SuppressionStrategy.NONE); assertThat(project.getNextBuildNumber(), is(1)); @@ -144,7 +153,7 @@ public void suppressNothing() throws Exception { @Issue("JENKINS-63673") @Test - public void suppressIndexing() throws Exception { + void suppressIndexing() throws Exception { try (MockSCMController controller = MockSCMController.create()) { ProjectWrapper project = createProject(controller, NoTriggerMultiBranchQueueDecisionHandler.SuppressionStrategy.INDEXING); assertThat(project.getNextBuildNumber(), is(1)); @@ -161,7 +170,7 @@ public void suppressIndexing() throws Exception { @Issue("JENKINS-63673") @Test - public void suppressEvents() throws Exception { + void suppressEvents() throws Exception { try (MockSCMController controller = MockSCMController.create()) { ProjectWrapper project = createProject(controller, NoTriggerMultiBranchQueueDecisionHandler.SuppressionStrategy.EVENTS); assertThat(project.getNextBuildNumber(), is(1)); @@ -193,7 +202,7 @@ private ProjectWrapper createProject(MockSCMController controller, NoTriggerMult @Issue("JENKINS-63673") @Test - public void suppressAllWhenJobCreatedBeforeAddingTheSuppressionStrategyParameter() throws Exception { + void suppressAllWhenJobCreatedBeforeAddingTheSuppressionStrategyParameter() throws Exception { try (MockSCMController controller = MockSCMController.create()) { String repositoryName = "repoName"; controller.createRepository(repositoryName); @@ -201,7 +210,7 @@ public void suppressAllWhenJobCreatedBeforeAddingTheSuppressionStrategyParameter String configXml = IOUtils.toString(configStream, StandardCharsets.UTF_8) .replace("CONTROLLER_ID_PLACEHOLDER", controller.getId()) .replace("REPOSITORY_NAME_PLACEHOLDER", repositoryName); - InputStream configReader = new ReaderInputStream(new StringReader(configXml), StandardCharsets.UTF_8); + InputStream configReader = ReaderInputStream.builder().setReader(new StringReader(configXml)).setCharset(StandardCharsets.UTF_8).get(); MultiBranchImpl loadedProject = (MultiBranchImpl) r.jenkins.createProjectFromXML("oldJob", configReader); r.waitUntilNoActivity(); diff --git a/src/test/java/jenkins/branch/NoTriggerMultiBranchQueueDecisionHandlerTest.java b/src/test/java/jenkins/branch/NoTriggerMultiBranchQueueDecisionHandlerTest.java index a9ab8aa1..27c50edc 100644 --- a/src/test/java/jenkins/branch/NoTriggerMultiBranchQueueDecisionHandlerTest.java +++ b/src/test/java/jenkins/branch/NoTriggerMultiBranchQueueDecisionHandlerTest.java @@ -23,16 +23,6 @@ */ package jenkins.branch; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - import com.cloudbees.hudson.plugins.folder.Folder; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.Action; @@ -41,27 +31,36 @@ import hudson.model.ItemGroup; import hudson.model.Job; import hudson.model.Queue.Task; +import jenkins.branch.NoTriggerMultiBranchQueueDecisionHandler.NoTriggerProperty; +import jenkins.branch.NoTriggerMultiBranchQueueDecisionHandler.SuppressionStrategy; +import jenkins.scm.api.SCMEvent; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; -import jenkins.branch.NoTriggerMultiBranchQueueDecisionHandler.NoTriggerProperty; -import jenkins.branch.NoTriggerMultiBranchQueueDecisionHandler.SuppressionStrategy; -import jenkins.scm.api.SCMEvent; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Test; -import org.junit.runner.RunWith; -@RunWith(JUnitParamsRunner.class) -public class NoTriggerMultiBranchQueueDecisionHandlerTest { +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +class NoTriggerMultiBranchQueueDecisionHandlerTest { private static final String BRANCH_INDEXING_CAUSE_ID = "indexing"; private static final String BRANCH_EVENT_CAUSE_ID = "event"; @Test - public void scheduleWhenNoJobIsPassed() { + void scheduleWhenNoJobIsPassed() { Task task = mock(Task.class); List actions = mock(List.class); @@ -72,7 +71,7 @@ public void scheduleWhenNoJobIsPassed() { } @Test - public void scheduleWhenNoMultiBranchIsPassed() { + void scheduleWhenNoMultiBranchIsPassed() { Job job = mock(JobImpl.class); Folder folder = mock(Folder.class); when(job.getParent()).thenReturn(folder); @@ -85,7 +84,7 @@ public void scheduleWhenNoMultiBranchIsPassed() { } @Test - public void scheduleWhenNoCauseActionsExist() { + void scheduleWhenNoCauseActionsExist() { JobImpl job = mockMultiBranchJob(); NoTriggerMultiBranchQueueDecisionHandler handler = spy(createHandler()); List actions = Arrays.asList(mock(Action.class), mock(Action.class)); @@ -96,9 +95,9 @@ public void scheduleWhenNoCauseActionsExist() { verify(handler, never()).getBranchProperties((MultiBranchProject) job.getParent(), job); } - @Test - @Parameters({BRANCH_INDEXING_CAUSE_ID, BRANCH_EVENT_CAUSE_ID}) - public void scheduleWhenNoPropertiesAreSet(String causeTypeId) { + @ParameterizedTest + @ValueSource(strings = {BRANCH_INDEXING_CAUSE_ID, BRANCH_EVENT_CAUSE_ID}) + void scheduleWhenNoPropertiesAreSet(String causeTypeId) { JobImpl job = mockMultiBranchJob(); NoTriggerMultiBranchQueueDecisionHandler handler = spy(createHandler()); List actions = new ArrayList<>(); @@ -115,14 +114,14 @@ public void scheduleWhenNoPropertiesAreSet(String causeTypeId) { verify(handler, never()).processAction(job, skippedAction); } - @Test - @Parameters({ + @ParameterizedTest + @CsvSource({ BRANCH_INDEXING_CAUSE_ID + ", true", BRANCH_INDEXING_CAUSE_ID + ", false", BRANCH_EVENT_CAUSE_ID + ", true", BRANCH_EVENT_CAUSE_ID + ", false" }) - public void overrideIndexTriggersJobPropertyTakesPrecedenceOverNoTriggerProperty(String causeTypeId, boolean override) { + void overrideIndexTriggersJobPropertyTakesPrecedenceOverNoTriggerProperty(String causeTypeId, boolean override) { JobImpl job = mockMultiBranchJob(); OverrideIndexTriggersJobProperty overrideTriggersProperty = new OverrideIndexTriggersJobProperty(override); when(job.getProperty(OverrideIndexTriggersJobProperty.class)).thenReturn(overrideTriggersProperty); @@ -142,9 +141,9 @@ public void overrideIndexTriggersJobPropertyTakesPrecedenceOverNoTriggerProperty verifyNoInteractions(noTriggerProperty); } - @Test - @Parameters({BRANCH_INDEXING_CAUSE_ID, BRANCH_EVENT_CAUSE_ID}) - public void suppressWhenBranchNameDoesNotMatchTheRegex(String causeTypeId) { + @ParameterizedTest + @ValueSource(strings = {BRANCH_INDEXING_CAUSE_ID, BRANCH_EVENT_CAUSE_ID}) + void suppressWhenBranchNameDoesNotMatchTheRegex(String causeTypeId) { JobImpl job = mockMultiBranchJob("test/branch-123"); NoTriggerProperty noTriggerProperty = mock(NoTriggerProperty.class); when(noTriggerProperty.getTriggeredBranchesRegex()).thenReturn("^main$"); @@ -160,9 +159,9 @@ public void suppressWhenBranchNameDoesNotMatchTheRegex(String causeTypeId) { verify(noTriggerProperty, never()).getStrategy(); } - @Test - @Parameters({BRANCH_INDEXING_CAUSE_ID, BRANCH_EVENT_CAUSE_ID}) - public void scheduleWhenBranchNameMatchesTheRegexAndNoneStrategyIsSet(String causeTypeId) { + @ParameterizedTest + @ValueSource(strings = {BRANCH_INDEXING_CAUSE_ID, BRANCH_EVENT_CAUSE_ID}) + void scheduleWhenBranchNameMatchesTheRegexAndNoneStrategyIsSet(String causeTypeId) { JobImpl job = mockMultiBranchJob("test/branch-123"); NoTriggerProperty noTriggerProperty = spy(new NoTriggerPropertyImpl(".*", SuppressionStrategy.NONE)); NoTriggerMultiBranchQueueDecisionHandler handler = createHandler(noTriggerProperty); @@ -176,9 +175,9 @@ public void scheduleWhenBranchNameMatchesTheRegexAndNoneStrategyIsSet(String cau verify(noTriggerProperty).getStrategy(); } - @Test - @Parameters({BRANCH_INDEXING_CAUSE_ID, BRANCH_EVENT_CAUSE_ID}) - public void suppressWhenBranchNameMatchesTheRegexAndStrategyShouldSuppressIt(String causeTypeId) { + @ParameterizedTest + @ValueSource(strings = {BRANCH_INDEXING_CAUSE_ID, BRANCH_EVENT_CAUSE_ID}) + void suppressWhenBranchNameMatchesTheRegexAndStrategyShouldSuppressIt(String causeTypeId) { JobImpl job = mockMultiBranchJob("test"); SuppressionStrategy strategy = BRANCH_INDEXING_CAUSE_ID.equals(causeTypeId) ? SuppressionStrategy.INDEXING : SuppressionStrategy.EVENTS; NoTriggerProperty noTriggerProperty = new NoTriggerPropertyImpl("test", strategy); @@ -191,7 +190,7 @@ public void suppressWhenBranchNameMatchesTheRegexAndStrategyShouldSuppressIt(Str } @Test - public void scheduleForEventCauseWhenBranchNameMatchesAndIndexingStrategyIsSet() { + void scheduleForEventCauseWhenBranchNameMatchesAndIndexingStrategyIsSet() { JobImpl job = mockMultiBranchJob("indexing"); NoTriggerProperty noTriggerProperty = new NoTriggerPropertyImpl(".*", SuppressionStrategy.INDEXING); NoTriggerMultiBranchQueueDecisionHandler handler = createHandler(noTriggerProperty); @@ -203,7 +202,7 @@ public void scheduleForEventCauseWhenBranchNameMatchesAndIndexingStrategyIsSet() } @Test - public void scheduleForIndexingCauseWhenBranchNameMatchesAndEventsStrategyIsSet() { + void scheduleForIndexingCauseWhenBranchNameMatchesAndEventsStrategyIsSet() { JobImpl job = mockMultiBranchJob("event"); NoTriggerProperty noTriggerProperty = new NoTriggerPropertyImpl(".*", SuppressionStrategy.EVENTS); NoTriggerMultiBranchQueueDecisionHandler handler = createHandler(noTriggerProperty); @@ -243,7 +242,7 @@ private static JobImpl mockMultiBranchJob() { private static CauseAction mockCauseAction(Cause... causes) { CauseAction action = mock(CauseAction.class); - when(action.getCauses()).thenReturn(Arrays.stream(causes).collect(Collectors.toList())); + when(action.getCauses()).thenReturn(Arrays.stream(causes).toList()); return action; } diff --git a/src/test/java/jenkins/branch/NoTriggerOrganizationFolderPropertyTest.java b/src/test/java/jenkins/branch/NoTriggerOrganizationFolderPropertyTest.java index 5f0922b5..d76037e0 100644 --- a/src/test/java/jenkins/branch/NoTriggerOrganizationFolderPropertyTest.java +++ b/src/test/java/jenkins/branch/NoTriggerOrganizationFolderPropertyTest.java @@ -23,38 +23,47 @@ */ package jenkins.branch; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; - import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.queue.QueueTaskFuture; -import java.util.Collections; import jenkins.branch.NoTriggerMultiBranchQueueDecisionHandler.SuppressionStrategy; import jenkins.branch.harness.MultiBranchImpl; import jenkins.plugins.git.GitSCMSource; import jenkins.plugins.git.GitSampleRepoRule; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import jenkins.plugins.git.traits.BranchDiscoveryTrait; import jenkins.scm.impl.SingleSCMNavigator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -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.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class NoTriggerOrganizationFolderPropertyTest { +import java.util.Collections; - @Rule - public JenkinsRule r = new JenkinsRule(); - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@WithJenkins +@WithGitSampleRepo +class NoTriggerOrganizationFolderPropertyTest { + + private JenkinsRule r; + private GitSampleRepoRule sampleRepo; + + @BeforeEach + void setUp(JenkinsRule rule, GitSampleRepoRule repo) { + r = rule; + sampleRepo = repo; + } @Issue("JENKINS-32396") @Test - public void smokes() throws Exception { + void smokes() throws Exception { sampleRepo.init(); sampleRepo.git("checkout", "-b", "newfeature"); sampleRepo.write("stuff", "content"); @@ -111,7 +120,7 @@ public void smokes() throws Exception { assertEquals(1, release.getNextBuildNumber()); assertEquals(3, newfeature.getNextBuildNumber()); QueueTaskFuture releaseBuild = release.scheduleBuild2(0); - assertNotNull("was able to schedule a manual build of the release branch", releaseBuild); + assertNotNull(releaseBuild, "was able to schedule a manual build of the release branch"); assertEquals(1, releaseBuild.get().getNumber()); assertEquals(2, release.getNextBuildNumber()); } diff --git a/src/test/java/jenkins/branch/OrganizationChildHealthMetricsPropertyTest.java b/src/test/java/jenkins/branch/OrganizationChildHealthMetricsPropertyTest.java index 11af0797..de25dbaa 100644 --- a/src/test/java/jenkins/branch/OrganizationChildHealthMetricsPropertyTest.java +++ b/src/test/java/jenkins/branch/OrganizationChildHealthMetricsPropertyTest.java @@ -32,9 +32,6 @@ import integration.harness.BasicMultiBranchProject; import integration.harness.BasicMultiBranchProjectFactory; import integration.harness.BasicSCMSourceCriteria; -import java.util.Collections; -import java.util.List; - import jenkins.scm.impl.SingleSCMNavigator; import jenkins.scm.impl.SingleSCMSource; import jenkins.scm.impl.mock.MockSCM; @@ -42,29 +39,48 @@ import jenkins.scm.impl.mock.MockSCMDiscoverBranches; import jenkins.scm.impl.mock.MockSCMHead; import jenkins.scm.impl.mock.MockSCMNavigator; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +import java.util.Collections; +import java.util.List; import static jenkins.branch.matchers.Extracting.extracting; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +@WithJenkins +class OrganizationChildHealthMetricsPropertyTest { -public class OrganizationChildHealthMetricsPropertyTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + /** + * All tests in this class only create items and do not affect other global configuration, thus we trade test + * execution time for the restriction on only touching items. + */ + private static JenkinsRule r; + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } - @Before - public void cleanOutAllItems() throws Exception { + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void configRoundTrip() throws Exception { + void configRoundTrip() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("stuff"); OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "top"); @@ -85,7 +101,7 @@ public void configRoundTrip() throws Exception { } @Test - public void given__orgFolder__when__created__then__property_is_missing() throws Exception { + void given__orgFolder__when__created__then__property_is_missing() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -100,7 +116,7 @@ public void given__orgFolder__when__created__then__property_is_missing() throws } @Test - public void given__orgFolder__when__scan__then__child_metrics_applied() throws Exception { + void given__orgFolder__when__scan__then__child_metrics_applied() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -123,7 +139,7 @@ public void given__orgFolder__when__scan__then__child_metrics_applied() throws E } @Test - public void given__orgFolder_property_changed__when__scan__then__child_metrics_updated() throws Exception { + void given__orgFolder_property_changed__when__scan__then__child_metrics_updated() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); diff --git a/src/test/java/jenkins/branch/OrganizationChildOrphanedItemsPropertyTest.java b/src/test/java/jenkins/branch/OrganizationChildOrphanedItemsPropertyTest.java index 59e65c3d..4aadb3e1 100644 --- a/src/test/java/jenkins/branch/OrganizationChildOrphanedItemsPropertyTest.java +++ b/src/test/java/jenkins/branch/OrganizationChildOrphanedItemsPropertyTest.java @@ -30,9 +30,6 @@ import integration.harness.BasicMultiBranchProject; import integration.harness.BasicMultiBranchProjectFactory; import integration.harness.BasicSCMSourceCriteria; -import java.util.Collections; -import java.util.List; - import jenkins.scm.impl.SingleSCMNavigator; import jenkins.scm.impl.SingleSCMSource; import jenkins.scm.impl.mock.MockSCM; @@ -40,29 +37,46 @@ import jenkins.scm.impl.mock.MockSCMDiscoverBranches; import jenkins.scm.impl.mock.MockSCMHead; import jenkins.scm.impl.mock.MockSCMNavigator; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +import java.util.Collections; +import java.util.List; import static jenkins.branch.matchers.Extracting.extracting; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; + +@WithJenkins +class OrganizationChildOrphanedItemsPropertyTest { -public class OrganizationChildOrphanedItemsPropertyTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + /** + * All tests in this class only create items and do not affect other global configuration, thus we trade test + * execution time for the restriction on only touching items. + */ + private static JenkinsRule r; + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } - @Before - public void cleanOutAllItems() throws Exception { + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void configRoundTrip() throws Exception { + void configRoundTrip() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("stuff"); OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "top"); @@ -87,7 +101,7 @@ public void configRoundTrip() throws Exception { } @Test - public void given__orgFolder__when__created__then__property_is_same_as_folder() throws Exception { + void given__orgFolder__when__created__then__property_is_same_as_folder() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -103,7 +117,7 @@ public void given__orgFolder__when__created__then__property_is_same_as_folder() } @Test - public void given__orgFolder__when__scan__then__child_strategy_applied() throws Exception { + void given__orgFolder__when__scan__then__child_strategy_applied() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -126,7 +140,7 @@ public void given__orgFolder__when__scan__then__child_strategy_applied() throws } @Test - public void given__same_as_parent__when__scan__then__parent_strategy_applied() throws Exception { + void given__same_as_parent__when__scan__then__parent_strategy_applied() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -150,7 +164,7 @@ public void given__same_as_parent__when__scan__then__parent_strategy_applied() t } @Test - public void given__orgFolder_property_changed__when__scan__then_child_strategy_updated() throws Exception { + void given__orgFolder_property_changed__when__scan__then_child_strategy_updated() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); diff --git a/src/test/java/jenkins/branch/OrganizationChildTriggersPropertyTest.java b/src/test/java/jenkins/branch/OrganizationChildTriggersPropertyTest.java index 14f631cb..001475e6 100644 --- a/src/test/java/jenkins/branch/OrganizationChildTriggersPropertyTest.java +++ b/src/test/java/jenkins/branch/OrganizationChildTriggersPropertyTest.java @@ -32,10 +32,6 @@ import integration.harness.BasicMultiBranchProject; import integration.harness.BasicMultiBranchProjectFactory; import integration.harness.BasicSCMSourceCriteria; -import java.util.Collections; -import java.util.List; -import java.util.Map; - import jenkins.scm.impl.SingleSCMNavigator; import jenkins.scm.impl.SingleSCMSource; import jenkins.scm.impl.mock.MockSCM; @@ -44,29 +40,49 @@ import jenkins.scm.impl.mock.MockSCMHead; import jenkins.scm.impl.mock.MockSCMNavigator; import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +import java.util.Collections; +import java.util.List; +import java.util.Map; import static jenkins.branch.matchers.Extracting.extracting; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; + +@WithJenkins +class OrganizationChildTriggersPropertyTest { -public class OrganizationChildTriggersPropertyTest { - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + /** + * All tests in this class only create items and do not affect other global configuration, thus we trade test + * execution time for the restriction on only touching items. + */ + private static JenkinsRule r; + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } - @Before - public void cleanOutAllItems() throws Exception { + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void configRoundTrip() throws Exception { + void configRoundTrip() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("stuff"); OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "top"); @@ -89,7 +105,7 @@ public void configRoundTrip() throws Exception { } @Test - public void given__orgFolder__when__created__then__child_triggers_default_to_1d() throws Exception { + void given__orgFolder__when__created__then__child_triggers_default_to_1d() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -112,7 +128,7 @@ public void given__orgFolder__when__created__then__child_triggers_default_to_1d( } @Test - public void given__orgFolder__when__scan__then__child_triggers_applied() throws Exception { + void given__orgFolder__when__scan__then__child_triggers_applied() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); @@ -134,7 +150,7 @@ public void given__orgFolder__when__scan__then__child_triggers_applied() throws } @Test - public void given__orgFolder_property_changed__when__then__scan__child_triggers_updated() throws Exception { + void given__orgFolder_property_changed__when__then__scan__child_triggers_updated() throws Exception { try (MockSCMController c = MockSCMController.create()) { OrganizationFolder prj = r.jenkins.createProject(OrganizationFolder.class, "foo"); prj.getSCMNavigators().add(new MockSCMNavigator(c, new MockSCMDiscoverBranches())); diff --git a/src/test/java/jenkins/branch/OrganizationFolderTest.java b/src/test/java/jenkins/branch/OrganizationFolderTest.java index 789436d6..afe49719 100644 --- a/src/test/java/jenkins/branch/OrganizationFolderTest.java +++ b/src/test/java/jenkins/branch/OrganizationFolderTest.java @@ -39,14 +39,6 @@ import hudson.security.Permission; import integration.harness.BasicMultiBranchProject; import integration.harness.BasicMultiBranchProjectFactory; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; import jenkins.branch.harness.MultiBranchImpl; import jenkins.scm.api.SCMNavigator; import jenkins.scm.api.SCMSource; @@ -59,24 +51,41 @@ import jenkins.scm.impl.mock.MockSCMDiscoverTags; import jenkins.scm.impl.mock.MockSCMHead; import jenkins.scm.impl.mock.MockSCMNavigator; -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.LogRecorder; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.stapler.DataBoundConstructor; +import org.springframework.security.core.Authentication; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; import static jenkins.branch.matchers.Extracting.extracting; 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.assertTrue; -import static org.junit.Assume.assumeThat; -import org.jvnet.hudson.test.LoggerRule; -import org.springframework.security.core.Authentication; - -public class OrganizationFolderTest { +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +@WithJenkins +class OrganizationFolderTest { public static class OrganizationFolderBranchProperty extends ParameterDefinitionBranchProperty { @@ -94,14 +103,17 @@ protected boolean isApplicable(@NonNull MultiBranchProjectDescriptor projectDesc } } - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; - @Rule - public LoggerRule logging = new LoggerRule().record(ComputedFolder.class, Level.FINE).record(OrganizationFolder.class, Level.FINE); + private LogRecorder logging = new LogRecorder().record(ComputedFolder.class, Level.FINE).record(OrganizationFolder.class, Level.FINE); + + @BeforeEach + void setUp(JenkinsRule rule) { + r = rule; + } @Test - public void configRoundTrip() throws Exception { + void configRoundTrip() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("stuff"); OrganizationFolder top = r.jenkins.createProject(OrganizationFolder.class, "top"); @@ -124,7 +136,7 @@ public void configRoundTrip() throws Exception { @Issue("JENKINS-48837") @Test - public void verifyBranchPropertiesAppliedOnNewProjects() throws Exception { + void verifyBranchPropertiesAppliedOnNewProjects() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("stuff"); OrganizationFolder top = r.jenkins.createProject(OrganizationFolder.class, "top"); @@ -164,7 +176,7 @@ public void verifyBranchPropertiesAppliedOnNewProjects() throws Exception { @Test @Issue("JENKINS-31516") - public void indexChildrenOnOrganizationFolderIndex() throws Exception { + void indexChildrenOnOrganizationFolderIndex() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("stuff"); OrganizationFolder top = r.jenkins.createProject(OrganizationFolder.class, "top"); @@ -181,7 +193,7 @@ public void indexChildrenOnOrganizationFolderIndex() throws Exception { @Issue("JENKINS-32782") @Test - public void emptyViewEquality() throws Exception { + void emptyViewEquality() throws Exception { OrganizationFolder top = r.jenkins.createProject(OrganizationFolder.class, "top"); View emptyView = top.getPrimaryView(); assertEquals(BaseEmptyView.VIEW_NAME, emptyView.getViewName()); @@ -192,10 +204,10 @@ public void emptyViewEquality() throws Exception { @Issue("JENKINS-34246") @Test - public void deletedMarker() throws Exception { - assumeThat("TODO fails if jth.jenkins-war.path includes WorkflowMultiBranchProjectFactory since SingleSCMSource ignores SCMSourceCriteria", - ExtensionList.lookup(MultiBranchProjectFactoryDescriptor.class).stream().map(d -> d.clazz).toArray(), - arrayContainingInAnyOrder(MockFactory.class, BasicMultiBranchProjectFactory.class)); + void deletedMarker() throws Exception { + assumeTrue( + ExtensionList.lookup(MultiBranchProjectFactoryDescriptor.class).stream().map(d -> d.clazz).toList().containsAll(List.of(MockFactory.class, BasicMultiBranchProjectFactory.class)), + "TODO fails if jth.jenkins-war.path includes WorkflowMultiBranchProjectFactory since SingleSCMSource ignores SCMSourceCriteria"); OrganizationFolder top = r.jenkins.createProject(OrganizationFolder.class, "top"); List projectFactories = top.getProjectFactories(); assertThat(projectFactories, extracting(MultiBranchProjectFactory::getDescriptor, hasItem(ExtensionList.lookupSingleton(ConfigRoundTripDescriptor.class)))); @@ -218,19 +230,18 @@ public void deletedMarker() throws Exception { * When an OrganizationFolder is created and provided with no {@link MultiBranchProjectFactory} implementations, * it should automatically add the enabled-by-default factories for the current Jenkins instance * when {@link OrganizationFolder#onCreatedFromScratch()} is called. - * @throws IOException */ @Test - public void defaultFactoriesWhenNeeded() throws IOException { + void defaultFactoriesWhenNeeded() { // programmatically create an OrganizationFolder OrganizationFolder newbie = new OrganizationFolder( r.jenkins, "newbie" ); // it should have no factories assertEquals( - "A newly-created OrganizationFolder has no MultiBranchProjectFactories.", 0, - newbie.getProjectFactories().size() ); + newbie.getProjectFactories().size(), + "A newly-created OrganizationFolder has no MultiBranchProjectFactories." ); // these are all of the MultiBranchProjectFactory definitions. ExtensionList factory_descriptors = r.jenkins.getExtensionList( MultiBranchProjectFactoryDescriptor.class ); @@ -255,8 +266,8 @@ public void defaultFactoriesWhenNeeded() throws IOException { } assertTrue( - "After #onCreatedFromScratch(), the enabled-by-default MultiBranchProjectFactory [" + factory_descriptor.getDisplayName()+ "] is present in an OrganizationFolder created with no initial factories.", - default_factory_was_present ); + default_factory_was_present, + "After #onCreatedFromScratch(), the enabled-by-default MultiBranchProjectFactory [" + factory_descriptor.getDisplayName()+ "] is present in an OrganizationFolder created with no initial factories." ); } } @@ -278,8 +289,8 @@ public void defaultFactoriesWhenNeeded() throws IOException { } assertTrue( - "After #onCreatedFromScratch() with no initial project factories, the OrganizationFolder MultiBranchProjectFactory [" + org_factory.getDescriptor().getDisplayName()+ "] is one of the enabled-by-default factories.", - org_factory_is_default_factory ); + org_factory_is_default_factory, + "After #onCreatedFromScratch() with no initial project factories, the OrganizationFolder MultiBranchProjectFactory [" + org_factory.getDescriptor().getDisplayName()+ "] is one of the enabled-by-default factories." ); } } @@ -288,16 +299,16 @@ public void defaultFactoriesWhenNeeded() throws IOException { * it should not add any other factories when {@link OrganizationFolder#onCreatedFromScratch()} is called. */ @Test - public void noDefaultFactoriesWhenNotNeeded() { + void noDefaultFactoriesWhenNotNeeded() { // programmatically create an OrganizationFolder OrganizationFolder newbie = new OrganizationFolder( r.jenkins, "newbie" ); // it should have no factories assertEquals( - "A newly-created OrganizationFolder has no MultiBranchProjectFactories.", 0, - newbie.getProjectFactories().size() ); + newbie.getProjectFactories().size(), + "A newly-created OrganizationFolder has no MultiBranchProjectFactories." ); // set exactly one non-default factory newbie.getProjectFactories().clear(); @@ -308,33 +319,30 @@ public void noDefaultFactoriesWhenNotNeeded() { newbie.onCreatedFromScratch(); assertEquals( - "An OrganizationFolder created with a non-default project factory should only have one factory after onCreatedFromScratch()", 1, - newbie.getProjectFactories().size() ); + newbie.getProjectFactories().size(), + "An OrganizationFolder created with a non-default project factory should only have one factory after onCreatedFromScratch()" ); assertEquals( - "An OrganizationFolder created with a non-default project factory should only have that particular factory after onCreatedFromScratch()", mock_factory.getDescriptor(), - newbie.getProjectFactories().get( 0 ).getDescriptor() ) ; + newbie.getProjectFactories().get( 0 ).getDescriptor(), + "An OrganizationFolder created with a non-default project factory should only have that particular factory after onCreatedFromScratch()" ) ; } @Test - public void modifyAclsWhenInComputedFolder() throws IOException, InterruptedException { + void modifyAclsWhenInComputedFolder() { Set suppressed_permissions = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList( - Item.CONFIGURE, Item.DELETE, View.CONFIGURE, View.CREATE, View.DELETE))); + Set.of(Item.CONFIGURE, Item.DELETE, View.CONFIGURE, View.CREATE, View.DELETE); // we need a ComputedFolder to be the parent of our OrganizationFolder - ComputedFolder computed_folder = new ComputedFolder(r.jenkins, "top") { + ComputedFolder computed_folder = new ComputedFolder<>(r.jenkins, "top") { @Override protected void computeChildren( - ChildObserver observer, - TaskListener listener) - throws IOException, InterruptedException - { + ChildObserver observer, + TaskListener listener) { /* * We don't actually need to compute children during a unit test. * We just need an OrganizationFolder to have this ComputedFolder @@ -359,18 +367,17 @@ protected void computeChildren( for( Permission perm : suppressed_permissions ) { assertFalse( - "OrganizationFolders in ComputedFolders should suppress the [" + perm.getId() + "] permission.", - org_folder.getACL().hasPermission2( some_user, perm ) ); + org_folder.getACL().hasPermission2( some_user, perm ), + "OrganizationFolders in ComputedFolders should suppress the [" + perm.getId() + "] permission." ); } } @Test - public void modifyAclsWhenNotInComputedFolder() throws IOException { + void modifyAclsWhenNotInComputedFolder() throws IOException { Set suppressed_permissions = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList( - Item.CONFIGURE, Item.DELETE, View.CONFIGURE, View.CREATE, View.DELETE))); + Set.of(Item.CONFIGURE, Item.DELETE, View.CONFIGURE, View.CREATE, View.DELETE); OrganizationFolder top = r.jenkins.createProject(OrganizationFolder.class, "top"); @@ -382,8 +389,8 @@ public void modifyAclsWhenNotInComputedFolder() throws IOException { for( Permission perm : suppressed_permissions ) { assertTrue( - "Organization Folders in non-computed parents do not suppress the [" + perm.getId() + "] permission.", - top.getACL().hasPermission2( some_user, perm ) ); + top.getACL().hasPermission2( some_user, perm ), + "Organization Folders in non-computed parents do not suppress the [" + perm.getId() + "] permission." ); } } @@ -397,14 +404,14 @@ public MockFactory() {} static boolean live = true; @Override public boolean recognizes(@NonNull ItemGroup parent, @NonNull String name, @NonNull List scmSources, - @NonNull Map attributes, @NonNull TaskListener listener) throws IOException, InterruptedException { + @NonNull Map attributes, @NonNull TaskListener listener) { return live; } @NonNull @Override public MultiBranchProject createNewProject(@NonNull ItemGroup parent, @NonNull String name, @NonNull List scmSources, @NonNull Map attributes, - @NonNull TaskListener listener) throws IOException, InterruptedException { + @NonNull TaskListener listener) { return new MultiBranchImpl(parent, name); } } diff --git a/src/test/java/jenkins/branch/OverrideIndexTriggersJobPropertyTest.java b/src/test/java/jenkins/branch/OverrideIndexTriggersJobPropertyTest.java index 35471128..bb94b341 100644 --- a/src/test/java/jenkins/branch/OverrideIndexTriggersJobPropertyTest.java +++ b/src/test/java/jenkins/branch/OverrideIndexTriggersJobPropertyTest.java @@ -27,31 +27,41 @@ import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.queue.QueueTaskFuture; -import java.util.Collections; -import static jenkins.branch.NoTriggerBranchPropertyTest.showComputation; import jenkins.branch.harness.MultiBranchImpl; import jenkins.plugins.git.GitSCMSource; import jenkins.plugins.git.GitSampleRepoRule; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import jenkins.plugins.git.traits.BranchDiscoveryTrait; import jenkins.scm.impl.SingleSCMNavigator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -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.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +import java.util.Collections; -public class OverrideIndexTriggersJobPropertyTest { +import static jenkins.branch.NoTriggerBranchPropertyTest.showComputation; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@WithJenkins +@WithGitSampleRepo +class OverrideIndexTriggersJobPropertyTest { - @Rule - public JenkinsRule r = new JenkinsRule(); - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + private JenkinsRule r; + private GitSampleRepoRule sampleRepo; + + @BeforeEach + void setUp(JenkinsRule rule, GitSampleRepoRule repo) { + r = rule; + sampleRepo = repo; + } @Issue("JENKINS-37219") @Test - public void overridesDisabledBranch() throws Exception { + void overridesDisabledBranch() throws Exception { sampleRepo.init(); sampleRepo.git("checkout", "-b", "newfeature"); sampleRepo.write("stuff", "content"); @@ -106,14 +116,14 @@ public void overridesDisabledBranch() throws Exception { showComputation(stuff); FreeStyleBuild releaseBuild = release.getBuildByNumber(1); - assertNotNull("release branch build was not triggered by commit", releaseBuild); + assertNotNull(releaseBuild, "release branch build was not triggered by commit"); assertEquals(1, releaseBuild.getNumber()); assertEquals(2, release.getNextBuildNumber()); } @Issue("JENKINS-37219") @Test - public void overridesDisabledOrg() throws Exception { + void overridesDisabledOrg() throws Exception { sampleRepo.init(); sampleRepo.git("checkout", "-b", "newfeature"); sampleRepo.write("stuff", "content"); @@ -179,14 +189,14 @@ public void overridesDisabledOrg() throws Exception { showComputation(stuff); FreeStyleBuild releaseBuild = release.getBuildByNumber(1); - assertNotNull("release branch build was not triggered by commit", releaseBuild); + assertNotNull(releaseBuild, "release branch build was not triggered by commit"); assertEquals(1, releaseBuild.getNumber()); assertEquals(2, release.getNextBuildNumber()); } @Issue("JENKINS-37219") @Test - public void overridesEnabled() throws Exception { + void overridesEnabled() throws Exception { sampleRepo.init(); sampleRepo.write("stuff", "content"); sampleRepo.git("add", "stuff"); @@ -214,7 +224,7 @@ public void overridesEnabled() throws Exception { QueueTaskFuture masterBuild = master.scheduleBuild2(0); - assertNotNull("was not able to schedule a manual build of the master branch", masterBuild); + assertNotNull(masterBuild, "was not able to schedule a manual build of the master branch"); assertEquals(2, masterBuild.get().getNumber()); assertEquals(3, master.getNextBuildNumber()); } diff --git a/src/test/java/jenkins/branch/ParameterDefinitionBranchPropertyTest.java b/src/test/java/jenkins/branch/ParameterDefinitionBranchPropertyTest.java index bbf85d5c..66626f97 100644 --- a/src/test/java/jenkins/branch/ParameterDefinitionBranchPropertyTest.java +++ b/src/test/java/jenkins/branch/ParameterDefinitionBranchPropertyTest.java @@ -34,43 +34,56 @@ import hudson.util.VersionNumber; import integration.harness.BasicDummyStepBranchProperty; import integration.harness.BasicMultiBranchProject; -import java.util.Arrays; -import java.util.Collections; - import jenkins.model.Jenkins; import jenkins.model.ParameterizedJobMixIn; import jenkins.scm.impl.mock.MockSCMController; import jenkins.scm.impl.mock.MockSCMDiscoverBranches; import jenkins.scm.impl.mock.MockSCMSource; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; 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 java.util.Arrays; +import java.util.Collections; + import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assume.assumeThat; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +@WithJenkins +class ParameterDefinitionBranchPropertyTest { -public class ParameterDefinitionBranchPropertyTest { /** * All tests in this class only create items and do not affect other global configuration, thus we trade test * execution time for the restriction on only touching items. */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } - @Before - public void cleanOutAllItems() throws Exception { + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void getSetParameterDefinitions() throws Exception { + void getSetParameterDefinitions() { ParameterDefinitionBranchPropertyImpl instance = new ParameterDefinitionBranchPropertyImpl(); instance.setParameterDefinitions(Collections.singletonList( new StringParameterDefinition("PARAM_STR", "PARAM_DEFAULT_0812673", "The param") @@ -87,14 +100,14 @@ public void getSetParameterDefinitions() throws Exception { } @Test - public void isApplicable_Job() throws Exception { + void isApplicable_Job() { assertThat("Jobs are not parameterized", new ParameterDefinitionBranchPropertyImpl().isApplicable((Class) Job.class), is(false)); } @Test - public void isApplicable_Job_implementing_ParameterizedJob() throws Exception { + void isApplicable_Job_implementing_ParameterizedJob() { assertThat("Parameterized Jobs are are Applicable", new ParameterDefinitionBranchPropertyImpl().isApplicable((Class) ParamJob.class), is(true)); @@ -107,19 +120,19 @@ protected ParamJob(ItemGroup parent, String name) { } @Test - public void jobDecorator_Job() throws Exception { + void jobDecorator_Job() { assertThat(new ParameterDefinitionBranchPropertyImpl().jobDecorator((Class) Job.class), nullValue()); } @Test - public void jobDecorator_Job_implementing_ParameterizedJob() throws Exception { + void jobDecorator_Job_implementing_ParameterizedJob() { assertThat(new ParameterDefinitionBranchPropertyImpl().jobDecorator((Class) ParamJob.class), notNullValue()); } @Issue("JENKINS-61438") @Test - public void choiceParameterIssue() throws Exception { - assumeThat(Jenkins.getVersion(), greaterThanOrEqualTo(new VersionNumber("2.242"))); + void choiceParameterIssue() throws Exception { + assumeTrue(Jenkins.getVersion().isNewerThanOrEqualTo(new VersionNumber("2.242"))); try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -149,8 +162,9 @@ instance, new BasicDummyStepBranchProperty() )); } } + @Test - public void configRoundtrip() throws Exception { + void configRoundtrip() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -182,7 +196,7 @@ instance, new BasicDummyStepBranchProperty() } @Test - public void parametersAreConfiguredOnBranchJobs() throws Exception { + void parametersAreConfiguredOnBranchJobs() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); diff --git a/src/test/java/jenkins/branch/PrimaryBranchHealthMetricTest.java b/src/test/java/jenkins/branch/PrimaryBranchHealthMetricTest.java index e7896ae4..72465568 100644 --- a/src/test/java/jenkins/branch/PrimaryBranchHealthMetricTest.java +++ b/src/test/java/jenkins/branch/PrimaryBranchHealthMetricTest.java @@ -3,16 +3,16 @@ import hudson.model.FreeStyleProject; import hudson.model.TopLevelItem; import integration.harness.HealthReportingMultiBranchProject; - -import java.util.Collections; - import jenkins.scm.impl.mock.MockSCMController; import jenkins.scm.impl.mock.MockSCMDiscoverBranches; import jenkins.scm.impl.mock.MockSCMSource; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + +import java.util.Collections; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -23,20 +23,29 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -public class PrimaryBranchHealthMetricTest { +@WithJenkins +class PrimaryBranchHealthMetricTest { + + /** + * All tests in this class only create items and do not affect other global configuration, thus we trade test + * execution time for the restriction on only touching items. + */ + private static JenkinsRule r; - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } - @Before - public void cleanOutAllItems() throws Exception { + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void given__multibranch_without_primary__when__reporting_health__then__empty() throws Exception { + void given__multibranch_without_primary__when__reporting_health__then__empty() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "stable"); @@ -52,7 +61,7 @@ public void given__multibranch_without_primary__when__reporting_health__then__em } @Test - public void given__multibranch_with_primary__when__reporting_health__then__primary_health() throws Exception { + void given__multibranch_with_primary__when__reporting_health__then__primary_health() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "stable"); @@ -74,7 +83,7 @@ public void given__multibranch_with_primary__when__reporting_health__then__prima } @Test - public void given__multibranch_with_primary__when__reporting_health__then__non_empty() throws Exception { + void given__multibranch_with_primary__when__reporting_health__then__non_empty() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); c.createBranch("foo", "stable"); diff --git a/src/test/java/jenkins/branch/ProjectNamingStrategyTest.java b/src/test/java/jenkins/branch/ProjectNamingStrategyTest.java index bfd4298b..2af4fcdb 100644 --- a/src/test/java/jenkins/branch/ProjectNamingStrategyTest.java +++ b/src/test/java/jenkins/branch/ProjectNamingStrategyTest.java @@ -9,10 +9,11 @@ import jenkins.scm.impl.mock.MockSCMDiscoverBranches; import jenkins.scm.impl.mock.MockSCMDiscoverChangeRequests; import jenkins.scm.impl.mock.MockSCMSource; -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.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -22,27 +23,38 @@ * multi-branch jobs via {@link MultiBranchProjectDisplayNamingTrait} are used to set the display name of change * request jobs inside the multi-branch project. */ -public class ProjectNamingStrategyTest { - @ClassRule - public static final JenkinsRule r = new JenkinsRule(); +@WithJenkins +class ProjectNamingStrategyTest { + + /** + * All tests in this class only create items and do not affect other global configuration, thus we trade test + * execution time for the restriction on only touching items. + */ + private static JenkinsRule r; public static final String REPO_NAME = "MyRepo"; + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } + @Test @Issue("JENKINS-55348") - public void testCompositeStrategy() throws Exception { + void testCompositeStrategy() throws Exception { testNamingStrategy(MultiBranchProjectDisplayNamingStrategy.RAW_AND_OBJECT_DISPLAY_NAME); } @Test @Issue("JENKINS-74811") - public void testRawStrategy() throws Exception { + void testRawStrategy() throws Exception { testNamingStrategy(MultiBranchProjectDisplayNamingStrategy.RAW); } @Test @Issue("JENKINS-55348") - public void testObjectNameStrategy() throws Exception { + void testObjectNameStrategy() throws Exception { testNamingStrategy(MultiBranchProjectDisplayNamingStrategy.OBJECT_DISPLAY_NAME); } diff --git a/src/test/java/jenkins/branch/RateLimitBranchPropertyTest.java b/src/test/java/jenkins/branch/RateLimitBranchPropertyTest.java index 67c4611a..51f363d6 100644 --- a/src/test/java/jenkins/branch/RateLimitBranchPropertyTest.java +++ b/src/test/java/jenkins/branch/RateLimitBranchPropertyTest.java @@ -39,38 +39,39 @@ import hudson.model.queue.QueueTaskFuture; import hudson.util.ListBoxModel; import integration.harness.BasicMultiBranchProject; +import jenkins.scm.impl.mock.MockSCMController; +import jenkins.scm.impl.mock.MockSCMDiscoverBranches; +import jenkins.scm.impl.mock.MockSCMSource; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.LogRecorder; +import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; + import java.io.IOException; import java.util.Collections; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; -import jenkins.scm.impl.mock.MockSCMController; -import jenkins.scm.impl.mock.MockSCMDiscoverBranches; -import jenkins.scm.impl.mock.MockSCMSource; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsRule; -import org.jvnet.hudson.test.LoggerRule; -import org.jvnet.hudson.test.TestExtension; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThanOrEqualTo; 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.Assume.assumeThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; -public class RateLimitBranchPropertyTest { +@WithJenkins +class RateLimitBranchPropertyTest { /** * How long to wait for a build that we expect will start. (Shouldn't affect test execution time) */ @@ -84,42 +85,46 @@ public class RateLimitBranchPropertyTest { * All tests in this class only create items and do not affect other global configuration, thus we trade test * execution time for the restriction on only touching items. */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; - @ClassRule - public static LoggerRule loggerRule = new LoggerRule().record(RateLimitBranchProperty.class, Level.FINE); + private static LogRecorder logging = new LogRecorder().record(RateLimitBranchProperty.class, Level.FINE); /** * Our logger. */ private static Logger LOGGER = Logger.getLogger(RateLimitBranchPropertyTest.class.getName()); - @Before - public void cleanOutAllItems() throws Exception { + + @BeforeAll + static void setUp(JenkinsRule rule) { + r = rule; + } + + @BeforeEach + void setUp() throws Exception { for (TopLevelItem i : r.getInstance().getItems()) { i.delete(); } } @Test - public void getCount() throws Exception { + void getCount() { for (int i = 1; i < 1001; i++) { assertThat(new RateLimitBranchProperty(i, "hour", false).getCount(), is(i)); } } @Test - public void getCount_lowerBound() throws Exception { + void getCount_lowerBound() { assertThat(new RateLimitBranchProperty(0, "hour", false).getCount(), is(1)); } @Test - public void getCount_upperBound() throws Exception { + void getCount_upperBound() { assertThat(new RateLimitBranchProperty(1001, "hour", false).getCount(), is(1000)); } @Test - public void getDurationName() throws Exception { + void getDurationName() { assertThat(new RateLimitBranchProperty(10, "hour", false).getDurationName(), is("hour")); assertThat(new RateLimitBranchProperty(10, "year", false).getDurationName(), is("year")); assertThat(new RateLimitBranchProperty(10, "minute", false).getDurationName(), is("minute")); @@ -127,18 +132,18 @@ public void getDurationName() throws Exception { } @Test - public void checkDurationNameExists() throws Exception { + void checkDurationNameExists() { ListBoxModel items = r.jenkins.getDescriptorByType(RateLimitBranchProperty.JobPropertyImpl.DescriptorImpl.class).doFillDurationNameItems(); - assertEquals(items.size(), 7); + assertEquals(7, items.size()); } @Test - public void rateLimitsBlockBuilds_maxRate() throws Exception { + void rateLimitsBlockBuilds_maxRate() throws Exception { rateLimitsBlockBuilds(1000); } @Test - public void rateLimitsBlockBuilds_medRate() throws Exception { + void rateLimitsBlockBuilds_medRate() throws Exception { rateLimitsBlockBuilds(500); } @@ -203,19 +208,17 @@ private void rateLimitsBlockBuilds(int rate) throws Exception { // it can take more than the requested delay... that's ok, but it should not be // more than 500ms longer (i.e. 5 of our Queue.maintain loops above) final long delay = (long)(60.f * 60.f / rate * 1000); - assumeThat("At least the rate implied delay but no more than 500ms longer", - System.currentTimeMillis() - startTime, - allOf( - greaterThanOrEqualTo(delay - 200L), - lessThanOrEqualTo(delay + 500L) - ) + assumeTrue( + System.currentTimeMillis() - startTime >= delay - 200L + && System.currentTimeMillis() - startTime <= delay + 500L, + "At least the rate implied delay but no more than 500ms longer" ); future.get(); } } @Test - public void rateLimitsConcurrentBuilds() throws Exception { + void rateLimitsConcurrentBuilds() throws Exception { int rate = 1000; try (final MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); @@ -294,12 +297,10 @@ public void rateLimitsConcurrentBuilds() throws Exception { // it can take more than the requested delay... that's ok, but it should not be // more than 500ms longer (i.e. 5 of our Queue.maintain loops above) final long delay = (long)(60.f * 60.f / rate * 1000); - assumeThat("At least the rate implied delay but no more than 500ms longer", - secondBuild.getStartTimeInMillis() - firstBuild.getStartTimeInMillis(), - allOf( - greaterThanOrEqualTo(delay - 200L), - lessThanOrEqualTo(delay + 500L) - ) + assumeTrue( + secondBuild.getStartTimeInMillis() - firstBuild.getStartTimeInMillis() >= delay - 200L + && secondBuild.getStartTimeInMillis() - firstBuild.getStartTimeInMillis() <= delay + 500L, + "At least the rate implied delay but no more than 500ms longer" ); future.get(); } @@ -307,7 +308,7 @@ public void rateLimitsConcurrentBuilds() throws Exception { } @Test - public void rateLimitsUserBoost() throws Exception { + void rateLimitsUserBoost() throws Exception { try (final MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); @@ -405,7 +406,7 @@ public void rateLimitsUserBoost() throws Exception { } @Test - public void configRoundtrip() throws Exception { + void configRoundtrip() throws Exception { try (MockSCMController c = MockSCMController.create()) { c.createRepository("foo"); BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo"); diff --git a/src/test/java/jenkins/branch/WorkspaceLocatorImplTest.java b/src/test/java/jenkins/branch/WorkspaceLocatorImplTest.java index e8ee8a3b..59078f7f 100644 --- a/src/test/java/jenkins/branch/WorkspaceLocatorImplTest.java +++ b/src/test/java/jenkins/branch/WorkspaceLocatorImplTest.java @@ -29,60 +29,76 @@ import hudson.scm.NullSCM; import hudson.slaves.DumbSlave; import hudson.slaves.WorkspaceList; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.Collections; -import java.util.logging.Level; -import java.util.stream.Collectors; -import static jenkins.branch.NoTriggerBranchPropertyTest.showComputation; +import hudson.util.ReflectionUtils; import jenkins.branch.harness.MultiBranchImpl; import jenkins.model.Jenkins; import jenkins.scm.impl.SingleSCMSource; -import org.junit.After; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.BuildWatcher; 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.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class WorkspaceLocatorImplTest { +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.logging.Level; + +import static jenkins.branch.NoTriggerBranchPropertyTest.showComputation; +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; - @ClassRule - public static BuildWatcher buildWatcher = new BuildWatcher(); - @Rule - public JenkinsRule r = new JenkinsRule(); - @Rule - public LoggerRule logging = new LoggerRule().record(WorkspaceLocatorImpl.class, Level.FINER); - @Rule - public TemporaryFolder tmp = new TemporaryFolder(); +@WithJenkins +class WorkspaceLocatorImplTest { + + private static BuildWatcher buildWatcher = new BuildWatcher(); + + private JenkinsRule r; + private LogRecorder logging = new LogRecorder().record(WorkspaceLocatorImpl.class, Level.FINER); + @TempDir + private File tmp; + + private WorkspaceLocatorImpl.Mode origMode; @SuppressWarnings("deprecation") - @Before - public void defaultPathMax() { + @BeforeEach + void setUp(JenkinsRule rule) { + r = rule; WorkspaceLocatorImpl.PATH_MAX = WorkspaceLocatorImpl.PATH_MAX_DEFAULT; - } - - WorkspaceLocatorImpl.Mode origMode; - @Before - public void saveMode() { origMode = WorkspaceLocatorImpl.MODE; + + Method before = ReflectionUtils.findMethod(BuildWatcher.class, "before"); + ReflectionUtils.makeAccessible(before); + ReflectionUtils.invokeMethod(before, buildWatcher); } - @After - public void restoreMode() { + + @AfterEach + void restoreMode() { WorkspaceLocatorImpl.MODE = origMode; } + @AfterAll + static void tearDown() { + Method after = ReflectionUtils.findMethod(BuildWatcher.class, "after"); + ReflectionUtils.makeAccessible(after); + ReflectionUtils.invokeMethod(after, buildWatcher); + } + @WithoutJenkins @SuppressWarnings("deprecation") @Test - public void minimize() { + void minimize() { assertEquals("a_b-NX345YSMOYT4QUL4OO7V6EGKM57BBNSYVIXGXHCE4KAEVPV5KZYQ", WorkspaceLocatorImpl.minimize("a/b")); assertEquals("a_b_c_d-UMWYJ45JQ6FA3WXMSI3YEOLVQ5P6SFYWN26FRECRSFBUGUD27Y5A", WorkspaceLocatorImpl.minimize("a/b/c/d")); assertEquals("stuff_dev_flow-L5GKER67QGVMJ2UD3JCSGKEV2ACON2O4VO4RNUZ27HGUY32SYVXQ", WorkspaceLocatorImpl.minimize("stuff/dev%2Fflow")); @@ -96,7 +112,7 @@ public void minimize() { assertEquals("lahblahblahblahblahblahXYZW-LRVIZHY37BWI3PKRF7WSERGRN3NGPY4T74VWKWNFRMR4IWGXJPQA", WorkspaceLocatorImpl.minimize("blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahXYZW")); assertEquals("ahblahblahblahblahblahXYZWV-KLYOGWEJODAVXII3MEM2SLNMRPE7HF6IADTBQ5MP66V3RYCL2LAA", WorkspaceLocatorImpl.minimize("blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahXYZWV")); assertEquals("hblahblahblahblahblahXYZWVU-OSF24EPB4C42KAUXYHPP66XDQHOHKWPHGKZLIWREKOGZDZ46T2PQ", WorkspaceLocatorImpl.minimize("blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahXYZWVU")); - + WorkspaceLocatorImpl.PATH_MAX = 40; assertEquals("a_b-NX345YSMOYT4QUL4OO7V6EGKM", WorkspaceLocatorImpl.minimize("a/b")); assertEquals("a_b_c_d-UMWYJ45JQ6FA3WXMSI3YEOLVQ", WorkspaceLocatorImpl.minimize("a/b/c/d")); @@ -111,7 +127,7 @@ public void minimize() { assertEquals("ahblahblahXYZW-LRVIZHY37BWI3PKRF7WSERGRN", WorkspaceLocatorImpl.minimize("blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahXYZW")); assertEquals("hblahblahXYZWV-KLYOGWEJODAVXII3MEM2SLNMR", WorkspaceLocatorImpl.minimize("blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahXYZWV")); assertEquals("blahblahXYZWVU-OSF24EPB4C42KAUXYHPP66XDQ", WorkspaceLocatorImpl.minimize("blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahXYZWVU")); - + WorkspaceLocatorImpl.PATH_MAX = 20; assertEquals("a_b-NX345YSMOYT4QUL", WorkspaceLocatorImpl.minimize("a/b")); assertEquals("_c_d-UMWYJ45JQ6FA3WX", WorkspaceLocatorImpl.minimize("a/b/c/d")); @@ -126,7 +142,7 @@ public void minimize() { assertEquals("XYZW-LRVIZHY37BWI3PK", WorkspaceLocatorImpl.minimize("blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahXYZW")); assertEquals("YZWV-KLYOGWEJODAVXII", WorkspaceLocatorImpl.minimize("blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahXYZWV")); assertEquals("ZWVU-OSF24EPB4C42KAU", WorkspaceLocatorImpl.minimize("blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahXYZWVU")); - + WorkspaceLocatorImpl.PATH_MAX = 1; assertEquals("b-NX345YSMOY", WorkspaceLocatorImpl.minimize("a/b")); assertEquals("d-UMWYJ45JQ6", WorkspaceLocatorImpl.minimize("a/b/c/d")); @@ -145,7 +161,7 @@ public void minimize() { @Issue({"JENKINS-34564", "JENKINS-38837", "JENKINS-2111"}) @Test - public void locate() throws Exception { + void locate() throws Exception { assertEquals("${JENKINS_HOME}/workspace/${ITEM_FULL_NAME}", r.jenkins.getRawWorkspaceDir()); MultiBranchImpl stuff = r.createProject(MultiBranchImpl.class, "stuff"); stuff.getSourcesList().add(new BranchSource(new SingleSCMSource("dev/flow", new NullSCM()))); @@ -164,15 +180,15 @@ public void locate() throws Exception { workspaceDir.setAccessible(true); // Poor historical default, and as per JENKINS-21942 even possible after some startup scenarios: workspaceDir.set(r.jenkins, "${ITEM_ROOTDIR}/workspace"); - assertEquals("JENKINS-34564 inactive in this case", new FilePath(master.getRootDir()).child("workspace"), r.jenkins.getWorkspaceFor(master)); + assertEquals(new FilePath(master.getRootDir()).child("workspace"), r.jenkins.getWorkspaceFor(master), "JENKINS-34564 inactive in this case"); // JENKINS-38837: customized root. workspaceDir.set(r.jenkins, "${JENKINS_HOME}/ws/${ITEM_FULLNAME}"); - assertEquals("ITEM_FULLNAME interpreted a little differently", r.jenkins.getRootPath().child("ws/stuff_dev_flow"), r.jenkins.getWorkspaceFor(master)); + assertEquals(r.jenkins.getRootPath().child("ws/stuff_dev_flow"), r.jenkins.getWorkspaceFor(master), "ITEM_FULLNAME interpreted a little differently"); } @Issue({"JENKINS-2111", "JENKINS-41068"}) @Test - public void delete() throws Exception { + void delete() throws Exception { MultiBranchImpl p = r.createProject(MultiBranchImpl.class, "p"); p.getSourcesList().add(new BranchSource(new SingleSCMSource("master", new NullSCM()))); BranchSource pr1Source = new BranchSource(new SingleSCMSource("PR-1", new NullSCM())); @@ -214,13 +230,13 @@ public void delete() throws Exception { @Issue("JENKINS-2111") @Test - public void deleteOffline() throws Exception { + void deleteOffline() throws Exception { WorkspaceLocatorImpl.MODE = WorkspaceLocatorImpl.Mode.ENABLED; FreeStyleProject p = r.createFreeStyleProject("a'b"); DumbSlave s = r.createSlave("remote", null, null); p.setAssignedNode(s); assertEquals(s, r.buildAndAssertSuccess(p).getBuiltOn()); - assertEquals(Collections.singletonList("a_b"), s.getWorkspaceRoot().listDirectories().stream().map(FilePath::getName).collect(Collectors.toList())); + assertEquals(Collections.singletonList("a_b"), s.getWorkspaceRoot().listDirectories().stream().map(FilePath::getName).toList()); s.getWorkspaceRoot().child(WorkspaceLocatorImpl.INDEX_FILE_NAME).copyTo(System.out); s.toComputer().disconnect(null); p.delete(); @@ -236,7 +252,7 @@ public void deleteOffline() throws Exception { @Issue({"JENKINS-2111", "JENKINS-58177"}) @Test - public void uniquification() throws Exception { + void uniquification() throws Exception { WorkspaceLocatorImpl.MODE = WorkspaceLocatorImpl.Mode.ENABLED; assertEquals("a_b", r.buildAndAssertSuccess(r.createFreeStyleProject("a'b")).getWorkspace().getName()); assertEquals("a_b_2", r.buildAndAssertSuccess(r.createFreeStyleProject("a(b")).getWorkspace().getName()); @@ -249,18 +265,18 @@ public void uniquification() throws Exception { @Issue("JENKINS-2111") @Test - public void move() throws Exception { + void move() throws Exception { WorkspaceLocatorImpl.MODE = WorkspaceLocatorImpl.Mode.ENABLED; FreeStyleProject p = r.createFreeStyleProject("old"); DumbSlave s = r.createSlave("remote", null, null); p.setAssignedNode(s); FilePath workspace = r.buildAndAssertSuccess(p).getWorkspace(); assertEquals("old", workspace.getName()); - assertEquals(Collections.singletonList("old"), s.getWorkspaceRoot().listDirectories().stream().map(FilePath::getName).collect(Collectors.toList())); + assertEquals(Collections.singletonList("old"), s.getWorkspaceRoot().listDirectories().stream().map(FilePath::getName).toList()); workspace.child("something").write("", null); p.renameTo("new"); WorkspaceLocatorImpl.Deleter.waitForTasksToFinish(); - assertEquals(Collections.singletonList("new"), s.getWorkspaceRoot().listDirectories().stream().map(FilePath::getName).collect(Collectors.toList())); + assertEquals(Collections.singletonList("new"), s.getWorkspaceRoot().listDirectories().stream().map(FilePath::getName).toList()); workspace = r.buildAndAssertSuccess(p).getWorkspace(); assertEquals("new", workspace.getName()); assertTrue(workspace.child("something").exists()); @@ -271,7 +287,7 @@ public void move() throws Exception { @Issue("JENKINS-54640") @Test - public void collisions() throws Exception { + void collisions() throws Exception { WorkspaceLocatorImpl.MODE = WorkspaceLocatorImpl.Mode.ENABLED; FilePath firstWs = r.buildAndAssertSuccess(r.createFreeStyleProject("first-project-with-a-rather-long-name")).getWorkspace(); assertEquals("_project-with-a-rather-long-name", firstWs.getName()); @@ -281,20 +297,20 @@ public void collisions() throws Exception { @Issue({"JENKINS-54654", "JENKINS-54968"}) @Test - public void getWorkspaceRoot() throws Exception { - File top = tmp.getRoot(); + void getWorkspaceRoot() throws Exception { + File top = tmp; Field workspaceDir = Jenkins.class.getDeclaredField("workspaceDir"); workspaceDir.setAccessible(true); workspaceDir.set(r.jenkins, "${ITEM_ROOTDIR}/workspace"); - assertNull("old default", WorkspaceLocatorImpl.getWorkspaceRoot(r.jenkins)); + assertNull(WorkspaceLocatorImpl.getWorkspaceRoot(r.jenkins), "old default"); workspaceDir.set(r.jenkins, "${JENKINS_HOME}/workspace/${ITEM_FULL_NAME}"); - assertEquals("new default", r.jenkins.getRootPath().child("workspace"), WorkspaceLocatorImpl.getWorkspaceRoot(r.jenkins)); + assertEquals(r.jenkins.getRootPath().child("workspace"), WorkspaceLocatorImpl.getWorkspaceRoot(r.jenkins), "new default"); workspaceDir.set(r.jenkins, "${JENKINS_HOME}/somewhere/else/${ITEM_FULLNAME}"); - assertEquals("something else using ${JENKINS_HOME} and also deprecated ${ITEM_FULLNAME}", r.jenkins.getRootPath().child("somewhere/else"), WorkspaceLocatorImpl.getWorkspaceRoot(r.jenkins)); + assertEquals(r.jenkins.getRootPath().child("somewhere/else"), WorkspaceLocatorImpl.getWorkspaceRoot(r.jenkins), "something else using ${JENKINS_HOME} and also deprecated ${ITEM_FULLNAME}"); workspaceDir.set(r.jenkins, top + File.separator + "${ITEM_FULL_NAME}"); - assertEquals("different location altogether", new FilePath(top), WorkspaceLocatorImpl.getWorkspaceRoot(r.jenkins)); + assertEquals(new FilePath(top), WorkspaceLocatorImpl.getWorkspaceRoot(r.jenkins), "different location altogether"); workspaceDir.set(r.jenkins, top + File.separator + "${ITEM_FULL_NAME}" + File.separator); - assertEquals("different location altogether (with slash)", new FilePath(top), WorkspaceLocatorImpl.getWorkspaceRoot(r.jenkins)); + assertEquals(new FilePath(top), WorkspaceLocatorImpl.getWorkspaceRoot(r.jenkins), "different location altogether (with slash)"); } } diff --git a/src/test/java/jenkins/branch/matchers/Extracting.java b/src/test/java/jenkins/branch/matchers/Extracting.java index 06ea4dd1..81ad0ab9 100644 --- a/src/test/java/jenkins/branch/matchers/Extracting.java +++ b/src/test/java/jenkins/branch/matchers/Extracting.java @@ -5,7 +5,6 @@ import org.hamcrest.TypeSafeDiagnosingMatcher; import java.util.function.Function; -import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class Extracting extends TypeSafeDiagnosingMatcher> { @@ -22,7 +21,7 @@ private Extracting(Function extractor, Matcher nex protected boolean matchesSafely(Iterable inColl, Description mismatchDescription) { final Iterable collection = StreamSupport.stream(inColl.spliterator(), false) .map(extractor) - .collect(Collectors.toList()); + .toList(); final boolean matches = nextMatcher.matches(collection); diff --git a/src/test/java/jenkins/branch/matchers/ExtractingTest.java b/src/test/java/jenkins/branch/matchers/ExtractingTest.java index 2e63628f..064bce6d 100644 --- a/src/test/java/jenkins/branch/matchers/ExtractingTest.java +++ b/src/test/java/jenkins/branch/matchers/ExtractingTest.java @@ -1,32 +1,35 @@ package jenkins.branch.matchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import static jenkins.branch.matchers.Extracting.extracting; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; -public class ExtractingTest { +class ExtractingTest { @Test - public void shouldExtractNothingFromEmptyIterable() { + void shouldExtractNothingFromEmptyIterable() { final Iterable data = Collections.emptyList(); assertThat(data, extracting(Tuple::getFoo, is(empty()))); } @Test - public void shouldExtractProperty() { + void shouldExtractProperty() { final Iterable data = Arrays.asList(tuple("a",1), tuple("b", 2)); assertThat(data, extracting(Tuple::getFoo, hasItem("a"))); } @Test - public void shouldExtractPropertyFromMultipleObjects() { + void shouldExtractPropertyFromMultipleObjects() { final Iterable data = Arrays.asList(tuple("a",1), tuple("b", 2)); assertThat(data, extracting(Tuple::getFoo, hasItems("a", "b"))); @@ -34,7 +37,7 @@ public void shouldExtractPropertyFromMultipleObjects() { } @Test - public void shouldSupportPartialMatchers() { + void shouldSupportPartialMatchers() { final Iterable data = Arrays.asList(tuple("a",1), tuple("b", 2), tuple("c", 3)); assertThat(data, extracting(Tuple::getFoo, hasItems("a", "c")));