From 70b6e22317762faff41336bf377acb5b5093d449 Mon Sep 17 00:00:00 2001 From: strangelookingnerd <49242855+strangelookingnerd@users.noreply.github.com> Date: Wed, 1 Oct 2025 14:16:29 +0200 Subject: [PATCH] Migrate tests to JUnit5 * Migrate annotations and imports * Migrate assertions * Remove public visibility for test classes and methods * Minor code cleanup --- pom.xml | 7 + .../AbstractGitHubWireMockTest.java | 59 +- .../ApiRateLimitCheckerTest.java | 84 ++- .../BranchDiscoveryTraitTest.java | 64 +- ...DefaultGitHubNotificationStrategyTest.java | 26 +- .../github_branch_source/EndpointTest.java | 66 +- .../github_branch_source/EventsTest.java | 83 +-- .../ForkPullRequestDiscoveryTrait2Test.java | 40 +- .../ForkPullRequestDiscoveryTraitTest.java | 65 +- ...ubAppCredentialsContextualizationTest.java | 14 +- ...bAppCredentialsJCasCCompatibilityTest.java | 31 +- ...ubBranchSourcesJCasCCompatibilityTest.java | 12 +- .../GitHubNotificationTest.java | 35 +- .../GitHubOrgWebHookTest.java | 41 +- .../GitHubSCMBuilderTest.java | 618 +++++++++++------- .../GitHubSCMFileSystemTest.java | 173 +++-- .../GitHubSCMNavigatorTest.java | 84 +-- .../GitHubSCMNavigatorTraitsTest.java | 233 +++---- .../GitHubSCMProbeTest.java | 66 +- .../GitHubSCMSourceHelperTest.java | 10 +- .../GitHubSCMSourceTest.java | 146 ++--- .../GitHubSCMSourceTraitsTest.java | 218 +++--- .../GitSCMSourceBase.java | 21 +- ...ppCredentialsAppInstallationTokenTest.java | 9 +- .../GithubAppCredentialsTest.java | 60 +- .../GithubSCMSourceBranchesTest.java | 49 +- .../GithubSCMSourcePRsTest.java | 58 +- .../GithubSCMSourceTagsTest.java | 113 ++-- ...IgnoreDraftPullRequestFilterTraitTest.java | 13 +- .../OriginPullRequestDiscoveryTraitTest.java | 75 +-- .../PullRequestSCMRevisionTest.java | 88 +-- .../SSHCheckoutTraitTest.java | 44 +- .../TagDiscoveryTraitTest.java | 27 +- ...ory.java => WireMockExtensionFactory.java} | 35 +- .../AccessInferredOwnerTest.java | 8 +- .../AccessInferredRepositoryTest.java | 15 +- .../AccessSpecifiedRepositoriesTest.java | 8 +- .../MigrationAdminMonitorTest.java | 20 +- .../RunWithCredentialsTest.java | 63 +- 39 files changed, 1499 insertions(+), 1382 deletions(-) rename src/test/java/org/jenkinsci/plugins/github_branch_source/{WireMockRuleFactory.java => WireMockExtensionFactory.java} (60%) diff --git a/pom.xml b/pom.xml index 357a97b38..6381f627a 100644 --- a/pom.xml +++ b/pom.xml @@ -37,6 +37,7 @@ 2.504 ${jenkins.baseline}.1 false + false @@ -135,6 +136,12 @@ workflow-multibranch test + + org.junit-pioneer + junit-pioneer + 2.3.0 + test + org.mockito mockito-core diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/AbstractGitHubWireMockTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/AbstractGitHubWireMockTest.java index f4636fa52..a48cada70 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/AbstractGitHubWireMockTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/AbstractGitHubWireMockTest.java @@ -1,42 +1,40 @@ package org.jenkinsci.plugins.github_branch_source; import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import com.github.tomakehurst.wiremock.common.FileSource; -import com.github.tomakehurst.wiremock.common.SingleRootFileSource; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.extension.Parameters; import com.github.tomakehurst.wiremock.extension.ResponseTransformer; import com.github.tomakehurst.wiremock.http.Request; import com.github.tomakehurst.wiremock.http.Response; -import com.github.tomakehurst.wiremock.junit.WireMockRule; -import java.io.File; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** @author Liam Newman */ +@WithJenkins public abstract class AbstractGitHubWireMockTest { // By default the wiremock tests will run without proxy // The tests will use only the stubbed data and will fail if requests are made for missing data. // You can use the proxy while writing and debugging tests. - private static final boolean useProxy = + private static final boolean USE_PROXY = !System.getProperty("test.github.useProxy", "false").equals("false"); - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + protected static JenkinsRule r; - public static WireMockRuleFactory factory = new WireMockRuleFactory(); + private static final WireMockExtensionFactory FACTORY = new WireMockExtensionFactory(); - @Rule - public WireMockRule githubRaw = - factory.getRule(WireMockConfiguration.options().dynamicPort().usingFilesUnderClasspath("raw")); + @RegisterExtension + protected final WireMockExtension githubRaw = + FACTORY.getExtension(WireMockConfiguration.options().dynamicPort().usingFilesUnderClasspath("raw")); - @Rule - public WireMockRule githubApi = factory.getRule(WireMockConfiguration.options() + @RegisterExtension + protected final WireMockExtension githubApi = FACTORY.getExtension(WireMockConfiguration.options() .dynamicPort() .usingFilesUnderClasspath("api") .extensions(new ResponseTransformer() { @@ -48,10 +46,11 @@ public Response transform(Request request, Response response, FileSource files, .but() .body(response.getBodyAsString() .replace( - "https://api.github.com/", "http://localhost:" + githubApi.port() + "/") + "https://api.github.com/", + "http://localhost:" + githubApi.getPort() + "/") .replace( "https://raw.githubusercontent.com/", - "http://localhost:" + githubRaw.port() + "/")) + "http://localhost:" + githubRaw.getPort() + "/")) .build(); } return response; @@ -63,11 +62,14 @@ public String getName() { } })); - @Before - public void prepareMockGitHub() { - prepareMockGitHubFileMappings(); + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; + } - if (useProxy) { + @BeforeEach + void beforeEach() throws Exception { + if (USE_PROXY) { githubApi.stubFor(get(urlMatching(".*")) .atPriority(10) .willReturn(aResponse().proxiedFrom("https://api.github.com/"))); @@ -76,17 +78,4 @@ public void prepareMockGitHub() { .willReturn(aResponse().proxiedFrom("https://raw.githubusercontent.com/"))); } } - - void prepareMockGitHubFileMappings() { - new File("src/test/resources/api/mappings").mkdirs(); - new File("src/test/resources/api/__files").mkdirs(); - new File("src/test/resources/raw/mappings").mkdirs(); - new File("src/test/resources/raw/__files").mkdirs(); - githubApi.enableRecordMappings( - new SingleRootFileSource("src/test/resources/api/mappings"), - new SingleRootFileSource("src/test/resources/api/__files")); - githubRaw.enableRecordMappings( - new SingleRootFileSource("src/test/resources/raw/mappings"), - new SingleRootFileSource("src/test/resources/raw/__files")); - } } diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/ApiRateLimitCheckerTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/ApiRateLimitCheckerTest.java index c1770c8ff..1cba5643a 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/ApiRateLimitCheckerTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/ApiRateLimitCheckerTest.java @@ -2,15 +2,11 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.resetAllScenarios; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; -import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.ScenarioMappingBuilder; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; import com.github.tomakehurst.wiremock.stubbing.Scenario; import hudson.util.LogTaskListener; @@ -25,14 +21,14 @@ import java.util.logging.Logger; import java.util.stream.Stream; import org.jenkinsci.plugins.github.config.GitHubServerConfig; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.kohsuke.github.GHRateLimit; import org.kohsuke.github.GitHub; import org.mockito.Mockito; -public class ApiRateLimitCheckerTest extends AbstractGitHubWireMockTest { +class ApiRateLimitCheckerTest extends AbstractGitHubWireMockTest { private RingBufferLogHandler handler; private LogTaskListener listener; @@ -57,26 +53,21 @@ private long countOfOutputLinesContaining(String substring) { return countOfOutputLines(m -> m.contains(substring)); } - public static int getRequestCount(WireMockServer server) { - return server.countRequestsMatching(RequestPatternBuilder.allRequests().build()) + private static int getRequestCount(WireMockExtension extension) { + return extension + .countRequestsMatching(RequestPatternBuilder.allRequests().build()) .getCount(); } - private class RateLimit { - final int remaining; - final int limit; - final Date reset; + private record RateLimit(int limit, int remaining, Date reset) {} - RateLimit(int limit, int remaining, Date reset) { - this.limit = limit; - this.remaining = remaining; - this.reset = reset; - } - } + @Override + @BeforeEach + void beforeEach() throws Exception { + super.beforeEach(); - @Before - public void setUp() throws Exception { - resetAllScenarios(); + githubApi.resetScenarios(); + githubRaw.resetScenarios(); handler = new RingBufferLogHandler(1000); final Logger logger = Logger.getLogger(getClass().getName()); @@ -98,13 +89,12 @@ public void setUp() throws Exception { ApiRateLimitChecker.resetLocalChecker(); } - @After - public void tearDown() throws Exception { + @AfterEach + void afterEach() { GitHubConfiguration.get().setEndpoints(new ArrayList<>()); } private void setupStubs(List scenarios) throws Exception { - githubApi.stubFor(get(urlEqualTo("/meta")) .willReturn(aResponse().withStatus(200).withBody("{\"verifiable_password_authentication\": false}"))); @@ -159,13 +149,13 @@ private void setupStubs(List scenarios) throws Exception { githubApi.stubFor(scenario); } - github = Connector.connect("http://localhost:" + githubApi.port(), null); + github = Connector.connect("http://localhost:" + githubApi.getPort(), null); initialRequestCount = getRequestCount(githubApi); assertEquals(2, initialRequestCount); } @Test - public void NoCheckerConfigured() throws Exception { + void NoCheckerConfigured() throws Exception { // set up scenarios List scenarios = new ArrayList<>(); long now = System.currentTimeMillis(); @@ -204,7 +194,7 @@ public void NoCheckerConfigured() throws Exception { } @Test - public void NoCheckerConfiguredWithEndpoint() throws Exception { + void NoCheckerConfiguredWithEndpoint() throws Exception { // set up scenarios List scenarios = new ArrayList<>(); long now = System.currentTimeMillis(); @@ -240,7 +230,7 @@ public void NoCheckerConfiguredWithEndpoint() throws Exception { * @author Julian V. Modesto */ @Test - public void ThrottleOnOverTestWithQuota() throws Exception { + void ThrottleOnOverTestWithQuota() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleOnOver); // set up scenarios @@ -269,7 +259,7 @@ public void ThrottleOnOverTestWithQuota() throws Exception { * @author Julian V. Modesto */ @Test - public void ThrottleOnNormalizeTestWithQuota() throws Exception { + void ThrottleOnNormalizeTestWithQuota() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleForNormalize); // set up scenarios @@ -296,7 +286,7 @@ public void ThrottleOnNormalizeTestWithQuota() throws Exception { * @author Marc Salles Navarro */ @Test - public void NoThrottleTestShouldNotThrottle() throws Exception { + void NoThrottleTestShouldNotThrottle() throws Exception { // set up scenarios List scenarios = new ArrayList<>(); int limit = 5000; @@ -324,8 +314,7 @@ public void NoThrottleTestShouldNotThrottle() throws Exception { * @author Marc Salles Navarro */ @Test - public void NoThrottleTestShouldNotThrottle404() throws Exception { - + void NoThrottleTestShouldNotThrottle404() throws Exception { setupStubs(new ArrayList<>()); GHRateLimit.Record initial = github.lastRateLimit().getCore(); assertEquals(2, getRequestCount(githubApi)); @@ -341,7 +330,8 @@ public void NoThrottleTestShouldNotThrottle404() throws Exception { github.getMeta(); // The core should be unknown, but different from initial - assertTrue(github.rateLimit().getCore() instanceof GHRateLimit.UnknownLimitRecord); + assertInstanceOf( + GHRateLimit.UnknownLimitRecord.class, github.rateLimit().getCore()); assertNotEquals(initial, github.rateLimit().getCore()); // there should be no output @@ -357,7 +347,7 @@ public void NoThrottleTestShouldNotThrottle404() throws Exception { * @author Marc Salles Navarro */ @Test - public void NoThrottleTestShouldFallbackToThrottleOnOverForGitHubDotCom() throws Exception { + void NoThrottleTestShouldFallbackToThrottleOnOverForGitHubDotCom() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleOnOver); // set up scenarios @@ -391,7 +381,7 @@ public void NoThrottleTestShouldFallbackToThrottleOnOverForGitHubDotCom() throws * @author Julian V. Modesto */ @Test - public void ThrottleOnOverTest() throws Exception { + void ThrottleOnOverTest() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleOnOver); // set up scenarios @@ -462,7 +452,7 @@ public void ThrottleOnOverTest() throws Exception { * @author Julian V. Modesto */ @Test - public void ThrottleForNormalizeTestWithinIdeal() throws Exception { + void ThrottleForNormalizeTestWithinIdeal() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleForNormalize); List scenarios = new ArrayList<>(); @@ -552,7 +542,7 @@ public void ThrottleForNormalizeTestWithinIdeal() throws Exception { * @author Julian V. Modesto */ @Test - public void NormalizeThrottleWithBurnedBuffer() throws Exception { + void NormalizeThrottleWithBurnedBuffer() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleForNormalize); long now = System.currentTimeMillis(); @@ -614,7 +604,7 @@ public void NormalizeThrottleWithBurnedBuffer() throws Exception { * @author Alex Taylor */ @Test - public void OnOverThrottleTimingRateLimitCheck() throws Exception { + void OnOverThrottleTimingRateLimitCheck() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleOnOver); // Longer timings that test defaults for more consistent measurements. @@ -695,7 +685,7 @@ public void OnOverThrottleTimingRateLimitCheck() throws Exception { * @author Alex Taylor */ @Test - public void NormalizeThrottleTimingRateLimitCheck() throws Exception { + void NormalizeThrottleTimingRateLimitCheck() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleForNormalize); ApiRateLimitChecker.setExpirationWaitMillis(60); @@ -763,7 +753,7 @@ public void NormalizeThrottleTimingRateLimitCheck() throws Exception { * @author Alex Taylor */ @Test - public void NormalizeExpectedIdealOverTime() throws Exception { + void NormalizeExpectedIdealOverTime() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleForNormalize); // Set up scenarios @@ -840,7 +830,7 @@ public void NormalizeExpectedIdealOverTime() throws Exception { * @author Alex Taylor */ @Test - public void OnOverExpectedIdealOverTime() throws Exception { + void OnOverExpectedIdealOverTime() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleOnOver); long start = System.currentTimeMillis(); @@ -894,7 +884,7 @@ public void OnOverExpectedIdealOverTime() throws Exception { * @author Alex Taylor */ @Test - public void ExpectedResetTimingNormalize() throws Exception { + void ExpectedResetTimingNormalize() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleForNormalize); // Use a longer notification interval to make the test produce stable output @@ -940,7 +930,7 @@ public void ExpectedResetTimingNormalize() throws Exception { * @author Alex Taylor */ @Test - public void ExpectedResetTimingOnOver() throws Exception { + void ExpectedResetTimingOnOver() throws Exception { GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleOnOver); // Use a longer notification interval to make the test produce stable output diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/BranchDiscoveryTraitTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/BranchDiscoveryTraitTest.java index 2b1540fcf..afab3740d 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/BranchDiscoveryTraitTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/BranchDiscoveryTraitTest.java @@ -1,34 +1,42 @@ package org.jenkinsci.plugins.github_branch_source; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; -import static org.junit.Assume.assumeThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import hudson.util.ListBoxModel; import java.util.Collections; import jenkins.scm.api.SCMHeadObserver; import jenkins.scm.api.trait.SCMHeadFilter; import jenkins.scm.api.trait.SCMHeadPrefilter; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class BranchDiscoveryTraitTest { - @ClassRule - public static JenkinsRule j = new JenkinsRule(); +@WithJenkins +class BranchDiscoveryTraitTest { + + private static JenkinsRule j; + + @BeforeAll + static void beforeAll(JenkinsRule rule) { + j = rule; + } @Test - public void given__discoverAll__when__appliedToContext__then__noFilter() throws Exception { + void given__discoverAll__when__appliedToContext__then__noFilter() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.wantBranches(), is(false)); - assumeThat(ctx.wantPRs(), is(false)); - assumeThat(ctx.prefilters(), is(Collections.emptyList())); - assumeThat(ctx.filters(), is(Collections.emptyList())); - assumeThat(ctx.authorities(), not(hasItem(instanceOf(BranchDiscoveryTrait.BranchSCMHeadAuthority.class)))); + assumeFalse(ctx.wantBranches()); + assumeFalse(ctx.wantPRs()); + assumeTrue(ctx.prefilters().isEmpty()); + assumeTrue(ctx.filters().isEmpty()); + assumeTrue(ctx.authorities().stream() + .noneMatch(item -> item instanceof BranchDiscoveryTrait.BranchSCMHeadAuthority)); BranchDiscoveryTrait instance = new BranchDiscoveryTrait(true, true); instance.decorateContext(ctx); assertThat(ctx.wantBranches(), is(true)); @@ -39,13 +47,14 @@ public void given__discoverAll__when__appliedToContext__then__noFilter() throws } @Test - public void given__excludingPRs__when__appliedToContext__then__filter() throws Exception { + void given__excludingPRs__when__appliedToContext__then__filter() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.wantBranches(), is(false)); - assumeThat(ctx.wantPRs(), is(false)); - assumeThat(ctx.prefilters(), is(Collections.emptyList())); - assumeThat(ctx.filters(), is(Collections.emptyList())); - assumeThat(ctx.authorities(), not(hasItem(instanceOf(BranchDiscoveryTrait.BranchSCMHeadAuthority.class)))); + assumeFalse(ctx.wantBranches()); + assumeFalse(ctx.wantPRs()); + assumeTrue(ctx.prefilters().isEmpty()); + assumeTrue(ctx.filters().isEmpty()); + assumeTrue(ctx.authorities().stream() + .noneMatch(item -> item instanceof BranchDiscoveryTrait.BranchSCMHeadAuthority)); BranchDiscoveryTrait instance = new BranchDiscoveryTrait(true, false); instance.decorateContext(ctx); assertThat(ctx.wantBranches(), is(true)); @@ -57,13 +66,14 @@ public void given__excludingPRs__when__appliedToContext__then__filter() throws E } @Test - public void given__onlyPRs__when__appliedToContext__then__filter() throws Exception { + void given__onlyPRs__when__appliedToContext__then__filter() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.wantBranches(), is(false)); - assumeThat(ctx.wantPRs(), is(false)); - assumeThat(ctx.prefilters(), is(Collections.emptyList())); - assumeThat(ctx.filters(), is(Collections.emptyList())); - assumeThat(ctx.authorities(), not(hasItem(instanceOf(BranchDiscoveryTrait.BranchSCMHeadAuthority.class)))); + assumeFalse(ctx.wantBranches()); + assumeFalse(ctx.wantPRs()); + assumeTrue(ctx.prefilters().isEmpty()); + assumeTrue(ctx.filters().isEmpty()); + assumeTrue(ctx.authorities().stream() + .noneMatch(item -> item instanceof BranchDiscoveryTrait.BranchSCMHeadAuthority)); BranchDiscoveryTrait instance = new BranchDiscoveryTrait(false, true); instance.decorateContext(ctx); assertThat(ctx.wantBranches(), is(true)); @@ -74,7 +84,7 @@ public void given__onlyPRs__when__appliedToContext__then__filter() throws Except } @Test - public void given__descriptor__when__displayingOptions__then__allThreePresent() { + void given__descriptor__when__displayingOptions__then__allThreePresent() { ListBoxModel options = j.jenkins .getDescriptorByType(BranchDiscoveryTrait.DescriptorImpl.class) .doFillStrategyIdItems(); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/DefaultGitHubNotificationStrategyTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/DefaultGitHubNotificationStrategyTest.java index c5b50f679..fcf5f839f 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/DefaultGitHubNotificationStrategyTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/DefaultGitHubNotificationStrategyTest.java @@ -24,8 +24,9 @@ package org.jenkinsci.plugins.github_branch_source; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; @@ -36,16 +37,23 @@ import java.util.logging.Logger; import jenkins.scm.api.SCMHeadOrigin; import jenkins.scm.api.mixin.ChangeRequestCheckoutStrategy; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class DefaultGitHubNotificationStrategyTest { - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +class DefaultGitHubNotificationStrategyTest { + + private JenkinsRule j; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + j = rule; + } @Test - public void given_basicJob_then_singleNotification() throws Exception { + void given_basicJob_then_singleNotification() throws Exception { List srcs = Arrays.asList( new GitHubSCMSource("example", "test", null, false), new GitHubSCMSource("", "", "http://github.com/example/test", true)); @@ -61,7 +69,7 @@ public void given_basicJob_then_singleNotification() throws Exception { } @Test - public void given_differentSCMheads_then_distinctNotifications() throws Exception { + void given_differentSCMheads_then_distinctNotifications() throws Exception { List srcs = Arrays.asList( new GitHubSCMSource("example", "test", "http://github.com/ignored/ignored", false), new GitHubSCMSource("", "", "http://github.com/example/test", true)); @@ -110,7 +118,7 @@ public void given_differentSCMheads_then_distinctNotifications() throws Exceptio } @Test - public void given_jobOrRun_then_differentURLs() throws Exception { + void given_jobOrRun_then_differentURLs() throws Exception { List srcs = Arrays.asList( new GitHubSCMSource("example", "test", null, false), new GitHubSCMSource("", "", "http://github.com/example/test", true)); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/EndpointTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/EndpointTest.java index 9693adbfb..afaf4c853 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/EndpointTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/EndpointTest.java @@ -1,9 +1,6 @@ package org.jenkinsci.plugins.github_branch_source; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import hudson.ExtensionList; import hudson.Functions; @@ -24,26 +21,26 @@ import org.htmlunit.WebRequest; import org.htmlunit.html.HtmlPage; import org.htmlunit.util.NameValuePair; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.stapler.StaplerRequest2; import org.kohsuke.stapler.StaplerResponse2; -import org.xml.sax.SAXException; -public class EndpointTest { - - @Rule - public final JenkinsRule j = new JenkinsRule(); +@WithJenkins +class EndpointTest { private String testUrl; - @Before - public void setUp() throws Exception { + private JenkinsRule j; + + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + j = rule; j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); MockAuthorizationStrategy auth = new MockAuthorizationStrategy(); auth.grant(Jenkins.MANAGE).everywhere().to("alice"); @@ -54,37 +51,34 @@ public void setUp() throws Exception { @Test @Issue("SECURITY-806") - public void cantGet_doCheckApiUri() throws IOException, SAXException { - try { - j.createWebClient() - .goTo(appendCrumb( - "descriptorByName/org.jenkinsci.plugins.github_branch_source.Endpoint/checkApiUri?apiUri=" - + testUrl)); - fail("Should not be able to do that"); - } catch (FailingHttpStatusCodeException e) { - assertEquals(405, e.getStatusCode()); - } + void cantGet_doCheckApiUri() { + FailingHttpStatusCodeException e = assertThrows(FailingHttpStatusCodeException.class, () -> j.createWebClient() + .goTo( + appendCrumb( + "descriptorByName/org.jenkinsci.plugins.github_branch_source.Endpoint/checkApiUri?apiUri=" + + testUrl), + "Should not be able to do that")); + assertEquals(405, e.getStatusCode()); assertFalse(TestRoot.get().visited); } @Test @Issue("SECURITY-806") - public void cantPostAsAnonymous_doCheckApiUri() throws Exception { - try { - post( - "descriptorByName/org.jenkinsci.plugins.github_branch_source.Endpoint/checkApiUri?apiUri=" - + testUrl, - null); - fail("Should not be able to do that"); - } catch (FailingHttpStatusCodeException e) { - assertEquals(403, e.getStatusCode()); - } + void cantPostAsAnonymous_doCheckApiUri() { + FailingHttpStatusCodeException e = assertThrows( + FailingHttpStatusCodeException.class, + () -> post( + "descriptorByName/org.jenkinsci.plugins.github_branch_source.Endpoint/checkApiUri?apiUri=" + + testUrl, + null), + "Should not be able to do that"); + assertEquals(403, e.getStatusCode()); assertFalse(TestRoot.get().visited); } @Test @Issue("SECURITY-806") - public void canPostAsAdmin_doCheckApiUri() throws Exception { + void canPostAsAdmin_doCheckApiUri() throws Exception { post( "descriptorByName/org.jenkinsci.plugins.github_branch_source.Endpoint/checkApiUri?apiUri=" + testUrl, "alice"); @@ -93,7 +87,7 @@ public void canPostAsAdmin_doCheckApiUri() throws Exception { @Test @Issue("JENKINS-73053") - public void manageCanSetupEndpoints() throws Exception { + void manageCanSetupEndpoints() throws Exception { HtmlPage htmlPage = j.createWebClient().login("alice").goTo("manage/configure"); assertTrue(htmlPage.getVisibleText().contains("GitHub Enterprise Servers")); } diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/EventsTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/EventsTest.java index 1f92a3fa1..ada82ed70 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/EventsTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/EventsTest.java @@ -27,9 +27,9 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; import jenkins.scm.api.SCMEvent; import jenkins.scm.api.SCMEvents; @@ -38,44 +38,46 @@ import org.apache.commons.io.IOUtils; import org.awaitility.Awaitility; import org.jenkinsci.plugins.github.extension.GHSubscriberEvent; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class EventsTest { +@WithJenkins +class EventsTest { /** All tests in this class only use Jenkins for the extensions */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + @SuppressWarnings("unused") + private static JenkinsRule r; - private static int defaultFireDelayInSeconds = GitHubSCMSource.getEventDelaySeconds(); + private static final int DEFAULT_FIRE_DELAY_IN_SECONDS = GitHubSCMSource.getEventDelaySeconds(); private static SCMEvent.Type firedEventType; private static GHSubscriberEvent ghEvent; - @BeforeClass - public static void setupDelay() { + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; GitHubSCMSource.setEventDelaySeconds(0); // fire immediately without delay } - @Before - public void resetFiredEvent() { + @BeforeEach + void beforeEach() { firedEventType = null; ghEvent = null; TestSCMEventListener.setReceived(false); } - @AfterClass - public static void resetDelay() { - GitHubSCMSource.setEventDelaySeconds(defaultFireDelayInSeconds); + @AfterAll + static void afterAll() { + GitHubSCMSource.setEventDelaySeconds(DEFAULT_FIRE_DELAY_IN_SECONDS); } @Test - public void given_ghPushEventCreated_then_createdHeadEventFired() throws Exception { + void given_ghPushEventCreated_then_createdHeadEventFired() throws Exception { PushGHEventSubscriber subscriber = new PushGHEventSubscriber(); firedEventType = SCMEvent.Type.CREATED; @@ -84,7 +86,7 @@ public void given_ghPushEventCreated_then_createdHeadEventFired() throws Excepti } @Test - public void given_ghPushEventDeleted_then_removedHeadEventFired() throws Exception { + void given_ghPushEventDeleted_then_removedHeadEventFired() throws Exception { PushGHEventSubscriber subscriber = new PushGHEventSubscriber(); firedEventType = SCMEvent.Type.REMOVED; @@ -93,7 +95,7 @@ public void given_ghPushEventDeleted_then_removedHeadEventFired() throws Excepti } @Test - public void given_ghPushEventUpdated_then_updatedHeadEventFired() throws Exception { + void given_ghPushEventUpdated_then_updatedHeadEventFired() throws Exception { PushGHEventSubscriber subscriber = new PushGHEventSubscriber(); firedEventType = SCMEvent.Type.UPDATED; @@ -102,7 +104,7 @@ public void given_ghPushEventUpdated_then_updatedHeadEventFired() throws Excepti } @Test - public void given_ghPullRequestEventOpened_then_createdHeadEventFired() throws Exception { + void given_ghPullRequestEventOpened_then_createdHeadEventFired() throws Exception { PullRequestGHEventSubscriber subscriber = new PullRequestGHEventSubscriber(); firedEventType = SCMEvent.Type.CREATED; @@ -111,7 +113,7 @@ public void given_ghPullRequestEventOpened_then_createdHeadEventFired() throws E } @Test - public void given_ghPullRequestEventClosed_then_removedHeadEventFired() throws Exception { + void given_ghPullRequestEventClosed_then_removedHeadEventFired() throws Exception { PullRequestGHEventSubscriber subscriber = new PullRequestGHEventSubscriber(); firedEventType = SCMEvent.Type.REMOVED; @@ -120,7 +122,7 @@ public void given_ghPullRequestEventClosed_then_removedHeadEventFired() throws E } @Test - public void given_ghPullRequestEventReopened_then_updatedHeadEventFired() throws Exception { + void given_ghPullRequestEventReopened_then_updatedHeadEventFired() throws Exception { PullRequestGHEventSubscriber subscriber = new PullRequestGHEventSubscriber(); firedEventType = SCMEvent.Type.UPDATED; @@ -129,7 +131,7 @@ public void given_ghPullRequestEventReopened_then_updatedHeadEventFired() throws } @Test - public void given_ghPullRequestEventSync_then_updatedHeadEventFired() throws Exception { + void given_ghPullRequestEventSync_then_updatedHeadEventFired() throws Exception { PullRequestGHEventSubscriber subscriber = new PullRequestGHEventSubscriber(); firedEventType = SCMEvent.Type.UPDATED; @@ -138,7 +140,7 @@ public void given_ghPullRequestEventSync_then_updatedHeadEventFired() throws Exc } @Test - public void given_ghPullRequestEventConvertedToDraft_then_updatedHeadEventFired() throws Exception { + void given_ghPullRequestEventConvertedToDraft_then_updatedHeadEventFired() throws Exception { PullRequestGHEventSubscriber subscriber = new PullRequestGHEventSubscriber(); firedEventType = SCMEvent.Type.UPDATED; @@ -147,7 +149,7 @@ public void given_ghPullRequestEventConvertedToDraft_then_updatedHeadEventFired( } @Test - public void given_ghPullRequestEventReadyForReview_then_updatedHeadEventFired() throws Exception { + void given_ghPullRequestEventReadyForReview_then_updatedHeadEventFired() throws Exception { PullRequestGHEventSubscriber subscriber = new PullRequestGHEventSubscriber(); firedEventType = SCMEvent.Type.UPDATED; @@ -156,7 +158,7 @@ public void given_ghPullRequestEventReadyForReview_then_updatedHeadEventFired() } @Test - public void given_ghRepositoryEventCreatedFromFork_then_createdSourceEventFired() throws Exception { + void given_ghRepositoryEventCreatedFromFork_then_createdSourceEventFired() throws Exception { GitHubRepositoryEventSubscriber subscriber = new GitHubRepositoryEventSubscriber(); firedEventType = SCMEvent.Type.CREATED; @@ -165,7 +167,7 @@ public void given_ghRepositoryEventCreatedFromFork_then_createdSourceEventFired( } @Test - public void given_ghRepositoryEventCreatedNotFork_then_noSourceEventFired() throws Exception { + void given_ghRepositoryEventCreatedNotFork_then_noSourceEventFired() throws Exception { GitHubRepositoryEventSubscriber subscriber = new GitHubRepositoryEventSubscriber(); ghEvent = callOnEvent(subscriber, "EventsTest/repositoryEventNotFiredNotFork.json"); @@ -173,40 +175,39 @@ public void given_ghRepositoryEventCreatedNotFork_then_noSourceEventFired() thro } @Test - public void given_ghRepositoryEventWrongAction_then_noSourceEventFired() throws Exception { + void given_ghRepositoryEventWrongAction_then_noSourceEventFired() throws Exception { GitHubRepositoryEventSubscriber subscriber = new GitHubRepositoryEventSubscriber(); ghEvent = callOnEvent(subscriber, "EventsTest/repositoryEventNotFiredWrongAction.json"); waitAndAssertReceived(false); } - private GHSubscriberEvent callOnEvent(PushGHEventSubscriber subscriber, String eventPayloadFile) - throws IOException { + private GHSubscriberEvent callOnEvent(PushGHEventSubscriber subscriber, String eventPayloadFile) throws Exception { GHSubscriberEvent event = createEvent(eventPayloadFile); subscriber.onEvent(event); return event; } private GHSubscriberEvent callOnEvent(PullRequestGHEventSubscriber subscriber, String eventPayloadFile) - throws IOException { + throws Exception { GHSubscriberEvent event = createEvent(eventPayloadFile); subscriber.onEvent(event); return event; } private GHSubscriberEvent callOnEvent(GitHubRepositoryEventSubscriber subscriber, String eventPayloadFile) - throws IOException { + throws Exception { GHSubscriberEvent event = createEvent(eventPayloadFile); subscriber.onEvent(event); return event; } - private GHSubscriberEvent createEvent(String eventPayloadFile) throws IOException { - String payload = IOUtils.toString(getClass().getResourceAsStream(eventPayloadFile)); + private GHSubscriberEvent createEvent(String eventPayloadFile) throws Exception { + String payload = IOUtils.toString(getClass().getResourceAsStream(eventPayloadFile), StandardCharsets.UTF_8); return new GHSubscriberEvent("myOrigin", null, payload); } - private void waitAndAssertReceived(boolean received) throws InterruptedException { + private void waitAndAssertReceived(boolean received) throws Exception { long watermark = SCMEvents.getWatermark(); // event will be fired by subscriber at some point SCMEvents.awaitOne(watermark, received ? 20 : 200, TimeUnit.MILLISECONDS); @@ -216,9 +217,9 @@ private void waitAndAssertReceived(boolean received) throws InterruptedException } assertEquals( - "Event should have " + ((!received) ? "not " : "") + "been received", received, - TestSCMEventListener.didReceive()); + TestSCMEventListener.didReceive(), + "Event should have " + ((!received) ? "not " : "") + "been received"); } @TestExtension @@ -237,8 +238,8 @@ public void onSCMSourceEvent(SCMSourceEvent event) { private void receiveEvent(SCMEvent.Type type, String origin) { eventReceived = true; - assertEquals("Event type should be the same", type, firedEventType); - assertEquals("Event origin should be the same", origin, ghEvent.getOrigin()); + assertEquals(type, firedEventType, "Event type should be the same"); + assertEquals(origin, ghEvent.getOrigin(), "Event origin should be the same"); } public static boolean didReceive() { diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/ForkPullRequestDiscoveryTrait2Test.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/ForkPullRequestDiscoveryTrait2Test.java index cb61162c6..c8efb3b45 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/ForkPullRequestDiscoveryTrait2Test.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/ForkPullRequestDiscoveryTrait2Test.java @@ -23,29 +23,35 @@ */ package org.jenkinsci.plugins.github_branch_source; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; import jenkins.branch.BranchSource; import jenkins.scm.api.trait.SCMSourceTrait; import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.For; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; @For(ForkPullRequestDiscoveryTrait.class) -public class ForkPullRequestDiscoveryTrait2Test { +@WithJenkins +class ForkPullRequestDiscoveryTrait2Test { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; - @Ignore( + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } + + @Disabled( "These tests fail because users get automatically migrated to URL-based configuration if they re-save the GitHubSCMSource") @Test - public void configRoundtrip() throws Exception { + void configRoundtrip() throws Exception { WorkflowMultiBranchProject p = r.createProject(WorkflowMultiBranchProject.class); assertRoundTrip(p, new ForkPullRequestDiscoveryTrait.TrustNobody(), false); @@ -55,13 +61,17 @@ public void configRoundtrip() throws Exception { } @Test - public void configRoundtripWithRawUrl() throws Exception { + void configRoundtripWithRawUrl() throws Exception { WorkflowMultiBranchProject p = r.createProject(WorkflowMultiBranchProject.class); - - assertRoundTrip(p, new ForkPullRequestDiscoveryTrait.TrustNobody(), true); - assertRoundTrip(p, new ForkPullRequestDiscoveryTrait.TrustEveryone(), true); - assertRoundTrip(p, new ForkPullRequestDiscoveryTrait.TrustContributors(), true); - assertRoundTrip(p, new ForkPullRequestDiscoveryTrait.TrustPermission(), true); + try { + assertRoundTrip(p, new ForkPullRequestDiscoveryTrait.TrustNobody(), true); + assertRoundTrip(p, new ForkPullRequestDiscoveryTrait.TrustEveryone(), true); + assertRoundTrip(p, new ForkPullRequestDiscoveryTrait.TrustContributors(), true); + assertRoundTrip(p, new ForkPullRequestDiscoveryTrait.TrustPermission(), true); + } finally { + // branch indexing may still be running which causes problems during shutdown + p.delete(); + } } private void assertRoundTrip( diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/ForkPullRequestDiscoveryTraitTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/ForkPullRequestDiscoveryTraitTest.java index dbf93e8ee..2dd024c22 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/ForkPullRequestDiscoveryTraitTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/ForkPullRequestDiscoveryTraitTest.java @@ -1,11 +1,11 @@ package org.jenkinsci.plugins.github_branch_source; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; -import static org.junit.Assume.assumeThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import hudson.util.XStream2; import java.util.Collections; @@ -15,23 +15,25 @@ import jenkins.scm.api.trait.SCMHeadFilter; import jenkins.scm.api.trait.SCMHeadPrefilter; import org.hamcrest.Matchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +class ForkPullRequestDiscoveryTraitTest { -public class ForkPullRequestDiscoveryTraitTest { @Test - public void xstream() throws Exception { + void xstream() { System.out.println(new XStream2() .toXML(new ForkPullRequestDiscoveryTrait(3, new ForkPullRequestDiscoveryTrait.TrustContributors()))); } @Test - public void given__discoverHeadMerge__when__appliedToContext__then__strategiesCorrect() throws Exception { + void given__discoverHeadMerge__when__appliedToContext__then__strategiesCorrect() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.wantBranches(), is(false)); - assumeThat(ctx.wantPRs(), is(false)); - assumeThat(ctx.prefilters(), is(Collections.emptyList())); - assumeThat(ctx.filters(), is(Collections.emptyList())); - assumeThat(ctx.authorities(), not(hasItem(instanceOf(ForkPullRequestDiscoveryTrait.TrustContributors.class)))); + assumeFalse(ctx.wantBranches()); + assumeFalse(ctx.wantPRs()); + assumeTrue(ctx.prefilters().isEmpty()); + assumeTrue(ctx.filters().isEmpty()); + assumeTrue(ctx.authorities().stream() + .noneMatch(item -> item instanceof ForkPullRequestDiscoveryTrait.TrustContributors)); ForkPullRequestDiscoveryTrait instance = new ForkPullRequestDiscoveryTrait( EnumSet.allOf(ChangeRequestCheckoutStrategy.class), new ForkPullRequestDiscoveryTrait.TrustContributors()); @@ -45,13 +47,14 @@ public void given__discoverHeadMerge__when__appliedToContext__then__strategiesCo } @Test - public void given__discoverHeadOnly__when__appliedToContext__then__strategiesCorrect() throws Exception { + void given__discoverHeadOnly__when__appliedToContext__then__strategiesCorrect() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.wantBranches(), is(false)); - assumeThat(ctx.wantPRs(), is(false)); - assumeThat(ctx.prefilters(), is(Collections.emptyList())); - assumeThat(ctx.filters(), is(Collections.emptyList())); - assumeThat(ctx.authorities(), not(hasItem(instanceOf(ForkPullRequestDiscoveryTrait.TrustContributors.class)))); + assumeFalse(ctx.wantBranches()); + assumeFalse(ctx.wantPRs()); + assumeTrue(ctx.prefilters().isEmpty()); + assumeTrue(ctx.filters().isEmpty()); + assumeTrue(ctx.authorities().stream() + .noneMatch(item -> item instanceof ForkPullRequestDiscoveryTrait.TrustContributors)); ForkPullRequestDiscoveryTrait instance = new ForkPullRequestDiscoveryTrait( EnumSet.of(ChangeRequestCheckoutStrategy.HEAD), new ForkPullRequestDiscoveryTrait.TrustContributors()); instance.decorateContext(ctx); @@ -64,13 +67,14 @@ public void given__discoverHeadOnly__when__appliedToContext__then__strategiesCor } @Test - public void given__discoverMergeOnly__when__appliedToContext__then__strategiesCorrect() throws Exception { + void given__discoverMergeOnly__when__appliedToContext__then__strategiesCorrect() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.wantBranches(), is(false)); - assumeThat(ctx.wantPRs(), is(false)); - assumeThat(ctx.prefilters(), is(Collections.emptyList())); - assumeThat(ctx.filters(), is(Collections.emptyList())); - assumeThat(ctx.authorities(), not(hasItem(instanceOf(ForkPullRequestDiscoveryTrait.TrustContributors.class)))); + assumeFalse(ctx.wantBranches()); + assumeFalse(ctx.wantPRs()); + assumeTrue(ctx.prefilters().isEmpty()); + assumeTrue(ctx.filters().isEmpty()); + assumeTrue(ctx.authorities().stream() + .noneMatch(item -> item instanceof ForkPullRequestDiscoveryTrait.TrustContributors)); ForkPullRequestDiscoveryTrait instance = new ForkPullRequestDiscoveryTrait( EnumSet.of(ChangeRequestCheckoutStrategy.MERGE), new ForkPullRequestDiscoveryTrait.TrustContributors()); instance.decorateContext(ctx); @@ -83,13 +87,14 @@ public void given__discoverMergeOnly__when__appliedToContext__then__strategiesCo } @Test - public void given__nonDefaultTrust__when__appliedToContext__then__authoritiesCorrect() throws Exception { + void given__nonDefaultTrust__when__appliedToContext__then__authoritiesCorrect() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.wantBranches(), is(false)); - assumeThat(ctx.wantPRs(), is(false)); - assumeThat(ctx.prefilters(), is(Collections.emptyList())); - assumeThat(ctx.filters(), is(Collections.emptyList())); - assumeThat(ctx.authorities(), not(hasItem(instanceOf(ForkPullRequestDiscoveryTrait.TrustContributors.class)))); + assumeFalse(ctx.wantBranches()); + assumeFalse(ctx.wantPRs()); + assumeTrue(ctx.prefilters().isEmpty()); + assumeTrue(ctx.filters().isEmpty()); + assumeTrue(ctx.authorities().stream() + .noneMatch(item -> item instanceof ForkPullRequestDiscoveryTrait.TrustContributors)); ForkPullRequestDiscoveryTrait instance = new ForkPullRequestDiscoveryTrait( EnumSet.allOf(ChangeRequestCheckoutStrategy.class), new ForkPullRequestDiscoveryTrait.TrustEveryone()); instance.decorateContext(ctx); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubAppCredentialsContextualizationTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubAppCredentialsContextualizationTest.java index 186700790..902c8ace2 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubAppCredentialsContextualizationTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubAppCredentialsContextualizationTest.java @@ -17,15 +17,17 @@ import java.util.Arrays; import jenkins.branch.BranchSource; import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; @Issue("JENKINS-73474") -public class GitHubAppCredentialsContextualizationTest extends AbstractGitHubWireMockTest { +class GitHubAppCredentialsContextualizationTest extends AbstractGitHubWireMockTest { - @Before - public void setUpWireMock() throws Exception { + @Override + @BeforeEach + void beforeEach() throws Exception { + super.beforeEach(); GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleOnOver); // Add wiremock responses for App, App Installation, and App Installation Token @@ -67,7 +69,7 @@ public void setUpWireMock() throws Exception { } @Test - public void ownerMustBeInferredFromRepository() throws Exception { + void ownerMustBeInferredFromRepository() throws Exception { final var store = CredentialsProvider.lookupStores(r.jenkins).iterator().next(); final var credentials = GitHubApp.createCredentials("myAppCredentialsWithoutOwner"); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubAppCredentialsJCasCCompatibilityTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubAppCredentialsJCasCCompatibilityTest.java index a3cbac1c8..227d69077 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubAppCredentialsJCasCCompatibilityTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubAppCredentialsJCasCCompatibilityTest.java @@ -14,10 +14,9 @@ import io.jenkins.plugins.casc.ConfigurationContext; import io.jenkins.plugins.casc.ConfiguratorRegistry; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; -import io.jenkins.plugins.casc.misc.EnvVarsRule; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; +import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import io.jenkins.plugins.casc.model.CNode; -import io.jenkins.plugins.casc.model.Mapping; import java.util.List; import java.util.Objects; import jenkins.model.Jenkins; @@ -26,24 +25,18 @@ import org.jenkinsci.plugins.github_branch_source.app_credentials.AccessSpecifiedRepositories; import org.jenkinsci.plugins.github_branch_source.app_credentials.DefaultPermissionsStrategy; import org.jenkinsci.plugins.github_branch_source.app_credentials.RepositoryAccessStrategy; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.RuleChain; +import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.SetEnvironmentVariable; -public class GitHubAppCredentialsJCasCCompatibilityTest { +@WithJenkinsConfiguredWithCode +@SetEnvironmentVariable(key = "GITHUB_APP_KEY", value = GitHubAppCredentialsJCasCCompatibilityTest.GITHUB_APP_KEY) +class GitHubAppCredentialsJCasCCompatibilityTest { - @ConfiguredWithCode("github-app-jcasc-minimal.yaml") - public static JenkinsConfiguredWithCodeRule j = new JenkinsConfiguredWithCodeRule(); - - private static final String GITHUB_APP_KEY = "SomeString"; - - @ClassRule - public static RuleChain chain = RuleChain.outerRule(new EnvVarsRule().set("GITHUB_APP_KEY", GITHUB_APP_KEY)) - .around(j); + protected static final String GITHUB_APP_KEY = "SomeString"; @Test @ConfiguredWithCode("github-app-jcasc-minimal.yaml") - public void should_support_configuration_as_code() throws Exception { + void should_support_configuration_as_code(JenkinsConfiguredWithCodeRule j) { List domainCredentials = SystemCredentialsProvider.getInstance().getDomainCredentials(); @@ -80,7 +73,7 @@ public void should_support_configuration_as_code() throws Exception { @Test @ConfiguredWithCode("github-app-jcasc-minimal.yaml") - public void should_support_configuration_export() throws Exception { + void should_support_configuration_export(JenkinsConfiguredWithCodeRule j) throws Exception { CNode credentials = getCredentials(); String exported = toYamlString(credentials) @@ -102,9 +95,8 @@ private CNode getCredentials() throws Exception { ConfiguratorRegistry registry = ConfiguratorRegistry.get(); ConfigurationContext context = new ConfigurationContext(registry); - Mapping configNode = Objects.requireNonNull(root.describe(root.getTargetComponent(context), context)) + return Objects.requireNonNull(root.describe(root.getTargetComponent(context), context)) .asMapping(); - return configNode; } private static void assertGitHubAppCredential( @@ -127,8 +119,7 @@ private static void assertGitHubAppCredential( assertThat(appCredentials.getDefaultPermissionsStrategy(), is(permissionsStrategy)); var actualRepoStrategy = appCredentials.getRepositoryAccessStrategy(); assertThat(actualRepoStrategy.getClass(), is(repoStrategy.getClass())); - if (actualRepoStrategy instanceof AccessSpecifiedRepositories) { - var actualRepos = (AccessSpecifiedRepositories) actualRepoStrategy; + if (actualRepoStrategy instanceof AccessSpecifiedRepositories actualRepos) { var expectedRepos = (AccessSpecifiedRepositories) repoStrategy; assertThat(actualRepos.getOwner(), is(expectedRepos.getOwner())); assertThat(actualRepos.getRepositories(), is(expectedRepos.getRepositories())); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubBranchSourcesJCasCCompatibilityTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubBranchSourcesJCasCCompatibilityTest.java index a76d1b614..d4b364fb4 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubBranchSourcesJCasCCompatibilityTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubBranchSourcesJCasCCompatibilityTest.java @@ -1,21 +1,21 @@ package org.jenkinsci.plugins.github_branch_source; import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; -import io.jenkins.plugins.casc.misc.RoundTripAbstractTest; +import io.jenkins.plugins.casc.misc.junit.jupiter.AbstractRoundTripTest; import org.jenkinsci.plugins.workflow.libs.GlobalLibraries; import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration; import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever; import org.jvnet.hudson.test.Issue; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import org.jvnet.hudson.test.JenkinsRule; -public class GitHubBranchSourcesJCasCCompatibilityTest extends RoundTripAbstractTest { +class GitHubBranchSourcesJCasCCompatibilityTest extends AbstractRoundTripTest { @Issue("JENKINS-57557") @Override - protected void assertConfiguredAsExpected(RestartableJenkinsRule restartableJenkinsRule, String s) { + protected void assertConfiguredAsExpected(JenkinsRule rule, String s) { assertEquals(1, GlobalLibraries.get().getLibraries().size()); final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubNotificationTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubNotificationTest.java index bba0c496b..126990b77 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubNotificationTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubNotificationTest.java @@ -24,23 +24,24 @@ package org.jenkinsci.plugins.github_branch_source; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assume.assumeThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import hudson.model.TaskListener; import java.util.Collections; import java.util.List; import jenkins.scm.api.SCMHeadObserver; import org.hamcrest.Matchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GitHubNotificationTest { +class GitHubNotificationTest { @Test - public void given__notificationsDisabled__when__appliedToContext__then__notificationsDisabled() throws Exception { + void given__notificationsDisabled__when__appliedToContext__then__notificationsDisabled() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.notificationsDisabled(), is(false)); + assumeFalse(ctx.notificationsDisabled()); ctx.withNotificationsDisabled(true); assertThat(ctx.notificationsDisabled(), is(true)); ctx.withNotificationsDisabled(false); @@ -48,25 +49,25 @@ public void given__notificationsDisabled__when__appliedToContext__then__notifica } @Test - public void given__defaultNotificationStrategy__when__appliedToContext__then__duplicatesRemoved() throws Exception { + void given__defaultNotificationStrategy__when__appliedToContext__then__duplicatesRemoved() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.notificationStrategies().size(), is(1)); + assumeTrue(ctx.notificationStrategies().size() == 1); ctx.withNotificationStrategy(new DefaultGitHubNotificationStrategy()); assertThat(ctx.notificationStrategies().size(), is(1)); } @Test - public void given__emptyStrategiesList__when__appliedToContext__then__defaultApplied() throws Exception { + void given__emptyStrategiesList__when__appliedToContext__then__defaultApplied() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.notificationStrategies().size(), is(1)); + assumeTrue(ctx.notificationStrategies().size() == 1); ctx.withNotificationStrategies(Collections.emptyList()); assertThat(ctx.notificationStrategies().size(), is(1)); } @Test - public void given__defaultStrategy__when__emptyStrategyList__then__strategyAdded() throws Exception { + void given__defaultStrategy__when__emptyStrategyList__then__strategyAdded() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.notificationStrategies().size(), is(1)); + assumeTrue(ctx.notificationStrategies().size() == 1); ctx.withNotificationStrategies(Collections.emptyList()); assertThat(ctx.notificationStrategies().size(), is(1)); ctx.withNotificationStrategy(new DefaultGitHubNotificationStrategy()); @@ -74,9 +75,9 @@ public void given__defaultStrategy__when__emptyStrategyList__then__strategyAdded } @Test - public void given__defaultStrategyList__when__emptyStrategyList__then__strategyAdded() throws Exception { + void given__defaultStrategyList__when__emptyStrategyList__then__strategyAdded() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.notificationStrategies().size(), is(1)); + assumeTrue(ctx.notificationStrategies().size() == 1); ctx.withNotificationStrategies(Collections.emptyList()); assertThat(ctx.notificationStrategies().size(), is(1)); ctx.withNotificationStrategies(Collections.singletonList(new DefaultGitHubNotificationStrategy())); @@ -84,16 +85,16 @@ public void given__defaultStrategyList__when__emptyStrategyList__then__strategyA } @Test - public void given__customStrategy__when__emptyStrategyList__then__noDefaultStrategy() throws Exception { + void given__customStrategy__when__emptyStrategyList__then__noDefaultStrategy() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.notificationStrategies().size(), is(1)); + assumeTrue(ctx.notificationStrategies().size() == 1); ctx.withNotificationStrategy(new TestNotificationStrategy()); List strategies = ctx.notificationStrategies(); assertThat(strategies.size(), is(1)); assertThat(strategies.get(0), Matchers.instanceOf(TestNotificationStrategy.class)); } - private final class TestNotificationStrategy extends AbstractGitHubNotificationStrategy { + private static class TestNotificationStrategy extends AbstractGitHubNotificationStrategy { @Override public List notifications( diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubOrgWebHookTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubOrgWebHookTest.java index 61e64bf1f..8057bd5ea 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubOrgWebHookTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubOrgWebHookTest.java @@ -27,43 +27,52 @@ import static com.github.tomakehurst.wiremock.client.WireMock.*; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; -import com.github.tomakehurst.wiremock.junit.WireMockRule; -import org.junit.Rule; -import org.junit.Test; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.github.GitHub; -public class GitHubOrgWebHookTest { +@WithJenkins +class GitHubOrgWebHookTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + @RegisterExtension + private static final WireMockExtension WIRE_MOCK_EXTENSION = WireMockExtension.newInstance() + .options(wireMockConfig().dynamicPort()) + .build(); - @Rule - public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort()); + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } @Issue("JENKINS-58942") @Test - public void registerCustom() throws Exception { + void registerCustom() throws Exception { System.setProperty("jenkins.hook.url", "https://mycorp/hook-proxy/"); // Return 404 for /rate_limit - wireMockRule.stubFor( + WIRE_MOCK_EXTENSION.stubFor( get(urlEqualTo("/api/rate_limit")).willReturn(aResponse().withStatus(404))); // validate api url - wireMockRule.stubFor(get(urlEqualTo("/api/")) + WIRE_MOCK_EXTENSION.stubFor(get(urlEqualTo("/api/")) .willReturn(aResponse().withBody("{\"rate_limit_url\": \"https://localhost/placeholder/\"}"))); - wireMockRule.stubFor( + WIRE_MOCK_EXTENSION.stubFor( get(urlEqualTo("/api/users/myorg")).willReturn(aResponse().withBody("{\"login\":\"myorg\"}"))); - wireMockRule.stubFor(get(urlEqualTo("/api/orgs/myorg")) + WIRE_MOCK_EXTENSION.stubFor(get(urlEqualTo("/api/orgs/myorg")) .willReturn(aResponse().withBody("{\"login\":\"myorg\",\"html_url\":\"https://github.com/myorg\"}"))); - wireMockRule.stubFor( + WIRE_MOCK_EXTENSION.stubFor( get(urlEqualTo("/api/orgs/myorg/hooks")).willReturn(aResponse().withBody("[]"))); - wireMockRule.stubFor(post(urlEqualTo("/api/orgs/myorg/hooks")) + WIRE_MOCK_EXTENSION.stubFor(post(urlEqualTo("/api/orgs/myorg/hooks")) .withRequestBody(matchingJsonPath("$.config.url", equalTo("https://mycorp/hook-proxy/github-webhook/"))) .willReturn(aResponse().withBody("{}"))); - GitHub hub = Connector.connect("http://localhost:" + wireMockRule.port() + "/api/", null); + GitHub hub = Connector.connect("http://localhost:" + WIRE_MOCK_EXTENSION.getPort() + "/api/", null); try { GitHubOrgWebHook.register(hub, "myorg"); } finally { diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMBuilderTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMBuilderTest.java index 1b39e0f4c..99a699b9b 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMBuilderTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMBuilderTest.java @@ -4,6 +4,7 @@ import static java.util.logging.Logger.getAnonymousLogger; import static jenkins.plugins.git.AbstractGitSCMSource.SCMRevisionImpl; import static jenkins.plugins.git.AbstractGitSCMSource.SpecificRevisionBuildChooser; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasSize; @@ -11,7 +12,6 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey; @@ -20,7 +20,6 @@ import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; -import hudson.model.Descriptor; import hudson.plugins.git.GitSCM; import hudson.plugins.git.Revision; import hudson.plugins.git.UserRemoteConfig; @@ -28,7 +27,6 @@ import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.impl.BuildChooserSetting; import hudson.util.LogTaskListener; -import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -42,39 +40,34 @@ import org.eclipse.jgit.transport.RemoteConfig; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +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.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.ValueSource; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mockito; -@RunWith(Parameterized.class) -public class GitHubSCMBuilderTest { - @ClassRule - public static JenkinsRule j = new JenkinsRule(); +@ParameterizedClass +@ValueSource(booleans = {true, false}) +@WithJenkins +class GitHubSCMBuilderTest { + + private static JenkinsRule j; private GitHubSCMSource source; private WorkflowMultiBranchProject owner; - private boolean configuredByUrl; - @Parameterized.Parameters - public static Collection generateParams() { - return Arrays.asList(new Object[] {true}, new Object[] {false}); - } + private final boolean configuredByUrl; public GitHubSCMBuilderTest(boolean configuredByUrl) { this.configuredByUrl = configuredByUrl; } - public void createGitHubSCMSourceForTest(boolean configuredByUrl, String repoUrlToConfigure) throws Exception { - if (configuredByUrl) { - // Throw an exception if we don't supply a URL - if (repoUrlToConfigure.isEmpty()) { - throw new Exception("Must supply a URL when testing single-URL configured jobs"); - } + private void createGitHubSCMSourceForTest(String repoUrlToConfigure) { + if (configuredByUrl && repoUrlToConfigure != null) { source = new GitHubSCMSource("", "", repoUrlToConfigure, true); } else { source = new GitHubSCMSource("tester", "test-repo", null, false); @@ -82,8 +75,13 @@ public void createGitHubSCMSourceForTest(boolean configuredByUrl, String repoUrl source.setOwner(owner); } - @Before - public void setUp() throws IOException, Descriptor.FormException { + @BeforeAll + static void beforeAll(JenkinsRule rule) { + j = rule; + } + + @BeforeEach + void beforeEach() throws Exception { owner = j.createProject(WorkflowMultiBranchProject.class); Credentials userPasswordCredential = new UsernamePasswordCredentialsImpl( CredentialsScope.GLOBAL, "user-pass", null, "git-user", "git-secret"); @@ -99,15 +97,15 @@ public void setUp() throws IOException, Descriptor.FormException { Domain.global(), Arrays.asList(userPasswordCredential, sshPrivateKeyCredential))); } - @After - public void tearDown() throws IOException, InterruptedException { + @AfterEach + void afterEach() throws Exception { SystemCredentialsProvider.getInstance().setDomainCredentialsMap(Collections.emptyMap()); owner.delete(); } @Test - public void given__cloud_branch_rev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_rev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); SCMRevisionImpl revision = new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); source.setCredentialsId(null); @@ -163,8 +161,8 @@ public void given__cloud_branch_rev_anon__when__build__then__scmBuilt() throws E } @Test - public void given__cloud_branch_rev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_rev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); SCMRevisionImpl revision = new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); source.setCredentialsId("user-pass"); @@ -220,8 +218,8 @@ public void given__cloud_branch_rev_userpass__when__build__then__scmBuilt() thro } @Test - public void given__cloud_branch_rev_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_rev_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); SCMRevisionImpl revision = new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision) @@ -278,8 +276,8 @@ public void given__cloud_branch_rev_userkey__when__build__then__scmBuilt() throw } @Test - public void given__cloud_branch_rev_anon_sshtrait_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_rev_anon_sshtrait_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); SCMRevisionImpl revision = new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); source.setCredentialsId(null); @@ -341,8 +339,8 @@ public void given__cloud_branch_rev_anon_sshtrait_anon__when__build__then__scmBu } @Test - public void given__cloud_branch_rev_userpass_sshtrait_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_rev_userpass_sshtrait_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); SCMRevisionImpl revision = new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); source.setCredentialsId("user-pass"); @@ -404,8 +402,8 @@ public void given__cloud_branch_rev_userpass_sshtrait_anon__when__build__then__s } @Test - public void given__cloud_branch_rev_userkey_sshtrait_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_rev_userkey_sshtrait_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); SCMRevisionImpl revision = new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision) @@ -468,8 +466,8 @@ public void given__cloud_branch_rev_userkey_sshtrait_anon__when__build__then__sc } @Test - public void given__cloud_branch_rev_anon_sshtrait_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_rev_anon_sshtrait_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); SCMRevisionImpl revision = new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); source.setCredentialsId(null); @@ -531,8 +529,8 @@ public void given__cloud_branch_rev_anon_sshtrait_userkey__when__build__then__sc } @Test - public void given__cloud_branch_rev_userpass_sshtrait_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_rev_userpass_sshtrait_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); SCMRevisionImpl revision = new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); source.setCredentialsId("user-pass"); @@ -594,8 +592,8 @@ public void given__cloud_branch_rev_userpass_sshtrait_userkey__when__build__then } @Test - public void given__cloud_branch_rev_userkey_sshtrait_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_rev_userkey_sshtrait_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); SCMRevisionImpl revision = new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision) @@ -658,8 +656,8 @@ public void given__cloud_branch_rev_userkey_sshtrait_userkey__when__build__then_ } @Test - public void given__cloud_branch_norev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_norev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); source.setCredentialsId(null); GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, null); @@ -700,8 +698,8 @@ public void given__cloud_branch_norev_anon__when__build__then__scmBuilt() throws } @Test - public void given__cloud_branch_norev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_norev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); source.setCredentialsId("user-pass"); GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, null); @@ -742,8 +740,8 @@ public void given__cloud_branch_norev_userpass__when__build__then__scmBuilt() th } @Test - public void given__cloud_branch_norev_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_branch_norev_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); BranchSCMHead head = new BranchSCMHead("test-branch"); GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, null) .withCredentials("user-key") @@ -785,8 +783,8 @@ public void given__cloud_branch_norev_userkey__when__build__then__scmBuilt() thr } @Test - public void given__server_branch_rev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_branch_rev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); BranchSCMHead head = new BranchSCMHead("test-branch"); AbstractGitSCMSource.SCMRevisionImpl revision = new AbstractGitSCMSource.SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); @@ -799,27 +797,37 @@ public void given__server_branch_rev_anon__when__build__then__scmBuilt() throws assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is(nullValue())); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch")); @@ -844,8 +852,8 @@ public void given__server_branch_rev_anon__when__build__then__scmBuilt() throws } @Test - public void given__server_branch_rev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_branch_rev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); BranchSCMHead head = new BranchSCMHead("test-branch"); AbstractGitSCMSource.SCMRevisionImpl revision = new AbstractGitSCMSource.SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); @@ -858,27 +866,37 @@ public void given__server_branch_rev_userpass__when__build__then__scmBuilt() thr assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-pass")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch")); @@ -903,8 +921,8 @@ public void given__server_branch_rev_userpass__when__build__then__scmBuilt() thr } @Test - public void given__server_branch_rev_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_branch_rev_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); BranchSCMHead head = new BranchSCMHead("test-branch"); AbstractGitSCMSource.SCMRevisionImpl revision = new AbstractGitSCMSource.SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe"); @@ -918,27 +936,37 @@ public void given__server_branch_rev_userkey__when__build__then__scmBuilt() thro assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("git@github.test:tester/test-repo.git")); + assertThat( + instance.remote(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("git@github.test:tester/test-repo.git")); + assertThat( + config.getUrl(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-key")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("git@github.test:tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch")); @@ -963,8 +991,8 @@ public void given__server_branch_rev_userkey__when__build__then__scmBuilt() thro } @Test - public void given__server_branch_norev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_branch_norev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); BranchSCMHead head = new BranchSCMHead("test-branch"); source.setCredentialsId(null); GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, null); @@ -975,27 +1003,37 @@ public void given__server_branch_norev_anon__when__build__then__scmBuilt() throw assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is(nullValue())); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch")); @@ -1005,8 +1043,8 @@ public void given__server_branch_norev_anon__when__build__then__scmBuilt() throw } @Test - public void given__server_branch_norev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_branch_norev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); BranchSCMHead head = new BranchSCMHead("test-branch"); source.setCredentialsId("user-pass"); GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, null); @@ -1017,27 +1055,37 @@ public void given__server_branch_norev_userpass__when__build__then__scmBuilt() t assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-pass")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch")); @@ -1047,8 +1095,8 @@ public void given__server_branch_norev_userpass__when__build__then__scmBuilt() t } @Test - public void given__server_branch_norev_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_branch_norev_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); BranchSCMHead head = new BranchSCMHead("test-branch"); GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, null) .withCredentials("user-key") @@ -1060,27 +1108,37 @@ public void given__server_branch_norev_userkey__when__build__then__scmBuilt() th assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("git@github.test:tester/test-repo.git")); + assertThat( + instance.remote(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/tester/test-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("git@github.test:tester/test-repo.git")); + assertThat( + config.getUrl(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-key")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("git@github.test:tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch")); @@ -1090,8 +1148,8 @@ public void given__server_branch_norev_userkey__when__build__then__scmBuilt() th } @Test - public void given__cloud_pullHead_rev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_pullHead_rev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1157,8 +1215,8 @@ public void given__cloud_pullHead_rev_anon__when__build__then__scmBuilt() throws } @Test - public void given__cloud_pullHead_rev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_pullHead_rev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1224,7 +1282,7 @@ public void given__cloud_pullHead_rev_userpass__when__build__then__scmBuilt() th } @Test - public void given__cloud_pullHead_rev_userkey__when__build__then__scmBuilt() throws Exception { + void given__cloud_pullHead_rev_userkey__when__build__then__scmBuilt() throws Exception { PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1236,7 +1294,7 @@ public void given__cloud_pullHead_rev_userkey__when__build__then__scmBuilt() thr ChangeRequestCheckoutStrategy.HEAD); PullRequestSCMRevision revision = new PullRequestSCMRevision( head, "deadbeefcafebabedeadbeefcafebabedeadbeef", "cafebabedeadbeefcafebabedeadbeefcafebabe"); - createGitHubSCMSourceForTest(false, null); + createGitHubSCMSourceForTest(null); GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision) .withCredentials("user-key") .withResolver(GitHubSCMBuilder.SSH); @@ -1292,8 +1350,8 @@ public void given__cloud_pullHead_rev_userkey__when__build__then__scmBuilt() thr } @Test - public void given__cloud_pullHead_norev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_pullHead_norev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1342,8 +1400,8 @@ public void given__cloud_pullHead_norev_anon__when__build__then__scmBuilt() thro } @Test - public void given__cloud_pullHead_norev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_pullHead_norev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1392,8 +1450,8 @@ public void given__cloud_pullHead_norev_userpass__when__build__then__scmBuilt() } @Test - public void given__cloud_pullHead_norev_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_pullHead_norev_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1443,8 +1501,8 @@ public void given__cloud_pullHead_norev_userkey__when__build__then__scmBuilt() t } @Test - public void given__server_pullHead_rev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullHead_rev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1465,27 +1523,37 @@ public void given__server_pullHead_rev_anon__when__build__then__scmBuilt() throw assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is(nullValue())); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); @@ -1510,8 +1578,8 @@ public void given__server_pullHead_rev_anon__when__build__then__scmBuilt() throw } @Test - public void given__server_pullHead_rev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullHead_rev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1532,27 +1600,37 @@ public void given__server_pullHead_rev_userpass__when__build__then__scmBuilt() t assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-pass")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); @@ -1577,8 +1655,8 @@ public void given__server_pullHead_rev_userpass__when__build__then__scmBuilt() t } @Test - public void given__server_pullHead_rev_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullHead_rev_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1600,27 +1678,37 @@ public void given__server_pullHead_rev_userkey__when__build__then__scmBuilt() th assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("git@github.test:tester/test-repo.git")); + assertThat( + instance.remote(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1")); - assertThat(config.getUrl(), is("git@github.test:tester/test-repo.git")); + assertThat( + config.getUrl(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-key")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("git@github.test:tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); @@ -1645,8 +1733,8 @@ public void given__server_pullHead_rev_userkey__when__build__then__scmBuilt() th } @Test - public void given__server_pullHead_norev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullHead_norev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1665,27 +1753,37 @@ public void given__server_pullHead_norev_anon__when__build__then__scmBuilt() thr assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is(nullValue())); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); @@ -1695,8 +1793,8 @@ public void given__server_pullHead_norev_anon__when__build__then__scmBuilt() thr } @Test - public void given__server_pullHead_norev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullHead_norev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1715,27 +1813,37 @@ public void given__server_pullHead_norev_userpass__when__build__then__scmBuilt() assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-pass")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); @@ -1745,8 +1853,8 @@ public void given__server_pullHead_norev_userpass__when__build__then__scmBuilt() } @Test - public void given__server_pullHead_norev_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullHead_norev_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1766,27 +1874,37 @@ public void given__server_pullHead_norev_userkey__when__build__then__scmBuilt() assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("git@github.test:tester/test-repo.git")); + assertThat( + instance.remote(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); assertThat(config.getName(), is("origin")); assertThat(config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1")); - assertThat(config.getUrl(), is("git@github.test:tester/test-repo.git")); + assertThat( + config.getUrl(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-key")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("git@github.test:tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(1)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); @@ -1796,8 +1914,8 @@ public void given__server_pullHead_norev_userkey__when__build__then__scmBuilt() } @Test - public void given__cloud_pullMerge_rev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_pullMerge_rev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1878,8 +1996,8 @@ public void given__cloud_pullMerge_rev_anon__when__build__then__scmBuilt() throw } @Test - public void given__cloud_pullMerge_rev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_pullMerge_rev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -1960,8 +2078,8 @@ public void given__cloud_pullMerge_rev_userpass__when__build__then__scmBuilt() t } @Test - public void given__cloud_pullMerge_rev_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_pullMerge_rev_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -2043,8 +2161,8 @@ public void given__cloud_pullMerge_rev_userkey__when__build__then__scmBuilt() th } @Test - public void given__cloud_pullMerge_norev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_pullMerge_norev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -2105,8 +2223,8 @@ public void given__cloud_pullMerge_norev_anon__when__build__then__scmBuilt() thr } @Test - public void given__cloud_pullMerge_norev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_pullMerge_norev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -2167,8 +2285,8 @@ public void given__cloud_pullMerge_norev_userpass__when__build__then__scmBuilt() } @Test - public void given__cloud_pullMerge_norev_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(false, null); + void given__cloud_pullMerge_norev_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest(null); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -2230,8 +2348,8 @@ public void given__cloud_pullMerge_norev_userkey__when__build__then__scmBuilt() } @Test - public void given__server_pullMerge_rev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullMerge_rev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -2252,16 +2370,22 @@ public void given__server_pullMerge_rev_anon__when__build__then__scmBuilt() thro assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); @@ -2270,12 +2394,16 @@ public void given__server_pullMerge_rev_anon__when__build__then__scmBuilt() thro config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1 " + "+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is(nullValue())); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(2)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); @@ -2312,8 +2440,8 @@ public void given__server_pullMerge_rev_anon__when__build__then__scmBuilt() thro } @Test - public void given__server_pullMerge_rev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullMerge_rev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -2334,16 +2462,22 @@ public void given__server_pullMerge_rev_userpass__when__build__then__scmBuilt() assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); @@ -2352,12 +2486,16 @@ public void given__server_pullMerge_rev_userpass__when__build__then__scmBuilt() config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1 " + "+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-pass")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(2)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); @@ -2394,8 +2532,8 @@ public void given__server_pullMerge_rev_userpass__when__build__then__scmBuilt() } @Test - public void given__server_pullMerge_rev_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullMerge_rev_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -2417,16 +2555,22 @@ public void given__server_pullMerge_rev_userkey__when__build__then__scmBuilt() t assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("git@github.test:tester/test-repo.git")); + assertThat( + instance.remote(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); @@ -2435,12 +2579,16 @@ public void given__server_pullMerge_rev_userkey__when__build__then__scmBuilt() t config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1 " + "+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("git@github.test:tester/test-repo.git")); + assertThat( + config.getUrl(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-key")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("git@github.test:tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(2)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); @@ -2477,8 +2625,8 @@ public void given__server_pullMerge_rev_userkey__when__build__then__scmBuilt() t } @Test - public void given__server_pullMerge_norev_anon__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullMerge_norev_anon__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -2497,16 +2645,22 @@ public void given__server_pullMerge_norev_anon__when__build__then__scmBuilt() th assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); @@ -2515,12 +2669,16 @@ public void given__server_pullMerge_norev_anon__when__build__then__scmBuilt() th config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1 " + "+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is(nullValue())); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(2)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); @@ -2540,8 +2698,8 @@ public void given__server_pullMerge_norev_anon__when__build__then__scmBuilt() th } @Test - public void given__server_pullMerge_norev_userpass__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullMerge_norev_userpass__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -2560,16 +2718,22 @@ public void given__server_pullMerge_norev_userpass__when__build__then__scmBuilt( assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("https://github.test/tester/test-repo.git")); + assertThat( + instance.remote(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); @@ -2578,12 +2742,16 @@ public void given__server_pullMerge_norev_userpass__when__build__then__scmBuilt( config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1 " + "+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("https://github.test/tester/test-repo.git")); + assertThat( + config.getUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-pass")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("https://github.test/tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(2)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); @@ -2603,8 +2771,8 @@ public void given__server_pullMerge_norev_userpass__when__build__then__scmBuilt( } @Test - public void given__server_pullMerge_norev_userkey__when__build__then__scmBuilt() throws Exception { - createGitHubSCMSourceForTest(true, "https://github.test/tester/test-repo.git"); + void given__server_pullMerge_norev_userkey__when__build__then__scmBuilt() throws Exception { + createGitHubSCMSourceForTest("https://github.test/tester/test-repo.git"); PullRequestSCMHead head = new PullRequestSCMHead( "PR-1", "qa", @@ -2624,16 +2792,22 @@ public void given__server_pullMerge_norev_userkey__when__build__then__scmBuilt() assertThat( "expecting guess value until withGitHubRemote called", instance.remote(), - is("https://github.test/tester/test-repo.git")); + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/tester/test-repo.git")); assertThat(instance.browser(), instanceOf(GithubWeb.class)); - assertThat(instance.browser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + instance.browser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); instance.withGitHubRemote(); - assertThat(instance.remote(), is("git@github.test:tester/test-repo.git")); + assertThat( + instance.remote(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); GitSCM actual = instance.build(); assertThat(actual.getBrowser(), instanceOf(GithubWeb.class)); - assertThat(actual.getBrowser().getRepoUrl(), is("https://github.test/qa/qa-repo")); + assertThat( + actual.getBrowser().getRepoUrl(), + is("https://" + (configuredByUrl ? "github.test" : "github.com") + "/qa/qa-repo")); assertThat(actual.getGitTool(), nullValue()); assertThat(actual.getUserRemoteConfigs(), hasSize(1)); UserRemoteConfig config = actual.getUserRemoteConfigs().get(0); @@ -2642,12 +2816,16 @@ public void given__server_pullMerge_norev_userkey__when__build__then__scmBuilt() config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1 " + "+refs/heads/test-branch:refs/remotes/origin/test-branch")); - assertThat(config.getUrl(), is("git@github.test:tester/test-repo.git")); + assertThat( + config.getUrl(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(config.getCredentialsId(), is("user-key")); RemoteConfig origin = actual.getRepositoryByName("origin"); assertThat(origin, notNullValue()); assertThat(origin.getURIs(), hasSize(1)); - assertThat(origin.getURIs().get(0).toString(), is("git@github.test:tester/test-repo.git")); + assertThat( + origin.getURIs().get(0).toString(), + is("git@" + (configuredByUrl ? "github.test" : "github.com") + ":tester/test-repo.git")); assertThat(origin.getFetchRefSpecs(), hasSize(2)); assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head")); assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1")); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMFileSystemTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMFileSystemTest.java index 7e921f0d8..04d8cc30b 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMFileSystemTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMFileSystemTest.java @@ -35,10 +35,11 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import hudson.AbortException; +import java.util.stream.Stream; import jenkins.plugins.git.AbstractGitSCMSource; import jenkins.scm.api.SCMFile; import jenkins.scm.api.SCMFileSystem; @@ -47,49 +48,50 @@ import jenkins.scm.api.SCMRevision; import jenkins.scm.api.mixin.ChangeRequestCheckoutStrategy; import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) -public class GitHubSCMFileSystemTest extends AbstractGitHubWireMockTest { +@ParameterizedClass(name = "{index}: revision={0}") +@MethodSource("revisions") +class GitHubSCMFileSystemTest extends AbstractGitHubWireMockTest { - public static SCMHead master = new BranchSCMHead("master"); + private static final SCMHead MASTER = new BranchSCMHead("master"); private final SCMRevision revision; - public static PullRequestSCMHead prHead = new PullRequestSCMHead( + private static final PullRequestSCMHead PR_HEAD = new PullRequestSCMHead( "PR-2", "stephenc", "yolo", "master", 2, - (BranchSCMHead) master, + (BranchSCMHead) MASTER, SCMHeadOrigin.Fork.DEFAULT, ChangeRequestCheckoutStrategy.HEAD); - public static PullRequestSCMRevision prHeadRevision = new PullRequestSCMRevision( - prHead, "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1"); + private static final PullRequestSCMRevision PR_HEAD_REVISION = new PullRequestSCMRevision( + PR_HEAD, "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1"); - public static PullRequestSCMHead prMerge = new PullRequestSCMHead( + private static final PullRequestSCMHead PR_MERGE = new PullRequestSCMHead( "PR-2", "stephenc", "yolo", "master", 2, - (BranchSCMHead) master, + (BranchSCMHead) MASTER, SCMHeadOrigin.Fork.DEFAULT, ChangeRequestCheckoutStrategy.MERGE); - public static PullRequestSCMRevision prMergeRevision = new PullRequestSCMRevision( - prMerge, + private static final PullRequestSCMRevision PR_MERGE_REVISION = new PullRequestSCMRevision( + PR_MERGE, "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1", "38814ca33833ff5583624c29f305be9133f27a40"); - public static PullRequestSCMRevision prMergeInvalidRevision = new PullRequestSCMRevision( - prMerge, "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1", null); + private static final PullRequestSCMRevision PR_MERGE_INVALID_REVISION = new PullRequestSCMRevision( + PR_MERGE, "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1", null); - public static PullRequestSCMRevision prMergeNotMergeableRevision = new PullRequestSCMRevision( - prMerge, + private static final PullRequestSCMRevision PR_MERGE_NOT_MERGEABLE_REVISION = new PullRequestSCMRevision( + PR_MERGE, "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1", PullRequestSCMRevision.NOT_MERGEABLE_HASH); @@ -97,77 +99,69 @@ public class GitHubSCMFileSystemTest extends AbstractGitHubWireMockTest { private GitHubSCMSource source; public GitHubSCMFileSystemTest(String revision) { - this.revision = revision == null ? null : new AbstractGitSCMSource.SCMRevisionImpl(master, revision); + this.revision = revision == null ? null : new AbstractGitSCMSource.SCMRevisionImpl(MASTER, revision); } - @Parameterized.Parameters(name = "{index}: revision={0}") - public static String[] revisions() { - return new String[] { - "c0e024f89969b976da165eecaa71e09dc60c3da1", // Pull Request #2, unmerged but exposed on target - // repo - "e301dc6d5bb7e6e18d80e85f19caa92c74e15e96", - null - }; + static Stream revisions() { + return Stream.of( + "c0e024f89969b976da165eecaa71e09dc60c3da1", // Pull Request #2, unmerged but exposed on target + "e301dc6d5bb7e6e18d80e85f19caa92c74e15e96", // repo + null); } - @Before @Override - public void prepareMockGitHub() { - super.prepareMockGitHub(); + @BeforeEach + void beforeEach() throws Exception { + super.beforeEach(); + githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls/2")) + .willReturn(aResponse() + .withHeader("Content-Type", "application/json; charset=utf-8") + .withBodyFile("body-yolo-pulls-2-mergeable-true.json"))); source = new GitHubSCMSource( null, - "http://localhost:" + githubApi.port(), + "http://localhost:" + githubApi.getPort(), GitHubSCMSource.DescriptorImpl.SAME, null, "cloudbeers", "yolo"); } - @Override - void prepareMockGitHubFileMappings() { - super.prepareMockGitHubFileMappings(); - githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls/2")) - .willReturn(aResponse() - .withHeader("Content-Type", "application/json; charset=utf-8") - .withBodyFile("body-yolo-pulls-2-mergeable-true.json"))); - } - @Test - public void haveFilesystem() throws Exception { - assertThat(SCMFileSystem.of(source, master, revision), notNullValue()); + void haveFilesystem() throws Exception { + assertThat(SCMFileSystem.of(source, MASTER, revision), notNullValue()); } @Test - public void rootIsADirectory() throws Exception { - SCMFileSystem fs = SCMFileSystem.of(source, master, revision); + void rootIsADirectory() throws Exception { + SCMFileSystem fs = SCMFileSystem.of(source, MASTER, revision); assertThat(fs.getRoot().getType(), is(SCMFile.Type.DIRECTORY)); } @Test - public void listFilesInRoot() throws Exception { - SCMFileSystem fs = SCMFileSystem.of(source, master, revision); + void listFilesInRoot() throws Exception { + SCMFileSystem fs = SCMFileSystem.of(source, MASTER, revision); assertThat(fs.getRoot().children(), hasItem(Matchers.hasProperty("name", is("README.md")))); } @Test - public void readmeIsAFile() throws Exception { - SCMFileSystem fs = SCMFileSystem.of(source, master, revision); + void readmeIsAFile() throws Exception { + SCMFileSystem fs = SCMFileSystem.of(source, MASTER, revision); assertThat(fs.getRoot().child("README.md").getType(), is(SCMFile.Type.REGULAR_FILE)); } @Test - public void readmeContents() throws Exception { - SCMFileSystem fs = SCMFileSystem.of(source, master, revision); + void readmeContents() throws Exception { + SCMFileSystem fs = SCMFileSystem.of(source, MASTER, revision); assertThat(fs.getRoot().child("README.md").contentAsString(), containsString("yolo")); } @Test - public void readFileFromDir() throws Exception { - assumeThat(revision, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class)); - assumeThat( - ((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash(), - is("c0e024f89969b976da165eecaa71e09dc60c3da1")); - SCMFileSystem fs = SCMFileSystem.of(source, master, revision); + void readFileFromDir() throws Exception { + assumeTrue(revision instanceof AbstractGitSCMSource.SCMRevisionImpl); + assumeTrue(((AbstractGitSCMSource.SCMRevisionImpl) revision) + .getHash() + .equals("c0e024f89969b976da165eecaa71e09dc60c3da1")); + SCMFileSystem fs = SCMFileSystem.of(source, MASTER, revision); String expected = "Some text\n"; // In previous versions of github-api, GHContent.read() (called by contentAsString()) @@ -191,33 +185,33 @@ public void readFileFromDir() throws Exception { } @Test - public void resolveDir() throws Exception { - assumeThat(revision, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class)); - assumeThat( - ((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash(), - is("c0e024f89969b976da165eecaa71e09dc60c3da1")); - SCMFileSystem fs = SCMFileSystem.of(source, master, revision); + void resolveDir() throws Exception { + assumeTrue(revision instanceof AbstractGitSCMSource.SCMRevisionImpl); + assumeTrue(((AbstractGitSCMSource.SCMRevisionImpl) revision) + .getHash() + .equals("c0e024f89969b976da165eecaa71e09dc60c3da1")); + SCMFileSystem fs = SCMFileSystem.of(source, MASTER, revision); assertThat(fs.getRoot().child("fu").getType(), is(SCMFile.Type.DIRECTORY)); } @Test - public void listDir() throws Exception { - assumeThat(revision, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class)); - assumeThat( - ((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash(), - is("c0e024f89969b976da165eecaa71e09dc60c3da1")); - SCMFileSystem fs = SCMFileSystem.of(source, master, revision); + void listDir() throws Exception { + assumeTrue(revision instanceof AbstractGitSCMSource.SCMRevisionImpl); + assumeTrue(((AbstractGitSCMSource.SCMRevisionImpl) revision) + .getHash() + .equals("c0e024f89969b976da165eecaa71e09dc60c3da1")); + SCMFileSystem fs = SCMFileSystem.of(source, MASTER, revision); assertThat( fs.getRoot().child("fu").children(), hasItem(Matchers.hasProperty("name", is("manchu.txt")))); } @Test - public void resolveDirPRHead() throws Exception { - assumeThat(revision, nullValue()); + void resolveDirPRHead() throws Exception { + assumeTrue(revision == null); - assertThat(prHeadRevision.isMerge(), is(false)); + assertThat(PR_HEAD_REVISION.isMerge(), is(false)); - SCMFileSystem fs = SCMFileSystem.of(source, prHead, prHeadRevision); + SCMFileSystem fs = SCMFileSystem.of(source, PR_HEAD, PR_HEAD_REVISION); assertThat(fs, instanceOf(GitHubSCMFileSystem.class)); // We can't check the sha, but we can check last modified @@ -228,12 +222,12 @@ public void resolveDirPRHead() throws Exception { } @Test - public void resolveDirPRMerge() throws Exception { - assumeThat(revision, nullValue()); + void resolveDirPRMerge() throws Exception { + assumeTrue(revision == null); - assertThat(prMergeRevision.isMerge(), is(true)); + assertThat(PR_MERGE_REVISION.isMerge(), is(true)); - SCMFileSystem fs = SCMFileSystem.of(source, prMerge, prMergeRevision); + SCMFileSystem fs = SCMFileSystem.of(source, PR_MERGE, PR_MERGE_REVISION); assertThat(fs, instanceOf(GitHubSCMFileSystem.class)); // We can't check the sha, but we can check last modified @@ -244,22 +238,19 @@ public void resolveDirPRMerge() throws Exception { } @Test - public void resolveDirPRInvalidMerge() throws Exception { - assumeThat(revision, nullValue()); + void resolveDirPRInvalidMerge() throws Exception { + assumeTrue(revision == null); - assertThat(prMergeInvalidRevision.isMerge(), is(true)); + assertThat(PR_MERGE_INVALID_REVISION.isMerge(), is(true)); - SCMFileSystem fs = SCMFileSystem.of(source, prMerge, prMergeInvalidRevision); + SCMFileSystem fs = SCMFileSystem.of(source, PR_MERGE, PR_MERGE_INVALID_REVISION); assertThat(fs, nullValue()); } - @Test(expected = AbortException.class) - public void resolveDirPRNotMergeable() throws Exception { - assumeThat(revision, nullValue()); - - assertThat(prMergeNotMergeableRevision.isMerge(), is(true)); - - SCMFileSystem fs = SCMFileSystem.of(source, prMerge, prMergeNotMergeableRevision); - fail(); + @Test + void resolveDirPRNotMergeable() { + assumeTrue(revision == null); + assertThat(PR_MERGE_NOT_MERGEABLE_REVISION.isMerge(), is(true)); + assertThrows(AbortException.class, () -> SCMFileSystem.of(source, PR_MERGE, PR_MERGE_NOT_MERGEABLE_REVISION)); } } diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMNavigatorTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMNavigatorTest.java index f2b8d395a..b1126e9fc 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMNavigatorTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMNavigatorTest.java @@ -27,7 +27,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.cloudbees.plugins.credentials.Credentials; import com.cloudbees.plugins.credentials.CredentialsScope; @@ -65,19 +65,19 @@ import jenkins.scm.api.trait.SCMTrait; import jenkins.scm.impl.NoOpProjectObserver; import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.MockFolder; import org.mockito.Mock; import org.mockito.Mockito; -public class GitHubSCMNavigatorTest extends AbstractGitHubWireMockTest { +class GitHubSCMNavigatorTest extends AbstractGitHubWireMockTest { @Mock private SCMSourceOwner scmSourceOwner; - private BaseStandardCredentials credentials; + private final BaseStandardCredentials credentials; { try { @@ -90,17 +90,17 @@ public class GitHubSCMNavigatorTest extends AbstractGitHubWireMockTest { private GitHubSCMNavigator navigator; - @Before @Override - public void prepareMockGitHub() { - super.prepareMockGitHub(); + @BeforeEach + void beforeEach() throws Exception { + super.beforeEach(); setCredentials(Collections.emptyList()); navigator = navigatorForRepoOwner("cloudbeers", null); } private GitHubSCMNavigator navigatorForRepoOwner(String repoOwner, @Nullable String credentialsId) { GitHubSCMNavigator navigator = new GitHubSCMNavigator(repoOwner); - navigator.setApiUri("http://localhost:" + githubApi.port()); + navigator.setApiUri("http://localhost:" + githubApi.getPort()); navigator.setCredentialsId(credentialsId); return navigator; } @@ -111,7 +111,7 @@ private void setCredentials(List credentials) { } @Test - public void fetchSmokes() throws Exception { + void fetchSmokes() throws Exception { final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -121,7 +121,7 @@ public void fetchSmokes() throws Exception { } @Test - public void fetchReposWithoutTeamSlug() throws Exception { + void fetchReposWithoutTeamSlug() throws Exception { final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -132,7 +132,7 @@ public void fetchReposWithoutTeamSlug() throws Exception { } @Test - public void fetchReposFromTeamSlug() throws Exception { + void fetchReposFromTeamSlug() throws Exception { final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -148,7 +148,7 @@ public void fetchReposFromTeamSlug() throws Exception { } @Test - public void fetchOneRepoWithTeamSlug_InTeam() throws Exception { + void fetchOneRepoWithTeamSlug_InTeam() throws Exception { final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -161,7 +161,7 @@ public void fetchOneRepoWithTeamSlug_InTeam() throws Exception { } @Test - public void fetchOneRepoWithTeamSlug_NotInTeam() throws Exception { + void fetchOneRepoWithTeamSlug_NotInTeam() throws Exception { final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -174,7 +174,7 @@ public void fetchOneRepoWithTeamSlug_NotInTeam() throws Exception { } @Test - public void fetchOneRepo_BelongingToAuthenticatedUser() throws Exception { + void fetchOneRepo_BelongingToAuthenticatedUser() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); final Set projectNames = new HashSet<>(); @@ -186,7 +186,7 @@ public void fetchOneRepo_BelongingToAuthenticatedUser() throws Exception { } @Test - public void fetchRepos_BelongingToAuthenticatedUser_FilteredByTopic() throws Exception { + void fetchRepos_BelongingToAuthenticatedUser_FilteredByTopic() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); navigator.setTraits(Collections.singletonList(new TopicsTrait("awesome"))); @@ -199,7 +199,7 @@ public void fetchRepos_BelongingToAuthenticatedUser_FilteredByTopic() throws Exc } @Test - public void fetchRepos_BelongingToAuthenticatedUser_FilteredByTopic_ExcludeForks() throws Exception { + void fetchRepos_BelongingToAuthenticatedUser_FilteredByTopic_ExcludeForks() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); navigator.setTraits(Arrays.asList(new TopicsTrait("api"), new ExcludeForkedRepositoriesTrait())); @@ -212,7 +212,7 @@ public void fetchRepos_BelongingToAuthenticatedUser_FilteredByTopic_ExcludeForks } @Test - public void fetchRepos_BelongingToAuthenticatedUser_FilteredByTopic_RemovesAll() throws Exception { + void fetchRepos_BelongingToAuthenticatedUser_FilteredByTopic_RemovesAll() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); navigator.setTraits(Collections.singletonList(new TopicsTrait("nope"))); @@ -225,7 +225,7 @@ public void fetchRepos_BelongingToAuthenticatedUser_FilteredByTopic_RemovesAll() } @Test - public void fetchRepos_BelongingToAuthenticatedUser_FilteredByMultipleTopics() throws Exception { + void fetchRepos_BelongingToAuthenticatedUser_FilteredByMultipleTopics() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); navigator.setTraits(Collections.singletonList(new TopicsTrait("cool, great,was-awesome"))); @@ -238,7 +238,7 @@ public void fetchRepos_BelongingToAuthenticatedUser_FilteredByMultipleTopics() t } @Test - public void fetchRepos_BelongingToAuthenticatedUser_ExcludeByTopic() throws Exception { + void fetchRepos_BelongingToAuthenticatedUser_ExcludeByTopic() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); navigator.setTraits(Collections.singletonList(new TopicsTrait("-awesome"))); @@ -251,7 +251,7 @@ public void fetchRepos_BelongingToAuthenticatedUser_ExcludeByTopic() throws Exce } @Test - public void fetchRepos_BelongingToAuthenticatedUser_ExcludeAndFilterByTopic() throws Exception { + void fetchRepos_BelongingToAuthenticatedUser_ExcludeAndFilterByTopic() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); navigator.setTraits(Collections.singletonList(new TopicsTrait("-awesome,octocat"))); @@ -264,7 +264,7 @@ public void fetchRepos_BelongingToAuthenticatedUser_ExcludeAndFilterByTopic() th } @Test - public void fetchOneRepo_BelongingToAuthenticatedUser_ExcludingArchived() throws Exception { + void fetchOneRepo_BelongingToAuthenticatedUser_ExcludingArchived() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); navigator.setTraits(Collections.singletonList(new ExcludeArchivedRepositoriesTrait())); @@ -277,7 +277,7 @@ public void fetchOneRepo_BelongingToAuthenticatedUser_ExcludingArchived() throws } @Test - public void fetchOneRepo_ExcludingPublic() throws Exception { + void fetchOneRepo_ExcludingPublic() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); navigator.setTraits(Collections.singletonList(new ExcludePublicRepositoriesTrait())); @@ -290,7 +290,7 @@ public void fetchOneRepo_ExcludingPublic() throws Exception { } @Test - public void fetchOneRepo_ExcludingPrivate() throws Exception { + void fetchOneRepo_ExcludingPrivate() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); navigator.setTraits(Collections.singletonList(new ExcludePrivateRepositoriesTrait())); @@ -303,7 +303,7 @@ public void fetchOneRepo_ExcludingPrivate() throws Exception { } @Test - public void fetchOneRepo_ExcludingForked() throws Exception { + void fetchOneRepo_ExcludingForked() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); navigator.setTraits(Collections.singletonList(new ExcludeForkedRepositoriesTrait())); @@ -316,7 +316,7 @@ public void fetchOneRepo_ExcludingForked() throws Exception { } @Test - public void fetchOneRepo_BelongingToOrg() throws Exception { + void fetchOneRepo_BelongingToOrg() throws Exception { final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -326,7 +326,7 @@ public void fetchOneRepo_BelongingToOrg() throws Exception { } @Test - public void fetchOneRepo_BelongingToOrg_ExcludingArchived() throws Exception { + void fetchOneRepo_BelongingToOrg_ExcludingArchived() throws Exception { navigator.setTraits(Collections.singletonList(new ExcludeArchivedRepositoriesTrait())); final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -337,7 +337,7 @@ public void fetchOneRepo_BelongingToOrg_ExcludingArchived() throws Exception { } @Test - public void fetchOneRepo_BelongingToUser() throws Exception { + void fetchOneRepo_BelongingToUser() throws Exception { navigator = navigatorForRepoOwner("stephenc", null); final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -348,7 +348,7 @@ public void fetchOneRepo_BelongingToUser() throws Exception { } @Test - public void fetchOneRepo_BelongingToUser_ExcludingArchived() throws Exception { + void fetchOneRepo_BelongingToUser_ExcludingArchived() throws Exception { navigator = navigatorForRepoOwner("stephenc", null); navigator.setTraits(Collections.singletonList(new ExcludeArchivedRepositoriesTrait())); final Set projectNames = new HashSet<>(); @@ -360,7 +360,7 @@ public void fetchOneRepo_BelongingToUser_ExcludingArchived() throws Exception { } @Test - public void fetchRepos_BelongingToAuthenticatedUser() throws Exception { + void fetchRepos_BelongingToAuthenticatedUser() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); final Set projectNames = new HashSet<>(); @@ -372,7 +372,7 @@ public void fetchRepos_BelongingToAuthenticatedUser() throws Exception { } @Test - public void fetchRepos_BelongingToAuthenticatedUser_ExcludingArchived() throws Exception { + void fetchRepos_BelongingToAuthenticatedUser_ExcludingArchived() throws Exception { setCredentials(Collections.singletonList(credentials)); navigator = navigatorForRepoOwner("stephenc", credentials.getId()); navigator.setTraits(Collections.singletonList(new ExcludeArchivedRepositoriesTrait())); @@ -385,7 +385,7 @@ public void fetchRepos_BelongingToAuthenticatedUser_ExcludingArchived() throws E } @Test - public void fetchRepos_BelongingToOrg() throws Exception { + void fetchRepos_BelongingToOrg() throws Exception { final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -395,7 +395,7 @@ public void fetchRepos_BelongingToOrg() throws Exception { } @Test - public void fetchRepos_BelongingToOrg_ExcludingArchived() throws Exception { + void fetchRepos_BelongingToOrg_ExcludingArchived() throws Exception { navigator.setTraits(Collections.singletonList(new ExcludeArchivedRepositoriesTrait())); final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -406,7 +406,7 @@ public void fetchRepos_BelongingToOrg_ExcludingArchived() throws Exception { } @Test - public void fetchRepos_BelongingToOrg_ExcludingPublic() throws Exception { + void fetchRepos_BelongingToOrg_ExcludingPublic() throws Exception { navigator.setTraits(Collections.singletonList(new ExcludePublicRepositoriesTrait())); final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -418,7 +418,7 @@ public void fetchRepos_BelongingToOrg_ExcludingPublic() throws Exception { } @Test - public void fetchRepos_BelongingToOrg_ExcludingPrivate() throws Exception { + void fetchRepos_BelongingToOrg_ExcludingPrivate() throws Exception { navigator.setTraits(Collections.singletonList(new ExcludePrivateRepositoriesTrait())); final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -429,7 +429,7 @@ public void fetchRepos_BelongingToOrg_ExcludingPrivate() throws Exception { } @Test - public void fetchRepos_BelongingToUser() throws Exception { + void fetchRepos_BelongingToUser() throws Exception { navigator = navigatorForRepoOwner("stephenc", null); final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -440,7 +440,7 @@ public void fetchRepos_BelongingToUser() throws Exception { } @Test - public void fetchRepos_BelongingToUser_ExcludingArchived() throws Exception { + void fetchRepos_BelongingToUser_ExcludingArchived() throws Exception { navigator = navigatorForRepoOwner("stephenc", null); navigator.setTraits(Collections.singletonList(new ExcludeArchivedRepositoriesTrait())); final Set projectNames = new HashSet<>(); @@ -452,7 +452,7 @@ public void fetchRepos_BelongingToUser_ExcludingArchived() throws Exception { } @Test - public void appliesFilters() throws Exception { + void appliesFilters() throws Exception { final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = getObserver(projectNames); @@ -462,7 +462,7 @@ public void appliesFilters() throws Exception { } @Test - public void fetchBadRepo() throws Exception { + void fetchBadRepo() throws Exception { final Set projectNames = new HashSet<>(); final SCMSourceObserver observer = new SCMSourceObserver() { @NonNull @@ -498,7 +498,7 @@ public void addAttribute(@NonNull String key, @Nullable Object value) } @Test - public void fetchActions() throws Exception { + void fetchActions() throws Exception { assertThat( navigator.fetchActions(Mockito.mock(SCMNavigatorOwner.class), null, null), Matchers.containsInAnyOrder( @@ -509,7 +509,7 @@ public void fetchActions() throws Exception { } @Test - public void fetchActionsWithAvatar() throws Exception { + void fetchActionsWithAvatar() throws Exception { navigator.setEnableAvatar(true); assertThat( navigator.fetchActions(Mockito.mock(SCMNavigatorOwner.class), null, null), @@ -521,7 +521,7 @@ public void fetchActionsWithAvatar() throws Exception { } @Test - public void doFillScanCredentials() throws Exception { + void doFillScanCredentials() throws Exception { final GitHubSCMNavigator.DescriptorImpl d = r.jenkins.getDescriptorByType(GitHubSCMNavigator.DescriptorImpl.class); final MockFolder dummy = r.createFolder("dummy"); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMNavigatorTraitsTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMNavigatorTraitsTest.java index 0caab92bc..4ac781698 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMNavigatorTraitsTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMNavigatorTraitsTest.java @@ -22,23 +22,34 @@ import jenkins.scm.impl.trait.WildcardSCMHeadFilterTrait; import org.hamcrest.Matcher; import org.hamcrest.Matchers; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class GitHubSCMNavigatorTraitsTest { - @ClassRule - public static JenkinsRule j = new JenkinsRule(); +@WithJenkins +class GitHubSCMNavigatorTraitsTest { - @Rule - public TestName currentTestName = new TestName(); + private static JenkinsRule j; + + private String currentTestName; + + @BeforeAll + static void beforeAll(JenkinsRule rule) { + j = rule; + } + + @BeforeEach + void beforeEach(TestInfo info) { + currentTestName = info.getTestMethod().orElseThrow().getName(); + } private GitHubSCMNavigator load() { - return load(currentTestName.getMethodName()); + return load(currentTestName); } private GitHubSCMNavigator load(String dataSet) { @@ -55,7 +66,7 @@ private static Matcher>> branchDiscoveryTraitItem } private static Matcher> sshCheckoutTraitItem(Matcher credentialsMatcher) { - return Matchers.>allOf( + return Matchers.allOf( Matchers.instanceOf(SSHCheckoutTrait.class), hasProperty("credentialsId", credentialsMatcher)); } @@ -91,7 +102,7 @@ private static Matcher wildcardSCMHeadFilterTraitItem(String includes, S } @Test - public void modern() throws Exception { + void modern() { GitHubSCMNavigator instance = load(); assertThat(instance.id(), is("https://api.github.com::cloudbeers")); assertThat(instance.getRepoOwner(), is("cloudbeers")); @@ -101,7 +112,7 @@ public void modern() throws Exception { } @Test - public void basic_cloud() throws Exception { + void basic_cloud() { GitHubSCMNavigator instance = load(); assertThat(instance.id(), is("https://api.github.com::cloudbeers")); assertThat(instance.getRepoOwner(), is("cloudbeers")); @@ -130,7 +141,7 @@ public void basic_cloud() throws Exception { } @Test - public void basic_server() throws Exception { + void basic_server() { GitHubSCMNavigator instance = load(); assertThat(instance.id(), is("https://github.test/api/v3::cloudbeers")); assertThat(instance.getRepoOwner(), is("cloudbeers")); @@ -160,7 +171,7 @@ public void basic_server() throws Exception { } @Test - public void use_agent_checkout() throws Exception { + void use_agent_checkout() { GitHubSCMNavigator instance = load(); assertThat(instance.id(), is("https://github.test/api/v3::cloudbeers")); assertThat(instance.getRepoOwner(), is("cloudbeers")); @@ -191,7 +202,7 @@ public void use_agent_checkout() throws Exception { @Issue("JENKINS-45467") @Test - public void same_checkout_credentials() throws Exception { + void same_checkout_credentials() { GitHubSCMNavigator instance = load(); assertThat(instance.id(), is("https://github.test/api/v3::cloudbeers")); assertThat(instance.getRepoOwner(), is("cloudbeers")); @@ -220,7 +231,7 @@ public void same_checkout_credentials() throws Exception { } @Test - public void limit_repositories() throws Exception { + void limit_repositories() { GitHubSCMNavigator instance = load(); assertThat(instance.id(), is("https://github.test/api/v3::cloudbeers")); assertThat(instance.getRepoOwner(), is("cloudbeers")); @@ -247,7 +258,7 @@ public void limit_repositories() throws Exception { } @Test - public void exclude_branches() throws Exception { + void exclude_branches() { GitHubSCMNavigator instance = load(); assertThat(instance.id(), is("https://api.github.com::cloudbeers")); assertThat(instance.getRepoOwner(), is("cloudbeers")); @@ -269,7 +280,7 @@ public void exclude_branches() throws Exception { } @Test - public void limit_branches() throws Exception { + void limit_branches() { GitHubSCMNavigator instance = load(); assertThat(instance.id(), is("https://api.github.com::cloudbeers")); assertThat(instance.getRepoOwner(), is("cloudbeers")); @@ -291,37 +302,37 @@ public void limit_branches() throws Exception { } @Test - public void build_000000() throws Exception { + void build_000000() { GitHubSCMNavigator instance = load(); assertThat(instance.getTraits(), empty()); } @Test - public void build_000001() throws Exception { + void build_000001() { GitHubSCMNavigator instance = load(); assertThat(instance.getTraits(), contains(forkPullRequestDiscoveryTraitItem(2))); } @Test - public void build_000010() throws Exception { + void build_000010() { GitHubSCMNavigator instance = load(); assertThat(instance.getTraits(), contains(forkPullRequestDiscoveryTraitItem(1))); } @Test - public void build_000011() throws Exception { + void build_000011() { GitHubSCMNavigator instance = load(); assertThat(instance.getTraits(), contains(forkPullRequestDiscoveryTraitItem(3))); } @Test - public void build_000100() throws Exception { + void build_000100() { GitHubSCMNavigator instance = load(); assertThat(instance.getTraits(), contains(originPullRequestDiscoveryTraitItem(2))); } @Test - public void build_000101() throws Exception { + void build_000101() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -329,7 +340,7 @@ public void build_000101() throws Exception { } @Test - public void build_000110() throws Exception { + void build_000110() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -337,7 +348,7 @@ public void build_000110() throws Exception { } @Test - public void build_000111() throws Exception { + void build_000111() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -345,13 +356,13 @@ public void build_000111() throws Exception { } @Test - public void build_001000() throws Exception { + void build_001000() { GitHubSCMNavigator instance = load(); assertThat(instance.getTraits(), contains(originPullRequestDiscoveryTraitItem(1))); } @Test - public void build_001001() throws Exception { + void build_001001() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -359,7 +370,7 @@ public void build_001001() throws Exception { } @Test - public void build_001010() throws Exception { + void build_001010() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -367,7 +378,7 @@ public void build_001010() throws Exception { } @Test - public void build_001011() throws Exception { + void build_001011() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -375,13 +386,13 @@ public void build_001011() throws Exception { } @Test - public void build_001100() throws Exception { + void build_001100() { GitHubSCMNavigator instance = load(); assertThat(instance.getTraits(), contains(originPullRequestDiscoveryTraitItem(3))); } @Test - public void build_001101() throws Exception { + void build_001101() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -389,7 +400,7 @@ public void build_001101() throws Exception { } @Test - public void build_001110() throws Exception { + void build_001110() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -397,7 +408,7 @@ public void build_001110() throws Exception { } @Test - public void build_001111() throws Exception { + void build_001111() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -405,13 +416,13 @@ public void build_001111() throws Exception { } @Test - public void build_010000() throws Exception { + void build_010000() { GitHubSCMNavigator instance = load(); assertThat(instance.getTraits(), contains(branchDiscoveryTraitItem(false, true))); } @Test - public void build_010001() throws Exception { + void build_010001() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -419,7 +430,7 @@ public void build_010001() throws Exception { } @Test - public void build_010010() throws Exception { + void build_010010() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -427,7 +438,7 @@ public void build_010010() throws Exception { } @Test - public void build_010011() throws Exception { + void build_010011() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -435,7 +446,7 @@ public void build_010011() throws Exception { } @Test - public void build_010100() throws Exception { + void build_010100() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -443,7 +454,7 @@ public void build_010100() throws Exception { } @Test - public void build_010101() throws Exception { + void build_010101() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -454,7 +465,7 @@ public void build_010101() throws Exception { } @Test - public void build_010110() throws Exception { + void build_010110() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -465,7 +476,7 @@ public void build_010110() throws Exception { } @Test - public void build_010111() throws Exception { + void build_010111() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -476,7 +487,7 @@ public void build_010111() throws Exception { } @Test - public void build_011000() throws Exception { + void build_011000() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -484,7 +495,7 @@ public void build_011000() throws Exception { } @Test - public void build_011001() throws Exception { + void build_011001() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -495,7 +506,7 @@ public void build_011001() throws Exception { } @Test - public void build_011010() throws Exception { + void build_011010() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -506,7 +517,7 @@ public void build_011010() throws Exception { } @Test - public void build_011011() throws Exception { + void build_011011() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -517,7 +528,7 @@ public void build_011011() throws Exception { } @Test - public void build_011100() throws Exception { + void build_011100() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -525,7 +536,7 @@ public void build_011100() throws Exception { } @Test - public void build_011101() throws Exception { + void build_011101() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -536,7 +547,7 @@ public void build_011101() throws Exception { } @Test - public void build_011110() throws Exception { + void build_011110() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -547,7 +558,7 @@ public void build_011110() throws Exception { } @Test - public void build_011111() throws Exception { + void build_011111() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -558,13 +569,13 @@ public void build_011111() throws Exception { } @Test - public void build_100000() throws Exception { + void build_100000() { GitHubSCMNavigator instance = load(); assertThat(instance.getTraits(), contains(branchDiscoveryTraitItem(true, false))); } @Test - public void build_100001() throws Exception { + void build_100001() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -572,7 +583,7 @@ public void build_100001() throws Exception { } @Test - public void build_100010() throws Exception { + void build_100010() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -580,7 +591,7 @@ public void build_100010() throws Exception { } @Test - public void build_100011() throws Exception { + void build_100011() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -588,7 +599,7 @@ public void build_100011() throws Exception { } @Test - public void build_100100() throws Exception { + void build_100100() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -596,7 +607,7 @@ public void build_100100() throws Exception { } @Test - public void build_100101() throws Exception { + void build_100101() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -607,7 +618,7 @@ public void build_100101() throws Exception { } @Test - public void build_100110() throws Exception { + void build_100110() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -618,7 +629,7 @@ public void build_100110() throws Exception { } @Test - public void build_100111() throws Exception { + void build_100111() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -629,7 +640,7 @@ public void build_100111() throws Exception { } @Test - public void build_101000() throws Exception { + void build_101000() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -637,7 +648,7 @@ public void build_101000() throws Exception { } @Test - public void build_101001() throws Exception { + void build_101001() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -648,7 +659,7 @@ public void build_101001() throws Exception { } @Test - public void build_101010() throws Exception { + void build_101010() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -659,7 +670,7 @@ public void build_101010() throws Exception { } @Test - public void build_101011() throws Exception { + void build_101011() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -670,7 +681,7 @@ public void build_101011() throws Exception { } @Test - public void build_101100() throws Exception { + void build_101100() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -678,7 +689,7 @@ public void build_101100() throws Exception { } @Test - public void build_101101() throws Exception { + void build_101101() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -689,7 +700,7 @@ public void build_101101() throws Exception { } @Test - public void build_101110() throws Exception { + void build_101110() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -700,7 +711,7 @@ public void build_101110() throws Exception { } @Test - public void build_101111() throws Exception { + void build_101111() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -711,13 +722,13 @@ public void build_101111() throws Exception { } @Test - public void build_110000() throws Exception { + void build_110000() { GitHubSCMNavigator instance = load(); assertThat(instance.getTraits(), contains(branchDiscoveryTraitItem(true, true))); } @Test - public void build_110001() throws Exception { + void build_110001() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -725,7 +736,7 @@ public void build_110001() throws Exception { } @Test - public void build_110010() throws Exception { + void build_110010() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -733,7 +744,7 @@ public void build_110010() throws Exception { } @Test - public void build_110011() throws Exception { + void build_110011() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -741,7 +752,7 @@ public void build_110011() throws Exception { } @Test - public void build_110100() throws Exception { + void build_110100() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -749,7 +760,7 @@ public void build_110100() throws Exception { } @Test - public void build_110101() throws Exception { + void build_110101() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -760,7 +771,7 @@ public void build_110101() throws Exception { } @Test - public void build_110110() throws Exception { + void build_110110() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -771,7 +782,7 @@ public void build_110110() throws Exception { } @Test - public void build_110111() throws Exception { + void build_110111() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -782,7 +793,7 @@ public void build_110111() throws Exception { } @Test - public void build_111000() throws Exception { + void build_111000() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -790,7 +801,7 @@ public void build_111000() throws Exception { } @Test - public void build_111001() throws Exception { + void build_111001() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -801,7 +812,7 @@ public void build_111001() throws Exception { } @Test - public void build_111010() throws Exception { + void build_111010() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -812,7 +823,7 @@ public void build_111010() throws Exception { } @Test - public void build_111011() throws Exception { + void build_111011() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -823,7 +834,7 @@ public void build_111011() throws Exception { } @Test - public void build_111100() throws Exception { + void build_111100() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -831,7 +842,7 @@ public void build_111100() throws Exception { } @Test - public void build_111101() throws Exception { + void build_111101() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -842,7 +853,7 @@ public void build_111101() throws Exception { } @Test - public void build_111110() throws Exception { + void build_111110() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -853,7 +864,7 @@ public void build_111110() throws Exception { } @Test - public void build_111111() throws Exception { + void build_111111() { GitHubSCMNavigator instance = load(); assertThat( instance.getTraits(), @@ -865,7 +876,7 @@ public void build_111111() throws Exception { @WithoutJenkins @Test - public void given__legacyCode__when__constructor_cloud__then__discoveryTraitDefaults() throws Exception { + void given__legacyCode__when__constructor_cloud__then__discoveryTraitDefaults() { GitHubSCMNavigator instance = new GitHubSCMNavigator(null, "cloudbeers", "bcaef157-f105-407f-b150-df7722eab6c1", "SAME"); assertThat(instance.id(), is("https://api.github.com::cloudbeers")); @@ -889,7 +900,7 @@ public void given__legacyCode__when__constructor_cloud__then__discoveryTraitDefa } @Test - public void given__legacyCode__when__constructor_server__then__discoveryTraitDefaults() throws Exception { + void given__legacyCode__when__constructor_server__then__discoveryTraitDefaults() { GitHubSCMNavigator instance = new GitHubSCMNavigator( "https://github.test/api/v3", "cloudbeers", @@ -917,14 +928,14 @@ public void given__legacyCode__when__constructor_server__then__discoveryTraitDef } @Test - public void given__instance__when__setTraits_empty__then__traitsEmpty() { + void given__instance__when__setTraits_empty__then__traitsEmpty() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(new SCMTrait[0]); assertThat(instance.getTraits(), is(Collections.>emptyList())); } @Test - public void given__instance__when__setTraits__then__traitsSet() { + void given__instance__when__setTraits__then__traitsSet() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits( Arrays.asList(new BranchDiscoveryTrait(BranchDiscoveryTrait.EXCLUDE_PRS), new SSHCheckoutTrait(null))); @@ -934,21 +945,21 @@ public void given__instance__when__setTraits__then__traitsSet() { } @Test - public void given__instance__when__setCredentials_empty__then__credentials_null() { + void given__instance__when__setCredentials_empty__then__credentials_null() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setCredentialsId(""); assertThat(instance.getCredentialsId(), is(nullValue())); } @Test - public void given__instance__when__setCredentials_null__then__credentials_null() { + void given__instance__when__setCredentials_null__then__credentials_null() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setCredentialsId(""); assertThat(instance.getCredentialsId(), is(nullValue())); } @Test - public void given__instance__when__setCredentials__then__credentials_set() { + void given__instance__when__setCredentials__then__credentials_set() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setCredentialsId("test"); assertThat(instance.getCredentialsId(), is("test")); @@ -956,28 +967,28 @@ public void given__instance__when__setCredentials__then__credentials_set() { @WithoutJenkins @Test - public void given__instance__when__setApiUri_null__then__set__to_api_github_com() { + void given__instance__when__setApiUri_null__then__set__to_api_github_com() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setApiUri(null); assertThat(instance.getApiUri(), is("https://api.github.com")); } @Test - public void given__instance__when__setApiUri_value__then__valueApplied() { + void given__instance__when__setApiUri_value__then__valueApplied() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setApiUri("https://github.test"); assertThat(instance.getApiUri(), is("https://github.test")); } @Test - public void given__instance__when__setApiUri_cloudUrl__then__valueApplied() { + void given__instance__when__setApiUri_cloudUrl__then__valueApplied() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setApiUri("https://github.com"); assertThat(instance.getApiUri(), is("https://github.com")); } @Test - public void given__legacyCode__when__setPattern_default__then__patternSetAndTraitRemoved() { + void given__legacyCode__when__setPattern_default__then__patternSetAndTraitRemoved() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -991,7 +1002,7 @@ public void given__legacyCode__when__setPattern_default__then__patternSetAndTrai } @Test - public void given__legacyCode__when__setPattern_custom__then__patternSetAndTraitAdded() { + void given__legacyCode__when__setPattern_custom__then__patternSetAndTraitAdded() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(Arrays.asList(new BranchDiscoveryTrait(true, false), new SSHCheckoutTrait("dummy"))); assertThat(instance.getPattern(), is(".*")); @@ -1002,7 +1013,7 @@ public void given__legacyCode__when__setPattern_custom__then__patternSetAndTrait } @Test - public void given__legacyCode__when__setPattern_custom__then__patternSetAndTraitUpdated() { + void given__legacyCode__when__setPattern_custom__then__patternSetAndTraitUpdated() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(new SCMTrait[] { new BranchDiscoveryTrait(true, false), new RegexSCMSourceFilterTrait("job.*"), new SSHCheckoutTrait("dummy") @@ -1016,28 +1027,28 @@ public void given__legacyCode__when__setPattern_custom__then__patternSetAndTrait } @Test - public void given__legacyCode__when__checkoutCredentials_SAME__then__noTraitAdded() { + void given__legacyCode__when__checkoutCredentials_SAME__then__noTraitAdded() { GitHubSCMNavigator instance = new GitHubSCMNavigator(null, "test", "scan", GitHubSCMSource.DescriptorImpl.SAME); assertThat(instance.getCheckoutCredentialsId(), is(GitHubSCMNavigator.DescriptorImpl.SAME)); assertThat(instance.getTraits(), not(hasItem(instanceOf(SSHCheckoutTrait.class)))); } @Test - public void given__legacyCode__when__checkoutCredentials_null__then__traitAdded_ANONYMOUS() { + void given__legacyCode__when__checkoutCredentials_null__then__traitAdded_ANONYMOUS() { GitHubSCMNavigator instance = new GitHubSCMNavigator(null, "test", "scan", null); assertThat(instance.getCheckoutCredentialsId(), is(GitHubSCMSource.DescriptorImpl.ANONYMOUS)); assertThat(instance.getTraits(), hasItem(sshCheckoutTraitItem(nullValue()))); } @Test - public void given__legacyCode__when__checkoutCredentials_value__then__traitAdded() { + void given__legacyCode__when__checkoutCredentials_value__then__traitAdded() { GitHubSCMNavigator instance = new GitHubSCMNavigator(null, "test", "scan", "value"); assertThat(instance.getCheckoutCredentialsId(), is("value")); assertThat(instance.getTraits(), hasItem(sshCheckoutTraitItem("value"))); } @Test - public void given__legacyCode__when__checkoutCredentials_ANONYMOUS__then__traitAdded() { + void given__legacyCode__when__checkoutCredentials_ANONYMOUS__then__traitAdded() { GitHubSCMNavigator instance = new GitHubSCMNavigator(null, "test", "scan", GitHubSCMSource.DescriptorImpl.ANONYMOUS); assertThat(instance.getCheckoutCredentialsId(), is(GitHubSCMSource.DescriptorImpl.ANONYMOUS)); @@ -1045,7 +1056,7 @@ public void given__legacyCode__when__checkoutCredentials_ANONYMOUS__then__traitA } @Test - public void given__legacyCode_withoutExcludes__when__setIncludes_default__then__traitRemoved() { + void given__legacyCode_withoutExcludes__when__setIncludes_default__then__traitRemoved() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -1061,7 +1072,7 @@ public void given__legacyCode_withoutExcludes__when__setIncludes_default__then__ } @Test - public void given__legacyCode_withoutExcludes__when__setIncludes_value__then__traitUpdated() { + void given__legacyCode_withoutExcludes__when__setIncludes_value__then__traitUpdated() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(new SCMTrait[] { new BranchDiscoveryTrait(true, false), @@ -1078,7 +1089,7 @@ public void given__legacyCode_withoutExcludes__when__setIncludes_value__then__tr } @Test - public void given__legacyCode_withoutTrait__when__setIncludes_value__then__traitAdded() { + void given__legacyCode_withoutTrait__when__setIncludes_value__then__traitAdded() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits( Arrays.asList(new BranchDiscoveryTrait(true, false), new RegexSCMSourceFilterTrait("job.*"))); @@ -1092,7 +1103,7 @@ public void given__legacyCode_withoutTrait__when__setIncludes_value__then__trait } @Test - public void given__legacyCode_withExcludes__when__setIncludes_default__then__traitUpdated() { + void given__legacyCode_withExcludes__when__setIncludes_default__then__traitUpdated() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -1108,7 +1119,7 @@ public void given__legacyCode_withExcludes__when__setIncludes_default__then__tra } @Test - public void given__legacyCode_withExcludes__when__setIncludes_value__then__traitUpdated() { + void given__legacyCode_withExcludes__when__setIncludes_value__then__traitUpdated() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(new SCMTrait[] { new BranchDiscoveryTrait(true, false), @@ -1125,7 +1136,7 @@ public void given__legacyCode_withExcludes__when__setIncludes_value__then__trait } @Test - public void given__legacyCode_withoutIncludes__when__setExcludes_default__then__traitRemoved() { + void given__legacyCode_withoutIncludes__when__setExcludes_default__then__traitRemoved() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -1141,7 +1152,7 @@ public void given__legacyCode_withoutIncludes__when__setExcludes_default__then__ } @Test - public void given__legacyCode_withoutIncludes__when__setExcludes_value__then__traitUpdated() { + void given__legacyCode_withoutIncludes__when__setExcludes_value__then__traitUpdated() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -1157,7 +1168,7 @@ public void given__legacyCode_withoutIncludes__when__setExcludes_value__then__tr } @Test - public void given__legacyCode_withoutTrait__when__setExcludes_value__then__traitAdded() { + void given__legacyCode_withoutTrait__when__setExcludes_value__then__traitAdded() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits( Arrays.asList(new BranchDiscoveryTrait(true, false), new RegexSCMSourceFilterTrait("job.*"))); @@ -1171,7 +1182,7 @@ public void given__legacyCode_withoutTrait__when__setExcludes_value__then__trait } @Test - public void given__legacyCode_withIncludes__when__setExcludes_default__then__traitUpdated() { + void given__legacyCode_withIncludes__when__setExcludes_default__then__traitUpdated() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -1187,7 +1198,7 @@ public void given__legacyCode_withIncludes__when__setExcludes_default__then__tra } @Test - public void given__legacyCode_withIncludes__when__setExcludes_value__then__traitUpdated() { + void given__legacyCode_withIncludes__when__setExcludes_value__then__traitUpdated() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -1203,7 +1214,7 @@ public void given__legacyCode_withIncludes__when__setExcludes_value__then__trait } @Test - public void given__legacyCode__when__setBuildOriginBranch__then__traitsMaintained() { + void given__legacyCode__when__setBuildOriginBranch__then__traitsMaintained() { GitHubSCMNavigator instance = new GitHubSCMNavigator("test"); instance.setTraits(Collections.emptyList()); assertThat(instance.getTraits(), is(empty())); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMProbeTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMProbeTest.java index 545600ddc..ade6487fc 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMProbeTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMProbeTest.java @@ -1,34 +1,35 @@ package org.jenkinsci.plugins.github_branch_source; import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.http.RequestMethod; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; import java.io.File; -import java.io.IOException; import jenkins.scm.api.SCMHeadOrigin; import jenkins.scm.api.mixin.ChangeRequestCheckoutStrategy; import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; -public class GitHubSCMProbeTest { +@WithJenkins +class GitHubSCMProbeTest { - @Rule - public JenkinsRule j = new JenkinsRule(); + private JenkinsRule j; - public static WireMockRuleFactory factory = new WireMockRuleFactory(); + private static final WireMockExtensionFactory FACTORY = new WireMockExtensionFactory(); - @Rule - public WireMockRule githubApi = factory.getRule(WireMockConfiguration.options() + @RegisterExtension + private static final WireMockExtension GITHUB_API = FACTORY.getExtension(WireMockConfiguration.options() .dynamicPort() .usingFilesUnderClasspath("cache_failure") .globalTemplating(true) @@ -36,30 +37,31 @@ public class GitHubSCMProbeTest { private GitHubSCMProbe probe; - @Before - public void setUp() throws Exception { + @BeforeEach + void beforeEach(JenkinsRule rule) throws Exception { + j = rule; // Clear all caches before each test File cacheBaseDir = new File(j.jenkins.getRootDir(), GitHubSCMProbe.class.getName() + ".cache"); if (cacheBaseDir.exists()) { FileUtils.cleanDirectory(cacheBaseDir); } - githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo")) + GITHUB_API.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBodyFile("body-cloudbeers-yolo-PucD6.json"))); // Return 404 for /rate_limit - githubApi.stubFor(get(urlEqualTo("/rate_limit")).willReturn(aResponse().withStatus(404))); + GITHUB_API.stubFor(get(urlEqualTo("/rate_limit")).willReturn(aResponse().withStatus(404))); // validate api url - githubApi.stubFor(get(urlEqualTo("/")) + GITHUB_API.stubFor(get(urlEqualTo("/")) .willReturn(aResponse().withBody("{\"rate_limit_url\": \"https://localhost/placeholder/\"}"))); } - void createProbeForPR(int number) throws IOException { - final GitHub github = Connector.connect("http://localhost:" + githubApi.port(), null); + private void createProbeForPR(int number) throws Exception { + final GitHub github = Connector.connect("http://localhost:" + GITHUB_API.getPort(), null); final GHRepository repo = github.getRepository("cloudbeers/yolo"); final PullRequestSCMHead head = new PullRequestSCMHead( @@ -72,13 +74,17 @@ void createProbeForPR(int number) throws IOException { new SCMHeadOrigin.Fork("rsandell"), ChangeRequestCheckoutStrategy.MERGE); probe = new GitHubSCMProbe( - "http://localhost:" + githubApi.port(), null, repo, head, new PullRequestSCMRevision(head, "a", "b")); + "http://localhost:" + GITHUB_API.getPort(), + null, + repo, + head, + new PullRequestSCMRevision(head, "a", "b")); } @Issue("JENKINS-54126") @Test - public void statWhenRootIs404() throws Exception { - githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/contents/?ref=refs%2Fpull%2F1%2Fmerge")) + void statWhenRootIs404() throws Exception { + GITHUB_API.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/contents/?ref=refs%2Fpull%2F1%2Fmerge")) .willReturn(aResponse().withStatus(404)) .atPriority(0)); @@ -89,8 +95,8 @@ public void statWhenRootIs404() throws Exception { @Issue("JENKINS-54126") @Test - public void statWhenDirIs404() throws Exception { - githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/contents/subdir?ref=refs%2Fpull%2F1%2Fmerge")) + void statWhenDirIs404() throws Exception { + GITHUB_API.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/contents/subdir?ref=refs%2Fpull%2F1%2Fmerge")) .willReturn(aResponse().withStatus(404)) .atPriority(0)); @@ -103,7 +109,7 @@ public void statWhenDirIs404() throws Exception { @Issue("JENKINS-54126") @Test - public void statWhenRoot404andThenIncorrectCached() throws Exception { + void statWhenRoot404andThenIncorrectCached() throws Exception { GitHubSCMSource.setCacheSize(10); createProbeForPR(9); @@ -149,7 +155,7 @@ public void statWhenRoot404andThenIncorrectCached() throws Exception { // Verify the expected requests were made if (hudson.Functions.isWindows()) { // On windows caching is disabled by default, so the work around doesn't happen - githubApi.verify( + GITHUB_API.verify( 3, RequestPatternBuilder.newRequestPattern( RequestMethod.GET, urlPathEqualTo("/repos/cloudbeers/yolo/contents/")) @@ -158,28 +164,28 @@ RequestMethod.GET, urlPathEqualTo("/repos/cloudbeers/yolo/contents/")) .withHeader("If-None-Match", absent())); } else { // 1. - githubApi.verify(RequestPatternBuilder.newRequestPattern( + GITHUB_API.verify(RequestPatternBuilder.newRequestPattern( RequestMethod.GET, urlPathEqualTo("/repos/cloudbeers/yolo/contents/")) .withHeader("Cache-Control", equalTo("max-age=0")) .withHeader("If-None-Match", absent()) .withHeader("If-Modified-Since", absent())); // 3. - githubApi.verify(RequestPatternBuilder.newRequestPattern( + GITHUB_API.verify(RequestPatternBuilder.newRequestPattern( RequestMethod.GET, urlPathEqualTo("/repos/cloudbeers/yolo/contents/")) .withHeader("Cache-Control", containing("max-age")) .withHeader("If-None-Match", absent()) .withHeader("If-Modified-Since", containing("GMT"))); // 4. - githubApi.verify(RequestPatternBuilder.newRequestPattern( + GITHUB_API.verify(RequestPatternBuilder.newRequestPattern( RequestMethod.GET, urlPathEqualTo("/repos/cloudbeers/yolo/contents/")) .withHeader("Cache-Control", equalTo("no-cache")) .withHeader("If-Modified-Since", absent()) .withHeader("If-None-Match", absent())); // 5. - githubApi.verify(RequestPatternBuilder.newRequestPattern( + GITHUB_API.verify(RequestPatternBuilder.newRequestPattern( RequestMethod.GET, urlPathEqualTo("/repos/cloudbeers/yolo/contents/")) .withHeader("Cache-Control", equalTo("max-age=0")) .withHeader("If-None-Match", equalTo("\"d3be5b35b8d84ef7ac03c0cc9c94ed81\""))); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceHelperTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceHelperTest.java index 284ff6143..8133010a8 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceHelperTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceHelperTest.java @@ -1,14 +1,14 @@ package org.jenkinsci.plugins.github_branch_source; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GitHubSCMSourceHelperTest { +class GitHubSCMSourceHelperTest { @Test - public void httpsUrl_non_github() { + void httpsUrl_non_github() { GitHubRepositoryInfo sut = GitHubRepositoryInfo.forRepositoryUrl("https://mygithub.com/jenkinsci/jenkins"); assertThat(sut.getRepoOwner(), is("jenkinsci")); assertThat(sut.getRepository(), is("jenkins")); @@ -16,7 +16,7 @@ public void httpsUrl_non_github() { } @Test - public void httpsUrl_github() { + void httpsUrl_github() { GitHubRepositoryInfo sut = GitHubRepositoryInfo.forRepositoryUrl("https://github.com/jenkinsci/jenkins"); assertThat(sut.getRepoOwner(), is("jenkinsci")); assertThat(sut.getRepository(), is("jenkins")); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceTest.java index 77666a076..0197a9512 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceTest.java @@ -29,6 +29,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -41,18 +42,17 @@ import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.cloudbees.jenkins.GitHubRepositoryName; import com.cloudbees.jenkins.GitHubRepositoryNameContributor; -import com.github.tomakehurst.wiremock.common.SingleRootFileSource; import com.github.tomakehurst.wiremock.stubbing.Scenario; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.AbortException; import hudson.ExtensionList; import hudson.model.FreeStyleProject; import hudson.model.Item; -import hudson.model.TaskListener; import hudson.model.User; import hudson.scm.SCM; import hudson.security.ACL; @@ -62,8 +62,6 @@ import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.LogTaskListener; -import java.io.File; -import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; @@ -75,37 +73,33 @@ import jenkins.scm.api.mixin.ChangeRequestCheckoutStrategy; import org.hamcrest.Matchers; import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.mockito.Mockito; -@RunWith(Parameterized.class) -public class GitHubSCMSourceTest extends GitSCMSourceBase { +@ParameterizedClass(name = "{index}: source={0}") +@MethodSource("sources") +class GitHubSCMSourceTest extends GitSCMSourceBase { public GitHubSCMSourceTest(GitHubSCMSource source) { this.source = source; } - @Parameterized.Parameters(name = "{index}: revision={0}") - public static GitHubSCMSource[] revisions() { + static GitHubSCMSource[] sources() { return new GitHubSCMSource[] { new GitHubSCMSource("cloudbeers", "yolo", null, false), new GitHubSCMSource("", "", "https://github.com/cloudbeers/yolo", true) }; } - @Before - public void prepareMockGitHubStubs() throws Exception { - new File("src/test/resources/api/mappings").mkdirs(); - new File("src/test/resources/api/__files").mkdirs(); - githubApi.enableRecordMappings( - new SingleRootFileSource("src/test/resources/api/mappings"), - new SingleRootFileSource("src/test/resources/api/__files")); - + @Override + @BeforeEach + void beforeEach() throws Exception { + super.beforeEach(); githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls/2")) .inScenario("Pull Request Merge Hash") .whenScenarioStateIs(Scenario.STARTED) @@ -131,8 +125,8 @@ public void prepareMockGitHubStubs() throws Exception { .willSetStateTo("Pull Request Merge Hash - retry 2")); } - SCMHeadEvent pushEvent = - new SCMHeadEvent(SCMEvent.Type.CREATED, System.currentTimeMillis(), null, null) { + final SCMHeadEvent pushEvent = + new SCMHeadEvent<>(SCMEvent.Type.CREATED, System.currentTimeMillis(), null, null) { @Override public boolean isMatch(@NonNull SCMNavigator scmNavigator) { return false; @@ -156,9 +150,8 @@ public boolean isMatch(@NonNull SCM scm) { } }; - SCMHeadEvent pullRequestEvent = - new SCMHeadEvent( - SCMEvent.Type.CREATED, System.currentTimeMillis(), null, null) { + final SCMHeadEvent pullRequestEvent = + new SCMHeadEvent<>(SCMEvent.Type.CREATED, System.currentTimeMillis(), null, null) { @Override public boolean isMatch(@NonNull SCMNavigator scmNavigator) { return false; @@ -184,7 +177,7 @@ public boolean isMatch(@NonNull SCM scm) { @Test @Issue("JENKINS-48035") - public void testGitHubRepositoryNameContributor() throws IOException { + void testGitHubRepositoryNameContributor() throws Exception { WorkflowMultiBranchProject job = r.createProject(WorkflowMultiBranchProject.class); job.setSourcesList(Arrays.asList(new BranchSource(source))); Collection names = GitHubRepositoryNameContributor.parseAssociatedNames(job); @@ -207,7 +200,7 @@ public void testGitHubRepositoryNameContributor() throws IOException { @Test @Issue("JENKINS-48035") - public void testGitHubRepositoryNameContributor_When_not_GitHub() throws IOException { + void testGitHubRepositoryNameContributor_When_not_GitHub() throws Exception { WorkflowMultiBranchProject job = r.createProject(WorkflowMultiBranchProject.class); job.setSourcesList(Arrays.asList(new BranchSource(new GitSCMSource("file://tmp/something")))); Collection names = GitHubRepositoryNameContributor.parseAssociatedNames(job); @@ -222,7 +215,7 @@ public void testGitHubRepositoryNameContributor_When_not_GitHub() throws IOExcep @Test @Issue("JENKINS-48035") - public void testGitHubRepositoryNameContributor_When_not_MultiBranch() throws IOException { + void testGitHubRepositoryNameContributor_When_not_MultiBranch() throws Exception { FreeStyleProject job = r.createProject(FreeStyleProject.class); Collection names = GitHubRepositoryNameContributor.parseAssociatedNames((Item) job); assertThat(names, Matchers.empty()); @@ -235,15 +228,10 @@ public void testGitHubRepositoryNameContributor_When_not_MultiBranch() throws IO } @Test - public void fetchSmokes() throws Exception { + void fetchSmokes() throws Exception { SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch( - new SCMSourceCriteria() { - @Override - public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { - return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; - } - }, + (SCMSourceCriteria) (probe, listener) -> probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE, collector, null, null); @@ -298,7 +286,7 @@ public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) thro } @Test - public void fetchSmokes_badMergeCommit() throws Exception { + void fetchSmokes_badMergeCommit() throws Exception { // make it so the merge commit is not found returns 404 // Causes PR 2 to fall back to null merge_commit_sha @@ -313,12 +301,7 @@ public void fetchSmokes_badMergeCommit() throws Exception { SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch( - new SCMSourceCriteria() { - @Override - public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { - return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; - } - }, + (SCMSourceCriteria) (probe, listener) -> probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE, collector, null, null); @@ -374,7 +357,7 @@ public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) thro } @Test - public void fetchSmokes_badUser() throws Exception { + void fetchSmokes_badUser() throws Exception { source.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), new ForkPullRequestDiscoveryTrait( @@ -396,12 +379,7 @@ public void fetchSmokes_badUser() throws Exception { SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch( - new SCMSourceCriteria() { - @Override - public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { - return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; - } - }, + (SCMSourceCriteria) (probe, listener) -> probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE, collector, null, null); @@ -448,7 +426,7 @@ public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) thro } @Test - public void fetchSmokes_badTarget() throws Exception { + void fetchSmokes_badTarget() throws Exception { // make it so the merge commit is not found returns 404 // Causes PR 2 to fall back to null merge_commit_sha // Then make it so refs/heads/master returns 404 for first call @@ -483,12 +461,7 @@ public void fetchSmokes_badTarget() throws Exception { SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch( - new SCMSourceCriteria() { - @Override - public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { - return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; - } - }, + (SCMSourceCriteria) (probe, listener) -> probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE, collector, null, null); @@ -535,7 +508,7 @@ public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) thro } @Test - public void fetchSmokesUnknownMergeable() throws Exception { + void fetchSmokesUnknownMergeable() throws Exception { // make it so PR-2 always returns mergeable = null githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls/2")) .inScenario("Pull Request Merge Hash") @@ -546,12 +519,7 @@ public void fetchSmokesUnknownMergeable() throws Exception { SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch( - new SCMSourceCriteria() { - @Override - public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { - return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; - } - }, + (SCMSourceCriteria) (probe, listener) -> probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE, collector, null, null); @@ -607,7 +575,7 @@ public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) thro } @Test - public void fetchSmokesUnknownFork() throws Exception { + void fetchSmokesUnknownFork() throws Exception { // make it so PR-2 always returns mergeable = null githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls/4")) .inScenario("Pull Request from Deleted Fork") @@ -624,12 +592,7 @@ public void fetchSmokesUnknownFork() throws Exception { SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch( - new SCMSourceCriteria() { - @Override - public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { - return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; - } - }, + (SCMSourceCriteria) (probe, listener) -> probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE, collector, null, null); @@ -647,19 +610,14 @@ public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) thro } @Test - public void fetchAltConfig() throws Exception { + void fetchAltConfig() throws Exception { source.setBuildForkPRMerge(false); source.setBuildForkPRHead(true); source.setBuildOriginPRMerge(false); source.setBuildOriginPRHead(false); SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch( - new SCMSourceCriteria() { - @Override - public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { - return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; - } - }, + (SCMSourceCriteria) (probe, listener) -> probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE, collector, null, null); @@ -701,7 +659,7 @@ public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) thro } @Test - public void fetchActions() throws Exception { + void fetchActions() throws Exception { assertThat( source.fetchActions(null, null), Matchers.containsInAnyOrder( @@ -712,7 +670,7 @@ public void fetchActions() throws Exception { } @Test - public void getTrustedRevisionReturnsRevisionIfRepoOwnerAndPullRequestBranchOwnerAreSameWithDifferentCase() + void getTrustedRevisionReturnsRevisionIfRepoOwnerAndPullRequestBranchOwnerAreSameWithDifferentCase() throws Exception { source.setBuildOriginPRHead(true); PullRequestSCMRevision revision = createRevision("CloudBeers"); @@ -735,7 +693,7 @@ private PullRequestSCMRevision createRevision(String sourceOwner) { } @Test - public void doFillCredentials() throws Exception { + void doFillCredentials() throws Exception { final GitHubSCMSource.DescriptorImpl d = r.jenkins.getDescriptorByType(GitHubSCMSource.DescriptorImpl.class); final WorkflowMultiBranchProject dummy = r.jenkins.add(new WorkflowMultiBranchProject(r.jenkins, "dummy"), "dummy"); @@ -792,7 +750,7 @@ public void doFillCredentials() throws Exception { @Test @Issue("JENKINS-68633") - public void doCheckCredentialsId() { + void doCheckCredentialsId() { GitHubSCMSource.DescriptorImpl descriptor = (GitHubSCMSource.DescriptorImpl) source.getDescriptor(); // If no credentials are supplied, display the warning @@ -810,7 +768,7 @@ public void doCheckCredentialsId() { @Test @Issue("JENKINS-65071") - public void testCheckIncludesBranchSCMHeadType() throws Exception { + void testCheckIncludesBranchSCMHeadType() { SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Mockito.when(mockSCMHeadObserver.getIncludes()) .thenReturn(Collections.singleton(new BranchSCMHead("existent-branch"))); @@ -822,13 +780,13 @@ public void testCheckIncludesBranchSCMHeadType() throws Exception { @Test @Issue("JENKINS-65071") - public void testCheckIncludesPullRequestSCMHeadType() throws Exception { + void testCheckIncludesPullRequestSCMHeadType() { SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Mockito.when(mockSCMHeadObserver.getIncludes()) .thenReturn(Collections.singleton(new PullRequestSCMHead( "PR-1", "rfvm", - "http://localhost:" + githubApi.port(), + "http://localhost:" + githubApi.getPort(), "master", 1, new BranchSCMHead("master"), @@ -842,7 +800,7 @@ public void testCheckIncludesPullRequestSCMHeadType() throws Exception { @Test @Issue("JENKINS-65071") - public void testCheckIncludesGitHubTagSCMHeadType() throws Exception { + void testCheckIncludesGitHubTagSCMHeadType() { SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Mockito.when(mockSCMHeadObserver.getIncludes()) .thenReturn( @@ -855,7 +813,7 @@ public void testCheckIncludesGitHubTagSCMHeadType() throws Exception { @Test @Issue("JENKINS-65071") - public void testCheckIncludesEmpty() throws Exception { + void testCheckIncludesEmpty() { SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Mockito.when(mockSCMHeadObserver.getIncludes()).thenReturn(Collections.emptySet()); @@ -866,7 +824,7 @@ public void testCheckIncludesEmpty() throws Exception { @Test @Issue("JENKINS-65071") - public void testCheckIncludesNull() throws Exception { + void testCheckIncludesNull() { SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Mockito.when(mockSCMHeadObserver.getIncludes()).thenReturn(null); @@ -877,7 +835,7 @@ public void testCheckIncludesNull() throws Exception { @Test @Issue("JENKINS-65071") - public void testShouldRetrieveBranchSCMHeadType() throws Exception { + void testShouldRetrieveBranchSCMHeadType() { SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Mockito.when(mockSCMHeadObserver.getIncludes()) .thenReturn(Collections.singleton(new BranchSCMHead("existent-branch"))); @@ -889,13 +847,13 @@ public void testShouldRetrieveBranchSCMHeadType() throws Exception { @Test @Issue("JENKINS-65071") - public void testShouldRetrievePullRequestSCMHeadType() throws Exception { + void testShouldRetrievePullRequestSCMHeadType() { SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Mockito.when(mockSCMHeadObserver.getIncludes()) .thenReturn(Collections.singleton(new PullRequestSCMHead( "PR-1", "rfvm", - "http://localhost:" + githubApi.port(), + "http://localhost:" + githubApi.getPort(), "master", 1, new BranchSCMHead("master"), @@ -909,7 +867,7 @@ public void testShouldRetrievePullRequestSCMHeadType() throws Exception { @Test @Issue("JENKINS-65071") - public void testShouldRetrieveTagSCMHeadType() throws Exception { + void testShouldRetrieveTagSCMHeadType() { SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Mockito.when(mockSCMHeadObserver.getIncludes()) .thenReturn( @@ -922,7 +880,7 @@ public void testShouldRetrieveTagSCMHeadType() throws Exception { @Test @Issue("JENKINS-65071") - public void testShouldRetrieveNullEvent() throws Exception { + void testShouldRetrieveNullEvent() { SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); assertTrue(this.source.shouldRetrieve(mockSCMHeadObserver, null, GitHubTagSCMHead.class)); assertTrue(this.source.shouldRetrieve(mockSCMHeadObserver, null, PullRequestSCMHead.class)); @@ -931,7 +889,7 @@ public void testShouldRetrieveNullEvent() throws Exception { @Test @Issue("JENKINS-67946") - public void testUserNamesWithAndWithoutUnderscores() { + void testUserNamesWithAndWithoutUnderscores() { // https://docs.github.com/en/enterprise-cloud@latest/admin/identity-and-access-management/managing-iam-for-your-enterprise/username-considerations-for-external-authentication#about-usernames-for-managed-user-accounts // https://github.com/github/docs/blob/bfe96c289aee3113724495a2e498c21e2ec404e4/content/admin/identity-and-access-management/using-enterprise-managed-users-for-iam/about-enterprise-managed-users.md#about--data-variablesproductprodname_emus- assertTrue("user_organization".matches(GitHubSCMSource.VALID_GITHUB_USER_NAME)); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceTraitsTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceTraitsTest.java index 2d3e24d2a..f0f814868 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceTraitsTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitHubSCMSourceTraitsTest.java @@ -1,5 +1,6 @@ package org.jenkinsci.plugins.github_branch_source; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -10,7 +11,6 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import java.util.Arrays; import java.util.Collections; @@ -23,23 +23,33 @@ import org.hamcrest.Matchers; import org.jenkinsci.plugins.structs.describable.DescribableModel; import org.jenkinsci.plugins.structs.describable.UninstantiatedDescribable; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class GitHubSCMSourceTraitsTest { +@WithJenkins +class GitHubSCMSourceTraitsTest { /** All tests in this class only use Jenkins for the extensions */ - @ClassRule - public static JenkinsRule r = new JenkinsRule(); + private static JenkinsRule r; - @Rule - public TestName currentTestName = new TestName(); + private String currentTestName; + + @BeforeAll + static void beforeAll(JenkinsRule rule) { + r = rule; + } + + @BeforeEach + void beforeEach(TestInfo info) { + currentTestName = info.getTestMethod().orElseThrow().getName(); + } private GitHubSCMSource load() { - return load(currentTestName.getMethodName()); + return load(currentTestName); } private GitHubSCMSource load(String dataSet) { @@ -48,7 +58,7 @@ private GitHubSCMSource load(String dataSet) { } @Test - public void given__configuredInstance__when__uninstantiating__then__deprecatedFieldsIgnored() throws Exception { + void given__configuredInstance__when__uninstantiating__then__deprecatedFieldsIgnored() { GitHubSCMSource instance = new GitHubSCMSource("repo-owner", "repo", null, false); instance.setId("test"); @@ -95,7 +105,7 @@ public void given__configuredInstance__when__uninstantiating__then__deprecatedFi } @Test - public void repositoryUrl() throws Exception { + void repositoryUrl() { GitHubSCMSource instance = load(); assertThat(instance.getId(), is("e4d8c11a-0d24-472f-b86b-4b017c160e9a")); @@ -118,7 +128,7 @@ public void repositoryUrl() throws Exception { } @Test - public void modern() throws Exception { + void modern() { GitHubSCMSource instance = load(); assertThat(instance.getId(), is("e4d8c11a-0d24-472f-b86b-4b017c160e9a")); assertThat(instance.getApiUri(), is(GitHubSCMSource.GITHUB_URL)); @@ -140,7 +150,7 @@ public void modern() throws Exception { } @Test - public void basic_cloud() throws Exception { + void basic_cloud() { GitHubSCMSource instance = load(); assertThat( instance.getId(), @@ -177,7 +187,7 @@ public void basic_cloud() throws Exception { } @Test - public void basic_server() throws Exception { + void basic_server() { GitHubSCMSource instance = load(); assertThat( instance.getId(), @@ -216,7 +226,7 @@ public void basic_server() throws Exception { } @Test - public void custom_checkout_credentials() throws Exception { + void custom_checkout_credentials() { GitHubSCMSource instance = load(); assertThat( instance.getId(), @@ -258,7 +268,7 @@ public void custom_checkout_credentials() throws Exception { @Issue("JENKINS-45467") @Test - public void same_checkout_credentials() throws Exception { + void same_checkout_credentials() { GitHubSCMSource instance = load(); assertThat( instance.getId(), @@ -297,7 +307,7 @@ public void same_checkout_credentials() throws Exception { } @Test - public void exclude_branches() throws Exception { + void exclude_branches() { GitHubSCMSource instance = load(); assertThat( instance.getId(), @@ -337,7 +347,7 @@ public void exclude_branches() throws Exception { } @Test - public void limit_branches() throws Exception { + void limit_branches() { GitHubSCMSource instance = load(); assertThat( instance.getId(), @@ -377,7 +387,7 @@ public void limit_branches() throws Exception { } @Test - public void use_agent_checkout() throws Exception { + void use_agent_checkout() { GitHubSCMSource instance = load(); assertThat( instance.getId(), @@ -416,7 +426,7 @@ public void use_agent_checkout() throws Exception { } @Test - public void given__legacyCode__when__constructor_cloud__then__discoveryTraitDefaults() throws Exception { + void given__legacyCode__when__constructor_cloud__then__discoveryTraitDefaults() { GitHubSCMSource instance = new GitHubSCMSource( "preserve-id", null, @@ -454,7 +464,7 @@ public void given__legacyCode__when__constructor_cloud__then__discoveryTraitDefa } @Test - public void given__legacyCode__when__constructor_server__then__discoveryTraitDefaults() throws Exception { + void given__legacyCode__when__constructor_server__then__discoveryTraitDefaults() { GitHubSCMSource instance = new GitHubSCMSource( null, "https://github.test/api/v3", @@ -494,14 +504,14 @@ public void given__legacyCode__when__constructor_server__then__discoveryTraitDef } @Test - public void given__instance__when__setTraits_empty__then__traitsEmpty() { + void given__instance__when__setTraits_empty__then__traitsEmpty() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits(Collections.emptyList()); assertThat(instance.getTraits(), is(Collections.emptyList())); } @Test - public void given__legacyCode__when__setBuildOriginBranch__then__traitsMaintained() { + void given__legacyCode__when__setBuildOriginBranch__then__traitsMaintained() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits(Collections.emptyList()); assertThat(instance.getTraits(), is(Collections.emptyList())); @@ -533,7 +543,7 @@ public void given__legacyCode__when__setBuildOriginBranch__then__traitsMaintaine } @Test - public void given__instance__when__setTraits__then__traitsSet() { + void given__instance__when__setTraits__then__traitsSet() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(BranchDiscoveryTrait.EXCLUDE_PRS), new SSHCheckoutTrait("value"))); @@ -548,7 +558,7 @@ public void given__instance__when__setTraits__then__traitsSet() { } @Test - public void given__instance__when__setApiUri__then__valueSet() { + void given__instance__when__setApiUri__then__valueSet() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); assertThat("initial default", instance.getApiUri(), is(GitHubSCMSource.GITHUB_URL)); instance.setApiUri("https://github.test/api/v3"); @@ -558,28 +568,28 @@ public void given__instance__when__setApiUri__then__valueSet() { } @Test - public void given__instance__when__setCredentials_empty__then__credentials_null() { + void given__instance__when__setCredentials_empty__then__credentials_null() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setCredentialsId(""); assertThat(instance.getCredentialsId(), is(nullValue())); } @Test - public void given__instance__when__setCredentials_null__then__credentials_null() { + void given__instance__when__setCredentials_null__then__credentials_null() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setCredentialsId(""); assertThat(instance.getCredentialsId(), is(nullValue())); } @Test - public void given__instance__when__setCredentials__then__credentials_set() { + void given__instance__when__setCredentials__then__credentials_set() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setCredentialsId("test"); assertThat(instance.getCredentialsId(), is("test")); } @Test - public void given__legacyCode_withoutExcludes__when__setIncludes_default__then__traitRemoved() { + void given__legacyCode_withoutExcludes__when__setIncludes_default__then__traitRemoved() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits( Arrays.asList(new BranchDiscoveryTrait(true, false), new WildcardSCMHeadFilterTrait("feature/*", ""))); @@ -598,7 +608,7 @@ public void given__legacyCode_withoutExcludes__when__setIncludes_default__then__ } @Test - public void given__legacyCode_withoutExcludes__when__setIncludes_value__then__traitUpdated() { + void given__legacyCode_withoutExcludes__when__setIncludes_value__then__traitUpdated() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits( Arrays.asList(new BranchDiscoveryTrait(true, false), new WildcardSCMHeadFilterTrait("feature/*", ""))); @@ -622,7 +632,7 @@ public void given__legacyCode_withoutExcludes__when__setIncludes_value__then__tr } @Test - public void given__legacyCode_withoutTrait__when__setIncludes_value__then__traitAdded() { + void given__legacyCode_withoutTrait__when__setIncludes_value__then__traitAdded() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits(Arrays.asList(new BranchDiscoveryTrait(true, false), new SSHCheckoutTrait("someValue"))); assertThat(instance.getIncludes(), is("*")); @@ -640,7 +650,7 @@ public void given__legacyCode_withoutTrait__when__setIncludes_value__then__trait } @Test - public void given__legacyCode_withExcludes__when__setIncludes_default__then__traitUpdated() { + void given__legacyCode_withExcludes__when__setIncludes_default__then__traitUpdated() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -666,7 +676,7 @@ public void given__legacyCode_withExcludes__when__setIncludes_default__then__tra } @Test - public void given__legacyCode_withExcludes__when__setIncludes_value__then__traitUpdated() { + void given__legacyCode_withExcludes__when__setIncludes_value__then__traitUpdated() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -692,7 +702,7 @@ public void given__legacyCode_withExcludes__when__setIncludes_value__then__trait } @Test - public void given__legacyCode_withoutIncludes__when__setExcludes_default__then__traitRemoved() { + void given__legacyCode_withoutIncludes__when__setExcludes_default__then__traitRemoved() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -713,7 +723,7 @@ public void given__legacyCode_withoutIncludes__when__setExcludes_default__then__ } @Test - public void given__legacyCode_withoutIncludes__when__setExcludes_value__then__traitUpdated() { + void given__legacyCode_withoutIncludes__when__setExcludes_value__then__traitUpdated() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -739,7 +749,7 @@ public void given__legacyCode_withoutIncludes__when__setExcludes_value__then__tr } @Test - public void given__legacyCode_withoutTrait__when__setExcludes_value__then__traitAdded() { + void given__legacyCode_withoutTrait__when__setExcludes_value__then__traitAdded() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits(Arrays.asList(new BranchDiscoveryTrait(true, false), new SSHCheckoutTrait("someValue"))); assertThat(instance.getIncludes(), is("*")); @@ -757,7 +767,7 @@ public void given__legacyCode_withoutTrait__when__setExcludes_value__then__trait } @Test - public void given__legacyCode_withIncludes__when__setExcludes_default__then__traitUpdated() { + void given__legacyCode_withIncludes__when__setExcludes_default__then__traitUpdated() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -783,7 +793,7 @@ public void given__legacyCode_withIncludes__when__setExcludes_default__then__tra } @Test - public void given__legacyCode_withIncludes__when__setExcludes_value__then__traitUpdated() { + void given__legacyCode_withIncludes__when__setExcludes_value__then__traitUpdated() { GitHubSCMSource instance = new GitHubSCMSource("testing", "test-repo"); instance.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, false), @@ -809,13 +819,13 @@ public void given__legacyCode_withIncludes__when__setExcludes_value__then__trait } @Test - public void build_000000() throws Exception { + void build_000000() { GitHubSCMSource instance = load(); assertThat(instance.getTraits(), empty()); } @Test - public void build_000001() throws Exception { + void build_000001() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -824,7 +834,7 @@ public void build_000001() throws Exception { } @Test - public void build_000010() throws Exception { + void build_000010() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -833,7 +843,7 @@ public void build_000010() throws Exception { } @Test - public void build_000011() throws Exception { + void build_000011() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -842,7 +852,7 @@ public void build_000011() throws Exception { } @Test - public void build_000100() throws Exception { + void build_000100() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -851,7 +861,7 @@ public void build_000100() throws Exception { } @Test - public void build_000101() throws Exception { + void build_000101() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -863,7 +873,7 @@ public void build_000101() throws Exception { } @Test - public void build_000110() throws Exception { + void build_000110() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -875,7 +885,7 @@ public void build_000110() throws Exception { } @Test - public void build_000111() throws Exception { + void build_000111() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -887,7 +897,7 @@ public void build_000111() throws Exception { } @Test - public void build_001000() throws Exception { + void build_001000() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -896,7 +906,7 @@ public void build_001000() throws Exception { } @Test - public void build_001001() throws Exception { + void build_001001() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -908,7 +918,7 @@ public void build_001001() throws Exception { } @Test - public void build_001010() throws Exception { + void build_001010() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -920,7 +930,7 @@ public void build_001010() throws Exception { } @Test - public void build_001011() throws Exception { + void build_001011() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -932,7 +942,7 @@ public void build_001011() throws Exception { } @Test - public void build_001100() throws Exception { + void build_001100() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -941,7 +951,7 @@ public void build_001100() throws Exception { } @Test - public void build_001101() throws Exception { + void build_001101() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -953,7 +963,7 @@ public void build_001101() throws Exception { } @Test - public void build_001110() throws Exception { + void build_001110() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -965,7 +975,7 @@ public void build_001110() throws Exception { } @Test - public void build_001111() throws Exception { + void build_001111() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -977,7 +987,7 @@ public void build_001111() throws Exception { } @Test - public void build_010000() throws Exception { + void build_010000() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -988,7 +998,7 @@ public void build_010000() throws Exception { } @Test - public void build_010001() throws Exception { + void build_010001() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1002,7 +1012,7 @@ public void build_010001() throws Exception { } @Test - public void build_010010() throws Exception { + void build_010010() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1016,7 +1026,7 @@ public void build_010010() throws Exception { } @Test - public void build_010011() throws Exception { + void build_010011() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1030,7 +1040,7 @@ public void build_010011() throws Exception { } @Test - public void build_010100() throws Exception { + void build_010100() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1044,7 +1054,7 @@ public void build_010100() throws Exception { } @Test - public void build_010101() throws Exception { + void build_010101() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1060,7 +1070,7 @@ public void build_010101() throws Exception { } @Test - public void build_010110() throws Exception { + void build_010110() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1076,7 +1086,7 @@ public void build_010110() throws Exception { } @Test - public void build_010111() throws Exception { + void build_010111() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1092,7 +1102,7 @@ public void build_010111() throws Exception { } @Test - public void build_011000() throws Exception { + void build_011000() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1106,7 +1116,7 @@ public void build_011000() throws Exception { } @Test - public void build_011001() throws Exception { + void build_011001() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1122,7 +1132,7 @@ public void build_011001() throws Exception { } @Test - public void build_011010() throws Exception { + void build_011010() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1138,7 +1148,7 @@ public void build_011010() throws Exception { } @Test - public void build_011011() throws Exception { + void build_011011() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1154,7 +1164,7 @@ public void build_011011() throws Exception { } @Test - public void build_011100() throws Exception { + void build_011100() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1168,7 +1178,7 @@ public void build_011100() throws Exception { } @Test - public void build_011101() throws Exception { + void build_011101() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1184,7 +1194,7 @@ public void build_011101() throws Exception { } @Test - public void build_011110() throws Exception { + void build_011110() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1200,7 +1210,7 @@ public void build_011110() throws Exception { } @Test - public void build_011111() throws Exception { + void build_011111() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1216,7 +1226,7 @@ public void build_011111() throws Exception { } @Test - public void build_100000() throws Exception { + void build_100000() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1227,7 +1237,7 @@ public void build_100000() throws Exception { } @Test - public void build_100001() throws Exception { + void build_100001() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1241,7 +1251,7 @@ public void build_100001() throws Exception { } @Test - public void build_100010() throws Exception { + void build_100010() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1255,7 +1265,7 @@ public void build_100010() throws Exception { } @Test - public void build_100011() throws Exception { + void build_100011() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1269,7 +1279,7 @@ public void build_100011() throws Exception { } @Test - public void build_100100() throws Exception { + void build_100100() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1283,7 +1293,7 @@ public void build_100100() throws Exception { } @Test - public void build_100101() throws Exception { + void build_100101() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1299,7 +1309,7 @@ public void build_100101() throws Exception { } @Test - public void build_100110() throws Exception { + void build_100110() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1315,7 +1325,7 @@ public void build_100110() throws Exception { } @Test - public void build_100111() throws Exception { + void build_100111() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1331,7 +1341,7 @@ public void build_100111() throws Exception { } @Test - public void build_101000() throws Exception { + void build_101000() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1345,7 +1355,7 @@ public void build_101000() throws Exception { } @Test - public void build_101001() throws Exception { + void build_101001() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1361,7 +1371,7 @@ public void build_101001() throws Exception { } @Test - public void build_101010() throws Exception { + void build_101010() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1377,7 +1387,7 @@ public void build_101010() throws Exception { } @Test - public void build_101011() throws Exception { + void build_101011() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1393,7 +1403,7 @@ public void build_101011() throws Exception { } @Test - public void build_101100() throws Exception { + void build_101100() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1407,7 +1417,7 @@ public void build_101100() throws Exception { } @Test - public void build_101101() throws Exception { + void build_101101() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1423,7 +1433,7 @@ public void build_101101() throws Exception { } @Test - public void build_101110() throws Exception { + void build_101110() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1439,7 +1449,7 @@ public void build_101110() throws Exception { } @Test - public void build_101111() throws Exception { + void build_101111() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1455,7 +1465,7 @@ public void build_101111() throws Exception { } @Test - public void build_110000() throws Exception { + void build_110000() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1466,7 +1476,7 @@ public void build_110000() throws Exception { } @Test - public void build_110001() throws Exception { + void build_110001() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1480,7 +1490,7 @@ public void build_110001() throws Exception { } @Test - public void build_110010() throws Exception { + void build_110010() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1494,7 +1504,7 @@ public void build_110010() throws Exception { } @Test - public void build_110011() throws Exception { + void build_110011() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1508,7 +1518,7 @@ public void build_110011() throws Exception { } @Test - public void build_110100() throws Exception { + void build_110100() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1522,7 +1532,7 @@ public void build_110100() throws Exception { } @Test - public void build_110101() throws Exception { + void build_110101() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1538,7 +1548,7 @@ public void build_110101() throws Exception { } @Test - public void build_110110() throws Exception { + void build_110110() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1554,7 +1564,7 @@ public void build_110110() throws Exception { } @Test - public void build_110111() throws Exception { + void build_110111() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1570,7 +1580,7 @@ public void build_110111() throws Exception { } @Test - public void build_111000() throws Exception { + void build_111000() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1584,7 +1594,7 @@ public void build_111000() throws Exception { } @Test - public void build_111001() throws Exception { + void build_111001() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1600,7 +1610,7 @@ public void build_111001() throws Exception { } @Test - public void build_111010() throws Exception { + void build_111010() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1616,7 +1626,7 @@ public void build_111010() throws Exception { } @Test - public void build_111011() throws Exception { + void build_111011() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1632,7 +1642,7 @@ public void build_111011() throws Exception { } @Test - public void build_111100() throws Exception { + void build_111100() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1646,7 +1656,7 @@ public void build_111100() throws Exception { } @Test - public void build_111101() throws Exception { + void build_111101() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1662,7 +1672,7 @@ public void build_111101() throws Exception { } @Test - public void build_111110() throws Exception { + void build_111110() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), @@ -1678,7 +1688,7 @@ public void build_111110() throws Exception { } @Test - public void build_111111() throws Exception { + void build_111111() { GitHubSCMSource instance = load(); assertThat( instance.getTraits(), diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitSCMSourceBase.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitSCMSourceBase.java index 481984c2f..32be9c22c 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GitSCMSourceBase.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GitSCMSourceBase.java @@ -3,27 +3,28 @@ import java.util.Arrays; import java.util.EnumSet; import jenkins.scm.api.mixin.ChangeRequestCheckoutStrategy; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; -public class GitSCMSourceBase extends AbstractGitHubWireMockTest { +class GitSCMSourceBase extends AbstractGitHubWireMockTest { - GitHubSCMSource source; - GitHub github; - GHRepository repo; + protected GitHubSCMSource source; + protected GitHub github; + protected GHRepository repo; - @Before - public void setupSourceTests() throws Exception { - super.prepareMockGitHub(); + @BeforeEach + @Override + void beforeEach() throws Exception { + super.beforeEach(); // force apiUri to point to test server - source.forceApiUri("http://localhost:" + githubApi.port()); + source.forceApiUri("http://localhost:" + githubApi.getPort()); source.setTraits(Arrays.asList( new BranchDiscoveryTrait(true, true), new ForkPullRequestDiscoveryTrait( EnumSet.of(ChangeRequestCheckoutStrategy.MERGE), new ForkPullRequestDiscoveryTrait.TrustContributors()))); - github = Connector.connect("http://localhost:" + githubApi.port(), null); + github = Connector.connect("http://localhost:" + githubApi.getPort(), null); repo = github.getRepository("cloudbeers/yolo"); } } diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubAppCredentialsAppInstallationTokenTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubAppCredentialsAppInstallationTokenTest.java index 08751db81..b77acd38e 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubAppCredentialsAppInstallationTokenTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubAppCredentialsAppInstallationTokenTest.java @@ -11,13 +11,12 @@ import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.hamcrest.number.BigDecimalCloseTo; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GithubAppCredentialsAppInstallationTokenTest { +class GithubAppCredentialsAppInstallationTokenTest { @Test - public void testAppInstallationTokenStale() throws Exception { - + void testAppInstallationTokenStale() throws Exception { GitHubAppCredentials.AppInstallationToken token; long now; @@ -85,7 +84,7 @@ public void testAppInstallationTokenStale() throws Exception { private static Matcher closeTo(long operand, long error) { BigDecimalCloseTo delegate = new BigDecimalCloseTo(new BigDecimal(operand), new BigDecimal(error)); - return new TypeSafeMatcher(Long.class) { + return new TypeSafeMatcher<>(Long.class) { @Override protected boolean matchesSafely(Long item) { return delegate.matches(new BigDecimal(item)); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubAppCredentialsTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubAppCredentialsTest.java index 7d9a8fb36..5b0f1f5e6 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubAppCredentialsTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubAppCredentialsTest.java @@ -5,7 +5,7 @@ import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.equalTo; import static org.jenkinsci.plugins.github_branch_source.Connector.createGitHubBuilder; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsStore; @@ -34,51 +34,52 @@ import java.util.logging.SimpleFormatter; import java.util.stream.Collectors; import jenkins.plugins.git.GitSampleRepoRule; +import jenkins.plugins.git.junit.jupiter.WithGitSampleRepo; import org.jenkinsci.plugins.github_branch_source.app_credentials.AccessSpecifiedRepositories; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.BuildWatcher; -import org.jvnet.hudson.test.LoggerRule; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.jvnet.hudson.test.junit.jupiter.BuildWatcherExtension; import org.kohsuke.github.GitHub; import org.kohsuke.github.authorization.AuthorizationProvider; -public class GithubAppCredentialsTest extends AbstractGitHubWireMockTest { +@WithGitSampleRepo +class GithubAppCredentialsTest extends AbstractGitHubWireMockTest { private static Slave agent; - private static final String myAppCredentialsId = "myAppCredentialsId"; - private static final String myAppCredentialsNoOwnerId = "myAppCredentialsNoOwnerId"; + private static final String MY_APP_CREDENTIALS_ID = "myAppCredentialsId"; + private static final String MY_APP_CREDENTIALS_NO_OWNER_ID = "myAppCredentialsNoOwnerId"; private static CredentialsStore store; private static GitHubAppCredentials appCredentials, appCredentialsNoOwner; private static LogRecorder logRecorder; - @Rule - public GitSampleRepoRule sampleRepo = new GitSampleRepoRule(); + private GitSampleRepoRule sampleRepo; - @Rule - public BuildWatcher buildWatcher = new BuildWatcher(); + @SuppressWarnings("unused") + @RegisterExtension + private static final BuildWatcherExtension BUILD_WATCHER = new BuildWatcherExtension(); // here to aid debugging - we can not use LoggerRule for the test assertion as it only captures // logs from the controller - @ClassRule - public static LoggerRule loggerRule = new LoggerRule().record(GitHubAppCredentials.class, Level.FINE); + @SuppressWarnings("unused") + private static final org.jvnet.hudson.test.LogRecorder LOG_RECORDER = + new org.jvnet.hudson.test.LogRecorder().record(GitHubAppCredentials.class, Level.FINE); - @BeforeClass - public static void setUpJenkins() throws Exception { + @BeforeAll + static void beforeAll() throws Exception { // Add credential (Must have valid private key for Jwt to work, but App doesn't have to actually // exist) store = CredentialsProvider.lookupStores(r.jenkins).iterator().next(); - appCredentials = GitHubApp.createCredentials(myAppCredentialsId); + appCredentials = GitHubApp.createCredentials(MY_APP_CREDENTIALS_ID); appCredentials.setRepositoryAccessStrategy( new AccessSpecifiedRepositories("cloudBeers", Collections.emptyList())); store.addCredentials(Domain.global(), appCredentials); - appCredentialsNoOwner = GitHubApp.createCredentials(myAppCredentialsNoOwnerId); + appCredentialsNoOwner = GitHubApp.createCredentials(MY_APP_CREDENTIALS_NO_OWNER_ID); appCredentialsNoOwner.setRepositoryAccessStrategy( new AccessSpecifiedRepositories(null, Collections.emptyList())); store.addCredentials(Domain.global(), appCredentialsNoOwner); @@ -95,11 +96,13 @@ public static void setUpJenkins() throws Exception { logRecorder.save(); t.enable(); // but even though we can not capture the logs we want to echo them - r.showAgentLogs(agent, loggerRule); + r.showAgentLogs(agent, LOG_RECORDER); } - @Before - public void setUpWireMock() throws Exception { + @BeforeEach + void beforeEach(GitSampleRepoRule repo) { + sampleRepo = repo; + GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleOnOver); // During credential refreshes we should never check rate_limit @@ -248,7 +251,7 @@ public void setUpWireMock() throws Exception { } @Test - public void testProviderRefresh() throws Exception { + void testProviderRefresh() throws Exception { final long notStaleSeconds = GitHubAppCredentials.AppInstallationToken.NOT_STALE_MINIMUM_SECONDS; try { appCredentials.setApiUri(githubApi.baseUrl()); @@ -351,7 +354,7 @@ public void testProviderRefresh() throws Exception { } @Test - public void testAgentRefresh() throws Exception { + void testAgentRefresh() throws Exception { final long notStaleSeconds = GitHubAppCredentials.AppInstallationToken.NOT_STALE_MINIMUM_SECONDS; try { appCredentials.setApiUri(githubApi.baseUrl()); @@ -364,7 +367,8 @@ public void testAgentRefresh() throws Exception { Thread.sleep(Duration.ofSeconds(GitHubAppCredentials.AppInstallationToken.NOT_STALE_MINIMUM_SECONDS + 2) .toMillis()); - final String gitCheckoutStep = String.format(" git url: REPO, credentialsId: '%s'", myAppCredentialsId); + final String gitCheckoutStep = + String.format(" git url: REPO, credentialsId: '%s'", MY_APP_CREDENTIALS_ID); final String jenkinsfile = String.join( "\n", @@ -468,7 +472,7 @@ public void testAgentRefresh() throws Exception { } @Test - public void testPassword() throws Exception { + void testPassword() throws Exception { long notStaleSeconds = GitHubAppCredentials.AppInstallationToken.NOT_STALE_MINIMUM_SECONDS; try { appCredentials.setApiUri(githubApi.baseUrl()); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourceBranchesTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourceBranchesTest.java index d34b2a321..0ce902ef8 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourceBranchesTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourceBranchesTest.java @@ -1,29 +1,26 @@ package org.jenkinsci.plugins.github_branch_source; import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import jenkins.scm.api.SCMHeadObserver; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kohsuke.github.GHBranch; import org.kohsuke.github.GHFileNotFoundException; import org.kohsuke.github.GHRepository; import org.mockito.Mockito; -public class GithubSCMSourceBranchesTest extends GitSCMSourceBase { +class GithubSCMSourceBranchesTest extends GitSCMSourceBase { public GithubSCMSourceBranchesTest() { this.source = new GitHubSCMSource("cloudbeers", "yolo", null, false); } @Test - public void testMissingSingleBranch() throws IOException { + void testMissingSingleBranch() { // Situation: Hitting the Github API for a branch and getting a 404 githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/branches/non-existent-branch")) .willReturn(aResponse() @@ -44,7 +41,7 @@ public void testMissingSingleBranch() throws IOException { } @Test - public void testExistentSingleBranch() throws IOException { + void testExistentSingleBranch() { // Situation: Hitting the Github API for a branch and getting an existing branch githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/branches/existent-branch")) .willReturn(aResponse() @@ -65,7 +62,7 @@ public void testExistentSingleBranch() throws IOException { } @Test - public void testThrownErrorSingleBranchException() throws IOException { + void testThrownErrorSingleBranchException() throws Exception { // Situation: When sending a request for a branch which exists, throw a GHNotFoundException githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/branches/existent-branch")) .willReturn(aResponse() @@ -82,17 +79,16 @@ public void testThrownErrorSingleBranchException() throws IOException { context.newRequest(new GitHubSCMSource("cloudbeers", "yolo", null, false), null); Mockito.doThrow(e).when(repoSpy).getBranch("existent-branch"); // Expected: This will throw an error when requesting a branch - try { - Iterator branches = new GitHubSCMSource.LazyBranches(request, repoSpy).iterator(); - fail("This should throw an exception"); - } catch (Error error) { - // Error is expected here so this is "success" - assertEquals("Bad Branch Request", error.getMessage()); - } + Error error = assertThrows( + Error.class, + () -> new GitHubSCMSource.LazyBranches(request, repoSpy).iterator(), + "This should throw an exception"); + // Error is expected here so this is "success" + assertEquals("Bad Branch Request", error.getMessage()); } @Test - public void testExistingMultipleBranchesWithDefaultInPosition1() throws IOException { + void testExistingMultipleBranchesWithDefaultInPosition1() { // Situation: Hitting github and getting back multiple branches where master is first in the lst // position githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/branches")) @@ -117,7 +113,7 @@ public void testExistingMultipleBranchesWithDefaultInPosition1() throws IOExcept } @Test - public void testExistingMultipleBranchesWithDefaultInPosition2() throws IOException { + void testExistingMultipleBranchesWithDefaultInPosition2() { // Situation: Hitting github and getting back multiple branches where master is first in the 2nd // position githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/branches")) @@ -139,7 +135,7 @@ public void testExistingMultipleBranchesWithDefaultInPosition2() throws IOExcept } @Test - public void testExistingMultipleBranchesWithNoDefault() throws IOException { + void testExistingMultipleBranchesWithNoDefault() { // Situation: Hitting github and getting back multiple branches where master is not in the list githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/branches")) .willReturn(aResponse() @@ -161,7 +157,7 @@ public void testExistingMultipleBranchesWithNoDefault() throws IOException { } @Test - public void testExistingMultipleBranchesWithThrownError() throws IOException { + void testExistingMultipleBranchesWithThrownError() throws Exception { // Situation: Hitting github and getting back multiple branches but throws an I/O error SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/branches")) @@ -177,12 +173,11 @@ public void testExistingMultipleBranchesWithThrownError() throws IOException { IOException error = new IOException("Thrown Branch Error"); Mockito.when(repoSpy.getBranches()).thenThrow(error); // Expected: In the iterator will throw an error when calling getBranches - try { - Iterator branches = new GitHubSCMSource.LazyBranches(request, repoSpy).iterator(); - fail("This should throw an exception"); - } catch (Exception e) { - // We swallow the new GetRef error and then throw the original one for some reason... - assertEquals("java.io.IOException: Thrown Branch Error", e.getMessage()); - } + Exception e = assertThrows( + Exception.class, + () -> new GitHubSCMSource.LazyBranches(request, repoSpy).iterator(), + "This should throw an exception"); + // We swallow the new GetRef error and then throw the original one for some reason... + assertEquals("java.io.IOException: Thrown Branch Error", e.getMessage()); } } diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourcePRsTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourcePRsTest.java index d1c1031ad..d018ffce7 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourcePRsTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourcePRsTest.java @@ -1,7 +1,7 @@ package org.jenkinsci.plugins.github_branch_source; import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.io.IOException; @@ -10,19 +10,19 @@ import jenkins.scm.api.SCMHeadObserver; import jenkins.scm.api.SCMHeadOrigin; import jenkins.scm.api.mixin.ChangeRequestCheckoutStrategy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kohsuke.github.GHPullRequest; import org.kohsuke.github.GHRepository; import org.mockito.Mockito; -public class GithubSCMSourcePRsTest extends GitSCMSourceBase { +class GithubSCMSourcePRsTest extends GitSCMSourceBase { public GithubSCMSourcePRsTest() { this.source = new GitHubSCMSource("cloudbeers", "yolo", null, false); } @Test - public void testClosedSinglePR() throws IOException { + void testClosedSinglePR() { // Situation: Hitting the Github API for a PR and getting a closed PR githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls/1")) .willReturn(aResponse() @@ -33,7 +33,7 @@ public void testClosedSinglePR() throws IOException { .thenReturn(Collections.singleton(new PullRequestSCMHead( "PR-1", "*", - "http://localhost:" + githubApi.port(), + "http://localhost:" + githubApi.getPort(), "master", 1, new BranchSCMHead("master"), @@ -51,7 +51,7 @@ public void testClosedSinglePR() throws IOException { // Single PR that is open: returns singleton @Test - public void testOpenSinglePR() throws IOException { + void testOpenSinglePR() { // Situation: Hitting the Github API for a PR and getting a open PR githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls/1")) .willReturn(aResponse() @@ -62,7 +62,7 @@ public void testOpenSinglePR() throws IOException { .thenReturn(Collections.singleton(new PullRequestSCMHead( "PR-1", "ataylor", - "http://localhost:" + githubApi.port(), + "http://localhost:" + githubApi.getPort(), "master", 1, new BranchSCMHead("master"), @@ -82,7 +82,7 @@ public void testOpenSinglePR() throws IOException { } @Test - public void testSinglePRThrowingExceptionOnGettingNumbers() throws Exception { + void testSinglePRThrowingExceptionOnGettingNumbers() throws Exception { // Situation: Hitting the Github API for a PR and an IO exception during the building of the // iterator githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls/1")) @@ -94,7 +94,7 @@ public void testSinglePRThrowingExceptionOnGettingNumbers() throws Exception { .thenReturn(Collections.singleton(new PullRequestSCMHead( "PR-1", "ataylor", - "http://localhost:" + githubApi.port(), + "http://localhost:" + githubApi.getPort(), "master", 1, new BranchSCMHead("master"), @@ -109,18 +109,14 @@ public void testSinglePRThrowingExceptionOnGettingNumbers() throws Exception { Mockito.when(mockRequest.getPullRequest(1)).thenThrow(new IOException("Number does not exist")); // Expected: This will fail when trying to generate the iterator - try { - Iterator pullRequest = new GitHubSCMSource("cloudbeers", "yolo", null, false) - .new LazyPullRequests(request, mockRequest) - .iterator(); - fail(); - } catch (Exception e) { - assertEquals("java.io.IOException: Number does not exist", e.getMessage()); - } + Exception e = assertThrows(Exception.class, () -> new GitHubSCMSource("cloudbeers", "yolo", null, false) + .new LazyPullRequests(request, mockRequest) + .iterator()); + assertEquals("java.io.IOException: Number does not exist", e.getMessage()); } @Test - public void testOpenSinglePRThrowsFileNotFoundOnObserve() throws Exception { + void testOpenSinglePRThrowsFileNotFoundOnObserve() throws Exception { // Situation: Hitting the Github API for a PR and an FileNotFound exception during the // getPullRequest githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls/1")) @@ -132,7 +128,7 @@ public void testOpenSinglePRThrowsFileNotFoundOnObserve() throws Exception { .thenReturn(Collections.singleton(new PullRequestSCMHead( "PR-1", "ataylor", - "http://localhost:" + githubApi.port(), + "http://localhost:" + githubApi.getPort(), "master", 1, new BranchSCMHead("master"), @@ -156,16 +152,12 @@ public void testOpenSinglePRThrowsFileNotFoundOnObserve() throws Exception { // Expected: In the iterator will have one item in it but when getting that item you receive an // FileNotFound exception assertTrue(pullRequestIterator.hasNext()); - try { - pullRequestIterator.next(); - fail(); - } catch (Exception e) { - assertEquals("java.io.FileNotFoundException: User not found", e.getMessage()); - } + Exception e = assertThrows(Exception.class, pullRequestIterator::next); + assertEquals("java.io.FileNotFoundException: User not found", e.getMessage()); } @Test - public void testOpenSinglePRThrowsIOOnObserve() throws Exception { + void testOpenSinglePRThrowsIOOnObserve() throws Exception { // Situation: Hitting the Github API for a PR and an IO exception during the getPullRequest githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls/1")) .willReturn(aResponse() @@ -176,7 +168,7 @@ public void testOpenSinglePRThrowsIOOnObserve() throws Exception { .thenReturn(Collections.singleton(new PullRequestSCMHead( "PR-1", "ataylor", - "http://localhost:" + githubApi.port(), + "http://localhost:" + githubApi.getPort(), "master", 1, new BranchSCMHead("master"), @@ -200,17 +192,13 @@ public void testOpenSinglePRThrowsIOOnObserve() throws Exception { // Expected: In the iterator will have one item in it but when getting that item you receive an // IO exception assertTrue(pullRequestIterator.hasNext()); - try { - pullRequestIterator.next(); - fail(); - } catch (Exception e) { - assertEquals("java.io.IOException: Failed to get user", e.getMessage()); - } + Exception e = assertThrows(Exception.class, pullRequestIterator::next); + assertEquals("java.io.IOException: Failed to get user", e.getMessage()); } // Multiple PRs @Test - public void testOpenMultiplePRs() throws IOException { + void testOpenMultiplePRs() throws Exception { // Situation: Hitting the Github API all the PRs and they are all Open. Then we close the // request at the end githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls?state=open")) @@ -235,7 +223,7 @@ public void testOpenMultiplePRs() throws IOException { // Multiple PRs @Test - public void testOpenMultiplePRsWithMasterAsOrigin() throws IOException { + void testOpenMultiplePRsWithMasterAsOrigin() { // Situation: Hitting the Github API all the PRs and they are all Open but the master is the // head branch githubApi.stubFor(get(urlEqualTo("/repos/cloudbeers/yolo/pulls?state=open&head=cloudbeers%3Amaster")) diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourceTagsTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourceTagsTest.java index 806812fe8..77231702b 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourceTagsTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/GithubSCMSourceTagsTest.java @@ -1,10 +1,6 @@ package org.jenkinsci.plugins.github_branch_source; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.io.IOException; @@ -14,7 +10,7 @@ import java.util.Iterator; import java.util.NoSuchElementException; import jenkins.scm.api.SCMHeadObserver; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.kohsuke.github.GHException; import org.kohsuke.github.GHFileNotFoundException; @@ -24,7 +20,7 @@ import org.kohsuke.github.PagedIterator; import org.mockito.Mockito; -public class GithubSCMSourceTagsTest extends GitSCMSourceBase { +class GithubSCMSourceTagsTest extends GitSCMSourceBase { public GithubSCMSourceTagsTest() { this.source = new GitHubSCMSource("cloudbeers", "yolo", null, false); @@ -32,7 +28,7 @@ public GithubSCMSourceTagsTest() { @Test @Issue("JENKINS-54403") - public void testMissingSingleTag() throws IOException { + void testMissingSingleTag() { // Scenario: a single tag which does not exist SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); @@ -51,7 +47,7 @@ public void testMissingSingleTag() throws IOException { @Test @Issue("JENKINS-54403") - public void testExistentSingleTag() throws IOException { + void testExistentSingleTag() { // Scenario: A single tag which does exist SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); @@ -70,7 +66,7 @@ public void testExistentSingleTag() throws IOException { } @Test - public void testThrownErrorSingleTagGHFileNotFound() throws IOException { + void testThrownErrorSingleTagGHFileNotFound() throws Exception { // Scenario: A single tag but getting back a FileNotFound when calling getRef SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Error e = new Error("Bad Tag Request", new GHFileNotFoundException()); @@ -89,7 +85,7 @@ public void testThrownErrorSingleTagGHFileNotFound() throws IOException { } @Test - public void testThrownErrorSingleTagOtherException() throws IOException { + void testThrownErrorSingleTagOtherException() throws Exception { // Scenario: A single tag but getting back another Error when calling getRef SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Error expectedError = new Error("Bad Tag Request", new RuntimeException()); @@ -103,17 +99,13 @@ public void testThrownErrorSingleTagOtherException() throws IOException { Mockito.doThrow(expectedError).when(repoSpy).getRef("tags/existent-tag"); // Expected: When getting the tag, an error is thrown so we have to catch it - try { - Iterator tags = new GitHubSCMSource.LazyTags(request, repoSpy).iterator(); - fail("This should throw an exception"); - } catch (Error e) { - // Error is expected here so this is "success" - assertEquals("Bad Tag Request", e.getMessage()); - } + Error e = assertThrows(Error.class, () -> new GitHubSCMSource.LazyTags(request, repoSpy).iterator()); + // Error is expected here so this is "success" + assertEquals("Bad Tag Request", e.getMessage()); } @Test - public void testExistingMultipleTags() throws IOException { + void testExistingMultipleTags() { // Scenario: Requesting multiple tags SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); @@ -134,24 +126,18 @@ public void testExistingMultipleTags() throws IOException { assertTrue(tags.hasNext()); assertEquals("refs/tags/existent-multiple-tags2", tags.next().getRef()); assertFalse(tags.hasNext()); - try { - tags.next(); - fail("This should throw an exception"); - } catch (NoSuchElementException e) { - // Error is expected here so this is "success" - assertNotEquals("This should throw an exception", e.getMessage()); - } - try { - tags.remove(); - fail("This should throw an exception"); - } catch (UnsupportedOperationException e) { - // Error is expected here so this is "success" - assertNotEquals("This should throw an exception", e.getMessage()); - } + NoSuchElementException nsee = assertThrows(NoSuchElementException.class, tags::next); + + // Error is expected here so this is "success" + assertNotEquals("This should throw an exception", nsee.getMessage()); + + UnsupportedOperationException uoe = assertThrows(UnsupportedOperationException.class, tags::remove); + // Error is expected here so this is "success" + assertNotEquals("This should throw an exception", uoe.getMessage()); } @Test - public void testExistingMultipleTagsGHFileNotFoundExceptionIterable() throws IOException { + void testExistingMultipleTagsGHFileNotFoundExceptionIterable() throws Exception { // Scenario: Requesting multiple tags but a FileNotFound is thrown // on the first returning the iterator and then an IO error is thrown on the iterator creation SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); @@ -175,16 +161,12 @@ public void testExistingMultipleTagsGHFileNotFoundExceptionIterable() throws IOE // Then for the second tag iterator created it returns an IO error Iterator tags = new GitHubSCMSource.LazyTags(request, repoSpy).iterator(); assertEquals(Collections.emptyIterator(), tags); - try { - Iterator tags2 = new GitHubSCMSource.LazyTags(request, repoSpy).iterator(); - fail("This should throw an exception"); - } catch (Error e) { - assertEquals("Bad Tag Request IOError", e.getMessage()); - } + Error e = assertThrows(Error.class, () -> new GitHubSCMSource.LazyTags(request, repoSpy).iterator()); + assertEquals("Bad Tag Request IOError", e.getMessage()); } @Test - public void testExistingMultipleTagsIteratorGHFileNotFoundExceptionOnHasNext() throws IOException { + void testExistingMultipleTagsIteratorGHFileNotFoundExceptionOnHasNext() throws Exception { // Scenario: multiple tags but returns a filenotfound on the first hasNext // and returns a IO error on the second hasNext SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); @@ -212,16 +194,12 @@ public void testExistingMultipleTagsIteratorGHFileNotFoundExceptionOnHasNext() t Iterator tags = new GitHubSCMSource.LazyTags(request, repoSpy).iterator(); Iterator tags2 = new GitHubSCMSource.LazyTags(request, repoSpy).iterator(); assertFalse(tags.hasNext()); - try { - tags.hasNext(); - fail("This should throw an exception"); - } catch (Error e) { - assertEquals("Bad Tag Request IOError", e.getMessage()); - } + Error e = assertThrows(Error.class, tags::hasNext); + assertEquals("Bad Tag Request IOError", e.getMessage()); } @Test - public void testExistingMultipleTagsIteratorGHExceptionOnHasNextAndHasAtLeastOne() throws IOException { + void testExistingMultipleTagsIteratorGHExceptionOnHasNextAndHasAtLeastOne() throws Exception { // Scenario: multiple tags but returns a GHException and found at least one tag SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Exception expectedError = new GHException("Bad Tag Request"); @@ -243,19 +221,15 @@ public void testExistingMultipleTagsIteratorGHExceptionOnHasNextAndHasAtLeastOne Mockito.when(iteratorSpy.hasNext()).thenReturn(true).thenThrow(expectedError); // Expected: First call to hasNext should work true and then will throw an error - try { - // First Call is fine - tags.hasNext(); - // Second Call fails - tags.hasNext(); - fail("This should throw an exception"); - } catch (GHException e) { - assertEquals("Bad Tag Request", e.getMessage()); - } + // First Call is fine + tags.hasNext(); + // Second Call fails + GHException e = assertThrows(GHException.class, tags::hasNext); + assertEquals("Bad Tag Request", e.getMessage()); } @Test - public void testExistingMultipleTagsIteratorGHExceptionOnHasNextAndDoesNotHaveOne() throws IOException { + void testExistingMultipleTagsIteratorGHExceptionOnHasNextAndDoesNotHaveOne() throws Exception { // Scenario: multiple tags but returns a GHException on the first tag SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); Exception expectedError = new GHException("Bad Tag Request"); @@ -277,17 +251,12 @@ public void testExistingMultipleTagsIteratorGHExceptionOnHasNextAndDoesNotHaveOn Mockito.when(iteratorSpy.hasNext()).thenThrow(expectedError); // Expected: First call to hasNext throws the GHException - try { - tags.hasNext(); - fail("This should throw an exception"); - } catch (GHException e) { - assertEquals("Bad Tag Request", e.getMessage()); - } + GHException e = assertThrows(GHException.class, tags::hasNext); + assertEquals("Bad Tag Request", e.getMessage()); } @Test - public void testExistingMultipleTagsIteratorGHExceptionOnHasNextButThrowsFileNotFoundOnGetRefs() - throws IOException { + void testExistingMultipleTagsIteratorGHExceptionOnHasNextButThrowsFileNotFoundOnGetRefs() throws Exception { // Scenario: multiple tags but catches a GH exception on hasNext and then // FilenotFound on getRefs SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); @@ -317,7 +286,7 @@ public void testExistingMultipleTagsIteratorGHExceptionOnHasNextButThrowsFileNot } @Test - public void testExistingMultipleTagsIteratorGHExceptionOnHasNextButThrowsIOErrorOnGetRefs() throws IOException { + void testExistingMultipleTagsIteratorGHExceptionOnHasNextButThrowsIOErrorOnGetRefs() throws Exception { // Scenario: making a request for a multiple tags but catches a GH exception on hasNext // and then throws on IO error getRefs SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class); @@ -343,12 +312,8 @@ public void testExistingMultipleTagsIteratorGHExceptionOnHasNextButThrowsIOError // Expected: First call to hasNext throws a GHException and then returns a IO exception on // getRefs so it returns an error - try { - tags.hasNext(); - fail("This should throw an exception"); - } catch (GHException e) { - // We suppress the new GetRef error and then throw the original one - assertEquals("Bad Tag Request", e.getMessage()); - } + GHException e = assertThrows(GHException.class, tags::hasNext); + // We suppress the new GetRef error and then throw the original one + assertEquals("Bad Tag Request", e.getMessage()); } } diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/IgnoreDraftPullRequestFilterTraitTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/IgnoreDraftPullRequestFilterTraitTest.java index 245308e1b..7965acacf 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/IgnoreDraftPullRequestFilterTraitTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/IgnoreDraftPullRequestFilterTraitTest.java @@ -4,7 +4,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -import java.io.IOException; import java.util.Collections; import java.util.List; import jenkins.scm.api.SCMHead; @@ -12,18 +11,18 @@ import jenkins.scm.api.SCMHeadOrigin; import jenkins.scm.api.mixin.ChangeRequestCheckoutStrategy; import jenkins.scm.api.trait.SCMHeadFilter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kohsuke.github.GHPullRequest; import org.mockito.Mockito; -public class IgnoreDraftPullRequestFilterTraitTest extends GitSCMSourceBase { +class IgnoreDraftPullRequestFilterTraitTest extends GitSCMSourceBase { public IgnoreDraftPullRequestFilterTraitTest() { this.source = new GitHubSCMSource("cloudbeers", "yolo", null, false); } @Test - public void testTraitFiltersDraft() throws IOException, InterruptedException { + void testTraitFiltersDraft() throws Exception { GitHubSCMSourceContext probe = new GitHubSCMSourceContext(null, SCMHeadObserver.collect()); IgnoreDraftPullRequestFilterTrait instance = new IgnoreDraftPullRequestFilterTrait(); instance.decorateContext(probe); @@ -33,7 +32,7 @@ public void testTraitFiltersDraft() throws IOException, InterruptedException { SCMHead scmHead = new PullRequestSCMHead( "PR-5", "cloudbeers", - "http://localhost:" + githubApi.port(), + "http://localhost:" + githubApi.getPort(), "feature/5", 5, new BranchSCMHead("master"), @@ -49,7 +48,7 @@ public void testTraitFiltersDraft() throws IOException, InterruptedException { } @Test - public void testTraitDoesNotFilterNonDraft() throws IOException, InterruptedException { + void testTraitDoesNotFilterNonDraft() throws Exception { GitHubSCMSourceContext probe = new GitHubSCMSourceContext(null, SCMHeadObserver.collect()); IgnoreDraftPullRequestFilterTrait instance = new IgnoreDraftPullRequestFilterTrait(); instance.decorateContext(probe); @@ -59,7 +58,7 @@ public void testTraitDoesNotFilterNonDraft() throws IOException, InterruptedExce SCMHead scmHead = new PullRequestSCMHead( "PR-5", "cloudbeers", - "http://localhost:" + githubApi.port(), + "http://localhost:" + githubApi.getPort(), "feature/5", 5, new BranchSCMHead("master"), diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/OriginPullRequestDiscoveryTraitTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/OriginPullRequestDiscoveryTraitTest.java index 356e142f1..a453f4559 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/OriginPullRequestDiscoveryTraitTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/OriginPullRequestDiscoveryTraitTest.java @@ -1,11 +1,11 @@ package org.jenkinsci.plugins.github_branch_source; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; -import static org.junit.Assume.assumeThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.util.Collections; import java.util.EnumSet; @@ -14,19 +14,20 @@ import jenkins.scm.api.trait.SCMHeadFilter; import jenkins.scm.api.trait.SCMHeadPrefilter; import org.hamcrest.Matchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +class OriginPullRequestDiscoveryTraitTest { -public class OriginPullRequestDiscoveryTraitTest { @Test - public void given__discoverHeadMerge__when__appliedToContext__then__strategiesCorrect() throws Exception { + void given__discoverHeadMerge__when__appliedToContext__then__strategiesCorrect() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.wantBranches(), is(false)); - assumeThat(ctx.wantPRs(), is(false)); - assumeThat(ctx.prefilters(), is(Collections.emptyList())); - assumeThat(ctx.filters(), is(Collections.emptyList())); - assumeThat( - ctx.authorities(), - not(hasItem(instanceOf(OriginPullRequestDiscoveryTrait.OriginChangeRequestSCMHeadAuthority.class)))); + assumeFalse(ctx.wantBranches()); + assumeFalse(ctx.wantPRs()); + assumeTrue(ctx.prefilters().isEmpty()); + assumeTrue(ctx.filters().isEmpty()); + assumeTrue(ctx.authorities().stream() + .noneMatch( + item -> item instanceof OriginPullRequestDiscoveryTrait.OriginChangeRequestSCMHeadAuthority)); OriginPullRequestDiscoveryTrait instance = new OriginPullRequestDiscoveryTrait(EnumSet.allOf(ChangeRequestCheckoutStrategy.class)); instance.decorateContext(ctx); @@ -41,15 +42,15 @@ public void given__discoverHeadMerge__when__appliedToContext__then__strategiesCo } @Test - public void given__discoverHeadOnly__when__appliedToContext__then__strategiesCorrect() throws Exception { + void given__discoverHeadOnly__when__appliedToContext__then__strategiesCorrect() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.wantBranches(), is(false)); - assumeThat(ctx.wantPRs(), is(false)); - assumeThat(ctx.prefilters(), is(Collections.emptyList())); - assumeThat(ctx.filters(), is(Collections.emptyList())); - assumeThat( - ctx.authorities(), - not(hasItem(instanceOf(OriginPullRequestDiscoveryTrait.OriginChangeRequestSCMHeadAuthority.class)))); + assumeFalse(ctx.wantBranches()); + assumeFalse(ctx.wantPRs()); + assumeTrue(ctx.prefilters().isEmpty()); + assumeTrue(ctx.filters().isEmpty()); + assumeTrue(ctx.authorities().stream() + .noneMatch( + item -> item instanceof OriginPullRequestDiscoveryTrait.OriginChangeRequestSCMHeadAuthority)); OriginPullRequestDiscoveryTrait instance = new OriginPullRequestDiscoveryTrait(EnumSet.of(ChangeRequestCheckoutStrategy.HEAD)); instance.decorateContext(ctx); @@ -64,15 +65,15 @@ public void given__discoverHeadOnly__when__appliedToContext__then__strategiesCor } @Test - public void given__discoverMergeOnly__when__appliedToContext__then__strategiesCorrect() throws Exception { + void given__discoverMergeOnly__when__appliedToContext__then__strategiesCorrect() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.wantBranches(), is(false)); - assumeThat(ctx.wantPRs(), is(false)); - assumeThat(ctx.prefilters(), is(Collections.emptyList())); - assumeThat(ctx.filters(), is(Collections.emptyList())); - assumeThat( - ctx.authorities(), - not(hasItem(instanceOf(OriginPullRequestDiscoveryTrait.OriginChangeRequestSCMHeadAuthority.class)))); + assumeFalse(ctx.wantBranches()); + assumeFalse(ctx.wantPRs()); + assumeTrue(ctx.prefilters().isEmpty()); + assumeTrue(ctx.filters().isEmpty()); + assumeTrue(ctx.authorities().stream() + .noneMatch( + item -> item instanceof OriginPullRequestDiscoveryTrait.OriginChangeRequestSCMHeadAuthority)); OriginPullRequestDiscoveryTrait instance = new OriginPullRequestDiscoveryTrait(EnumSet.of(ChangeRequestCheckoutStrategy.MERGE)); instance.decorateContext(ctx); @@ -87,15 +88,15 @@ public void given__discoverMergeOnly__when__appliedToContext__then__strategiesCo } @Test - public void given__programmaticConstructor__when__appliedToContext__then__strategiesCorrect() throws Exception { + void given__programmaticConstructor__when__appliedToContext__then__strategiesCorrect() { GitHubSCMSourceContext ctx = new GitHubSCMSourceContext(null, SCMHeadObserver.none()); - assumeThat(ctx.wantBranches(), is(false)); - assumeThat(ctx.wantPRs(), is(false)); - assumeThat(ctx.prefilters(), is(Collections.emptyList())); - assumeThat(ctx.filters(), is(Collections.emptyList())); - assumeThat( - ctx.authorities(), - not(hasItem(instanceOf(OriginPullRequestDiscoveryTrait.OriginChangeRequestSCMHeadAuthority.class)))); + assumeFalse(ctx.wantBranches()); + assumeFalse(ctx.wantPRs()); + assumeTrue(ctx.prefilters().isEmpty()); + assumeTrue(ctx.filters().isEmpty()); + assumeTrue(ctx.authorities().stream() + .noneMatch( + item -> item instanceof OriginPullRequestDiscoveryTrait.OriginChangeRequestSCMHeadAuthority)); OriginPullRequestDiscoveryTrait instance = new OriginPullRequestDiscoveryTrait(EnumSet.allOf(ChangeRequestCheckoutStrategy.class)); instance.decorateContext(ctx); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/PullRequestSCMRevisionTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/PullRequestSCMRevisionTest.java index 49448a40a..5ba1717c7 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/PullRequestSCMRevisionTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/PullRequestSCMRevisionTest.java @@ -30,63 +30,59 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import hudson.AbortException; import jenkins.scm.api.SCMHead; import jenkins.scm.api.SCMHeadOrigin; import jenkins.scm.api.mixin.ChangeRequestCheckoutStrategy; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; -public class PullRequestSCMRevisionTest extends AbstractGitHubWireMockTest { +class PullRequestSCMRevisionTest extends AbstractGitHubWireMockTest { private GitHub github; private GHRepository repo; - @Before - public void setupRevisionTests() throws Exception { - github = Connector.connect("http://localhost:" + githubApi.port(), null); - repo = github.getRepository("cloudbeers/yolo"); - } - - public static SCMHead master = new BranchSCMHead("master"); - public static PullRequestSCMHead prHead = new PullRequestSCMHead( + private static final SCMHead MASTER = new BranchSCMHead("master"); + private static final PullRequestSCMHead PR_HEAD = new PullRequestSCMHead( "", "stephenc", "yolo", "master", 1, - (BranchSCMHead) master, + (BranchSCMHead) MASTER, SCMHeadOrigin.DEFAULT, ChangeRequestCheckoutStrategy.HEAD); - public static PullRequestSCMHead prMerge = new PullRequestSCMHead( + private static final PullRequestSCMHead PR_MERGE = new PullRequestSCMHead( "", "stephenc", "yolo", "master", 1, - (BranchSCMHead) master, + (BranchSCMHead) MASTER, SCMHeadOrigin.DEFAULT, ChangeRequestCheckoutStrategy.MERGE); + @Override + @BeforeEach + void beforeEach() throws Exception { + super.beforeEach(); + github = Connector.connect("http://localhost:" + githubApi.getPort(), null); + repo = github.getRepository("cloudbeers/yolo"); + } + @Test - public void createHeadwithNullMergeRevision() throws Exception { - PullRequestSCMHead currentHead = prHead; - PullRequestSCMHead otherHead = prMerge; + void createHeadWithNullMergeRevision() { + PullRequestSCMHead currentHead = PR_HEAD; + PullRequestSCMHead otherHead = PR_MERGE; PullRequestSCMRevision currentRevision = new PullRequestSCMRevision(currentHead, "master-revision", "pr-branch-revision"); assertThat(currentRevision.toString(), is("pr-branch-revision")); - try { - currentRevision.validateMergeHash(); - } catch (AbortException e) { - fail("Validation should succeed, but: " + e.getMessage()); - } + assertDoesNotThrow(currentRevision::validateMergeHash, "Validation should succeed, but: "); // equivalence assertTrue(currentRevision.equivalent( @@ -117,19 +113,15 @@ public void createHeadwithNullMergeRevision() throws Exception { } @Test - public void createHeadwithMergeRevision() throws Exception { - PullRequestSCMHead currentHead = prHead; - PullRequestSCMHead otherHead = prMerge; + void createHeadWithMergeRevision() { + PullRequestSCMHead currentHead = PR_HEAD; + PullRequestSCMHead otherHead = PR_MERGE; PullRequestSCMRevision currentRevision = new PullRequestSCMRevision(currentHead, "master-revision", "pr-branch-revision", "pr-merge-revision"); assertThat(currentRevision.toString(), is("pr-branch-revision")); - try { - currentRevision.validateMergeHash(); - } catch (AbortException e) { - fail("Validation should succeed, but: " + e.getMessage()); - } + assertDoesNotThrow(currentRevision::validateMergeHash, "Validation should succeed, but: "); // equivalence assertTrue(currentRevision.equivalent( @@ -160,19 +152,15 @@ public void createHeadwithMergeRevision() throws Exception { } @Test - public void createMergewithNullMergeRevision() throws Exception { - PullRequestSCMHead currentHead = prMerge; - PullRequestSCMHead otherHead = prHead; + void createMergeWithNullMergeRevision() { + PullRequestSCMHead currentHead = PR_MERGE; + PullRequestSCMHead otherHead = PR_HEAD; PullRequestSCMRevision currentRevision = new PullRequestSCMRevision(currentHead, "master-revision", "pr-branch-revision"); assertThat(currentRevision.toString(), is("pr-branch-revision+master-revision (UNKNOWN_MERGE_STATE)")); - try { - currentRevision.validateMergeHash(); - } catch (AbortException e) { - fail("Validation should succeed, but: " + e.getMessage()); - } + assertDoesNotThrow(currentRevision::validateMergeHash, "Validation should succeed, but: "); // equivalence assertTrue(currentRevision.equivalent( @@ -204,9 +192,9 @@ public void createMergewithNullMergeRevision() throws Exception { } @Test - public void createMergewithNotMergeableRevision() throws Exception { - PullRequestSCMHead currentHead = prMerge; - PullRequestSCMHead otherHead = prHead; + void createMergeWithNotMergeableRevision() { + PullRequestSCMHead currentHead = PR_MERGE; + PullRequestSCMHead otherHead = PR_HEAD; PullRequestSCMRevision currentRevision = new PullRequestSCMRevision( currentHead, "master-revision", "pr-branch-revision", PullRequestSCMRevision.NOT_MERGEABLE_HASH); @@ -252,19 +240,15 @@ public void createMergewithNotMergeableRevision() throws Exception { } @Test - public void createMergewithMergeRevision() throws Exception { - PullRequestSCMHead currentHead = prMerge; - PullRequestSCMHead otherHead = prHead; + void createMergeWithMergeRevision() { + PullRequestSCMHead currentHead = PR_MERGE; + PullRequestSCMHead otherHead = PR_HEAD; PullRequestSCMRevision currentRevision = new PullRequestSCMRevision(currentHead, "master-revision", "pr-branch-revision", "pr-merge-revision"); assertThat(currentRevision.toString(), is("pr-branch-revision+master-revision (pr-merge-revision)")); - try { - currentRevision.validateMergeHash(); - } catch (AbortException e) { - fail("Validation should succeed, but: " + e.getMessage()); - } + assertDoesNotThrow(currentRevision::validateMergeHash, "Validation should succeed, but: "); // equivalence assertTrue(currentRevision.equivalent( diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/SSHCheckoutTraitTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/SSHCheckoutTraitTest.java index 5f7b44337..39007b0f2 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/SSHCheckoutTraitTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/SSHCheckoutTraitTest.java @@ -1,10 +1,10 @@ package org.jenkinsci.plugins.github_branch_source; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assume.assumeThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import hudson.model.Item; import hudson.model.User; @@ -14,71 +14,77 @@ import hudson.security.SecurityRealm; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.MockFolder; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class SSHCheckoutTraitTest { - @ClassRule - public static JenkinsRule j = new JenkinsRule(); +@WithJenkins +class SSHCheckoutTraitTest { + + private static JenkinsRule j; + + @BeforeAll + static void beforeAll(JenkinsRule rule, TestInfo info) { + j = rule; + } @Test - public void given__legacyConfig__when__creatingTrait__then__convertedToModern() throws Exception { + void given__legacyConfig__when__creatingTrait__then__convertedToModern() { assertThat(new SSHCheckoutTrait(GitHubSCMSource.DescriptorImpl.ANONYMOUS).getCredentialsId(), is(nullValue())); } @Test - public void given__sshCheckoutWithCredentials__when__decorating__then__credentialsApplied_with_repositoryUrl() - throws Exception { + void given__sshCheckoutWithCredentials__when__decorating__then__credentialsApplied_with_repositoryUrl() { SSHCheckoutTrait instance = new SSHCheckoutTrait("keyId"); GitHubSCMSource source = new GitHubSCMSource("", "", "https://github.com/example/does-not-exist", true); source.setCredentialsId("scanId"); GitHubSCMBuilder probe = new GitHubSCMBuilder(source, new BranchSCMHead("master"), null); - assumeThat(probe.credentialsId(), is("scanId")); + assumeTrue(probe.credentialsId().equals("scanId")); instance.decorateBuilder(probe); assertThat(probe.credentialsId(), is("keyId")); } @Test - public void given__sshCheckoutWithCredentials__when__decorating__then__credentialsApplied() throws Exception { + void given__sshCheckoutWithCredentials__when__decorating__then__credentialsApplied() { SSHCheckoutTrait instance = new SSHCheckoutTrait("keyId"); GitHubSCMSource source = new GitHubSCMSource("example", "does-not-exist"); source.setApiUri("https://github.test"); source.setCredentialsId("scanId"); GitHubSCMBuilder probe = new GitHubSCMBuilder(source, new BranchSCMHead("master"), null); - assumeThat(probe.credentialsId(), is("scanId")); + assumeTrue(probe.credentialsId().equals("scanId")); instance.decorateBuilder(probe); assertThat(probe.credentialsId(), is("keyId")); } @Test - public void given__sshCheckoutWithAgentKey__when__decorating__then__useAgentKeyApplied_with_repositoryUrl() - throws Exception { + void given__sshCheckoutWithAgentKey__when__decorating__then__useAgentKeyApplied_with_repositoryUrl() { SSHCheckoutTrait instance = new SSHCheckoutTrait(null); GitHubSCMSource source = new GitHubSCMSource("", "", "https://github.com/example/does-not-exist", true); source.setCredentialsId("scanId"); GitHubSCMBuilder probe = new GitHubSCMBuilder(source, new BranchSCMHead("master"), null); - assumeThat(probe.credentialsId(), is("scanId")); + assumeTrue(probe.credentialsId().equals("scanId")); instance.decorateBuilder(probe); assertThat(probe.credentialsId(), is(nullValue())); } @Test - public void given__sshCheckoutWithAgentKey__when__decorating__then__useAgentKeyApplied() throws Exception { + void given__sshCheckoutWithAgentKey__when__decorating__then__useAgentKeyApplied() { SSHCheckoutTrait instance = new SSHCheckoutTrait(null); GitHubSCMSource source = new GitHubSCMSource("example", "does-not-exist"); source.setApiUri("https://github.test"); source.setCredentialsId("scanId"); GitHubSCMBuilder probe = new GitHubSCMBuilder(source, new BranchSCMHead("master"), null); - assumeThat(probe.credentialsId(), is("scanId")); + assumeTrue(probe.credentialsId().equals("scanId")); instance.decorateBuilder(probe); assertThat(probe.credentialsId(), is(nullValue())); } @Test - public void given__descriptor__when__displayingCredentials__then__contractEnforced() throws Exception { + void given__descriptor__when__displayingCredentials__then__contractEnforced() throws Exception { final SSHCheckoutTrait.DescriptorImpl d = j.jenkins.getDescriptorByType(SSHCheckoutTrait.DescriptorImpl.class); final MockFolder dummy = j.createFolder("dummy"); SecurityRealm realm = j.jenkins.getSecurityRealm(); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/TagDiscoveryTraitTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/TagDiscoveryTraitTest.java index e4e52e83c..1c06f375f 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/TagDiscoveryTraitTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/TagDiscoveryTraitTest.java @@ -1,9 +1,9 @@ package org.jenkinsci.plugins.github_branch_source; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.*; import java.util.Collections; import jenkins.scm.api.SCMHead; @@ -14,16 +14,23 @@ import jenkins.scm.impl.ChangeRequestSCMHeadCategory; import jenkins.scm.impl.TagSCMHeadCategory; import jenkins.scm.impl.UncategorizedSCMHeadCategory; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class TagDiscoveryTraitTest { - @ClassRule - public static JenkinsRule j = new JenkinsRule(); +@WithJenkins +class TagDiscoveryTraitTest { + + private static JenkinsRule j; + + @BeforeAll + static void beforeAll(JenkinsRule rule) { + j = rule; + } @Test - public void decorateContext() throws Exception { + void decorateContext() { GitHubSCMSourceContext probe = new GitHubSCMSourceContext(null, SCMHeadObserver.collect()); assertThat(probe.wantBranches(), is(false)); assertThat(probe.wantPRs(), is(false)); @@ -37,14 +44,14 @@ public void decorateContext() throws Exception { } @Test - public void includeCategory() throws Exception { + void includeCategory() { assertThat(new TagDiscoveryTrait().includeCategory(ChangeRequestSCMHeadCategory.DEFAULT), is(false)); assertThat(new TagDiscoveryTrait().includeCategory(UncategorizedSCMHeadCategory.DEFAULT), is(false)); assertThat(new TagDiscoveryTrait().includeCategory(TagSCMHeadCategory.DEFAULT), is(true)); } @Test - public void authority() throws Exception { + void authority() throws Exception { try (GitHubSCMSourceRequest probe = new GitHubSCMSourceContext(null, SCMHeadObserver.collect()) .newRequest(new GitHubSCMSource("does-not-exist", "http://does-not-exist.test"), null)) { TagDiscoveryTrait.TagSCMHeadAuthority instance = new TagDiscoveryTrait.TagSCMHeadAuthority(); @@ -67,7 +74,7 @@ public void authority() throws Exception { } @Test - public void authority_with_repositoryUrl() throws Exception { + void authority_with_repositoryUrl() throws Exception { try (GitHubSCMSourceRequest probe = new GitHubSCMSourceContext(null, SCMHeadObserver.collect()) .newRequest(new GitHubSCMSource("", "", "https://github.com/example/does-not-exist", true), null)) { TagDiscoveryTrait.TagSCMHeadAuthority instance = new TagDiscoveryTrait.TagSCMHeadAuthority(); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/WireMockRuleFactory.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/WireMockExtensionFactory.java similarity index 60% rename from src/test/java/org/jenkinsci/plugins/github_branch_source/WireMockRuleFactory.java rename to src/test/java/org/jenkinsci/plugins/github_branch_source/WireMockExtensionFactory.java index 48c485dee..fe007cf82 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/WireMockRuleFactory.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/WireMockExtensionFactory.java @@ -30,36 +30,33 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; -import com.github.tomakehurst.wiremock.common.SingleRootFileSource; import com.github.tomakehurst.wiremock.core.Options; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; -public class WireMockRuleFactory { - private String urlToMock = System.getProperty("wiremock.record"); +public class WireMockExtensionFactory { + private final String urlToMock = System.getProperty("wiremock.record"); - public WireMockRule getRule(int port) { - return getRule(wireMockConfig().port(port)); + public WireMockExtension getExtension(int port) { + return getExtension(wireMockConfig().port(port)); } - public WireMockRule getRule(Options options) { + public WireMockExtension getExtension(Options options) { if (urlToMock != null && !urlToMock.isEmpty()) { - return new WireMockRecorderRule(options, urlToMock); + return new WireMockRecorderExtension(options, urlToMock); } else { - return new WireMockRule(options); + return new WireMockRecorderExtension(options, null); } } - private class WireMockRecorderRule extends WireMockRule { - // needed for WireMockRule file location - private String mappingLocation = "src/test/resources"; + private static class WireMockRecorderExtension extends WireMockExtension { - public WireMockRecorderRule(Options options, String url) { - super(options); - this.stubFor( - get(urlMatching(".*")).atPriority(10).willReturn(aResponse().proxiedFrom(url))); - this.enableRecordMappings( - new SingleRootFileSource(mappingLocation + "/mappings"), - new SingleRootFileSource(mappingLocation + "/__files")); + public WireMockRecorderExtension(Options options, String url) { + super(new Builder().options(options)); + if (url != null) { + this.stubFor(get(urlMatching(".*")) + .atPriority(10) + .willReturn(aResponse().proxiedFrom(url))); + } } } } diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessInferredOwnerTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessInferredOwnerTest.java index 54d822d3b..bf350f65c 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessInferredOwnerTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessInferredOwnerTest.java @@ -5,14 +5,14 @@ import static org.hamcrest.Matchers.nullValue; import org.jenkinsci.plugins.github_branch_source.GitHubAppUsageContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class AccessInferredOwnerTest { +class AccessInferredOwnerTest { private final RepositoryAccessStrategy strategy = new AccessInferredOwner(); @Test - public void smokes() { + void smokes() { assertThat( strategy.forContext(GitHubAppUsageContext.builder() .inferredOwner("inferred-owner") @@ -22,7 +22,7 @@ public void smokes() { } @Test - public void requiresInferredOwner() { + void requiresInferredOwner() { assertThat(strategy.forContext(GitHubAppUsageContext.builder().build()), nullValue()); assertThat( strategy.forContext(GitHubAppUsageContext.builder() diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessInferredRepositoryTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessInferredRepositoryTest.java index 5d2f43e09..c5ee76afd 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessInferredRepositoryTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessInferredRepositoryTest.java @@ -6,15 +6,14 @@ import java.util.List; import org.jenkinsci.plugins.github_branch_source.GitHubAppUsageContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class AccessInferredRepositoryTest { +class AccessInferredRepositoryTest { private final RepositoryAccessStrategy strategy = new AccessInferredRepository(); @Test - public void smokes() { - final var strategy = new AccessInferredRepository(); + void smokes() { assertThat( strategy.forContext(GitHubAppUsageContext.builder() .inferredOwner("inferred-owner") @@ -24,9 +23,7 @@ public void smokes() { } @Test - public void constrainedUsageAllowsMultiRepositoryAccess() { - final var strategy = new AccessInferredRepository(); - + void constrainedUsageAllowsMultiRepositoryAccess() { assertThat( strategy.forContext(GitHubAppUsageContext.builder() .inferredOwner("inferred-owner") @@ -43,7 +40,7 @@ public void constrainedUsageAllowsMultiRepositoryAccess() { } @Test - public void requiresInferredOwner() { + void requiresInferredOwner() { assertThat(strategy.forContext(GitHubAppUsageContext.builder().build()), nullValue()); assertThat( strategy.forContext(GitHubAppUsageContext.builder() @@ -59,7 +56,7 @@ public void requiresInferredOwner() { } @Test - public void requiresInferredRepository() { + void requiresInferredRepository() { assertThat( strategy.forContext(GitHubAppUsageContext.builder() .inferredOwner("inferred-owner") diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessSpecifiedRepositoriesTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessSpecifiedRepositoriesTest.java index 0f3a7eaca..a86e8b069 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessSpecifiedRepositoriesTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/AccessSpecifiedRepositoriesTest.java @@ -5,15 +5,15 @@ import java.util.List; import org.jenkinsci.plugins.github_branch_source.GitHubAppUsageContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class AccessSpecifiedRepositoriesTest { +class AccessSpecifiedRepositoriesTest { private final RepositoryAccessStrategy strategy = new AccessSpecifiedRepositories("owner", List.of("repo-one", "repo-two")); @Test - public void smokes() { + void smokes() { assertThat( strategy.forContext(GitHubAppUsageContext.builder() .inferredOwner("inferred-owner") @@ -23,7 +23,7 @@ public void smokes() { } @Test - public void trustedUsageAllowsArbitraryRepositoryAccess() { + void trustedUsageAllowsArbitraryRepositoryAccess() { assertThat( strategy.forContext(GitHubAppUsageContext.builder() .inferredOwner("inferred-owner") diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/MigrationAdminMonitorTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/MigrationAdminMonitorTest.java index a157eee18..fc1763828 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/MigrationAdminMonitorTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/MigrationAdminMonitorTest.java @@ -6,28 +6,34 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import hudson.ExtensionList; import hudson.security.ACL; import org.jenkinsci.plugins.github_branch_source.GitHubAppCredentials; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; -public class MigrationAdminMonitorTest { +@WithJenkins +class MigrationAdminMonitorTest { - @Rule - public JenkinsRule r = new JenkinsRule(); + private JenkinsRule r; + + @BeforeEach + void beforeEach(JenkinsRule rule) { + r = rule; + } // Checks the migration behavior for credentials created prior to the introduction of the repository access // strategy and the default permissions strategy. @Test @LocalData - public void smokes() throws Throwable { + void smokes() { // LocalData based on the following code at commit 50351eb /* var store = CredentialsProvider.lookupStores(r.jenkins).iterator().next(); diff --git a/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/RunWithCredentialsTest.java b/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/RunWithCredentialsTest.java index fccd43e45..b51542082 100644 --- a/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/RunWithCredentialsTest.java +++ b/src/test/java/org/jenkinsci/plugins/github_branch_source/app_credentials/RunWithCredentialsTest.java @@ -16,12 +16,10 @@ import com.github.tomakehurst.wiremock.http.HttpHeader; import com.github.tomakehurst.wiremock.http.HttpHeaders; import hudson.ProxyConfiguration; -import hudson.model.Descriptor.FormException; import hudson.model.InvisibleAction; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; -import java.io.IOException; import java.net.URI; import java.net.http.HttpResponse.BodyHandlers; import java.time.Duration; @@ -32,7 +30,6 @@ import java.util.Arrays; import java.util.List; import java.util.Set; -import java.util.concurrent.ExecutionException; import net.sf.json.JSONObject; import org.jenkinsci.plugins.github_branch_source.AbstractGitHubWireMockTest; import org.jenkinsci.plugins.github_branch_source.ApiRateLimitChecker; @@ -46,29 +43,25 @@ import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.jenkinsci.plugins.workflow.steps.StepExecutions; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.BuildWatcher; -import org.jvnet.hudson.test.FlagRule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.BuildWatcherExtension; import org.kohsuke.stapler.DataBoundConstructor; /** * This creates a pipeline job that logs the repositories accessible from the contextualized credentials. * It asserts that the correct repositories are accessible based on the repository access strategy set on the credentials. */ -public class RunWithCredentialsTest extends AbstractGitHubWireMockTest { +class RunWithCredentialsTest extends AbstractGitHubWireMockTest { - @ClassRule - public static BuildWatcher watcher = new BuildWatcher(); + @SuppressWarnings("unused") + @RegisterExtension + private static final BuildWatcherExtension WATCHER = new BuildWatcherExtension(); - @Rule - public FlagRule resetAllowUnsafeRepoInference = new FlagRule<>( - () -> GitHubAppCredentials.ALLOW_UNSAFE_REPOSITORY_INFERENCE, - x -> GitHubAppCredentials.ALLOW_UNSAFE_REPOSITORY_INFERENCE = x); + private boolean resetAllowUnsafeRepoInference; private enum InstallationAccessToken { TOKEN, @@ -100,8 +93,10 @@ private String createTokenExpiration() { private CredentialsStore credentialsStore; private WorkflowJob project; - @Before - public void setup() throws IOException, FormException, InterruptedException, ExecutionException { + @BeforeEach + void beforeEach() throws Exception { + resetAllowUnsafeRepoInference = GitHubAppCredentials.ALLOW_UNSAFE_REPOSITORY_INFERENCE; + GitHubConfiguration.get().setApiRateLimitChecker(ApiRateLimitChecker.ThrottleOnOver); // Tests here use WorkflowJob+GithubProjectProperty for simplicity. We could switch to Multibranch Projects // instead to avoid this flag. @@ -118,7 +113,7 @@ public void setup() throws IOException, FormException, InterruptedException, Exe project.addProperty(new GithubProjectProperty("https://github.com/cloudbeers/repository-a/")); project.setDefinition(new CpsFlowDefinition( "getAccessibleRepositories(credentialsId: '" + credentials.getId() - + "', githubApiUri: 'http://localhost:" + githubApi.port() + "/installation/repositories')", + + "', githubApiUri: 'http://localhost:" + githubApi.getPort() + "/installation/repositories')", true)); // Sub app @@ -216,8 +211,10 @@ private void multipleInstallations() { .withBodyFile("../AppCredentials/files/body-mapping-githubapp-installations-multiple.json"))); } - @After - public void cleanup() throws IOException, InterruptedException { + @AfterEach + void afterEach() throws Exception { + GitHubAppCredentials.ALLOW_UNSAFE_REPOSITORY_INFERENCE = resetAllowUnsafeRepoInference; + if (project != null) { project.delete(); } @@ -227,7 +224,7 @@ public void cleanup() throws IOException, InterruptedException { } @Test - public void inferredRepository() throws Exception { + void inferredRepository() throws Exception { multipleInstallations(); credentials.setRepositoryAccessStrategy(new AccessInferredRepository()); @@ -239,7 +236,7 @@ public void inferredRepository() throws Exception { } @Test - public void inferredOwner() throws Exception { + void inferredOwner() throws Exception { multipleInstallations(); credentials.setRepositoryAccessStrategy(new AccessInferredOwner()); @@ -251,7 +248,7 @@ public void inferredOwner() throws Exception { } @Test - public void specifiedRepositoriesA() throws Exception { + void specifiedRepositoriesA() throws Exception { multipleInstallations(); credentials.setRepositoryAccessStrategy( @@ -264,7 +261,7 @@ public void specifiedRepositoriesA() throws Exception { } @Test - public void specifiedRepositoriesB() throws Exception { + void specifiedRepositoriesB() throws Exception { multipleInstallations(); credentials.setRepositoryAccessStrategy( @@ -277,7 +274,7 @@ public void specifiedRepositoriesB() throws Exception { } @Test - public void specifiedRepositoriesAB() throws Exception { + void specifiedRepositoriesAB() throws Exception { multipleInstallations(); credentials.setRepositoryAccessStrategy( @@ -290,7 +287,7 @@ public void specifiedRepositoriesAB() throws Exception { } @Test - public void specifiedRepositoriesABC() throws Exception { + void specifiedRepositoriesABC() throws Exception { multipleInstallations(); credentials.setRepositoryAccessStrategy(new AccessSpecifiedRepositories( @@ -305,7 +302,7 @@ public void specifiedRepositoriesABC() throws Exception { } @Test - public void specifiedRepositoryWithOwner() throws Exception { + void specifiedRepositoryWithOwner() throws Exception { simpleInstallations(); credentials.setRepositoryAccessStrategy(new AccessSpecifiedRepositories("cloudbeers", List.of())); @@ -317,7 +314,7 @@ public void specifiedRepositoryWithOwner() throws Exception { } @Test - public void specifiedRepositoryWithoutOwner() throws Exception { + void specifiedRepositoryWithoutOwner() throws Exception { simpleInstallations(); // Owner is inferred from the context in this case @@ -335,7 +332,7 @@ public void specifiedRepositoryWithoutOwner() throws Exception { * not part of a MultiBranchProject. */ @Test - public void propertiesStepAllowsAccessBypass() throws Exception { + void propertiesStepAllowsAccessBypass() throws Exception { multipleInstallations(); credentials.setRepositoryAccessStrategy(new AccessInferredRepository()); @@ -343,7 +340,7 @@ public void propertiesStepAllowsAccessBypass() throws Exception { project.setDefinition(new CpsFlowDefinition( "properties([githubProjectProperty('https://github.com/cloudbeers/repository-b/')])\n" + "getAccessibleRepositories(credentialsId: '" + credentials.getId() - + "', githubApiUri: 'http://localhost:" + githubApi.port() + "/installation/repositories')", + + "', githubApiUri: 'http://localhost:" + githubApi.getPort() + "/installation/repositories')", true)); // First build uses the property configured in RunWithCredentialsTest#before @@ -371,7 +368,7 @@ public GetAccessibleRepositories(String credentialsId, String githubApiUri) { } @Override - public StepExecution start(StepContext context) throws Exception { + public StepExecution start(StepContext context) { return StepExecutions.synchronous(context, c -> { var run = c.get(Run.class); var credentials =