From b447f834ea0db47c623306431c6fce9bf6a0bee4 Mon Sep 17 00:00:00 2001 From: strangelookingnerd Date: Thu, 23 Jan 2025 16:18:53 +0100 Subject: [PATCH 1/3] Migrate tests to JUnit5 * Migrate annotations and imports * Migrate assertions * Migrate GHMock Rule to Extension * Migrate to DataProviderRunner to ParameterizedTest * Remove public visibility for test classes and methods * Minor clean up --- pom.xml | 20 +-- .../jenkins/GitHubCommitNotifierTest.java | 67 ++++--- .../jenkins/GitHubPushTriggerTest.java | 25 +-- .../GitHubSetCommitStatusBuilderTest.java | 60 ++++--- .../GitHubWebHookCrumbExclusionTest.java | 25 ++- .../jenkins/GitHubWebHookFullTest.java | 71 ++++---- .../cloudbees/jenkins/GitHubWebHookTest.java | 28 ++- .../jenkins/GlobalConfigSubmitTest.java | 24 ++- .../github/GitHubRepositoryNameTest.java | 142 +++++++-------- .../github/GithubLinkActionFactoryTest.java | 38 ++-- .../github/GithubLinkAnnotatorTest.java | 56 +++--- .../github/GithubProjectPropertyTest.java | 29 ++-- .../hudson/plugins/github/GithubUrlTest.java | 22 +-- .../plugins/github/admin/GHRepoNameTest.java | 16 +- .../GitHubHookRegisterProblemMonitorTest.java | 75 ++++---- .../github/admin/ValidateRepoNameTest.java | 31 ++-- .../common/CombineErrorHandlerTest.java | 55 +++--- .../github/common/ExpandableMessageTest.java | 18 +- .../github/config/ConfigAsCodeTest.java | 27 +-- .../github/config/GitHubPluginConfigTest.java | 47 ++--- .../GitHubServerConfigIntegrationTest.java | 91 +++++----- .../github/config/GitHubServerConfigTest.java | 28 +-- .../github/config/HookSecretConfigTest.java | 34 ++-- .../github/extension/CryptoUtilTest.java | 26 +-- .../extension/GHEventsSubscriberTest.java | 10 +- .../GitHubClientCacheCleanupTest.java | 40 +++-- .../internal/GitHubClientCacheOpsTest.java | 56 +++--- .../github/migration/MigratorTest.java | 26 +-- .../status/GitHubCommitStatusSetterTest.java | 60 ++++--- .../github/status/err/ErrorHandlersTest.java | 18 +- .../sources/BuildRefBackrefSourceTest.java | 27 +-- .../ConditionalStatusResultSourceTest.java | 20 +-- .../DefaultStatusResultSourceTest.java | 29 ++-- .../ManuallyEnteredRepositorySourceTest.java | 12 +- .../sources/ManuallyEnteredSourcesTest.java | 16 +- .../sources/misc/AnyBuildResultTest.java | 18 +- .../BetterThanOrEqualBuildResultTest.java | 30 ++-- .../plugins/github/test/GHMockRule.java | 164 ------------------ .../github/test/GitHubMockExtension.java | 123 +++++++++++++ .../test/GitHubServerConfigMatcher.java | 5 - .../plugins/github/test/HookSecretHelper.java | 8 +- .../github/test/InjectJenkinsMembersRule.java | 39 ----- .../github/util/BuildDataHelperTest.java | 31 ++-- .../github/util/JobInfoHelpersTest.java | 34 ++-- .../plugins/github/util/XSSApiTest.java | 19 +- .../github/webhook/GHEventHeaderTest.java | 26 +-- .../github/webhook/GHEventPayloadTest.java | 12 +- .../RequirePostWithGHHookPayloadTest.java | 126 +++++++------- .../github/webhook/WebhookManagerTest.java | 58 ++++--- .../DefaultPushGHEventListenerTest.java | 29 ++-- .../subscriber/PingGHEventSubscriberTest.java | 26 +-- .../repos-repo.json | 0 .../user.json | 0 53 files changed, 1037 insertions(+), 1080 deletions(-) delete mode 100644 src/test/java/org/jenkinsci/plugins/github/test/GHMockRule.java create mode 100644 src/test/java/org/jenkinsci/plugins/github/test/GitHubMockExtension.java delete mode 100644 src/test/java/org/jenkinsci/plugins/github/test/InjectJenkinsMembersRule.java rename src/test/resources/org/jenkinsci/plugins/github/test/{GHMockRule => GitHubMockExtension}/repos-repo.json (100%) rename src/test/resources/org/jenkinsci/plugins/github/test/{GHMockRule => GitHubMockExtension}/user.json (100%) diff --git a/pom.xml b/pom.xml index 3c03e05cc..2d0137060 100755 --- a/pom.xml +++ b/pom.xml @@ -64,7 +64,7 @@ https://repo.jenkins-ci.org/public/ - + repo.jenkins-ci.org @@ -135,6 +135,11 @@ mockito-core test + + org.mockito + mockito-junit-jupiter + test + @@ -172,18 +177,11 @@ test - - com.tngtech.java - junit-dataprovider - 1.13.1 - test - - - com.github.tomakehurst - wiremock-jre8-standalone - 2.35.2 + org.wiremock + wiremock-standalone + 3.10.0 test diff --git a/src/test/java/com/cloudbees/jenkins/GitHubCommitNotifierTest.java b/src/test/java/com/cloudbees/jenkins/GitHubCommitNotifierTest.java index 55d96ab56..7ea4c3ef3 100644 --- a/src/test/java/com/cloudbees/jenkins/GitHubCommitNotifierTest.java +++ b/src/test/java/com/cloudbees/jenkins/GitHubCommitNotifierTest.java @@ -1,7 +1,7 @@ package com.cloudbees.jenkins; import com.github.tomakehurst.wiremock.common.Slf4jNotifier; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.Build; @@ -13,24 +13,22 @@ import hudson.plugins.git.Revision; import hudson.plugins.git.util.BuildData; import hudson.util.VersionNumber; +import jakarta.inject.Inject; import org.eclipse.jgit.lib.ObjectId; import org.jenkinsci.plugins.github.config.GitHubPluginConfig; -import org.jenkinsci.plugins.github.test.GHMockRule; -import org.jenkinsci.plugins.github.test.GHMockRule.FixedGHRepoNameTestContributor; -import org.jenkinsci.plugins.github.test.InjectJenkinsMembersRule; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.RuleChain; -import org.junit.runner.RunWith; +import org.jenkinsci.plugins.github.test.GitHubMockExtension; +import org.jenkinsci.plugins.github.test.GitHubMockExtension.FixedGHRepoNameTestContributor; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import jakarta.inject.Inject; +import org.mockito.junit.jupiter.MockitoExtension; import static com.cloudbees.jenkins.GitHubSetCommitStatusBuilderTest.SOME_SHA; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; @@ -45,43 +43,42 @@ * * @author Oleg Nenashev */ -@RunWith(MockitoJUnitRunner.class) +@WithJenkins +@ExtendWith(MockitoExtension.class) public class GitHubCommitNotifierTest { - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) public BuildData data; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) public Revision rev; @Inject public GitHubPluginConfig config; - public JenkinsRule jRule = new JenkinsRule(); + private JenkinsRule jRule; - @Rule - public RuleChain chain = RuleChain.outerRule(jRule).around(new InjectJenkinsMembersRule(jRule, this)); - - @Rule - public GHMockRule github = new GHMockRule( - new WireMockRule( - wireMockConfig().dynamicPort().notifier(new Slf4jNotifier(true)) - )) + @RegisterExtension + static GitHubMockExtension github = new GitHubMockExtension(WireMockExtension.newInstance() + .options(wireMockConfig().dynamicPort().notifier(new Slf4jNotifier(true)))) .stubUser() .stubRepo() .stubStatuses(); - @Before - public void before() throws Throwable { - when(data.getLastBuiltRevision()).thenReturn(rev); - data.lastBuild = new hudson.plugins.git.util.Build(rev, rev, 0, Result.SUCCESS); - when(rev.getSha1()).thenReturn(ObjectId.fromString(SOME_SHA)); + @BeforeEach + void before(JenkinsRule rule) throws Throwable { + jRule = rule; + jRule.getInstance().getInjector().injectMembers(this); + + when(data.getLastBuiltRevision()).thenReturn(rev); + data.lastBuild = new hudson.plugins.git.util.Build(rev, rev, 0, Result.SUCCESS); + when(rev.getSha1()).thenReturn(ObjectId.fromString(SOME_SHA)); } @Test @Issue("JENKINS-23641") - public void testNoBuildData() throws Exception { + void testNoBuildData() throws Exception { FreeStyleProject prj = jRule.createFreeStyleProject("23641_noBuildData"); prj.getPublishersList().add(new GitHubCommitNotifier()); Build b = prj.scheduleBuild2(0).get(); @@ -91,7 +88,7 @@ public void testNoBuildData() throws Exception { @Test @Issue("JENKINS-23641") - public void testNoBuildRevision() throws Exception { + void testNoBuildRevision() throws Exception { FreeStyleProject prj = jRule.createFreeStyleProject(); prj.setScm(new GitSCM("http://non.existent.git.repo.nowhere/repo.git")); prj.getPublishersList().add(new GitHubCommitNotifier()); @@ -103,7 +100,7 @@ public void testNoBuildRevision() throws Exception { @Test @Issue("JENKINS-25312") - public void testMarkUnstableOnCommitNotifierFailure() throws Exception { + void testMarkUnstableOnCommitNotifierFailure() throws Exception { FreeStyleProject prj = jRule.createFreeStyleProject(); prj.getPublishersList().add(new GitHubCommitNotifier(Result.UNSTABLE.toString())); Build b = prj.scheduleBuild2(0).get(); @@ -112,7 +109,7 @@ public void testMarkUnstableOnCommitNotifierFailure() throws Exception { @Test @Issue("JENKINS-25312") - public void testMarkSuccessOnCommitNotifierFailure() throws Exception { + void testMarkSuccessOnCommitNotifierFailure() throws Exception { FreeStyleProject prj = jRule.createFreeStyleProject(); prj.getPublishersList().add(new GitHubCommitNotifier(Result.SUCCESS.toString())); Build b = prj.scheduleBuild2(0).get(); @@ -120,7 +117,7 @@ public void testMarkSuccessOnCommitNotifierFailure() throws Exception { } @Test - public void shouldWriteStatusOnGH() throws Exception { + void shouldWriteStatusOnGH() throws Exception { config.getConfigs().add(github.serverConfig()); FreeStyleProject prj = jRule.createFreeStyleProject(); @@ -136,7 +133,7 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen prj.scheduleBuild2(0).get(); - github.service().verify(1, postRequestedFor(urlPathMatching(".*/" + SOME_SHA))); + github.verify(1, postRequestedFor(urlPathMatching(".*/" + SOME_SHA))); } private Build safelyGenerateBuild(FreeStyleProject prj) throws InterruptedException, java.util.concurrent.ExecutionException { diff --git a/src/test/java/com/cloudbees/jenkins/GitHubPushTriggerTest.java b/src/test/java/com/cloudbees/jenkins/GitHubPushTriggerTest.java index 79508225b..cf301eb75 100644 --- a/src/test/java/com/cloudbees/jenkins/GitHubPushTriggerTest.java +++ b/src/test/java/com/cloudbees/jenkins/GitHubPushTriggerTest.java @@ -5,19 +5,19 @@ import hudson.plugins.git.util.Build; import hudson.plugins.git.util.BuildData; import hudson.util.FormValidation; +import jakarta.inject.Inject; import org.eclipse.jgit.lib.ObjectId; import org.jenkinsci.plugins.github.admin.GitHubHookRegisterProblemMonitor; import org.jenkinsci.plugins.github.webhook.subscriber.DefaultPushGHEventListenerTest; 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.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -import jakarta.inject.Inject; import java.io.IOException; import java.util.HashMap; import java.util.concurrent.TimeUnit; @@ -30,7 +30,8 @@ /** * @author lanwen (Merkushev Kirill) */ -public class GitHubPushTriggerTest { +@WithJenkins +class GitHubPushTriggerTest { private static final GitHubRepositoryName REPO = new GitHubRepositoryName("host", "user", "repo"); private static final GitSCM REPO_GIT_SCM = new GitSCM("git://host/user/repo.git"); @@ -40,11 +41,11 @@ public class GitHubPushTriggerTest { @Inject private GitHubPushTrigger.DescriptorImpl descriptor; - @Rule - public JenkinsRule jRule = new JenkinsRule(); + private JenkinsRule jRule; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jRule = rule; jRule.getInstance().getInjector().injectMembers(this); } @@ -53,7 +54,7 @@ public void setUp() throws Exception { */ @Test @Issue("JENKINS-27136") - public void shouldStartWorkflowByTrigger() throws Exception { + void shouldStartWorkflowByTrigger() throws Exception { WorkflowJob job = jRule.getInstance().createProject(WorkflowJob.class, "test-workflow-job"); GitHubPushTrigger trigger = new GitHubPushTrigger(); trigger.start(job, false); @@ -79,7 +80,7 @@ public void shouldStartWorkflowByTrigger() throws Exception { @Test @Issue("JENKINS-24690") - public void shouldReturnWaringOnHookProblem() throws Exception { + void shouldReturnWaringOnHookProblem() throws Exception { monitor.registerProblem(REPO, new IOException()); FreeStyleProject job = jRule.createFreeStyleProject(); job.setScm(REPO_GIT_SCM); @@ -89,7 +90,7 @@ public void shouldReturnWaringOnHookProblem() throws Exception { } @Test - public void shouldReturnOkOnNoAnyProblem() throws Exception { + void shouldReturnOkOnNoAnyProblem() throws Exception { FreeStyleProject job = jRule.createFreeStyleProject(); job.setScm(REPO_GIT_SCM); diff --git a/src/test/java/com/cloudbees/jenkins/GitHubSetCommitStatusBuilderTest.java b/src/test/java/com/cloudbees/jenkins/GitHubSetCommitStatusBuilderTest.java index 55976dd43..20f0e75dd 100644 --- a/src/test/java/com/cloudbees/jenkins/GitHubSetCommitStatusBuilderTest.java +++ b/src/test/java/com/cloudbees/jenkins/GitHubSetCommitStatusBuilderTest.java @@ -1,7 +1,7 @@ package com.cloudbees.jenkins; import com.github.tomakehurst.wiremock.common.Slf4jNotifier; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.Build; @@ -11,26 +11,25 @@ import hudson.plugins.git.Revision; import hudson.plugins.git.util.BuildData; import hudson.tasks.Builder; +import jakarta.inject.Inject; import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.lib.ObjectId; import org.jenkinsci.plugins.github.config.GitHubPluginConfig; -import org.jenkinsci.plugins.github.test.GHMockRule; -import org.jenkinsci.plugins.github.test.GHMockRule.FixedGHRepoNameTestContributor; -import org.jenkinsci.plugins.github.test.InjectJenkinsMembersRule; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.RuleChain; -import org.junit.runner.RunWith; +import org.jenkinsci.plugins.github.test.GitHubMockExtension; +import org.jenkinsci.plugins.github.test.GitHubMockExtension.FixedGHRepoNameTestContributor; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -import jakarta.inject.Inject; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; @@ -44,44 +43,43 @@ * * @author Oleg Nenashev */ -@RunWith(MockitoJUnitRunner.class) +@WithJenkins +@ExtendWith(MockitoExtension.class) public class GitHubSetCommitStatusBuilderTest { public static final String SOME_SHA = StringUtils.repeat("f", 40); - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) public BuildData data; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) public Revision rev; @Inject public GitHubPluginConfig config; - public JenkinsRule jRule = new JenkinsRule(); + private JenkinsRule jRule; - @Rule - public RuleChain chain = RuleChain.outerRule(jRule).around(new InjectJenkinsMembersRule(jRule, this)); - - @Rule - public GHMockRule github = new GHMockRule( - new WireMockRule( - wireMockConfig().dynamicPort().notifier(new Slf4jNotifier(true)) - )) + @RegisterExtension + static GitHubMockExtension github = new GitHubMockExtension(WireMockExtension.newInstance() + .options(wireMockConfig().dynamicPort().notifier(new Slf4jNotifier(true)))) .stubUser() .stubRepo() .stubStatuses(); - @Before - public void before() throws Throwable { - when(data.getLastBuiltRevision()).thenReturn(rev); - data.lastBuild = new hudson.plugins.git.util.Build(rev, rev, 0, Result.SUCCESS); - when(rev.getSha1()).thenReturn(ObjectId.fromString(SOME_SHA)); + @BeforeEach + void before(JenkinsRule rule) throws Throwable { + jRule = rule; + jRule.getInstance().getInjector().injectMembers(this); + + when(data.getLastBuiltRevision()).thenReturn(rev); + data.lastBuild = new hudson.plugins.git.util.Build(rev, rev, 0, Result.SUCCESS); + when(rev.getSha1()).thenReturn(ObjectId.fromString(SOME_SHA)); } @Test @Issue("JENKINS-23641") - public void shouldIgnoreIfNoBuildData() throws Exception { + void shouldIgnoreIfNoBuildData() throws Exception { FreeStyleProject prj = jRule.createFreeStyleProject("23641_noBuildData"); prj.getBuildersList().add(new GitHubSetCommitStatusBuilder()); Build b = prj.scheduleBuild2(0).get(); @@ -91,7 +89,7 @@ public void shouldIgnoreIfNoBuildData() throws Exception { @Test @LocalData @Issue("JENKINS-32132") - public void shouldLoadNullStatusMessage() throws Exception { + void shouldLoadNullStatusMessage() throws Exception { config.getConfigs().add(github.serverConfig()); FreeStyleProject prj = jRule.getInstance().getItemByFullName("step", FreeStyleProject.class); @@ -107,7 +105,7 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen prj.getBuildersList().replaceBy(builders); prj.scheduleBuild2(0).get(); - github.service().verify(1, postRequestedFor(urlPathMatching(".*/" + SOME_SHA))); + github.verify(1, postRequestedFor(urlPathMatching(".*/" + SOME_SHA))); } @TestExtension diff --git a/src/test/java/com/cloudbees/jenkins/GitHubWebHookCrumbExclusionTest.java b/src/test/java/com/cloudbees/jenkins/GitHubWebHookCrumbExclusionTest.java index 581efa08a..bd23444d6 100644 --- a/src/test/java/com/cloudbees/jenkins/GitHubWebHookCrumbExclusionTest.java +++ b/src/test/java/com/cloudbees/jenkins/GitHubWebHookCrumbExclusionTest.java @@ -1,29 +1,28 @@ package com.cloudbees.jenkins; -import org.junit.Before; -import org.junit.Test; - import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class GitHubWebHookCrumbExclusionTest { +class GitHubWebHookCrumbExclusionTest { private GitHubWebHookCrumbExclusion exclusion; private HttpServletRequest req; private HttpServletResponse resp; private FilterChain chain; - @Before - public void before() { + @BeforeEach + void before() { exclusion = new GitHubWebHookCrumbExclusion(); req = mock(HttpServletRequest.class); resp = mock(HttpServletResponse.class); @@ -31,35 +30,35 @@ public void before() { } @Test - public void testFullPath() throws Exception { + void testFullPath() throws Exception { when(req.getPathInfo()).thenReturn("/github-webhook/"); assertTrue(exclusion.process(req, resp, chain)); verify(chain, times(1)).doFilter(req, resp); } @Test - public void testFullPathWithoutSlash() throws Exception { + void testFullPathWithoutSlash() throws Exception { when(req.getPathInfo()).thenReturn("/github-webhook"); assertTrue(exclusion.process(req, resp, chain)); verify(chain, times(1)).doFilter(req, resp); } @Test - public void testInvalidPath() throws Exception { + void testInvalidPath() throws Exception { when(req.getPathInfo()).thenReturn("/some-other-url/"); assertFalse(exclusion.process(req, resp, chain)); verify(chain, never()).doFilter(req, resp); } @Test - public void testNullPath() throws Exception { + void testNullPath() throws Exception { when(req.getPathInfo()).thenReturn(null); assertFalse(exclusion.process(req, resp, chain)); verify(chain, never()).doFilter(req, resp); } @Test - public void testEmptyPath() throws Exception { + void testEmptyPath() throws Exception { when(req.getPathInfo()).thenReturn(""); assertFalse(exclusion.process(req, resp, chain)); verify(chain, never()).doFilter(req, resp); diff --git a/src/test/java/com/cloudbees/jenkins/GitHubWebHookFullTest.java b/src/test/java/com/cloudbees/jenkins/GitHubWebHookFullTest.java index 2c8383932..6ad740517 100644 --- a/src/test/java/com/cloudbees/jenkins/GitHubWebHookFullTest.java +++ b/src/test/java/com/cloudbees/jenkins/GitHubWebHookFullTest.java @@ -5,28 +5,27 @@ import io.restassured.builder.RequestSpecBuilder; import io.restassured.http.Header; import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; import org.apache.commons.io.IOUtils; import org.jenkinsci.plugins.github.config.GitHubPluginConfig; import org.jenkinsci.plugins.github.webhook.GHEventHeader; import org.jenkinsci.plugins.github.webhook.GHEventPayload; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExternalResource; +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.kohsuke.github.GHEvent; -import jakarta.inject.Inject; import java.io.File; import java.io.IOException; import static io.restassured.RestAssured.given; import static io.restassured.config.EncoderConfig.encoderConfig; import static io.restassured.config.RestAssuredConfig.newConfig; -import static java.lang.String.format; import static jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static jakarta.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED; import static jakarta.servlet.http.HttpServletResponse.SC_OK; +import static java.lang.String.format; import static org.apache.commons.lang3.ClassUtils.PACKAGE_SEPARATOR; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.notNullValue; @@ -37,6 +36,7 @@ /** * @author lanwen (Merkushev Kirill) */ +@WithJenkins public class GitHubWebHookFullTest { // GitHub doesn't send the charset per docs, so re-use the exact content-type from the handler @@ -48,37 +48,28 @@ public class GitHubWebHookFullTest { public static final String NOT_NULL_VALUE = "nonnull"; private RequestSpecification spec; - + @Inject private GitHubPluginConfig config; - @ClassRule - public static JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; - @Rule - public ExternalResource inject = new ExternalResource() { - @Override - protected void before() throws Throwable { - jenkins.getInstance().getInjector().injectMembers(GitHubWebHookFullTest.this); - } - }; - - @Rule - public ExternalResource setup = new ExternalResource() { - @Override - protected void before() throws Throwable { - spec = new RequestSpecBuilder() - .setConfig(newConfig() - .encoderConfig(encoderConfig() - .defaultContentCharset(Charsets.UTF_8.name()) - // GitHub doesn't add charsets, so don't test with them - .appendDefaultContentCharsetToContentTypeIfUndefined(false))) - .build(); - } - }; + @BeforeEach + void before(JenkinsRule rule) throws Throwable { + jenkins = rule; + jenkins.getInstance().getInjector().injectMembers(this); + + spec = new RequestSpecBuilder() + .setConfig(newConfig() + .encoderConfig(encoderConfig() + .defaultContentCharset(Charsets.UTF_8.name()) + // GitHub doesn't add charsets, so don't test with them + .appendDefaultContentCharsetToContentTypeIfUndefined(false))) + .build(); + } @Test - public void shouldParseJsonWebHookFromGH() throws Exception { + void shouldParseJsonWebHookFromGH() throws Exception { removeSecretIn(config); given().spec(spec) .header(eventHeader(GHEvent.PUSH)) @@ -90,10 +81,10 @@ public void shouldParseJsonWebHookFromGH() throws Exception { @Test - public void shouldParseJsonWebHookFromGHWithSignHeader() throws Exception { + void shouldParseJsonWebHookFromGHWithSignHeader() throws Exception { String hash = "355e155fc3d10c4e5f2c6086a01281d2e947d932"; String secret = "123"; - + storeSecretIn(config, secret); given().spec(spec) .header(eventHeader(GHEvent.PUSH)) @@ -105,7 +96,7 @@ public void shouldParseJsonWebHookFromGHWithSignHeader() throws Exception { } @Test - public void shouldParseFormWebHookOrServiceHookFromGH() throws Exception { + void shouldParseFormWebHookOrServiceHookFromGH() throws Exception { given().spec(spec) .header(eventHeader(GHEvent.PUSH)) .header(FORM_CONTENT_TYPE) @@ -115,7 +106,7 @@ public void shouldParseFormWebHookOrServiceHookFromGH() throws Exception { } @Test - public void shouldParsePingFromGH() throws Exception { + void shouldParsePingFromGH() throws Exception { given().spec(spec) .header(eventHeader(GHEvent.PING)) .header(JSON_CONTENT_TYPE) @@ -128,7 +119,7 @@ public void shouldParsePingFromGH() throws Exception { } @Test - public void shouldReturnErrOnEmptyPayloadAndHeader() throws Exception { + void shouldReturnErrOnEmptyPayloadAndHeader() throws Exception { given().spec(spec) .log().all() .expect().log().all() @@ -139,7 +130,7 @@ public void shouldReturnErrOnEmptyPayloadAndHeader() throws Exception { } @Test - public void shouldReturnErrOnEmptyPayload() throws Exception { + void shouldReturnErrOnEmptyPayload() throws Exception { given().spec(spec) .header(eventHeader(GHEvent.PUSH)) .log().all() @@ -151,7 +142,7 @@ public void shouldReturnErrOnEmptyPayload() throws Exception { } @Test - public void shouldReturnErrOnGetReq() throws Exception { + void shouldReturnErrOnGetReq() throws Exception { given().spec(spec) .log().all().expect().log().all() .statusCode(SC_METHOD_NOT_ALLOWED) @@ -160,7 +151,7 @@ public void shouldReturnErrOnGetReq() throws Exception { } @Test - public void shouldProcessSelfTest() throws Exception { + void shouldProcessSelfTest() throws Exception { given().spec(spec) .header(new Header(GitHubWebHook.URL_VALIDATION_HEADER, NOT_NULL_VALUE)) .log().all() @@ -192,7 +183,7 @@ public static String classpath(Class clazz, String path) { throw new RuntimeException(format("Can't load %s for class %s", path, clazz), e); } } - + private String getPath(){ return jenkins.getInstance().getRootUrl() + GitHubWebHook.URLNAME.concat("/"); } diff --git a/src/test/java/com/cloudbees/jenkins/GitHubWebHookTest.java b/src/test/java/com/cloudbees/jenkins/GitHubWebHookTest.java index 668d50783..649040da0 100644 --- a/src/test/java/com/cloudbees/jenkins/GitHubWebHookTest.java +++ b/src/test/java/com/cloudbees/jenkins/GitHubWebHookTest.java @@ -1,36 +1,33 @@ package com.cloudbees.jenkins; import com.google.inject.Inject; - import hudson.model.Item; -import hudson.model.Job; - import org.jenkinsci.plugins.github.extension.GHEventsSubscriber; -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.JenkinsRule; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.github.GHEvent; import java.util.Set; import static com.google.common.collect.Sets.immutableEnumSet; import static java.util.Arrays.asList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.everyItem; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; /** * @author lanwen (Merkushev Kirill) */ -public class GitHubWebHookTest { +@WithJenkins +class GitHubWebHookTest { public static final String PAYLOAD = "{}"; - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; @Inject private IssueSubscriber subscriber; @@ -41,25 +38,26 @@ public class GitHubWebHookTest { @Inject private ThrowablePullRequestSubscriber throwablePullRequestSubscriber; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jenkins = rule; jenkins.getInstance().getInjector().injectMembers(this); } @Test - public void shouldCallExtensionInterestedInIssues() throws Exception { + void shouldCallExtensionInterestedInIssues() throws Exception { new GitHubWebHook().doIndex(GHEvent.ISSUES, PAYLOAD); assertThat("should get interested event", subscriber.lastEvent(), equalTo(GHEvent.ISSUES)); } @Test - public void shouldNotCallAnyExtensionsWithPublicEventIfNotRegistered() throws Exception { + void shouldNotCallAnyExtensionsWithPublicEventIfNotRegistered() throws Exception { new GitHubWebHook().doIndex(GHEvent.PUBLIC, PAYLOAD); assertThat("should not get not interested event", subscriber.lastEvent(), nullValue()); } @Test - public void shouldCatchThrowableOnFailedSubscriber() throws Exception { + void shouldCatchThrowableOnFailedSubscriber() throws Exception { new GitHubWebHook().doIndex(GHEvent.PULL_REQUEST, PAYLOAD); assertThat("each extension should get event", asList( diff --git a/src/test/java/com/cloudbees/jenkins/GlobalConfigSubmitTest.java b/src/test/java/com/cloudbees/jenkins/GlobalConfigSubmitTest.java index 01e8dacb4..5b0f24c96 100644 --- a/src/test/java/com/cloudbees/jenkins/GlobalConfigSubmitTest.java +++ b/src/test/java/com/cloudbees/jenkins/GlobalConfigSubmitTest.java @@ -3,10 +3,11 @@ import org.htmlunit.html.HtmlForm; import org.htmlunit.html.HtmlPage; import org.jenkinsci.plugins.github.GitHubPlugin; -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.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.xml.sax.SAXException; import java.io.IOException; @@ -20,7 +21,8 @@ * * @author Seiji Sogabe */ -@Ignore("Have troubles with memory consumption") +@WithJenkins +@Disabled("Have troubles with memory consumption") public class GlobalConfigSubmitTest { public static final String OVERRIDE_HOOK_URL_CHECKBOX = "_.isOverrideHookUrl"; @@ -28,11 +30,15 @@ public class GlobalConfigSubmitTest { private static final String WEBHOOK_URL = "http://jenkinsci.example.com/jenkins/github-webhook/"; - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; + + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jenkins = rule; + } @Test - public void shouldSetHookUrl() throws Exception { + void shouldSetHookUrl() throws Exception { HtmlForm form = globalConfig(); form.getInputByName(OVERRIDE_HOOK_URL_CHECKBOX).setChecked(true); @@ -43,7 +49,7 @@ public void shouldSetHookUrl() throws Exception { } @Test - public void shouldNotSetHookUrl() throws Exception { + void shouldNotSetHookUrl() throws Exception { GitHubPlugin.configuration().setHookUrl(WEBHOOK_URL); HtmlForm form = globalConfig(); @@ -56,7 +62,7 @@ public void shouldNotSetHookUrl() throws Exception { } @Test - public void shouldNotOverrideAPreviousHookUrlIfNotChecked() throws Exception { + void shouldNotOverrideAPreviousHookUrlIfNotChecked() throws Exception { GitHubPlugin.configuration().setHookUrl(WEBHOOK_URL); HtmlForm form = globalConfig(); diff --git a/src/test/java/com/coravy/hudson/plugins/github/GitHubRepositoryNameTest.java b/src/test/java/com/coravy/hudson/plugins/github/GitHubRepositoryNameTest.java index b22dc7bc5..00fd8fbc7 100644 --- a/src/test/java/com/coravy/hudson/plugins/github/GitHubRepositoryNameTest.java +++ b/src/test/java/com/coravy/hudson/plugins/github/GitHubRepositoryNameTest.java @@ -1,13 +1,15 @@ package com.coravy.hudson.plugins.github; import com.cloudbees.jenkins.GitHubRepositoryName; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; import org.apache.commons.lang3.StringUtils; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import static com.cloudbees.jenkins.GitHubRepositoryName.create; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; @@ -15,68 +17,72 @@ import static org.jenkinsci.plugins.github.test.GitHubRepoNameMatchers.withHost; import static org.jenkinsci.plugins.github.test.GitHubRepoNameMatchers.withRepoName; import static org.jenkinsci.plugins.github.test.GitHubRepoNameMatchers.withUserName; -import static org.hamcrest.MatcherAssert.assertThat; /** * Unit tests of {@link GitHubRepositoryName} */ -@RunWith(DataProviderRunner.class) public class GitHubRepositoryNameTest { public static final String FULL_REPO_NAME = "jenkins/jenkins"; public static final String VALID_HTTPS_GH_PROJECT = "https://github.com/" + FULL_REPO_NAME; - @Test - @DataProvider({ - "git@github.com:jenkinsci/jenkins.git/, github.com, jenkinsci, jenkins", - "git@github.com:jenkinsci/jenkins.git, github.com, jenkinsci, jenkins", - "git@github.com:jenkinsci/jenkins/, github.com, jenkinsci, jenkins", - "git@github.com:jenkinsci/jenkins, github.com, jenkinsci, jenkins", - "org-12345@github.com:jenkinsci/jenkins.git/, github.com, jenkinsci, jenkins", - "org-12345@github.com:jenkinsci/jenkins.git, github.com, jenkinsci, jenkins", - "org-12345@github.com:jenkinsci/jenkins/, github.com, jenkinsci, jenkins", - "org-12345@github.com:jenkinsci/jenkins, github.com, jenkinsci, jenkins", - "org-12345@gh.company.com:jenkinsci/jenkins.git/, gh.company.com, jenkinsci, jenkins", - "git@gh.company.com:jenkinsci/jenkins.git, gh.company.com, jenkinsci, jenkins", - "git@gh.company.com:jenkinsci/jenkins, gh.company.com, jenkinsci, jenkins", - "git@gh.company.com:jenkinsci/jenkins/, gh.company.com, jenkinsci, jenkins", - "git://github.com/jenkinsci/jenkins.git/, github.com, jenkinsci, jenkins", - "git://github.com/jenkinsci/jenkins.git, github.com, jenkinsci, jenkins", - "git://github.com/jenkinsci/jenkins/, github.com, jenkinsci, jenkins", - "git://github.com/jenkinsci/jenkins, github.com, jenkinsci, jenkins", - "https://user@github.com/jenkinsci/jenkins.git, github.com, jenkinsci, jenkins", - "https://user@github.com/jenkinsci/jenkins.git/, github.com, jenkinsci, jenkins", - "https://user@github.com/jenkinsci/jenkins, github.com, jenkinsci, jenkins", - "https://user@github.com/jenkinsci/jenkins/, github.com, jenkinsci, jenkins", - "https://employee@gh.company.com/jenkinsci/jenkins.git/, gh.company.com, jenkinsci, jenkins", - "https://employee@gh.company.com/jenkinsci/jenkins.git, gh.company.com, jenkinsci, jenkins", - "https://employee@gh.company.com/jenkinsci/jenkins, gh.company.com, jenkinsci, jenkins", - "https://employee@gh.company.com/jenkinsci/jenkins/, gh.company.com, jenkinsci, jenkins", - "git://company.net/jenkinsci/jenkins.git/, company.net, jenkinsci, jenkins", - "git://company.net/jenkinsci/jenkins.git, company.net, jenkinsci, jenkins", - "git://company.net/jenkinsci/jenkins, company.net, jenkinsci, jenkins", - "git://company.net/jenkinsci/jenkins/, company.net, jenkinsci, jenkins", - "https://github.com/jenkinsci/jenkins.git/, github.com, jenkinsci, jenkins", - "https://github.com/jenkinsci/jenkins.git, github.com, jenkinsci, jenkins", - "https://github.com/jenkinsci/jenkins, github.com, jenkinsci, jenkins", - "https://github.com/jenkinsci/jenkins/, github.com, jenkinsci, jenkins", - "ssh://git@github.com/jenkinsci/jenkins.git/, github.com, jenkinsci, jenkins", - "ssh://git@github.com/jenkinsci/jenkins.git, github.com, jenkinsci, jenkins", - "ssh://git@github.com/jenkinsci/jenkins, github.com, jenkinsci, jenkins", - "ssh://git@github.com/jenkinsci/jenkins/, github.com, jenkinsci, jenkins", - "ssh://org-12345@github.com/jenkinsci/jenkins.git/, github.com, jenkinsci, jenkins", - "ssh://org-12345@github.com/jenkinsci/jenkins.git, github.com, jenkinsci, jenkins", - "ssh://org-12345@github.com/jenkinsci/jenkins, github.com, jenkinsci, jenkins", - "ssh://org-12345@github.com/jenkinsci/jenkins/, github.com, jenkinsci, jenkins", - "ssh://github.com/jenkinsci/jenkins.git/, github.com, jenkinsci, jenkins", - "ssh://github.com/jenkinsci/jenkins.git, github.com, jenkinsci, jenkins", - "ssh://github.com/jenkinsci/jenkins, github.com, jenkinsci, jenkins", - "ssh://github.com/jenkinsci/jenkins/, github.com, jenkinsci, jenkins", - "git+ssh://git@github.com/jenkinsci/jenkins.git, github.com, jenkinsci, jenkins", - "git+ssh://org-12345@github.com/jenkinsci/jenkins.git, github.com, jenkinsci, jenkins", - "git+ssh://github.com/jenkinsci/jenkins, github.com, jenkinsci, jenkins", - }) - public void githubFullRepo(String url, String host, String user, String repo) { + public static Object[][] repos() { + return new Object[][]{ + new Object[]{"git@github.com:jenkinsci/jenkins.git/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"git@github.com:jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"git@github.com:jenkinsci/jenkins/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"git@github.com:jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"org-12345@github.com:jenkinsci/jenkins.git/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"org-12345@github.com:jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"org-12345@github.com:jenkinsci/jenkins/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"org-12345@github.com:jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"org-12345@gh.company.com:jenkinsci/jenkins.git/", "gh.company.com", "jenkinsci", "jenkins"}, + new Object[]{"git@gh.company.com:jenkinsci/jenkins.git", "gh.company.com", "jenkinsci", "jenkins"}, + new Object[]{"git@gh.company.com:jenkinsci/jenkins", "gh.company.com", "jenkinsci", "jenkins"}, + new Object[]{"git@gh.company.com:jenkinsci/jenkins/", "gh.company.com", "jenkinsci", "jenkins"}, + new Object[]{"git://github.com/jenkinsci/jenkins.git/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"git://github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"git://github.com/jenkinsci/jenkins/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"git://github.com/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"https://user@github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"https://user@github.com/jenkinsci/jenkins.git/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"https://user@github.com/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"https://user@github.com/jenkinsci/jenkins/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"https://employee@gh.company.com/jenkinsci/jenkins.git/", "gh.company.com", "jenkinsci", "jenkins"}, + new Object[]{"https://employee@gh.company.com/jenkinsci/jenkins.git", "gh.company.com", "jenkinsci", "jenkins"}, + new Object[]{"https://employee@gh.company.com/jenkinsci/jenkins", "gh.company.com", "jenkinsci", "jenkins"}, + new Object[]{"https://employee@gh.company.com/jenkinsci/jenkins/", "gh.company.com", "jenkinsci", "jenkins"}, + new Object[]{"git://company.net/jenkinsci/jenkins.git/", "company.net", "jenkinsci", "jenkins"}, + new Object[]{"git://company.net/jenkinsci/jenkins.git", "company.net", "jenkinsci", "jenkins"}, + new Object[]{"git://company.net/jenkinsci/jenkins", "company.net", "jenkinsci", "jenkins"}, + new Object[]{"git://company.net/jenkinsci/jenkins/", "company.net", "jenkinsci", "jenkins"}, + new Object[]{"https://github.com/jenkinsci/jenkins.git/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"https://github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"https://github.com/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"https://github.com/jenkinsci/jenkins/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"ssh://git@github.com/jenkinsci/jenkins.git/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"ssh://git@github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"ssh://git@github.com/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins", + new Object[]{"ssh://git@github.com/jenkinsci/jenkins/", "github.com", "jenkinsci", "jenkins", + new Object[]{"ssh://org-12345@github.com/jenkinsci/jenkins.git/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"ssh://org-12345@github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"ssh://org-12345@github.com/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"ssh://org-12345@github.com/jenkinsci/jenkins/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"ssh://github.com/jenkinscRi/jenkins.git/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"ssh://github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"ssh://github.com/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"ssh://github.com/jenkinsci/jenkins/", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"git+ssh://git@github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"git+ssh://org-12345@github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins"}, + new Object[]{"git+ssh://github.com/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins"} + } + } + }; + } + + @ParameterizedTest + @MethodSource("repos") + void githubFullRepo(String url, String host, String user, String repo) { assertThat(url, repo(allOf( withHost(host), withUserName(user), @@ -85,7 +91,7 @@ public void githubFullRepo(String url, String host, String user, String repo) { } @Test - public void trimWhitespace() { + void trimWhitespace() { assertThat(" https://user@github.com/jenkinsci/jenkins/ ", repo(allOf( withHost("github.com"), withUserName("jenkinsci"), @@ -93,35 +99,33 @@ public void trimWhitespace() { ))); } - @Test - @DataProvider(value = { - "gopher://gopher.floodgap.com", + @ParameterizedTest + @ValueSource(strings = {"gopher://gopher.floodgap.com", "https//github.com/jenkinsci/jenkins", - "", - "null" - }, trimValues = false) - public void badUrl(String url) { + ""}) + @NullSource + void badUrl(String url) { assertThat(url, repo(nullValue(GitHubRepositoryName.class))); } @Test - public void shouldCreateFromProjectProp() { + void shouldCreateFromProjectProp() { assertThat("project prop vs direct", create(new GithubProjectProperty(VALID_HTTPS_GH_PROJECT)), equalTo(create(VALID_HTTPS_GH_PROJECT))); } @Test - public void shouldIgnoreNull() { + void shouldIgnoreNull() { assertThat("null project prop", create((GithubProjectProperty) null), nullValue()); } @Test - public void shouldIgnoreNullValueOfPP() { + void shouldIgnoreNullValueOfPP() { assertThat("null project prop", create(new GithubProjectProperty(null)), nullValue()); } @Test - public void shouldIgnoreBadValueOfPP() { + void shouldIgnoreBadValueOfPP() { assertThat("null project prop", create(new GithubProjectProperty(StringUtils.EMPTY)), nullValue()); } } diff --git a/src/test/java/com/coravy/hudson/plugins/github/GithubLinkActionFactoryTest.java b/src/test/java/com/coravy/hudson/plugins/github/GithubLinkActionFactoryTest.java index 60cd872f8..b616ad756 100644 --- a/src/test/java/com/coravy/hudson/plugins/github/GithubLinkActionFactoryTest.java +++ b/src/test/java/com/coravy/hudson/plugins/github/GithubLinkActionFactoryTest.java @@ -1,30 +1,34 @@ package com.coravy.hudson.plugins.github; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.MatcherAssert.assertThat; - -import java.io.IOException; -import java.util.Collection; - +import com.coravy.hudson.plugins.github.GithubLinkAction.GithubLinkActionFactory; +import hudson.model.Action; import org.jenkinsci.plugins.workflow.job.WorkflowJob; -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 com.coravy.hudson.plugins.github.GithubLinkAction.GithubLinkActionFactory; +import java.io.IOException; +import java.util.Collection; -import hudson.model.Action; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; -public class GithubLinkActionFactoryTest { - @Rule - public final JenkinsRule rule = new JenkinsRule(); +@WithJenkins +class GithubLinkActionFactoryTest { + private JenkinsRule rule; private final GithubLinkActionFactory factory = new GithubLinkActionFactory(); private static final String PROJECT_URL = "https://github.com/jenkinsci/github-plugin/"; + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + this.rule = rule; + } + private WorkflowJob createExampleJob() throws IOException { return rule.getInstance().createProject(WorkflowJob.class, "example"); } @@ -34,7 +38,7 @@ private GithubProjectProperty createExampleProperty() { } @Test - public void shouldCreateGithubLinkActionForJobWithGithubProjectProperty() throws IOException { + void shouldCreateGithubLinkActionForJobWithGithubProjectProperty() throws IOException { final WorkflowJob job = createExampleJob(); final GithubProjectProperty property = createExampleProperty(); job.addProperty(property); @@ -48,7 +52,7 @@ public void shouldCreateGithubLinkActionForJobWithGithubProjectProperty() throws } @Test - public void shouldNotCreateGithubLinkActionForJobWithoutGithubProjectProperty() throws IOException { + void shouldNotCreateGithubLinkActionForJobWithoutGithubProjectProperty() throws IOException { final WorkflowJob job = createExampleJob(); final Collection actions = factory.createFor(job); diff --git a/src/test/java/com/coravy/hudson/plugins/github/GithubLinkAnnotatorTest.java b/src/test/java/com/coravy/hudson/plugins/github/GithubLinkAnnotatorTest.java index 1f89c547e..3cf8f517e 100644 --- a/src/test/java/com/coravy/hudson/plugins/github/GithubLinkAnnotatorTest.java +++ b/src/test/java/com/coravy/hudson/plugins/github/GithubLinkAnnotatorTest.java @@ -1,35 +1,34 @@ package com.coravy.hudson.plugins.github; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; import hudson.MarkupText; import hudson.plugins.git.GitChangeSet; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.jvnet.hudson.test.Issue; + import java.util.ArrayList; import java.util.Random; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.jvnet.hudson.test.Issue; import static java.lang.String.format; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertThrows; -@RunWith(DataProviderRunner.class) -public class GithubLinkAnnotatorTest { +class GithubLinkAnnotatorTest { - private final static String GITHUB_URL = "http://github.com/juretta/iphone-project-tools"; - private final static String SHA1 = "badbeef136cd854f4dd6fa40bf94c0c657681dd5"; - private final static Random RANDOM = new Random(); + private static final String GITHUB_URL = "http://github.com/juretta/iphone-project-tools"; + private static final String SHA1 = "badbeef136cd854f4dd6fa40bf94c0c657681dd5"; + private static final Random RANDOM = new Random(); private final String expectedChangeSetAnnotation = " (" + "" + "commit: " + SHA1.substring(0, 7) + ")"; private static GitChangeSet changeSet; - @Before - public void createChangeSet() throws Exception { + @BeforeEach + void createChangeSet() throws Exception { ArrayList lines = new ArrayList(); lines.add("commit " + SHA1); lines.add("tree 66236cf9a1ac0c589172b450ed01f019a5697c49"); @@ -56,8 +55,7 @@ private static Object[] genActualAndExpected(String keyword) { }; } - @DataProvider - public static Object[][] annotations() { + static Object[][] annotations() { return new Object[][]{ genActualAndExpected("Closes"), genActualAndExpected("Close"), @@ -66,36 +64,38 @@ public static Object[][] annotations() { }; } - @Test - @UseDataProvider("annotations") - public void inputIsExpected(String input, String expected) throws Exception { + @ParameterizedTest + @MethodSource("annotations") + void inputIsExpected(String input, String expected) throws Exception { assertThat(format("For input '%s'", input), annotate(input, null), is(expected)); } - @Test - @UseDataProvider("annotations") - public void inputIsExpectedWithChangeSet(String input, String expected) throws Exception { + @ParameterizedTest + @MethodSource("annotations") + void inputIsExpectedWithChangeSet(String input, String expected) throws Exception { assertThat(format("For changeset input '%s'", input), annotate(input, changeSet), is(expected + expectedChangeSetAnnotation)); } //Test to verify that fake url starting with sentences like javascript are not validated - @Test(expected = IllegalArgumentException.class) + @Test @Issue("SECURITY-3246") - public void urlValidationTest() { + void urlValidationTest() { GithubLinkAnnotator annotator = new GithubLinkAnnotator(); - annotator.annotate(new GithubUrl("javascript:alert(1); //"), null, null); + assertThrows(IllegalArgumentException.class, () -> + annotator.annotate(new GithubUrl("javascript:alert(1); //"), null, null)); } //Test to verify that fake url are not validated - @Test(expected = IllegalArgumentException.class) + @Test @Issue("SECURITY-3246") - public void urlHtmlAttributeValidationTest() { + void urlHtmlAttributeValidationTest() { GithubLinkAnnotator annotator = new GithubLinkAnnotator(); - annotator.annotate(new GithubUrl("a' onclick=alert(777) foo='bar/\n"), null, null); + assertThrows(IllegalArgumentException.class, () -> + annotator.annotate(new GithubUrl("a' onclick=alert(777) foo='bar/\n"), null, null)); } private String annotate(final String originalText, GitChangeSet changeSet) { diff --git a/src/test/java/com/coravy/hudson/plugins/github/GithubProjectPropertyTest.java b/src/test/java/com/coravy/hudson/plugins/github/GithubProjectPropertyTest.java index f99b3ae27..99389402f 100644 --- a/src/test/java/com/coravy/hudson/plugins/github/GithubProjectPropertyTest.java +++ b/src/test/java/com/coravy/hudson/plugins/github/GithubProjectPropertyTest.java @@ -2,22 +2,29 @@ import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.structs.DescribableHelper; -import org.junit.Ignore; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -@Ignore("It failed to instantiate class org.jenkinsci.plugins.workflow.flow.FlowDefinition - dunno how to fix it") -public class GithubProjectPropertyTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; - @Rule - public JenkinsRule j = new JenkinsRule(); +@WithJenkins +@Disabled("It failed to instantiate class org.jenkinsci.plugins.workflow.flow.FlowDefinition - dunno how to fix it") +class GithubProjectPropertyTest { + + private JenkinsRule j; + + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + j = rule; + } @Test - public void configRoundTrip() throws Exception { + void configRoundTrip() throws Exception { WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); j.configRoundtrip(p); assertNull(p.getProperty(GithubProjectProperty.class)); diff --git a/src/test/java/com/coravy/hudson/plugins/github/GithubUrlTest.java b/src/test/java/com/coravy/hudson/plugins/github/GithubUrlTest.java index 9ec0b032b..fae3d9427 100644 --- a/src/test/java/com/coravy/hudson/plugins/github/GithubUrlTest.java +++ b/src/test/java/com/coravy/hudson/plugins/github/GithubUrlTest.java @@ -1,23 +1,13 @@ package com.coravy.hudson.plugins.github; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class GithubUrlTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } +class GithubUrlTest { @Test - public final void testBaseUrlWithTree() { + void testBaseUrlWithTree() { GithubUrl url = new GithubUrl( "http://github.com/juretta/iphone-project-tools/tree/master"); assertEquals("http://github.com/juretta/iphone-project-tools/", url @@ -29,7 +19,7 @@ public final void testBaseUrlWithTree() { } @Test - public final void testBaseUrl() { + void testBaseUrl() { GithubUrl url = new GithubUrl( "http://github.com/juretta/iphone-project-tools"); assertEquals("http://github.com/juretta/iphone-project-tools/", url @@ -37,7 +27,7 @@ public final void testBaseUrl() { } @Test - public final void testCommitId() { + void testCommitId() { GithubUrl url = new GithubUrl( "http://github.com/juretta/hudson-github-plugin/tree/master"); assertEquals( diff --git a/src/test/java/org/jenkinsci/plugins/github/admin/GHRepoNameTest.java b/src/test/java/org/jenkinsci/plugins/github/admin/GHRepoNameTest.java index 80edfbedd..9e1540d0c 100644 --- a/src/test/java/org/jenkinsci/plugins/github/admin/GHRepoNameTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/admin/GHRepoNameTest.java @@ -1,22 +1,22 @@ package org.jenkinsci.plugins.github.admin; import com.cloudbees.jenkins.GitHubRepositoryName; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.stapler.StaplerRequest2; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.when; /** * @author lanwen (Merkushev Kirill) */ -@RunWith(MockitoJUnitRunner.class) -public class GHRepoNameTest { +@ExtendWith(MockitoExtension.class) +class GHRepoNameTest { public static final String REPO_NAME_PARAMETER = "repo"; private static final String REPO = "https://github.com/user/repo"; @@ -28,7 +28,7 @@ public class GHRepoNameTest { private GHRepoName anno; @Test - public void shouldExtractRepoNameFromForm() throws Exception { + void shouldExtractRepoNameFromForm() throws Exception { when(req.getParameter(REPO_NAME_PARAMETER)).thenReturn(REPO); GitHubRepositoryName repo = new GHRepoName.PayloadHandler().parse(req, anno, null, REPO_NAME_PARAMETER); @@ -36,7 +36,7 @@ public void shouldExtractRepoNameFromForm() throws Exception { } @Test - public void shouldReturnNullOnNoAnyParam() throws Exception { + void shouldReturnNullOnNoAnyParam() throws Exception { GitHubRepositoryName repo = new GHRepoName.PayloadHandler().parse(req, anno, null, REPO_NAME_PARAMETER); assertThat("should not parse repo", repo, nullValue()); diff --git a/src/test/java/org/jenkinsci/plugins/github/admin/GitHubHookRegisterProblemMonitorTest.java b/src/test/java/org/jenkinsci/plugins/github/admin/GitHubHookRegisterProblemMonitorTest.java index c63a35653..6738ed09b 100644 --- a/src/test/java/org/jenkinsci/plugins/github/admin/GitHubHookRegisterProblemMonitorTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/admin/GitHubHookRegisterProblemMonitorTest.java @@ -5,33 +5,34 @@ import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.plugins.git.GitSCM; -import org.jenkinsci.plugins.github.extension.GHSubscriberEvent; +import jakarta.inject.Inject; import org.jenkinsci.plugins.github.GitHubPlugin; import org.jenkinsci.plugins.github.config.GitHubServerConfig; import org.jenkinsci.plugins.github.extension.GHEventsSubscriber; +import org.jenkinsci.plugins.github.extension.GHSubscriberEvent; import org.jenkinsci.plugins.github.webhook.WebhookManager; import org.jenkinsci.plugins.github.webhook.WebhookManagerTest; import org.jenkinsci.plugins.github.webhook.subscriber.PingGHEventSubscriber; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; import org.kohsuke.github.GHEvent; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -import jakarta.inject.Inject; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import static com.cloudbees.jenkins.GitHubRepositoryName.create; import static com.cloudbees.jenkins.GitHubWebHookFullTest.classpath; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; @@ -39,15 +40,15 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.when; /** * @author lanwen (Merkushev Kirill) */ @Issue("JENKINS-24690") -@RunWith(MockitoJUnitRunner.class) -public class GitHubHookRegisterProblemMonitorTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +class GitHubHookRegisterProblemMonitorTest { private static final GitHubRepositoryName REPO = new GitHubRepositoryName("host", "user", "repo"); private static final String REPO_GIT_URI = "host/user/repo.git"; private static final GitSCM REPO_GIT_SCM = new GitSCM("git://"+REPO_GIT_URI); @@ -63,12 +64,11 @@ public class GitHubHookRegisterProblemMonitorTest { @Inject private PingGHEventSubscriber pingSubscr; - @Rule - public JenkinsRule jRule = new JenkinsRule(); + private JenkinsRule jRule; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) private GitHub github; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) private GHRepository ghRepository; class GitHubServerConfigForTest extends GitHubServerConfig { @@ -78,8 +78,9 @@ public GitHubServerConfigForTest(String credentialsId) { } } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jRule = rule; jRule.getInstance().getInjector().injectMembers(this); GitHubServerConfig config = new GitHubServerConfigForTest(""); config.setApiUrl("http://" + REPO_GIT_URI); @@ -89,13 +90,13 @@ public void setUp() throws Exception { } @Test - public void shouldRegisterProblem() throws Exception { + void shouldRegisterProblem() throws Exception { monitor.registerProblem(REPO, new IOException()); assertThat("should register problem", monitor.isProblemWith(REPO), is(true)); } @Test - public void shouldResolveProblem() throws Exception { + void shouldResolveProblem() throws Exception { monitor.registerProblem(REPO, new IOException()); monitor.resolveProblem(REPO); @@ -103,19 +104,19 @@ public void shouldResolveProblem() throws Exception { } @Test - public void shouldNotAddNullRepo() throws Exception { + void shouldNotAddNullRepo() throws Exception { monitor.registerProblem(null, new IOException()); assertThat("should be no problems", monitor.getProblems().keySet(), empty()); } @Test - public void shouldNotAddNullExc() throws Exception { + void shouldNotAddNullExc() throws Exception { monitor.registerProblem(REPO, null); assertThat("should be no problems", monitor.getProblems().keySet(), empty()); } @Test - public void shouldDoNothingOnNullResolve() throws Exception { + void shouldDoNothingOnNullResolve() throws Exception { monitor.registerProblem(REPO, new IOException()); monitor.resolveProblem(null); @@ -123,18 +124,18 @@ public void shouldDoNothingOnNullResolve() throws Exception { } @Test - public void shouldBeDeactivatedByDefault() throws Exception { + void shouldBeDeactivatedByDefault() throws Exception { assertThat("should be deactivated", monitor.isActivated(), is(false)); } @Test - public void shouldBeActivatedOnProblems() throws Exception { + void shouldBeActivatedOnProblems() throws Exception { monitor.registerProblem(REPO, new IOException()); assertThat("active on problems", monitor.isActivated(), is(true)); } @Test - public void shouldResolveOnIgnoring() throws Exception { + void shouldResolveOnIgnoring() throws Exception { monitor.registerProblem(REPO, new IOException()); monitor.doIgnore(REPO); @@ -142,7 +143,7 @@ public void shouldResolveOnIgnoring() throws Exception { } @Test - public void shouldNotRegisterNewOnIgnoring() throws Exception { + void shouldNotRegisterNewOnIgnoring() throws Exception { monitor.doIgnore(REPO); monitor.registerProblem(REPO, new IOException()); @@ -150,7 +151,7 @@ public void shouldNotRegisterNewOnIgnoring() throws Exception { } @Test - public void shouldRemoveFromIgnoredOnDisignore() throws Exception { + void shouldRemoveFromIgnoredOnDisignore() throws Exception { monitor.doIgnore(REPO); monitor.doDisignore(REPO); @@ -158,7 +159,7 @@ public void shouldRemoveFromIgnoredOnDisignore() throws Exception { } @Test - public void shouldNotAddRepoTwiceToIgnore() throws Exception { + void shouldNotAddRepoTwiceToIgnore() throws Exception { monitor.doIgnore(REPO); monitor.doIgnore(REPO); @@ -167,12 +168,12 @@ public void shouldNotAddRepoTwiceToIgnore() throws Exception { @Test @LocalData - public void shouldLoadIgnoredList() throws Exception { + void shouldLoadIgnoredList() throws Exception { assertThat("loaded", monitor.getIgnored(), hasItem(equalTo(REPO))); } @Test - public void shouldReportAboutHookProblemOnRegister() throws IOException { + void shouldReportAboutHookProblemOnRegister() throws IOException { FreeStyleProject job = jRule.createFreeStyleProject(); job.addTrigger(new GitHubPushTrigger()); job.setScm(REPO_GIT_SCM); @@ -186,7 +187,7 @@ public void shouldReportAboutHookProblemOnRegister() throws IOException { } @Test - public void shouldNotReportAboutHookProblemOnRegister() throws IOException { + void shouldNotReportAboutHookProblemOnRegister() throws IOException { FreeStyleProject job = jRule.createFreeStyleProject(); job.addTrigger(new GitHubPushTrigger()); job.setScm(REPO_GIT_SCM); @@ -198,7 +199,7 @@ public void shouldNotReportAboutHookProblemOnRegister() throws IOException { } @Test - public void shouldReportAboutHookProblemOnUnregister() throws IOException { + void shouldReportAboutHookProblemOnUnregister() throws IOException { when(github.getRepository("user/repo")) .thenThrow(new RuntimeException("shouldReportAboutHookProblemOnUnregister")); WebhookManager.forHookUrl(WebhookManagerTest.HOOK_ENDPOINT) @@ -208,7 +209,7 @@ public void shouldReportAboutHookProblemOnUnregister() throws IOException { } @Test - public void shouldNotReportAboutHookAuthProblemOnUnregister() { + void shouldNotReportAboutHookAuthProblemOnUnregister() { WebhookManager.forHookUrl(WebhookManagerTest.HOOK_ENDPOINT) .unregisterFor(REPO, Collections.emptyList()); @@ -216,7 +217,7 @@ public void shouldNotReportAboutHookAuthProblemOnUnregister() { } @Test - public void shouldResolveOnPingHook() { + void shouldResolveOnPingHook() { monitor.registerProblem(REPO_FROM_PING_PAYLOAD, new IOException()); GHEventsSubscriber.processEvent(new GHSubscriberEvent("shouldResolveOnPingHook", GHEvent.PING, classpath("payloads/ping.json"))).apply(pingSubscr); @@ -225,26 +226,26 @@ public void shouldResolveOnPingHook() { } @Test - public void shouldShowManagementLinkIfNonEmptyProblems() throws Exception { + void shouldShowManagementLinkIfNonEmptyProblems() throws Exception { monitor.registerProblem(REPO, new IOException()); assertThat("link on problems", link.getIconFileName(), notNullValue()); } @Test - public void shouldShowManagementLinkIfNonEmptyIgnores() throws Exception { + void shouldShowManagementLinkIfNonEmptyIgnores() throws Exception { monitor.doIgnore(REPO); assertThat("link on ignores", link.getIconFileName(), notNullValue()); } @Test - public void shouldShowManagementLinkIfBoth() throws Exception { + void shouldShowManagementLinkIfBoth() throws Exception { monitor.registerProblem(REPO_FROM_PING_PAYLOAD, new IOException()); monitor.doIgnore(REPO); assertThat("link on ignores", link.getIconFileName(), notNullValue()); } @Test - public void shouldNotShowManagementLinkIfNoAny() throws Exception { + void shouldNotShowManagementLinkIfNoAny() throws Exception { assertThat("link on no any", link.getIconFileName(), nullValue()); } } diff --git a/src/test/java/org/jenkinsci/plugins/github/admin/ValidateRepoNameTest.java b/src/test/java/org/jenkinsci/plugins/github/admin/ValidateRepoNameTest.java index 6635d65bf..4f79e5229 100644 --- a/src/test/java/org/jenkinsci/plugins/github/admin/ValidateRepoNameTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/admin/ValidateRepoNameTest.java @@ -1,23 +1,23 @@ package org.jenkinsci.plugins.github.admin; import com.cloudbees.jenkins.GitHubRepositoryName; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.stapler.Function; import org.kohsuke.stapler.StaplerRequest2; import org.kohsuke.stapler.StaplerResponse2; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.InvocationTargetException; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * @author lanwen (Merkushev Kirill) */ -@RunWith(MockitoJUnitRunner.class) -public class ValidateRepoNameTest { +@ExtendWith(MockitoExtension.class) +class ValidateRepoNameTest { public static final Object ANY_INSTANCE = null; public static final GitHubRepositoryName VALID_REPO = new GitHubRepositoryName("", "", ""); @@ -30,21 +30,18 @@ public class ValidateRepoNameTest { @Mock private StaplerResponse2 resp; - @Rule - public ExpectedException exc = ExpectedException.none(); - @Test - public void shouldThrowInvocationExcOnNullsInArgs() throws Exception { - ValidateRepoName.Processor processor = new ValidateRepoName.Processor(); - processor.setTarget(target); - - exc.expect(InvocationTargetException.class); + void shouldThrowInvocationExcOnNullsInArgs() { + assertThrows(InvocationTargetException.class, () -> { + ValidateRepoName.Processor processor = new ValidateRepoName.Processor(); + processor.setTarget(target); - processor.invoke(req, resp, ANY_INSTANCE, new Object[]{null}); + processor.invoke(req, resp, ANY_INSTANCE, new Object[]{null}); + }); } @Test - public void shouldNotThrowInvocationExcNameInArgs() throws Exception { + void shouldNotThrowInvocationExcNameInArgs() throws Exception { ValidateRepoName.Processor processor = new ValidateRepoName.Processor(); processor.setTarget(target); diff --git a/src/test/java/org/jenkinsci/plugins/github/common/CombineErrorHandlerTest.java b/src/test/java/org/jenkinsci/plugins/github/common/CombineErrorHandlerTest.java index e64e248cf..737ce8624 100644 --- a/src/test/java/org/jenkinsci/plugins/github/common/CombineErrorHandlerTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/common/CombineErrorHandlerTest.java @@ -5,22 +5,19 @@ import hudson.model.TaskListener; import org.jenkinsci.plugins.github.status.err.ChangingBuildStatusErrorHandler; import org.jenkinsci.plugins.github.status.err.ShallowAnyErrorHandler; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Answers; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; -import edu.umd.cs.findbugs.annotations.NonNull; - import static java.util.Arrays.asList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.jenkinsci.plugins.github.common.CombineErrorHandler.errorHandling; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -28,8 +25,8 @@ /** * @author lanwen (Merkushev Kirill) */ -@RunWith(MockitoJUnitRunner.class) -public class CombineErrorHandlerTest { +@ExtendWith(MockitoExtension.class) +class CombineErrorHandlerTest { @Mock(answer = Answers.RETURNS_MOCKS) private Run run; @@ -37,25 +34,22 @@ public class CombineErrorHandlerTest { @Mock private TaskListener listener; - @Rule - public ExpectedException exc = ExpectedException.none(); - @Test - public void shouldRethrowExceptionIfNoMatch() throws Exception { - exc.expect(CombineErrorHandler.ErrorHandlingException.class); + void shouldRethrowExceptionIfNoMatch() { + assertThrows(CombineErrorHandler.ErrorHandlingException.class, () -> - errorHandling().handle(new RuntimeException(), run, listener); + errorHandling().handle(new RuntimeException(), run, listener)); } @Test - public void shouldRethrowExceptionIfNullHandlersList() throws Exception { - exc.expect(CombineErrorHandler.ErrorHandlingException.class); + void shouldRethrowExceptionIfNullHandlersList() { + assertThrows(CombineErrorHandler.ErrorHandlingException.class, () -> - errorHandling().withHandlers(null).handle(new RuntimeException(), run, listener); + errorHandling().withHandlers(null).handle(new RuntimeException(), run, listener)); } @Test - public void shouldHandleExceptionsWithHandler() throws Exception { + void shouldHandleExceptionsWithHandler() throws Exception { boolean handled = errorHandling() .withHandlers(Collections.singletonList(new ShallowAnyErrorHandler())) .handle(new RuntimeException(), run, listener); @@ -64,23 +58,20 @@ public void shouldHandleExceptionsWithHandler() throws Exception { } @Test - public void shouldRethrowExceptionIfExceptionInside() throws Exception { - exc.expect(CombineErrorHandler.ErrorHandlingException.class); - - errorHandling() - .withHandlers(Collections.singletonList( - new ErrorHandler() { - @Override - public boolean handle(Exception e, @NonNull Run run, @NonNull TaskListener listener) { + void shouldRethrowExceptionIfExceptionInside() { + assertThrows(CombineErrorHandler.ErrorHandlingException.class, () -> + + errorHandling() + .withHandlers(Collections.singletonList( + (e, run, listener) -> { throw new RuntimeException("wow"); } - } - )) - .handle(new RuntimeException(), run, listener); + )) + .handle(new RuntimeException(), run, listener)); } @Test - public void shouldHandleExceptionWithFirstMatchAndSetStatus() throws Exception { + void shouldHandleExceptionWithFirstMatchAndSetStatus() throws Exception { boolean handled = errorHandling() .withHandlers(asList( new ChangingBuildStatusErrorHandler(Result.FAILURE.toString()), diff --git a/src/test/java/org/jenkinsci/plugins/github/common/ExpandableMessageTest.java b/src/test/java/org/jenkinsci/plugins/github/common/ExpandableMessageTest.java index bac327f22..cf96bdc0b 100644 --- a/src/test/java/org/jenkinsci/plugins/github/common/ExpandableMessageTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/common/ExpandableMessageTest.java @@ -9,10 +9,11 @@ import hudson.model.ParametersDefinitionProperty; import hudson.model.StringParameterDefinition; import hudson.model.StringParameterValue; -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.TestBuilder; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.io.IOException; import java.util.concurrent.TimeUnit; @@ -24,7 +25,8 @@ /** * @author lanwen (Merkushev Kirill) */ -public class ExpandableMessageTest { +@WithJenkins +class ExpandableMessageTest { public static final String ENV_VAR_JOB_NAME = "JOB_NAME"; public static final String CUSTOM_BUILD_PARAM = "FOO"; @@ -32,11 +34,15 @@ public class ExpandableMessageTest { public static final String MSG_FORMAT = "%s - %s - %s"; public static final String DEFAULT_TOKEN_TEMPLATE = "${ENV, var=\"%s\"}"; - @Rule - public JenkinsRule jRule = new JenkinsRule(); + private JenkinsRule jRule; + + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jRule = rule; + } @Test - public void shouldExpandEnvAndBuildVars() throws Exception { + void shouldExpandEnvAndBuildVars() throws Exception { MessageExpander expander = new MessageExpander(new ExpandableMessage( format(MSG_FORMAT, asVar(ENV_VAR_JOB_NAME), diff --git a/src/test/java/org/jenkinsci/plugins/github/config/ConfigAsCodeTest.java b/src/test/java/org/jenkinsci/plugins/github/config/ConfigAsCodeTest.java index 2888c7d3f..053605235 100755 --- a/src/test/java/org/jenkinsci/plugins/github/config/ConfigAsCodeTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/config/ConfigAsCodeTest.java @@ -5,10 +5,10 @@ import io.jenkins.plugins.casc.ConfiguratorRegistry; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; 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 org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; @@ -18,17 +18,24 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.jenkinsci.plugins.github.test.GitHubServerConfigMatcher.*; - -public class ConfigAsCodeTest { - - @Rule - public JenkinsConfiguredWithCodeRule r = new JenkinsConfiguredWithCodeRule(); +import static org.jenkinsci.plugins.github.test.GitHubServerConfigMatcher.withApiUrl; +import static org.jenkinsci.plugins.github.test.GitHubServerConfigMatcher.withApiUrlS; +import static org.jenkinsci.plugins.github.test.GitHubServerConfigMatcher.withClientCacheSize; +import static org.jenkinsci.plugins.github.test.GitHubServerConfigMatcher.withClientCacheSizeS; +import static org.jenkinsci.plugins.github.test.GitHubServerConfigMatcher.withCredsId; +import static org.jenkinsci.plugins.github.test.GitHubServerConfigMatcher.withCredsIdS; +import static org.jenkinsci.plugins.github.test.GitHubServerConfigMatcher.withIsManageHooks; +import static org.jenkinsci.plugins.github.test.GitHubServerConfigMatcher.withIsManageHooksS; +import static org.jenkinsci.plugins.github.test.GitHubServerConfigMatcher.withName; +import static org.jenkinsci.plugins.github.test.GitHubServerConfigMatcher.withNameS; + +@WithJenkinsConfiguredWithCode +class ConfigAsCodeTest { @SuppressWarnings("deprecation") @Test @ConfiguredWithCode("configuration-as-code.yml") - public void shouldSupportConfigurationAsCode() throws Exception { + void shouldSupportConfigurationAsCode(JenkinsConfiguredWithCodeRule r) throws Exception { GitHubPluginConfig gitHubPluginConfig = GitHubPluginConfig.all().get(GitHubPluginConfig.class); @@ -66,7 +73,7 @@ public void shouldSupportConfigurationAsCode() throws Exception { @Test @ConfiguredWithCode("configuration-as-code.yml") - public void exportConfiguration() throws Exception { + void exportConfiguration(JenkinsConfiguredWithCodeRule r) throws Exception { GitHubPluginConfig globalConfiguration = GitHubPluginConfig.all().get(GitHubPluginConfig.class); ConfiguratorRegistry registry = ConfiguratorRegistry.get(); diff --git a/src/test/java/org/jenkinsci/plugins/github/config/GitHubPluginConfigTest.java b/src/test/java/org/jenkinsci/plugins/github/config/GitHubPluginConfigTest.java index 2b1ddca3d..08327a5ba 100644 --- a/src/test/java/org/jenkinsci/plugins/github/config/GitHubPluginConfigTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/config/GitHubPluginConfigTest.java @@ -3,18 +3,19 @@ import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.domains.Domain; -import org.htmlunit.HttpMethod; -import org.htmlunit.Page; -import org.htmlunit.WebRequest; import hudson.security.GlobalMatrixAuthorizationStrategy; import hudson.util.Secret; import jenkins.model.Jenkins; +import org.htmlunit.HttpMethod; +import org.htmlunit.Page; +import org.htmlunit.WebRequest; import org.jenkinsci.plugins.github.GitHubPlugin; import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.net.URL; import java.util.Arrays; @@ -26,29 +27,34 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author lanwen (Merkushev Kirill) */ -public class GitHubPluginConfigTest { +@WithJenkins +class GitHubPluginConfigTest { - @Rule - public JenkinsRule j = new JenkinsRule(); + private JenkinsRule j; + + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + j = rule; + } @Test - public void shouldNotManageHooksOnEmptyCreds() throws Exception { + void shouldNotManageHooksOnEmptyCreds() throws Exception { assertThat(GitHubPlugin.configuration().isManageHooks(), is(false)); } @Test - public void shouldManageHooksOnManagedConfig() throws Exception { + void shouldManageHooksOnManagedConfig() throws Exception { GitHubPlugin.configuration().getConfigs().add(new GitHubServerConfig("")); assertThat(GitHubPlugin.configuration().isManageHooks(), is(true)); } @Test - public void shouldNotManageHooksOnNotManagedConfig() throws Exception { + void shouldNotManageHooksOnNotManagedConfig() throws Exception { GitHubServerConfig conf = new GitHubServerConfig(""); conf.setManageHooks(false); GitHubPlugin.configuration().getConfigs().add(conf); @@ -57,23 +63,23 @@ public void shouldNotManageHooksOnNotManagedConfig() throws Exception { @Test @Issue("SECURITY-799") - public void shouldNotAllowSSRFUsingHookUrl() throws Exception { + void shouldNotAllowSSRFUsingHookUrl() throws Exception { final String targetUrl = "www.google.com"; final URL urlForSSRF = new URL(j.getURL() + "descriptorByName/github-plugin-configuration/checkHookUrl?value=" + targetUrl); - + j.jenkins.setCrumbIssuer(null); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); - + GlobalMatrixAuthorizationStrategy strategy = new GlobalMatrixAuthorizationStrategy(); strategy.add(Jenkins.ADMINISTER, "admin"); strategy.add(Jenkins.READ, "user"); j.jenkins.setAuthorizationStrategy(strategy); - + { // as read-only user JenkinsRule.WebClient wc = j.createWebClient(); wc.getOptions().setThrowExceptionOnFailingStatusCode(false); wc.login("user"); - + Page page = wc.getPage(new WebRequest(urlForSSRF, HttpMethod.POST)); assertThat(page.getWebResponse().getStatusCode(), equalTo(403)); } @@ -81,7 +87,7 @@ public void shouldNotAllowSSRFUsingHookUrl() throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); wc.getOptions().setThrowExceptionOnFailingStatusCode(false); wc.login("admin"); - + Page page = wc.getPage(new WebRequest(urlForSSRF, HttpMethod.POST)); assertThat(page.getWebResponse().getStatusCode(), equalTo(200)); } @@ -89,7 +95,7 @@ public void shouldNotAllowSSRFUsingHookUrl() throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); wc.getOptions().setThrowExceptionOnFailingStatusCode(false); wc.login("admin"); - + Page page = wc.getPage(new WebRequest(urlForSSRF, HttpMethod.GET)); assertThat(page.getWebResponse().getStatusCode(), not(equalTo(200))); } @@ -97,7 +103,7 @@ public void shouldNotAllowSSRFUsingHookUrl() throws Exception { @Test @Issue("JENKINS-62097") - public void configRoundtrip() throws Exception { + void configRoundtrip() throws Exception { assertHookSecrets(""); j.configRoundtrip(); assertHookSecrets(""); @@ -109,6 +115,7 @@ public void configRoundtrip() throws Exception { j.configRoundtrip(); assertHookSecrets("#1; #2"); } + private void assertHookSecrets(String expected) { assertEquals(expected, GitHubPlugin.configuration().getHookSecretConfigs().stream().map(HookSecretConfig::getHookSecret).filter(Objects::nonNull).map(Secret::getPlainText).collect(Collectors.joining("; "))); } diff --git a/src/test/java/org/jenkinsci/plugins/github/config/GitHubServerConfigIntegrationTest.java b/src/test/java/org/jenkinsci/plugins/github/config/GitHubServerConfigIntegrationTest.java index 0f04a2aa8..22cd50c0a 100644 --- a/src/test/java/org/jenkinsci/plugins/github/config/GitHubServerConfigIntegrationTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/config/GitHubServerConfigIntegrationTest.java @@ -5,29 +5,29 @@ import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.domains.Domain; -import org.htmlunit.HttpMethod; -import org.htmlunit.Page; -import org.htmlunit.WebRequest; import hudson.security.GlobalMatrixAuthorizationStrategy; import hudson.util.Secret; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import jenkins.model.Jenkins; import net.sf.json.JSONObject; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.ee9.servlet.DefaultServlet; import org.eclipse.jetty.ee9.servlet.ServletContextHandler; import org.eclipse.jetty.ee9.servlet.ServletHolder; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.htmlunit.HttpMethod; +import org.htmlunit.Page; +import org.htmlunit.WebRequest; import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.For; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URL; import java.util.HashMap; @@ -40,68 +40,69 @@ /** * Integration counterpart of GitHubServerConfigTest */ +@WithJenkins @For(GitHubServerConfig.class) -public class GitHubServerConfigIntegrationTest { - - @Rule - public JenkinsRule j = new JenkinsRule(); - +class GitHubServerConfigIntegrationTest { + + private JenkinsRule j; + private Server server; private AttackerServlet attackerServlet; private String attackerUrl; - - @Before - public void setupServer() throws Exception { + + @BeforeEach + void setupServer(JenkinsRule rule) throws Exception { + j = rule; setupAttackerServer(); } - - @After - public void stopServer() { + + @AfterEach + void stopServer() { try { server.stop(); } catch (Exception e) { e.printStackTrace(); } } - + private void setupAttackerServer() throws Exception { this.server = new Server(); ServerConnector serverConnector = new ServerConnector(this.server); server.addConnector(serverConnector); - + ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); context.setContextPath("/*"); - + this.attackerServlet = new AttackerServlet(); ServletHolder servletHolder = new ServletHolder(attackerServlet); context.addServlet(servletHolder, "/*"); - + server.setHandler(context); - + server.start(); - + String host = serverConnector.getHost(); if (host == null) { host = "localhost"; } - + this.attackerUrl = "http://" + host + ":" + serverConnector.getLocalPort(); } - + @Test @Issue("SECURITY-804") - public void shouldNotAllow_CredentialsLeakage_usingVerifyCredentials() throws Exception { + void shouldNotAllow_CredentialsLeakage_usingVerifyCredentials() throws Exception { final String credentialId = "cred_id"; final String secret = "my-secret-access-token"; - + setupCredentials(credentialId, secret); - + final URL url = new URL( j.getURL() + "descriptorByName/org.jenkinsci.plugins.github.config.GitHubServerConfig/verifyCredentials?" + "apiUrl=" + attackerUrl + "&credentialsId=" + credentialId ); - + j.jenkins.setCrumbIssuer(null); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); @@ -111,25 +112,25 @@ public void shouldNotAllow_CredentialsLeakage_usingVerifyCredentials() throws Ex strategy.add(Jenkins.READ, "admin"); strategy.add(Jenkins.READ, "user"); j.jenkins.setAuthorizationStrategy(strategy); - + { // as read-only user JenkinsRule.WebClient wc = j.createWebClient(); wc.getOptions().setThrowExceptionOnFailingStatusCode(false); wc.login("user"); - + Page page = wc.getPage(new WebRequest(url, HttpMethod.POST)); assertThat(page.getWebResponse().getStatusCode(), equalTo(403)); - + assertThat(attackerServlet.secretCreds, isEmptyOrNullString()); } { // only admin (with Manage permission) can verify the credentials JenkinsRule.WebClient wc = j.createWebClient(); wc.getOptions().setThrowExceptionOnFailingStatusCode(false); wc.login("admin"); - + Page page = wc.getPage(new WebRequest(url, HttpMethod.POST)); assertThat(page.getWebResponse().getStatusCode(), equalTo(200)); - + assertThat(attackerServlet.secretCreds, not(isEmptyOrNullString())); attackerServlet.secretCreds = null; } @@ -137,14 +138,14 @@ public void shouldNotAllow_CredentialsLeakage_usingVerifyCredentials() throws Ex JenkinsRule.WebClient wc = j.createWebClient(); wc.getOptions().setThrowExceptionOnFailingStatusCode(false); wc.login("admin"); - + Page page = wc.getPage(new WebRequest(url, HttpMethod.GET)); assertThat(page.getWebResponse().getStatusCode(), not(equalTo(200))); - + assertThat(attackerServlet.secretCreds, isEmptyOrNullString()); } } - + private void setupCredentials(String credentialId, String secret) throws Exception { CredentialsStore store = CredentialsProvider.lookupStores(j.jenkins).iterator().next(); // currently not required to follow the UI restriction in terms of path constraint when hitting directly the URL @@ -152,10 +153,10 @@ private void setupCredentials(String credentialId, String secret) throws Excepti Credentials credentials = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialId, "", Secret.fromString(secret)); store.addCredentials(domain, credentials); } - + private static class AttackerServlet extends DefaultServlet { public String secretCreds; - + @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { switch (request.getRequestURI()) { @@ -164,7 +165,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t break; } } - + private void onUser(HttpServletRequest request, HttpServletResponse response) throws IOException { secretCreds = request.getHeader("Authorization"); response.getWriter().write(JSONObject.fromObject( diff --git a/src/test/java/org/jenkinsci/plugins/github/config/GitHubServerConfigTest.java b/src/test/java/org/jenkinsci/plugins/github/config/GitHubServerConfigTest.java index 78a2c1d1f..db6fb0939 100644 --- a/src/test/java/org/jenkinsci/plugins/github/config/GitHubServerConfigTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/config/GitHubServerConfigTest.java @@ -1,16 +1,16 @@ package org.jenkinsci.plugins.github.config; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.net.URI; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.jenkinsci.plugins.github.config.GitHubServerConfig.GITHUB_URL; import static org.jenkinsci.plugins.github.config.GitHubServerConfig.allowedToManageHooks; import static org.jenkinsci.plugins.github.config.GitHubServerConfig.isUrlCustom; import static org.jenkinsci.plugins.github.config.GitHubServerConfig.withHost; -import static org.hamcrest.MatcherAssert.assertThat; /** * @author lanwen (Merkushev Kirill) @@ -21,56 +21,56 @@ public class GitHubServerConfigTest { public static final String DEFAULT_GH_API_HOST = "api.github.com"; @Test - public void shouldMatchAllowedConfig() throws Exception { + void shouldMatchAllowedConfig() throws Exception { assertThat(allowedToManageHooks().apply(new GitHubServerConfig("")), is(true)); } @Test - public void shouldNotMatchNotAllowedConfig() throws Exception { + void shouldNotMatchNotAllowedConfig() throws Exception { GitHubServerConfig input = new GitHubServerConfig(""); input.setManageHooks(false); assertThat(allowedToManageHooks().apply(input), is(false)); } @Test - public void shouldMatchNonEqualToGHUrl() throws Exception { + void shouldMatchNonEqualToGHUrl() throws Exception { assertThat(isUrlCustom(CUSTOM_GH_SERVER), is(true)); } @Test - public void shouldNotMatchEmptyUrl() throws Exception { + void shouldNotMatchEmptyUrl() throws Exception { assertThat(isUrlCustom(""), is(false)); } @Test - public void shouldNotMatchNullUrl() throws Exception { + void shouldNotMatchNullUrl() throws Exception { assertThat(isUrlCustom(null), is(false)); } @Test - public void shouldNotMatchDefaultUrl() throws Exception { + void shouldNotMatchDefaultUrl() throws Exception { assertThat(isUrlCustom(GITHUB_URL), is(false)); } @Test - public void shouldMatchDefaultConfigWithGHDefaultHost() throws Exception { + void shouldMatchDefaultConfigWithGHDefaultHost() throws Exception { assertThat(withHost(DEFAULT_GH_API_HOST).apply(new GitHubServerConfig("")), is(true)); } @Test - public void shouldNotMatchNonDefaultConfigWithGHDefaultHost() throws Exception { + void shouldNotMatchNonDefaultConfigWithGHDefaultHost() throws Exception { GitHubServerConfig input = new GitHubServerConfig(""); input.setApiUrl(CUSTOM_GH_SERVER); assertThat(withHost(DEFAULT_GH_API_HOST).apply(input), is(false)); } @Test - public void shouldNotMatchDefaultConfigWithNonDefaultHost() throws Exception { + void shouldNotMatchDefaultConfigWithNonDefaultHost() throws Exception { assertThat(withHost(URI.create(CUSTOM_GH_SERVER).getHost()).apply(new GitHubServerConfig("")), is(false)); } @Test - public void shouldGuessNameIfNotProvided() throws Exception { + void shouldGuessNameIfNotProvided() throws Exception { GitHubServerConfig input = new GitHubServerConfig(""); input.setApiUrl(CUSTOM_GH_SERVER); assertThat(input.getName(), is(nullValue())); @@ -78,14 +78,14 @@ public void shouldGuessNameIfNotProvided() throws Exception { } @Test - public void shouldPickCorrectNamesForGitHub() throws Exception { + void shouldPickCorrectNamesForGitHub() throws Exception { GitHubServerConfig input = new GitHubServerConfig(""); assertThat(input.getName(), is(nullValue())); assertThat(input.getDisplayName(), is("GitHub (https://github.com)")); } @Test - public void shouldUseNameIfProvided() throws Exception { + void shouldUseNameIfProvided() throws Exception { GitHubServerConfig input = new GitHubServerConfig(""); input.setApiUrl(CUSTOM_GH_SERVER); input.setName("Test Example"); diff --git a/src/test/java/org/jenkinsci/plugins/github/config/HookSecretConfigTest.java b/src/test/java/org/jenkinsci/plugins/github/config/HookSecretConfigTest.java index 8e73fcc11..98889a813 100644 --- a/src/test/java/org/jenkinsci/plugins/github/config/HookSecretConfigTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/config/HookSecretConfigTest.java @@ -1,51 +1,51 @@ package org.jenkinsci.plugins.github.config; import org.jenkinsci.plugins.github.GitHubPlugin; -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.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.jenkinsci.plugins.github.test.HookSecretHelper.storeSecret; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Test for storing hook secrets. */ +@WithJenkins @SuppressWarnings("deprecation") -public class HookSecretConfigTest { +class HookSecretConfigTest { private static final String SECRET_INIT = "test"; - @Rule - public JenkinsRule jenkinsRule = new JenkinsRule(); + private JenkinsRule jenkinsRule; private HookSecretConfig hookSecretConfig; - @Before - public void setup() { + @BeforeEach + void setup(JenkinsRule rule) { + jenkinsRule = rule; storeSecret(SECRET_INIT); } @Test - public void shouldStoreNewSecrets() { + void shouldStoreNewSecrets() { storeSecret(SECRET_INIT); hookSecretConfig = GitHubPlugin.configuration().getHookSecretConfig(); - assertNotNull("Secret is persistent", hookSecretConfig.getHookSecret()); - assertEquals("Secret correctly stored", SECRET_INIT, hookSecretConfig.getHookSecret().getPlainText()); + assertNotNull(hookSecretConfig.getHookSecret(), "Secret is persistent"); + assertEquals(SECRET_INIT, hookSecretConfig.getHookSecret().getPlainText(), "Secret correctly stored"); } @Test - public void shouldOverwriteExistingSecrets() { + void shouldOverwriteExistingSecrets() { final String newSecret = "test2"; storeSecret(newSecret); hookSecretConfig = GitHubPlugin.configuration().getHookSecretConfig(); - assertNotNull("Secret is persistent", hookSecretConfig.getHookSecret()); - assertEquals("Secret correctly stored", newSecret, hookSecretConfig.getHookSecret().getPlainText()); + assertNotNull(hookSecretConfig.getHookSecret(), "Secret is persistent"); + assertEquals(newSecret, hookSecretConfig.getHookSecret().getPlainText(), "Secret correctly stored"); } } \ No newline at end of file diff --git a/src/test/java/org/jenkinsci/plugins/github/extension/CryptoUtilTest.java b/src/test/java/org/jenkinsci/plugins/github/extension/CryptoUtilTest.java index 0be1f0a13..f252c4dc2 100644 --- a/src/test/java/org/jenkinsci/plugins/github/extension/CryptoUtilTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/extension/CryptoUtilTest.java @@ -1,40 +1,46 @@ package org.jenkinsci.plugins.github.extension; import hudson.util.Secret; -import org.junit.ClassRule; -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 static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import static org.jenkinsci.plugins.github.webhook.GHWebhookSignature.webhookSignature; -import static org.hamcrest.MatcherAssert.assertThat; /** * Tests for utility class that deals with crypto/hashing of data. * * @author martinmine */ -public class CryptoUtilTest { +@WithJenkins +class CryptoUtilTest { private static final String SIGNATURE = "85d155c55ed286a300bd1cf124de08d87e914f3a"; private static final String PAYLOAD = "foo"; private static final String SECRET = "bar"; - @ClassRule - public static JenkinsRule jRule = new JenkinsRule(); + private JenkinsRule jRule; + + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jRule = rule; + } @Test - public void shouldComputeSHA1Signature() throws Exception { + void shouldComputeSHA1Signature() throws Exception { assertThat("signature is valid", webhookSignature( - PAYLOAD, + PAYLOAD, Secret.fromString(SECRET) ).sha1(), equalTo(SIGNATURE)); } @Test - public void shouldMatchSignature() throws Exception { + void shouldMatchSignature() throws Exception { assertThat("signature should match", webhookSignature( - PAYLOAD, + PAYLOAD, Secret.fromString(SECRET) ).matches(SIGNATURE), equalTo(true)); } diff --git a/src/test/java/org/jenkinsci/plugins/github/extension/GHEventsSubscriberTest.java b/src/test/java/org/jenkinsci/plugins/github/extension/GHEventsSubscriberTest.java index 0f0187f2c..18f4c0666 100644 --- a/src/test/java/org/jenkinsci/plugins/github/extension/GHEventsSubscriberTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/extension/GHEventsSubscriberTest.java @@ -1,9 +1,7 @@ package org.jenkinsci.plugins.github.extension; import hudson.model.Item; -import hudson.model.Job; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kohsuke.github.GHEvent; import java.util.Set; @@ -15,16 +13,16 @@ /** * @author lanwen (Merkushev Kirill) */ -public class GHEventsSubscriberTest { +class GHEventsSubscriberTest { @Test - public void shouldReturnEmptySetInsteadOfNull() throws Exception { + void shouldReturnEmptySetInsteadOfNull() throws Exception { Set set = GHEventsSubscriber.extractEvents().apply(new NullSubscriber()); assertThat("null should be replaced", set, hasSize(0)); } @Test - public void shouldMatchAgainstEmptySetInsteadOfNull() throws Exception { + void shouldMatchAgainstEmptySetInsteadOfNull() throws Exception { boolean result = GHEventsSubscriber.isInterestedIn(GHEvent.PUSH).apply(new NullSubscriber()); assertThat("null should be replaced", result, is(false)); } diff --git a/src/test/java/org/jenkinsci/plugins/github/internal/GitHubClientCacheCleanupTest.java b/src/test/java/org/jenkinsci/plugins/github/internal/GitHubClientCacheCleanupTest.java index 45250e78f..f89645b77 100644 --- a/src/test/java/org/jenkinsci/plugins/github/internal/GitHubClientCacheCleanupTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/internal/GitHubClientCacheCleanupTest.java @@ -1,13 +1,14 @@ package org.jenkinsci.plugins.github.internal; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import hudson.Functions; import org.jenkinsci.plugins.github.config.GitHubServerConfig; -import org.jenkinsci.plugins.github.test.GHMockRule; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.jenkinsci.plugins.github.test.GitHubMockExtension; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.github.GitHub; import java.io.IOException; @@ -28,33 +29,36 @@ /** * @author lanwen (Merkushev Kirill) */ -public class GitHubClientCacheCleanupTest { +@WithJenkins +class GitHubClientCacheCleanupTest { public static final String DEFAULT_CREDS_ID = ""; public static final String CHANGED_CREDS_ID = "id"; - @Rule - public JenkinsRule jRule = new JenkinsRule(); + private JenkinsRule jRule; - @Rule - public GHMockRule github = new GHMockRule(new WireMockRule(wireMockConfig().dynamicPort())).stubUser(); + @RegisterExtension + static GitHubMockExtension github = new GitHubMockExtension(WireMockExtension.newInstance() + .options(wireMockConfig().dynamicPort())) + .stubUser(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jRule = rule; assumeThat("ignore for windows (dunno how to fix it without win - heed help!)", Functions.isWindows(), is(false) ); } @Test - public void shouldCreateCachedFolder() throws Exception { + void shouldCreateCachedFolder() throws Exception { makeCachedRequestWithCredsId(DEFAULT_CREDS_ID); it("should create cached dir", 1); } @Test - public void shouldCreateOnlyOneCachedFolderForSameCredsAndApi() throws Exception { + void shouldCreateOnlyOneCachedFolderForSameCredsAndApi() throws Exception { makeCachedRequestWithCredsId(DEFAULT_CREDS_ID); makeCachedRequestWithCredsId(DEFAULT_CREDS_ID); @@ -62,7 +66,7 @@ public void shouldCreateOnlyOneCachedFolderForSameCredsAndApi() throws Exception } @Test - public void shouldCreateCachedFolderForEachCreds() throws Exception { + void shouldCreateCachedFolderForEachCreds() throws Exception { makeCachedRequestWithCredsId(DEFAULT_CREDS_ID); makeCachedRequestWithCredsId(CHANGED_CREDS_ID); @@ -70,7 +74,7 @@ public void shouldCreateCachedFolderForEachCreds() throws Exception { } @Test - public void shouldRemoveCachedDirAfterClean() throws Exception { + void shouldRemoveCachedDirAfterClean() throws Exception { makeCachedRequestWithCredsId(DEFAULT_CREDS_ID); clearRedundantCaches(Collections.emptyList()); @@ -79,7 +83,7 @@ public void shouldRemoveCachedDirAfterClean() throws Exception { } @Test - public void shouldRemoveOnlyNotActiveCachedDirAfterClean() throws Exception { + void shouldRemoveOnlyNotActiveCachedDirAfterClean() throws Exception { makeCachedRequestWithCredsId(DEFAULT_CREDS_ID); makeCachedRequestWithCredsId(CHANGED_CREDS_ID); @@ -93,7 +97,7 @@ public void shouldRemoveOnlyNotActiveCachedDirAfterClean() throws Exception { } @Test - public void shouldRemoveCacheWhichNotEnabled() throws Exception { + void shouldRemoveCacheWhichNotEnabled() throws Exception { makeCachedRequestWithCredsId(CHANGED_CREDS_ID); GitHubServerConfig config = new GitHubServerConfig(CHANGED_CREDS_ID); diff --git a/src/test/java/org/jenkinsci/plugins/github/internal/GitHubClientCacheOpsTest.java b/src/test/java/org/jenkinsci/plugins/github/internal/GitHubClientCacheOpsTest.java index 3aa50f93b..af03c5ead 100644 --- a/src/test/java/org/jenkinsci/plugins/github/internal/GitHubClientCacheOpsTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/internal/GitHubClientCacheOpsTest.java @@ -2,12 +2,12 @@ import okhttp3.Cache; import org.jenkinsci.plugins.github.config.GitHubServerConfig; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import java.io.File; @@ -23,20 +23,25 @@ /** * @author lanwen (Merkushev Kirill) */ -public class GitHubClientCacheOpsTest { +@WithJenkins +class GitHubClientCacheOpsTest { public static final String CREDENTIALS_ID = "credsid"; public static final String CREDENTIALS_ID_2 = "credsid2"; public static final String CUSTOM_API_URL = "http://api.some.unk/"; - @ClassRule - public static TemporaryFolder tmp = new TemporaryFolder(); + @TempDir + public static File tmp; - @Rule - public JenkinsRule jRule = new JenkinsRule(); + private JenkinsRule jRule; + + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jRule = rule; + } @Test - public void shouldPointToSameCacheForOneConfig() throws Exception { + void shouldPointToSameCacheForOneConfig() throws Exception { GitHubServerConfig config = new GitHubServerConfig(CREDENTIALS_ID); Cache cache1 = toCacheDir().apply(config); @@ -47,7 +52,7 @@ public void shouldPointToSameCacheForOneConfig() throws Exception { } @Test - public void shouldPointToDifferentCachesOnChangedApiPath() throws Exception { + void shouldPointToDifferentCachesOnChangedApiPath() throws Exception { GitHubServerConfig config = new GitHubServerConfig(CREDENTIALS_ID); config.setApiUrl(CUSTOM_API_URL); @@ -61,7 +66,7 @@ public void shouldPointToDifferentCachesOnChangedApiPath() throws Exception { } @Test - public void shouldPointToDifferentCachesOnChangedCreds() throws Exception { + void shouldPointToDifferentCachesOnChangedCreds() throws Exception { GitHubServerConfig config = new GitHubServerConfig(CREDENTIALS_ID); GitHubServerConfig config2 = new GitHubServerConfig(CREDENTIALS_ID_2); @@ -74,30 +79,30 @@ public void shouldPointToDifferentCachesOnChangedCreds() throws Exception { @Test @WithoutJenkins - public void shouldNotAcceptFilesInFilter() throws Exception { + void shouldNotAcceptFilesInFilter() throws Exception { assertThat("file should not be accepted", - notInCaches(newHashSet("file")).accept(tmp.newFile().toPath()), is(false)); + notInCaches(newHashSet("file")).accept(File.createTempFile("junit", null, tmp).toPath()), is(false)); } @Test @WithoutJenkins - public void shouldNotAcceptDirsInFilterWithNameFromSet() throws Exception { - File dir = tmp.newFolder(); + void shouldNotAcceptDirsInFilterWithNameFromSet() throws Exception { + File dir = newFolder(tmp, "junit"); assertThat("should not accept folders from set", notInCaches(newHashSet(dir.getName())).accept(dir.toPath()), is(false)); } @Test @WithoutJenkins - public void shouldAcceptDirsInFilterWithNameNotInSet() throws Exception { - File dir = tmp.newFolder(); + void shouldAcceptDirsInFilterWithNameNotInSet() throws Exception { + File dir = newFolder(tmp, "junit"); assertThat("should accept folders not in set", notInCaches(newHashSet(dir.getName() + "abc")).accept(dir.toPath()), is(true)); } @Test @WithoutJenkins - public void shouldReturnEnabledOnCacheGreaterThan0() throws Exception { + void shouldReturnEnabledOnCacheGreaterThan0() throws Exception { GitHubServerConfig config = new GitHubServerConfig(CREDENTIALS_ID); config.setClientCacheSize(1); @@ -106,7 +111,7 @@ public void shouldReturnEnabledOnCacheGreaterThan0() throws Exception { @Test @WithoutJenkins - public void shouldReturnNotEnabledOnCacheEq0() throws Exception { + void shouldReturnNotEnabledOnCacheEq0() throws Exception { GitHubServerConfig config = new GitHubServerConfig(CREDENTIALS_ID); config.setClientCacheSize(0); @@ -115,7 +120,7 @@ public void shouldReturnNotEnabledOnCacheEq0() throws Exception { @Test @WithoutJenkins - public void shouldReturnNotEnabledOnCacheLessThan0() throws Exception { + void shouldReturnNotEnabledOnCacheLessThan0() throws Exception { GitHubServerConfig config = new GitHubServerConfig(CREDENTIALS_ID); config.setClientCacheSize(-1); @@ -124,7 +129,14 @@ public void shouldReturnNotEnabledOnCacheLessThan0() throws Exception { @Test @WithoutJenkins - public void shouldHaveEnabledCacheByDefault() throws Exception { + void shouldHaveEnabledCacheByDefault() throws Exception { assertThat("default cache", withEnabledCache().apply(new GitHubServerConfig(CREDENTIALS_ID)), is(true)); } + + private static File newFolder(File root, String... subDirs) { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + result.mkdirs(); + return result; + } } diff --git a/src/test/java/org/jenkinsci/plugins/github/migration/MigratorTest.java b/src/test/java/org/jenkinsci/plugins/github/migration/MigratorTest.java index 04539fcc6..c4720205f 100644 --- a/src/test/java/org/jenkinsci/plugins/github/migration/MigratorTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/migration/MigratorTest.java @@ -7,9 +7,10 @@ import jenkins.model.Jenkins; import org.jenkinsci.plugins.github.GitHubPlugin; import org.jenkinsci.plugins.github.config.GitHubServerConfig; -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; import java.io.IOException; @@ -30,10 +31,10 @@ /** * @author lanwen (Merkushev Kirill) */ -public class MigratorTest { +@WithJenkins +class MigratorTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; public static final String HOOK_FROM_LOCAL_DATA = "http://some.proxy.example.com/webhook"; public static final String CUSTOM_GH_URL = "http://custom.github.example.com/api/v3"; @@ -41,12 +42,17 @@ public class MigratorTest { public static final String TOKEN2 = "some-oauth-token2"; public static final String TOKEN3 = "some-oauth-token3"; + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jenkins = rule; + } + /** * Just ignore malformed hook in old config */ @Test @LocalData - public void shouldNotThrowExcMalformedHookUrlInOldConfig() throws IOException { + void shouldNotThrowExcMalformedHookUrlInOldConfig() throws IOException { FreeStyleProject job = jenkins.createFreeStyleProject(); GitHubPushTrigger trigger = new GitHubPushTrigger(); trigger.start(job, true); @@ -60,7 +66,7 @@ public void shouldNotThrowExcMalformedHookUrlInOldConfig() throws IOException { @Test @LocalData - public void shouldMigrateHookUrl() { + void shouldMigrateHookUrl() { assertThat("in plugin - override", GitHubPlugin.configuration().isOverrideHookUrl(), is(true)); assertThat("in plugin", valueOf(GitHubPlugin.configuration().getHookUrl()), is(HOOK_FROM_LOCAL_DATA)); @@ -70,7 +76,7 @@ public void shouldMigrateHookUrl() { @Test @LocalData - public void shouldMigrateCredentials() throws Exception { + void shouldMigrateCredentials() throws Exception { assertThat("should migrate 3 configs", GitHubPlugin.configuration().getConfigs(), hasSize(3)); assertThat("migrate custom url", GitHubPlugin.configuration().getConfigs(), hasItems( both(withApiUrl(is(CUSTOM_GH_URL))).and(withCredsWithToken(TOKEN2)), @@ -81,7 +87,7 @@ public void shouldMigrateCredentials() throws Exception { @Test @LocalData - public void shouldLoadDataAfterStart() throws Exception { + void shouldLoadDataAfterStart() throws Exception { assertThat("should load 2 configs", GitHubPlugin.configuration().getConfigs(), hasSize(2)); assertThat("migrate custom url", GitHubPlugin.configuration().getConfigs(), hasItems( withApiUrl(is(CUSTOM_GH_URL)), @@ -92,7 +98,7 @@ public void shouldLoadDataAfterStart() throws Exception { } @Test - public void shouldConvertCredsToServerConfig() throws Exception { + void shouldConvertCredsToServerConfig() throws Exception { GitHubServerConfig conf = new Migrator().toGHServerConfig() .apply(new Credential("name", CUSTOM_GH_URL, "token")); assertThat(conf, both(withCredsWithToken("token")).and(withApiUrl(is(CUSTOM_GH_URL)))); diff --git a/src/test/java/org/jenkinsci/plugins/github/status/GitHubCommitStatusSetterTest.java b/src/test/java/org/jenkinsci/plugins/github/status/GitHubCommitStatusSetterTest.java index 5f4ccbe1b..0e3491cae 100644 --- a/src/test/java/org/jenkinsci/plugins/github/status/GitHubCommitStatusSetterTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/status/GitHubCommitStatusSetterTest.java @@ -2,7 +2,7 @@ import com.cloudbees.jenkins.GitHubSetCommitStatusBuilder; import com.github.tomakehurst.wiremock.common.Slf4jNotifier; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; @@ -11,6 +11,7 @@ import hudson.model.Result; import hudson.plugins.git.Revision; import hudson.plugins.git.util.BuildData; +import jakarta.inject.Inject; import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.lib.ObjectId; import org.jenkinsci.plugins.github.config.GitHubPluginConfig; @@ -20,21 +21,19 @@ import org.jenkinsci.plugins.github.status.sources.BuildDataRevisionShaSource; import org.jenkinsci.plugins.github.status.sources.DefaultCommitContextSource; import org.jenkinsci.plugins.github.status.sources.DefaultStatusResultSource; -import org.jenkinsci.plugins.github.test.GHMockRule; -import org.jenkinsci.plugins.github.test.GHMockRule.FixedGHRepoNameTestContributor; -import org.jenkinsci.plugins.github.test.InjectJenkinsMembersRule; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.RuleChain; -import org.junit.runner.RunWith; +import org.jenkinsci.plugins.github.test.GitHubMockExtension; +import org.jenkinsci.plugins.github.test.GitHubMockExtension.FixedGHRepoNameTestContributor; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -import jakarta.inject.Inject; import java.util.Collections; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; @@ -47,44 +46,43 @@ * * @author Oleg Nenashev */ -@RunWith(MockitoJUnitRunner.class) +@WithJenkins +@ExtendWith(MockitoExtension.class) public class GitHubCommitStatusSetterTest { public static final String SOME_SHA = StringUtils.repeat("f", 40); - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) public BuildData data; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) public Revision rev; @Inject public GitHubPluginConfig config; - public JenkinsRule jRule = new JenkinsRule(); + private JenkinsRule jRule; - @Rule - public RuleChain chain = RuleChain.outerRule(jRule).around(new InjectJenkinsMembersRule(jRule, this)); - - @Rule - public GHMockRule github = new GHMockRule( - new WireMockRule( - wireMockConfig().dynamicPort().notifier(new Slf4jNotifier(true)) - )) + @RegisterExtension + static GitHubMockExtension github = new GitHubMockExtension(WireMockExtension.newInstance() + .options(wireMockConfig().dynamicPort().notifier(new Slf4jNotifier(true)))) .stubUser() .stubRepo() .stubStatuses(); - @Before - public void before() throws Throwable { - when(data.getLastBuiltRevision()).thenReturn(rev); - data.lastBuild = new hudson.plugins.git.util.Build(rev, rev, 0, Result.SUCCESS); - when(rev.getSha1()).thenReturn(ObjectId.fromString(SOME_SHA)); + @BeforeEach + void before(JenkinsRule rule) throws Throwable { + jRule = rule; + jRule.getInstance().getInjector().injectMembers(this); + + when(data.getLastBuiltRevision()).thenReturn(rev); + data.lastBuild = new hudson.plugins.git.util.Build(rev, rev, 0, Result.SUCCESS); + when(rev.getSha1()).thenReturn(ObjectId.fromString(SOME_SHA)); } @Test - public void shouldSetGHCommitStatus() throws Exception { + void shouldSetGHCommitStatus() throws Exception { config.getConfigs().add(github.serverConfig()); FreeStyleProject prj = jRule.createFreeStyleProject(); @@ -106,11 +104,11 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen prj.getPublishersList().add(statusSetter); prj.scheduleBuild2(0).get(); - github.service().verify(1, postRequestedFor(urlPathMatching(".*/" + SOME_SHA))); + github.verify(1, postRequestedFor(urlPathMatching(".*/" + SOME_SHA))); } @Test - public void shouldHandleError() throws Exception { + void shouldHandleError() throws Exception { FreeStyleProject prj = jRule.createFreeStyleProject(); GitHubCommitStatusSetter statusSetter = new GitHubCommitStatusSetter(); diff --git a/src/test/java/org/jenkinsci/plugins/github/status/err/ErrorHandlersTest.java b/src/test/java/org/jenkinsci/plugins/github/status/err/ErrorHandlersTest.java index 2bbe64a36..e0aaa945e 100644 --- a/src/test/java/org/jenkinsci/plugins/github/status/err/ErrorHandlersTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/status/err/ErrorHandlersTest.java @@ -3,21 +3,21 @@ import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.verify; /** * @author lanwen (Merkushev Kirill) */ -@RunWith(MockitoJUnitRunner.class) -public class ErrorHandlersTest { +@ExtendWith(MockitoExtension.class) +class ErrorHandlersTest { @Mock private Run run; @@ -26,7 +26,7 @@ public class ErrorHandlersTest { private TaskListener listener; @Test - public void shouldSetFailureResultStatus() throws Exception { + void shouldSetFailureResultStatus() throws Exception { boolean handled = new ChangingBuildStatusErrorHandler(Result.FAILURE.toString()) .handle(new RuntimeException(), run, listener); @@ -35,7 +35,7 @@ public void shouldSetFailureResultStatus() throws Exception { } @Test - public void shouldSetFailureResultStatusOnUnknownSetup() throws Exception { + void shouldSetFailureResultStatusOnUnknownSetup() throws Exception { boolean handled = new ChangingBuildStatusErrorHandler("") .handle(new RuntimeException(), run, listener); @@ -44,7 +44,7 @@ public void shouldSetFailureResultStatusOnUnknownSetup() throws Exception { } @Test - public void shouldHandleAndDoNothing() throws Exception { + void shouldHandleAndDoNothing() throws Exception { boolean handled = new ShallowAnyErrorHandler().handle(new RuntimeException(), run, listener); assertThat("handling", handled, is(true)); diff --git a/src/test/java/org/jenkinsci/plugins/github/status/sources/BuildRefBackrefSourceTest.java b/src/test/java/org/jenkinsci/plugins/github/status/sources/BuildRefBackrefSourceTest.java index fea0e24a7..d27ff4055 100644 --- a/src/test/java/org/jenkinsci/plugins/github/status/sources/BuildRefBackrefSourceTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/status/sources/BuildRefBackrefSourceTest.java @@ -1,16 +1,16 @@ package org.jenkinsci.plugins.github.status.sources; -import hudson.model.FreeStyleProject; import hudson.model.Run; import hudson.model.TaskListener; import org.jenkinsci.plugins.displayurlapi.DisplayURLProvider; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Answers; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -18,20 +18,25 @@ /** * @author pupssman (Kalinin Ivan) */ -@RunWith(MockitoJUnitRunner.class) -public class BuildRefBackrefSourceTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +class BuildRefBackrefSourceTest { - @Rule - public JenkinsRule jenkinsRule = new JenkinsRule(); + private JenkinsRule jenkinsRule; @Mock(answer = Answers.RETURNS_MOCKS) private TaskListener listener; - @Test + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jenkinsRule = rule; + } + /** * @throws Exception */ - public void shouldReturnRunAbsoluteUrl() throws Exception { + @Test + void shouldReturnRunAbsoluteUrl() throws Exception { Run run = jenkinsRule.buildAndAssertSuccess(jenkinsRule.createFreeStyleProject()); String result = new BuildRefBackrefSource().get(run, listener); diff --git a/src/test/java/org/jenkinsci/plugins/github/status/sources/ConditionalStatusResultSourceTest.java b/src/test/java/org/jenkinsci/plugins/github/status/sources/ConditionalStatusResultSourceTest.java index ab5bd0a24..9f7e1695b 100644 --- a/src/test/java/org/jenkinsci/plugins/github/status/sources/ConditionalStatusResultSourceTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/status/sources/ConditionalStatusResultSourceTest.java @@ -6,27 +6,27 @@ import org.jenkinsci.plugins.github.extension.status.GitHubStatusResultSource; import org.jenkinsci.plugins.github.extension.status.misc.ConditionalResult; import org.jenkinsci.plugins.github.status.sources.misc.AnyBuildResult; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GHCommitState; import org.mockito.Answers; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import static java.util.Arrays.asList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.jenkinsci.plugins.github.status.sources.misc.BetterThanOrEqualBuildResult.betterThanOrEqualTo; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.when; /** * @author lanwen (Merkushev Kirill) */ -@RunWith(MockitoJUnitRunner.class) -public class ConditionalStatusResultSourceTest { +@ExtendWith(MockitoExtension.class) +class ConditionalStatusResultSourceTest { @Mock(answer = Answers.RETURNS_MOCKS) private Run run; @@ -35,7 +35,7 @@ public class ConditionalStatusResultSourceTest { private TaskListener listener; @Test - public void shouldReturnPendingByDefault() throws Exception { + void shouldReturnPendingByDefault() throws Exception { GitHubStatusResultSource.StatusResult res = new ConditionalStatusResultSource(null).get(run, listener); assertThat("state", res.getState(), is(GHCommitState.PENDING)); @@ -43,7 +43,7 @@ public void shouldReturnPendingByDefault() throws Exception { } @Test - public void shouldReturnPendingIfNoMatch() throws Exception { + void shouldReturnPendingIfNoMatch() throws Exception { when(run.getResult()).thenReturn(Result.FAILURE); GitHubStatusResultSource.StatusResult res = new ConditionalStatusResultSource( @@ -57,7 +57,7 @@ public void shouldReturnPendingIfNoMatch() throws Exception { } @Test - public void shouldReturnFirstMatch() throws Exception { + void shouldReturnFirstMatch() throws Exception { GitHubStatusResultSource.StatusResult res = new ConditionalStatusResultSource(asList( AnyBuildResult.onAnyResult(GHCommitState.FAILURE, "1"), betterThanOrEqualTo(Result.SUCCESS, GHCommitState.SUCCESS, "2") @@ -68,7 +68,7 @@ public void shouldReturnFirstMatch() throws Exception { } @Test - public void shouldReturnFirstMatch2() throws Exception { + void shouldReturnFirstMatch2() throws Exception { when(run.getResult()).thenReturn(Result.SUCCESS); GitHubStatusResultSource.StatusResult res = new ConditionalStatusResultSource(asList( diff --git a/src/test/java/org/jenkinsci/plugins/github/status/sources/DefaultStatusResultSourceTest.java b/src/test/java/org/jenkinsci/plugins/github/status/sources/DefaultStatusResultSourceTest.java index d4a93e6c3..c06176aae 100644 --- a/src/test/java/org/jenkinsci/plugins/github/status/sources/DefaultStatusResultSourceTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/status/sources/DefaultStatusResultSourceTest.java @@ -1,20 +1,17 @@ package org.jenkinsci.plugins.github.status.sources; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; + import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import org.jenkinsci.plugins.github.extension.status.GitHubStatusResultSource; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kohsuke.github.GHCommitState; import org.mockito.Answers; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -23,11 +20,8 @@ /** * @author lanwen (Merkushev Kirill) */ -@RunWith(DataProviderRunner.class) -public class DefaultStatusResultSourceTest { - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); +@ExtendWith(MockitoExtension.class) +class DefaultStatusResultSourceTest { @Mock(answer = Answers.RETURNS_MOCKS) private Run run; @@ -35,8 +29,7 @@ public class DefaultStatusResultSourceTest { @Mock(answer = Answers.RETURNS_MOCKS) private TaskListener listener; - @DataProvider - public static Object[][] results() { + static Object[][] results() { return new Object[][]{ {Result.SUCCESS, GHCommitState.SUCCESS}, {Result.UNSTABLE, GHCommitState.FAILURE}, @@ -45,9 +38,9 @@ public static Object[][] results() { }; } - @Test - @UseDataProvider("results") - public void shouldReturnConditionalResult(Result actual, GHCommitState expected) throws Exception { + @ParameterizedTest + @MethodSource("results") + void shouldReturnConditionalResult(Result actual, GHCommitState expected) throws Exception { when(run.getResult()).thenReturn(actual); GitHubStatusResultSource.StatusResult result = new DefaultStatusResultSource().get(run, listener); diff --git a/src/test/java/org/jenkinsci/plugins/github/status/sources/ManuallyEnteredRepositorySourceTest.java b/src/test/java/org/jenkinsci/plugins/github/status/sources/ManuallyEnteredRepositorySourceTest.java index 954f9ff48..2f7d840f5 100644 --- a/src/test/java/org/jenkinsci/plugins/github/status/sources/ManuallyEnteredRepositorySourceTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/status/sources/ManuallyEnteredRepositorySourceTest.java @@ -2,12 +2,12 @@ import hudson.model.Run; import hudson.model.TaskListener; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GHRepository; import org.mockito.Answers; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.PrintStream; import java.util.List; @@ -19,8 +19,8 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class ManuallyEnteredRepositorySourceTest { +@ExtendWith(MockitoExtension.class) +class ManuallyEnteredRepositorySourceTest { @Mock(answer = Answers.RETURNS_MOCKS) private Run run; @@ -31,7 +31,7 @@ public class ManuallyEnteredRepositorySourceTest { private PrintStream logger; @Test - public void nullName() { + void nullName() { ManuallyEnteredRepositorySource instance = spy(new ManuallyEnteredRepositorySource("a")); doReturn(logger).when(listener).getLogger(); List repos = instance.repos(run, listener); diff --git a/src/test/java/org/jenkinsci/plugins/github/status/sources/ManuallyEnteredSourcesTest.java b/src/test/java/org/jenkinsci/plugins/github/status/sources/ManuallyEnteredSourcesTest.java index 791da1f22..14e606dd2 100644 --- a/src/test/java/org/jenkinsci/plugins/github/status/sources/ManuallyEnteredSourcesTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/status/sources/ManuallyEnteredSourcesTest.java @@ -3,21 +3,21 @@ import hudson.EnvVars; import hudson.model.Run; import hudson.model.TaskListener; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Answers; import org.mockito.ArgumentMatchers; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.Mockito.when; /** * @author lanwen (Merkushev Kirill) */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ManuallyEnteredSourcesTest { public static final String EXPANDED = "expanded"; @@ -32,7 +32,7 @@ public class ManuallyEnteredSourcesTest { @Test - public void shouldExpandContext() throws Exception { + void shouldExpandContext() throws Exception { when(run.getEnvironment(listener)).thenReturn(env); when(env.expand(ArgumentMatchers.anyString())).thenReturn(EXPANDED); @@ -41,7 +41,7 @@ public void shouldExpandContext() throws Exception { } @Test - public void shouldExpandSha() throws Exception { + void shouldExpandSha() throws Exception { when(run.getEnvironment(listener)).thenReturn(env); when(env.expand(ArgumentMatchers.anyString())).thenReturn(EXPANDED); @@ -50,7 +50,7 @@ public void shouldExpandSha() throws Exception { } @Test - public void shouldExpandBackref() throws Exception { + void shouldExpandBackref() throws Exception { when(run.getEnvironment(listener)).thenReturn(env); when(env.expand(ArgumentMatchers.anyString())).thenReturn(EXPANDED); diff --git a/src/test/java/org/jenkinsci/plugins/github/status/sources/misc/AnyBuildResultTest.java b/src/test/java/org/jenkinsci/plugins/github/status/sources/misc/AnyBuildResultTest.java index 32437ffb5..145a24266 100644 --- a/src/test/java/org/jenkinsci/plugins/github/status/sources/misc/AnyBuildResultTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/status/sources/misc/AnyBuildResultTest.java @@ -1,29 +1,29 @@ package org.jenkinsci.plugins.github.status.sources.misc; import hudson.model.Run; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GHCommitState; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author lanwen (Merkushev Kirill) */ -@RunWith(MockitoJUnitRunner.class) -public class AnyBuildResultTest { +@ExtendWith(MockitoExtension.class) +class AnyBuildResultTest { @Mock private Run run; @Test - public void shouldMatchEveryTime() throws Exception { + void shouldMatchEveryTime() throws Exception { boolean matches = AnyBuildResult.onAnyResult(GHCommitState.ERROR, "").matches(run); - - assertTrue("matching", matches); + + assertTrue(matches, "matching"); verifyNoMoreInteractions(run); } diff --git a/src/test/java/org/jenkinsci/plugins/github/status/sources/misc/BetterThanOrEqualBuildResultTest.java b/src/test/java/org/jenkinsci/plugins/github/status/sources/misc/BetterThanOrEqualBuildResultTest.java index 086da733f..75cd588ea 100644 --- a/src/test/java/org/jenkinsci/plugins/github/status/sources/misc/BetterThanOrEqualBuildResultTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/status/sources/misc/BetterThanOrEqualBuildResultTest.java @@ -1,37 +1,29 @@ package org.jenkinsci.plugins.github.status.sources.misc; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; import hudson.model.Result; import hudson.model.Run; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kohsuke.github.GHCommitState; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.jenkinsci.plugins.github.status.sources.misc.BetterThanOrEqualBuildResult.betterThanOrEqualTo; -import static org.hamcrest.MatcherAssert.assertThat; /** * @author lanwen (Merkushev Kirill) */ -@RunWith(DataProviderRunner.class) -public class BetterThanOrEqualBuildResultTest { - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); +@ExtendWith(MockitoExtension.class) +class BetterThanOrEqualBuildResultTest { @Mock private Run run; - @DataProvider - public static Object[][] results() { + static Object[][] results() { return new Object[][]{ {Result.SUCCESS, Result.SUCCESS, true}, {Result.UNSTABLE, Result.UNSTABLE, true}, @@ -44,9 +36,9 @@ public static Object[][] results() { }; } - @Test - @UseDataProvider("results") - public void shouldMatch(Result defined, Result real, boolean expect) throws Exception { + @ParameterizedTest + @MethodSource("results") + void shouldMatch(Result defined, Result real, boolean expect) throws Exception { Mockito.when(run.getResult()).thenReturn(real); boolean matched = betterThanOrEqualTo(defined, GHCommitState.FAILURE, "").matches(run); diff --git a/src/test/java/org/jenkinsci/plugins/github/test/GHMockRule.java b/src/test/java/org/jenkinsci/plugins/github/test/GHMockRule.java deleted file mode 100644 index 34189b827..000000000 --- a/src/test/java/org/jenkinsci/plugins/github/test/GHMockRule.java +++ /dev/null @@ -1,164 +0,0 @@ -package org.jenkinsci.plugins.github.test; - -import com.cloudbees.jenkins.GitHubRepositoryName; -import com.cloudbees.jenkins.GitHubRepositoryNameContributor; -import com.github.tomakehurst.wiremock.junit.WireMockRule; -import hudson.model.Item; -import org.jenkinsci.plugins.github.config.GitHubServerConfig; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static com.cloudbees.jenkins.GitHubWebHookFullTest.classpath; -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.post; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; -import static java.lang.String.format; -import static java.net.HttpURLConnection.HTTP_CREATED; - -/** - * Mocks GitHub on localhost with some predefined methods - * - * @author lanwen (Merkushev Kirill) - */ -public class GHMockRule implements TestRule { - - /** - * This repo is used in resource files - */ - public static final GitHubRepositoryName REPO = new GitHubRepositoryName("localhost", "org", "repo"); - - /** - * Wiremock service itself. You can interact with it directly by {@link #service()} method - */ - private WireMockRule service; - - /** - * List of additional stubs. Launched after wiremock has been started - */ - private List setups = new ArrayList<>(); - - public GHMockRule(WireMockRule mocked) { - this.service = mocked; - } - - /** - * @return wiremock rule - */ - public WireMockRule service() { - return service; - } - - /** - * Ready-to-use global config with wiremock service. Just add it to plugin config - * {@code GitHubPlugin.configuration().getConfigs().add(github.serverConfig());} - * - * @return part of global plugin config - */ - public GitHubServerConfig serverConfig() { - GitHubServerConfig conf = new GitHubServerConfig("creds"); - conf.setApiUrl("http://localhost:" + service().port()); - return conf; - } - - /** - * Main method of rule. Firstly starts wiremock, then run predefined setups - */ - @Override - public Statement apply(final Statement base, Description description) { - return service.apply(new Statement() { - @Override - public void evaluate() throws Throwable { - for (Runnable callable : setups) { - callable.run(); - } - base.evaluate(); - } - }, description); - } - - /** - * Stubs /user response with predefined content - * - * More info: https://developer.github.com/v3/users/#get-the-authenticated-user - */ - public GHMockRule stubUser() { - return addSetup(new Runnable() { - @Override - public void run() { - service().stubFor(get(urlPathEqualTo("/user")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "application/json; charset=utf-8") - .withBody(classpath(GHMockRule.class, "user.json")))); - } - }); - } - - /** - * Stubs /repos/org/repo response with predefined content - * - * More info: https://developer.github.com/v3/repos/#get - */ - public GHMockRule stubRepo() { - return addSetup(new Runnable() { - @Override - public void run() { - String repo = format("/repos/%s/%s", REPO.getUserName(), REPO.getRepositoryName()); - service().stubFor( - get(urlPathMatching(repo)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "application/json; charset=utf-8") - .withBody(classpath(GHMockRule.class, "repos-repo.json")))); - } - }); - } - - /** - * Returns 201 CREATED on POST to statuses endpoint (but without content) - * - * More info: https://developer.github.com/v3/repos/statuses/ - */ - public GHMockRule stubStatuses() { - return addSetup(new Runnable() { - @Override - public void run() { - service().stubFor( - post(urlPathMatching( - format("/repos/%s/%s/statuses/.*", REPO.getUserName(), REPO.getRepositoryName())) - ).willReturn(aResponse().withStatus(HTTP_CREATED))); - } - }); - } - - /** - * When we call one of predefined stub* methods, wiremock is not not started yet, so we need to create a closure - * - * @param setup closure to setup wiremock - */ - private GHMockRule addSetup(Runnable setup) { - setups.add(setup); - return this; - } - - /** - * Adds predefined repo to list which job can return. This is useful to avoid SCM usage. - * - * {@code @TestExtension - * public static final FixedGHRepoNameTestContributor CONTRIBUTOR = new FixedGHRepoNameTestContributor(); - * } - */ - public static class FixedGHRepoNameTestContributor extends GitHubRepositoryNameContributor { - @Override - public void parseAssociatedNames(Item job, Collection result) { - result.add(GHMockRule.REPO); - } - } -} diff --git a/src/test/java/org/jenkinsci/plugins/github/test/GitHubMockExtension.java b/src/test/java/org/jenkinsci/plugins/github/test/GitHubMockExtension.java new file mode 100644 index 000000000..fc5687a9f --- /dev/null +++ b/src/test/java/org/jenkinsci/plugins/github/test/GitHubMockExtension.java @@ -0,0 +1,123 @@ +package org.jenkinsci.plugins.github.test; + +import com.cloudbees.jenkins.GitHubRepositoryName; +import com.cloudbees.jenkins.GitHubRepositoryNameContributor; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; +import hudson.model.Item; +import org.jenkinsci.plugins.github.config.GitHubServerConfig; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import static com.cloudbees.jenkins.GitHubWebHookFullTest.classpath; +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.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; +import static java.lang.String.format; +import static java.net.HttpURLConnection.HTTP_CREATED; +import static java.net.HttpURLConnection.HTTP_OK; + +/** + * Mocks GitHub on localhost with some predefined methods + * + * @author lanwen (Merkushev Kirill) + */ +public class GitHubMockExtension extends WireMockExtension { + + /** + * This repo is used in resource files + */ + public static final GitHubRepositoryName REPO = new GitHubRepositoryName("localhost", "org", "repo"); + + /** + * List of additional stubs. Launched after wiremock has been started + */ + private final List setups = new ArrayList<>(); + + public GitHubMockExtension(Builder builder) { + super(builder); + } + + @Override + protected void onBeforeEach(WireMockRuntimeInfo wireMockRuntimeInfo) { + super.onBeforeAll(wireMockRuntimeInfo); + + for (Runnable setup : setups) { + setup.run(); + } + } + + /** + * Ready-to-use global config with wiremock service. Just add it to plugin config + * {@code GitHubPlugin.configuration().getConfigs().add(github.serverConfig());} + * + * @return part of global plugin config + */ + public GitHubServerConfig serverConfig() { + GitHubServerConfig conf = new GitHubServerConfig("creds"); + conf.setApiUrl("http://localhost:" + getPort()); + return conf; + } + + /** + * Stubs /user response with predefined content + *

+ * More info: https://developer.github.com/v3/users/#get-the-authenticated-user + */ + public GitHubMockExtension stubUser() { + setups.add(() -> + stubFor(get(urlPathEqualTo("/user")) + .willReturn(aResponse() + .withStatus(HTTP_OK) + .withHeader("Content-Type", "application/json; charset=utf-8") + .withBody(classpath(GitHubMockExtension.class, "user.json"))))); + return this; + } + + /** + * Stubs /repos/org/repo response with predefined content + *

+ * More info: https://developer.github.com/v3/repos/#get + */ + public GitHubMockExtension stubRepo() { + setups.add(() -> + stubFor(get(urlPathMatching(format("/repos/%s/%s", REPO.getUserName(), REPO.getRepositoryName()))) + .willReturn(aResponse() + .withStatus(HTTP_OK) + .withHeader("Content-Type", "application/json; charset=utf-8") + .withBody(classpath(GitHubMockExtension.class, "repos-repo.json"))))); + return this; + } + + /** + * Returns 201 CREATED on POST to statuses endpoint (but without content) + *

+ * More info: https://developer.github.com/v3/repos/statuses/ + */ + public GitHubMockExtension stubStatuses() { + setups.add(() -> + stubFor(post(urlPathMatching(format("/repos/%s/%s/statuses/.*", REPO.getUserName(), REPO.getRepositoryName()))) + .willReturn(aResponse() + .withStatus(HTTP_CREATED)))); + return this; + } + + /** + * Adds predefined repo to list which job can return. This is useful to avoid SCM usage. + *

+ * {@code @TestExtension + * public static final FixedGHRepoNameTestContributor CONTRIBUTOR = new FixedGHRepoNameTestContributor(); + * } + */ + public static class FixedGHRepoNameTestContributor extends GitHubRepositoryNameContributor { + @Override + public void parseAssociatedNames(Item job, Collection result) { + result.add(GitHubMockExtension.REPO); + } + } + +} diff --git a/src/test/java/org/jenkinsci/plugins/github/test/GitHubServerConfigMatcher.java b/src/test/java/org/jenkinsci/plugins/github/test/GitHubServerConfigMatcher.java index 6763e8dd0..2a391af6e 100644 --- a/src/test/java/org/jenkinsci/plugins/github/test/GitHubServerConfigMatcher.java +++ b/src/test/java/org/jenkinsci/plugins/github/test/GitHubServerConfigMatcher.java @@ -5,10 +5,6 @@ import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import org.jenkinsci.plugins.github.config.GitHubServerConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Map; import static org.hamcrest.Matchers.is; import static org.jenkinsci.plugins.github.config.GitHubServerConfig.tokenFor; @@ -17,7 +13,6 @@ * @author lanwen (Merkushev Kirill) */ public final class GitHubServerConfigMatcher { - private static final Logger LOG = LoggerFactory.getLogger(GitHubServerConfigMatcher.class); private GitHubServerConfigMatcher() { } diff --git a/src/test/java/org/jenkinsci/plugins/github/test/HookSecretHelper.java b/src/test/java/org/jenkinsci/plugins/github/test/HookSecretHelper.java index 0d6d7e3db..b2d7d8960 100644 --- a/src/test/java/org/jenkinsci/plugins/github/test/HookSecretHelper.java +++ b/src/test/java/org/jenkinsci/plugins/github/test/HookSecretHelper.java @@ -27,7 +27,7 @@ private HookSecretHelper() { /** * Stores the secret and sets it as the current hook secret. - * + * * @param config where to save * @param secretText The secret/key. */ @@ -56,13 +56,13 @@ public void run() { config.setHookSecretConfigs(Collections.singletonList(new HookSecretConfig(credentials.getId()))); } - + /** * Stores the secret and sets it as the current hook secret. * @param secretText The secret/key. */ public static void storeSecret(final String secretText) { - storeSecretIn(Jenkins.getInstance().getDescriptorByType(GitHubPluginConfig.class), secretText); + storeSecretIn(Jenkins.get().getDescriptorByType(GitHubPluginConfig.class), secretText); } /** @@ -78,6 +78,6 @@ public static void removeSecretIn(GitHubPluginConfig config) { * Unsets the current hook secret. */ public static void removeSecret() { - removeSecretIn(Jenkins.getInstance().getDescriptorByType(GitHubPluginConfig.class)); + removeSecretIn(Jenkins.get().getDescriptorByType(GitHubPluginConfig.class)); } } diff --git a/src/test/java/org/jenkinsci/plugins/github/test/InjectJenkinsMembersRule.java b/src/test/java/org/jenkinsci/plugins/github/test/InjectJenkinsMembersRule.java deleted file mode 100644 index ae0127783..000000000 --- a/src/test/java/org/jenkinsci/plugins/github/test/InjectJenkinsMembersRule.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.jenkinsci.plugins.github.test; - -import org.junit.rules.ExternalResource; -import org.jvnet.hudson.test.JenkinsRule; - -/** - * Helpful class to make possible usage of - * {@code @Inject - * public GitHubPluginConfig config; - * } - * - * in test fields instead of static calls {@link org.jenkinsci.plugins.github.GitHubPlugin#configuration()} - * - * See {@link com.cloudbees.jenkins.GitHubSetCommitStatusBuilderTest} for example - * Should be used after JenkinsRule initialized - * - * {@code public RuleChain chain = RuleChain.outerRule(jRule).around(new InjectJenkinsMembersRule(jRule, this)); } - * - * @author lanwen (Merkushev Kirill) - */ -public class InjectJenkinsMembersRule extends ExternalResource { - - private JenkinsRule jRule; - private Object instance; - - /** - * @param jRule Jenkins rule - * @param instance test class instance - */ - public InjectJenkinsMembersRule(JenkinsRule jRule, Object instance) { - this.jRule = jRule; - this.instance = instance; - } - - @Override - protected void before() throws Throwable { - jRule.getInstance().getInjector().injectMembers(instance); - } -} diff --git a/src/test/java/org/jenkinsci/plugins/github/util/BuildDataHelperTest.java b/src/test/java/org/jenkinsci/plugins/github/util/BuildDataHelperTest.java index 0f58cc9e0..0cf91e16b 100644 --- a/src/test/java/org/jenkinsci/plugins/github/util/BuildDataHelperTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/util/BuildDataHelperTest.java @@ -1,10 +1,8 @@ package org.jenkinsci.plugins.github.util; import hudson.plugins.git.util.BuildData; - -import org.junit.Test; -import org.junit.experimental.runners.Enclosed; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import java.util.ArrayList; @@ -20,16 +18,16 @@ /** * @author Manuel de la Peña */ -@RunWith(Enclosed.class) -public class BuildDataHelperTest { +class BuildDataHelperTest { - public static class WhenBuildingRegularJobs { + @Nested + class WhenBuildingRegularJobs { private static final String GITHUB_USERNAME = "user1"; @Test @Issue("JENKINS-53149") - public void shouldCalculateDataBuildFromProject() throws Exception { + void shouldCalculateDataBuildFromProject() throws Exception { BuildData projectBuildData = new BuildData(); projectBuildData.remoteUrls = new HashSet<>(); @@ -48,7 +46,7 @@ public void shouldCalculateDataBuildFromProject() throws Exception { @Test @Issue("JENKINS-53149") - public void shouldCalculateDataBuildFromProjectWithTwoBuildDatas() throws Exception { + void shouldCalculateDataBuildFromProjectWithTwoBuildDatas() throws Exception { BuildData sharedLibBuildData = new BuildData(); sharedLibBuildData.remoteUrls = new HashSet<>(); @@ -74,7 +72,7 @@ public void shouldCalculateDataBuildFromProjectWithTwoBuildDatas() throws Except @Test @Issue("JENKINS-53149") - public void shouldCalculateDataBuildFromProjectWithEmptyBuildDatas() throws Exception { + void shouldCalculateDataBuildFromProjectWithEmptyBuildDatas() throws Exception { BuildData buildData = BuildDataHelper.calculateBuildData( "master", "project/master", Collections.EMPTY_LIST); @@ -83,7 +81,7 @@ public void shouldCalculateDataBuildFromProjectWithEmptyBuildDatas() throws Exce @Test @Issue("JENKINS-53149") - public void shouldCalculateDataBuildFromProjectWithNullBuildDatas() throws Exception { + void shouldCalculateDataBuildFromProjectWithNullBuildDatas() throws Exception { BuildData buildData = BuildDataHelper.calculateBuildData( "master", "project/master", null); @@ -92,13 +90,14 @@ public void shouldCalculateDataBuildFromProjectWithNullBuildDatas() throws Excep } - public static class WhenBuildingOrganizationJobs { + @Nested + class WhenBuildingOrganizationJobs { private static final String ORGANIZATION_NAME = "Organization"; @Test @Issue("JENKINS-53149") - public void shouldCalculateDataBuildFromProject() throws Exception { + void shouldCalculateDataBuildFromProject() throws Exception { BuildData projectBuildData = new BuildData(); projectBuildData.remoteUrls = new HashSet<>(); @@ -117,7 +116,7 @@ public void shouldCalculateDataBuildFromProject() throws Exception { @Test @Issue("JENKINS-53149") - public void shouldCalculateDataBuildFromProjectWithTwoBuildDatas() throws Exception { + void shouldCalculateDataBuildFromProjectWithTwoBuildDatas() throws Exception { BuildData sharedLibBuildData = new BuildData(); sharedLibBuildData.remoteUrls = new HashSet<>(); @@ -143,7 +142,7 @@ public void shouldCalculateDataBuildFromProjectWithTwoBuildDatas() throws Except @Test @Issue("JENKINS-53149") - public void shouldCalculateDataBuildFromProjectWithEmptyBuildDatas() throws Exception { + void shouldCalculateDataBuildFromProjectWithEmptyBuildDatas() throws Exception { BuildData buildData = BuildDataHelper.calculateBuildData( "master", ORGANIZATION_NAME + "/project/master", Collections.EMPTY_LIST); @@ -152,7 +151,7 @@ public void shouldCalculateDataBuildFromProjectWithEmptyBuildDatas() throws Exce @Test @Issue("JENKINS-53149") - public void shouldCalculateDataBuildFromProjectWithNullBuildDatas() throws Exception { + void shouldCalculateDataBuildFromProjectWithNullBuildDatas() throws Exception { BuildData buildData = BuildDataHelper.calculateBuildData( "master", ORGANIZATION_NAME + "/project/master", null); diff --git a/src/test/java/org/jenkinsci/plugins/github/util/JobInfoHelpersTest.java b/src/test/java/org/jenkinsci/plugins/github/util/JobInfoHelpersTest.java index f7881acc7..93e8a2b65 100644 --- a/src/test/java/org/jenkinsci/plugins/github/util/JobInfoHelpersTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/util/JobInfoHelpersTest.java @@ -4,9 +4,10 @@ import hudson.model.FreeStyleProject; import hudson.model.Item; import org.jenkinsci.plugins.workflow.job.WorkflowJob; -import org.junit.ClassRule; -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 static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -19,13 +20,18 @@ /** * @author lanwen (Merkushev Kirill) */ -public class JobInfoHelpersTest { +@WithJenkins +class JobInfoHelpersTest { - @ClassRule - public static JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; + + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jenkins = rule; + } @Test - public void shouldMatchForProjectWithTrigger() throws Exception { + void shouldMatchForProjectWithTrigger() throws Exception { FreeStyleProject prj = jenkins.createFreeStyleProject(); prj.addTrigger(new GitHubPushTrigger()); @@ -33,7 +39,7 @@ public void shouldMatchForProjectWithTrigger() throws Exception { } @Test - public void shouldSeeProjectWithTriggerIsAliveForCleaner() throws Exception { + void shouldSeeProjectWithTriggerIsAliveForCleaner() throws Exception { FreeStyleProject prj = jenkins.createFreeStyleProject(); prj.addTrigger(new GitHubPushTrigger()); @@ -41,31 +47,31 @@ public void shouldSeeProjectWithTriggerIsAliveForCleaner() throws Exception { } @Test - public void shouldNotMatchProjectWithoutTrigger() throws Exception { + void shouldNotMatchProjectWithoutTrigger() throws Exception { FreeStyleProject prj = jenkins.createFreeStyleProject(); assertThat("without trigger", withTrigger(GitHubPushTrigger.class).apply(prj), is(false)); } @Test - public void shouldNotMatchNullProject() throws Exception { + void shouldNotMatchNullProject() throws Exception { assertThat("null project", withTrigger(GitHubPushTrigger.class).apply(null), is(false)); } @Test - public void shouldReturnNotBuildableOnNullProject() throws Exception { + void shouldReturnNotBuildableOnNullProject() throws Exception { assertThat("null project", isBuildable().apply(null), is(false)); } @Test - public void shouldSeeProjectWithoutTriggerIsNotAliveForCleaner() throws Exception { + void shouldSeeProjectWithoutTriggerIsNotAliveForCleaner() throws Exception { FreeStyleProject prj = jenkins.createFreeStyleProject(); assertThat("without trigger", isAlive().apply(prj), is(false)); } @Test - public void shouldGetTriggerFromAbstractProject() throws Exception { + void shouldGetTriggerFromAbstractProject() throws Exception { GitHubPushTrigger trigger = new GitHubPushTrigger(); FreeStyleProject prj = jenkins.createFreeStyleProject(); @@ -75,7 +81,7 @@ public void shouldGetTriggerFromAbstractProject() throws Exception { } @Test - public void shouldGetTriggerFromWorkflow() throws Exception { + void shouldGetTriggerFromWorkflow() throws Exception { GitHubPushTrigger trigger = new GitHubPushTrigger(); WorkflowJob job = jenkins.getInstance().createProject(WorkflowJob.class, "Test Workflow"); job.addTrigger(trigger); @@ -84,7 +90,7 @@ public void shouldGetTriggerFromWorkflow() throws Exception { } @Test - public void shouldNotGetTriggerWhenNoOne() throws Exception { + void shouldNotGetTriggerWhenNoOne() throws Exception { FreeStyleProject prj = jenkins.createFreeStyleProject(); assertThat("without trigger in project", triggerFrom((Item) prj, GitHubPushTrigger.class), nullValue()); diff --git a/src/test/java/org/jenkinsci/plugins/github/util/XSSApiTest.java b/src/test/java/org/jenkinsci/plugins/github/util/XSSApiTest.java index 4ce33af75..e1bc391e7 100644 --- a/src/test/java/org/jenkinsci/plugins/github/util/XSSApiTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/util/XSSApiTest.java @@ -1,10 +1,7 @@ package org.jenkinsci.plugins.github.util; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import static java.lang.String.format; import static org.hamcrest.MatcherAssert.assertThat; @@ -13,11 +10,9 @@ /** * @author lanwen (Merkushev Kirill) */ -@RunWith(DataProviderRunner.class) -public class XSSApiTest { +class XSSApiTest { - @DataProvider - public static Object[][] links() { + static Object[][] links() { return new Object[][]{ new Object[]{"javascript:alert(1);//", ""}, new Object[]{"javascript:alert(1)://", ""}, @@ -37,9 +32,9 @@ public static Object[][] links() { }; } - @Test - @UseDataProvider("links") - public void shouldSanitizeUrl(String url, String expected) throws Exception { + @ParameterizedTest + @MethodSource("links") + void shouldSanitizeUrl(String url, String expected) throws Exception { assertThat(format("For %s", url), XSSApi.asValidHref(url), is(expected)); } } diff --git a/src/test/java/org/jenkinsci/plugins/github/webhook/GHEventHeaderTest.java b/src/test/java/org/jenkinsci/plugins/github/webhook/GHEventHeaderTest.java index 6d29dbb3b..ee350a301 100644 --- a/src/test/java/org/jenkinsci/plugins/github/webhook/GHEventHeaderTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/webhook/GHEventHeaderTest.java @@ -1,28 +1,29 @@ package org.jenkinsci.plugins.github.webhook; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.github.GHEvent; import org.kohsuke.stapler.StaplerRequest2; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; /** * @author lanwen (Merkushev Kirill) */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class GHEventHeaderTest { public static final String STRING_PUSH_HEADER = "push"; public static final String PARAM_NAME = "event"; public static final String UNKNOWN_EVENT = "unkn"; - + @Mock private StaplerRequest2 req; @@ -30,7 +31,7 @@ public class GHEventHeaderTest { private GHEventHeader ann; @Test - public void shouldReturnParsedPushHeader() throws Exception { + void shouldReturnParsedPushHeader() throws Exception { when(req.getHeader(GHEventHeader.PayloadHandler.EVENT_HEADER)).thenReturn(STRING_PUSH_HEADER); Object event = new GHEventHeader.PayloadHandler().parse(req, ann, GHEvent.class, PARAM_NAME); @@ -39,22 +40,23 @@ public void shouldReturnParsedPushHeader() throws Exception { } @Test - public void shouldReturnNullOnEmptyHeader() throws Exception { + void shouldReturnNullOnEmptyHeader() throws Exception { Object event = new GHEventHeader.PayloadHandler().parse(req, ann, GHEvent.class, PARAM_NAME); assertThat("event with empty header", event, nullValue()); } @Test - public void shouldReturnNullOnUnknownEventHeader() throws Exception { + void shouldReturnNullOnUnknownEventHeader() throws Exception { when(req.getHeader(GHEventHeader.PayloadHandler.EVENT_HEADER)).thenReturn(UNKNOWN_EVENT); Object event = new GHEventHeader.PayloadHandler().parse(req, ann, GHEvent.class, PARAM_NAME); assertThat("event with unknown event header", event, nullValue()); } - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExcOnWrongTypeOfHeader() throws Exception { - new GHEventHeader.PayloadHandler().parse(req, ann, String.class, PARAM_NAME); + + @Test + void shouldThrowExcOnWrongTypeOfHeader() { + assertThrows(IllegalArgumentException.class, () -> + new GHEventHeader.PayloadHandler().parse(req, ann, String.class, PARAM_NAME)); } } diff --git a/src/test/java/org/jenkinsci/plugins/github/webhook/GHEventPayloadTest.java b/src/test/java/org/jenkinsci/plugins/github/webhook/GHEventPayloadTest.java index f83af5f06..3c0b1a17e 100644 --- a/src/test/java/org/jenkinsci/plugins/github/webhook/GHEventPayloadTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/webhook/GHEventPayloadTest.java @@ -1,11 +1,11 @@ package org.jenkinsci.plugins.github.webhook; import com.cloudbees.jenkins.GitHubWebHookFullTest; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.kohsuke.stapler.StaplerRequest2; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -16,7 +16,7 @@ /** * @author lanwen (Merkushev Kirill) */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class GHEventPayloadTest { public static final String NOT_EMPTY_PAYLOAD_CONTENT = "{}"; @@ -30,7 +30,7 @@ public class GHEventPayloadTest { private GHEventPayload ann; @Test - public void shouldReturnPayloadFromForm() throws Exception { + void shouldReturnPayloadFromForm() throws Exception { when(req.getContentType()).thenReturn(GitHubWebHookFullTest.FORM); when(req.getParameter(PARAM_NAME)).thenReturn(NOT_EMPTY_PAYLOAD_CONTENT); Object payload = new GHEventPayload.PayloadHandler().parse(req, ann, String.class, PARAM_NAME); @@ -40,7 +40,7 @@ public void shouldReturnPayloadFromForm() throws Exception { } @Test - public void shouldReturnNullOnUnknownContentType() throws Exception { + void shouldReturnNullOnUnknownContentType() throws Exception { when(req.getContentType()).thenReturn(UNKNOWN_CONTENT_TYPE); Object payload = new GHEventPayload.PayloadHandler().parse(req, ann, String.class, PARAM_NAME); diff --git a/src/test/java/org/jenkinsci/plugins/github/webhook/RequirePostWithGHHookPayloadTest.java b/src/test/java/org/jenkinsci/plugins/github/webhook/RequirePostWithGHHookPayloadTest.java index d1725fda6..d6942dd06 100644 --- a/src/test/java/org/jenkinsci/plugins/github/webhook/RequirePostWithGHHookPayloadTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/webhook/RequirePostWithGHHookPayloadTest.java @@ -1,138 +1,142 @@ package org.jenkinsci.plugins.github.webhook; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.github.GHEvent; import org.kohsuke.stapler.StaplerRequest2; import org.mockito.Mock; import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.InvocationTargetException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.jenkinsci.plugins.github.test.HookSecretHelper.storeSecret; import static org.jenkinsci.plugins.github.test.HookSecretHelper.removeSecret; +import static org.jenkinsci.plugins.github.test.HookSecretHelper.storeSecret; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; /** * @author lanwen (Merkushev Kirill) */ -@RunWith(MockitoJUnitRunner.class) -public class RequirePostWithGHHookPayloadTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +class RequirePostWithGHHookPayloadTest { private static final String SECRET_CONTENT = "secret"; private static final String PAYLOAD = "sample payload"; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) private StaplerRequest2 req; - @Rule - public JenkinsRule jenkinsRule = new JenkinsRule(); + private JenkinsRule jenkinsRule; @Spy private RequirePostWithGHHookPayload.Processor processor; - @Before - public void setSecret() { + @BeforeEach + void setSecret(JenkinsRule rule) throws Exception { + jenkinsRule = rule; storeSecret(SECRET_CONTENT); } @Test - public void shouldPassOnlyPost() throws Exception { + void shouldPassOnlyPost() throws Exception { when(req.getMethod()).thenReturn("POST"); new RequirePostWithGHHookPayload.Processor().shouldBePostMethod(req); } - @Test(expected = InvocationTargetException.class) - public void shouldNotPassOnNotPost() throws Exception { + @Test + void shouldNotPassOnNotPost() { when(req.getMethod()).thenReturn("GET"); - new RequirePostWithGHHookPayload.Processor().shouldBePostMethod(req); + assertThrows(InvocationTargetException.class, () -> + new RequirePostWithGHHookPayload.Processor().shouldBePostMethod(req)); } @Test - public void shouldPassOnGHEventAndNotBlankPayload() throws Exception { + void shouldPassOnGHEventAndNotBlankPayload() throws Exception { new RequirePostWithGHHookPayload.Processor().shouldContainParseablePayload( new Object[]{GHEvent.PUSH, "{}"}); } - @Test(expected = InvocationTargetException.class) - public void shouldNotPassOnNullGHEventAndNotBlankPayload() throws Exception { - new RequirePostWithGHHookPayload.Processor().shouldContainParseablePayload( - new Object[]{null, "{}"}); + @Test + void shouldNotPassOnNullGHEventAndNotBlankPayload() { + assertThrows(InvocationTargetException.class, () -> + new RequirePostWithGHHookPayload.Processor().shouldContainParseablePayload( + new Object[]{null, "{}"})); } - @Test(expected = InvocationTargetException.class) - public void shouldNotPassOnGHEventAndBlankPayload() throws Exception { - new RequirePostWithGHHookPayload.Processor().shouldContainParseablePayload( - new Object[]{GHEvent.PUSH, " "}); + @Test + void shouldNotPassOnGHEventAndBlankPayload() { + assertThrows(InvocationTargetException.class, () -> + new RequirePostWithGHHookPayload.Processor().shouldContainParseablePayload( + new Object[]{GHEvent.PUSH, " "})); } - @Test(expected = InvocationTargetException.class) - public void shouldNotPassOnNulls() throws Exception { - new RequirePostWithGHHookPayload.Processor().shouldContainParseablePayload( - new Object[]{null, null}); + @Test + void shouldNotPassOnNulls() { + assertThrows(InvocationTargetException.class, () -> + new RequirePostWithGHHookPayload.Processor().shouldContainParseablePayload( + new Object[]{null, null})); } - @Test(expected = InvocationTargetException.class) - public void shouldNotPassOnGreaterCountOfArgs() throws Exception { - new RequirePostWithGHHookPayload.Processor().shouldContainParseablePayload( - new Object[]{GHEvent.PUSH, "{}", " "} - ); + @Test + void shouldNotPassOnGreaterCountOfArgs() { + assertThrows(InvocationTargetException.class, () -> + new RequirePostWithGHHookPayload.Processor().shouldContainParseablePayload( + new Object[]{GHEvent.PUSH, "{}", " "} + )); } - @Test(expected = InvocationTargetException.class) - public void shouldNotPassOnLessCountOfArgs() throws Exception { - new RequirePostWithGHHookPayload.Processor().shouldContainParseablePayload( - new Object[]{GHEvent.PUSH} - ); + @Test + void shouldNotPassOnLessCountOfArgs() { + assertThrows(InvocationTargetException.class, () -> + new RequirePostWithGHHookPayload.Processor().shouldContainParseablePayload( + new Object[]{GHEvent.PUSH} + )); } @Test @Issue("JENKINS-37481") - public void shouldPassOnAbsentSignatureInRequestIfSecretIsNotConfigured() throws Exception { - doReturn(PAYLOAD).when(processor).payloadFrom(req, null); + void shouldPassOnAbsentSignatureInRequestIfSecretIsNotConfigured() throws Exception { removeSecret(); processor.shouldProvideValidSignature(req, null); } - @Test(expected = InvocationTargetException.class) + @Test @Issue("JENKINS-48012") - public void shouldNotPassOnAbsentSignatureInRequest() throws Exception { - doReturn(PAYLOAD).when(processor).payloadFrom(req, null); - - processor.shouldProvideValidSignature(req, null); + void shouldNotPassOnAbsentSignatureInRequest() { + assertThrows(InvocationTargetException.class, () -> + processor.shouldProvideValidSignature(req, null)); } - @Test(expected = InvocationTargetException.class) - public void shouldNotPassOnInvalidSignature() throws Exception { + @Test + void shouldNotPassOnInvalidSignature() { final String signature = "sha1=a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"; - when(req.getHeader(RequirePostWithGHHookPayload.Processor.SIGNATURE_HEADER)).thenReturn(signature); doReturn(PAYLOAD).when(processor).payloadFrom(req, null); - - processor.shouldProvideValidSignature(req, null); + assertThrows(InvocationTargetException.class, () -> + processor.shouldProvideValidSignature(req, null)); } - @Test(expected = InvocationTargetException.class) - public void shouldNotPassOnMalformedSignature() throws Exception { + @Test + void shouldNotPassOnMalformedSignature() { final String signature = "49d5f5cf800a81f257324912969a2d325d13d3fc"; - when(req.getHeader(RequirePostWithGHHookPayload.Processor.SIGNATURE_HEADER)).thenReturn(signature); doReturn(PAYLOAD).when(processor).payloadFrom(req, null); - - processor.shouldProvideValidSignature(req, null); + assertThrows(InvocationTargetException.class, () -> + processor.shouldProvideValidSignature(req, null)); } @Test - public void shouldPassWithValidSignature() throws Exception { + void shouldPassWithValidSignature() throws Exception { final String signature = "sha1=49d5f5cf800a81f257324912969a2d325d13d3fc"; when(req.getHeader(RequirePostWithGHHookPayload.Processor.SIGNATURE_HEADER)).thenReturn(signature); @@ -143,7 +147,7 @@ public void shouldPassWithValidSignature() throws Exception { @Test @Issue("JENKINS-37481") - public void shouldIgnoreSignHeaderOnNotDefinedSignInConfig() throws Exception { + void shouldIgnoreSignHeaderOnNotDefinedSignInConfig() throws Exception { removeSecret(); final String signature = "sha1=49d5f5cf800a81f257324912969a2d325d13d3fc"; @@ -153,7 +157,7 @@ public void shouldIgnoreSignHeaderOnNotDefinedSignInConfig() throws Exception { } @Test - public void shouldReturnValidPayloadOnApplicationJson() { + void shouldReturnValidPayloadOnApplicationJson() { final String payload = "test"; doReturn(GHEventPayload.PayloadHandler.APPLICATION_JSON).when(req).getContentType(); @@ -164,7 +168,7 @@ public void shouldReturnValidPayloadOnApplicationJson() { } @Test - public void shouldReturnValidPayloadOnFormUrlEncoded() { + void shouldReturnValidPayloadOnFormUrlEncoded() { final String payload = "test"; doReturn(GHEventPayload.PayloadHandler.FORM_URLENCODED).when(req).getContentType(); diff --git a/src/test/java/org/jenkinsci/plugins/github/webhook/WebhookManagerTest.java b/src/test/java/org/jenkinsci/plugins/github/webhook/WebhookManagerTest.java index fcb3462f1..3f68c066f 100644 --- a/src/test/java/org/jenkinsci/plugins/github/webhook/WebhookManagerTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/webhook/WebhookManagerTest.java @@ -11,12 +11,13 @@ import hudson.plugins.git.GitSCM; import org.jenkinsci.plugins.github.GitHubPlugin; import org.jenkinsci.plugins.github.config.GitHubServerConfig; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; 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; import org.kohsuke.github.GHEvent; import org.kohsuke.github.GHHook; import org.kohsuke.github.GHRepository; @@ -24,7 +25,7 @@ import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; import java.net.MalformedURLException; @@ -36,12 +37,12 @@ import static com.google.common.collect.ImmutableList.copyOf; import static com.google.common.collect.Lists.asList; import static com.google.common.collect.Lists.newArrayList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.jenkinsci.plugins.github.test.HookSecretHelper.storeSecretIn; import static org.jenkinsci.plugins.github.webhook.WebhookManager.forHookUrl; -import static org.hamcrest.MatcherAssert.assertThat; import static org.kohsuke.github.GHEvent.CREATE; import static org.kohsuke.github.GHEvent.PULL_REQUEST; import static org.kohsuke.github.GHEvent.PUSH; @@ -51,8 +52,8 @@ import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; @@ -62,15 +63,15 @@ /** * @author lanwen (Merkushev Kirill) */ -@RunWith(MockitoJUnitRunner.class) +@WithJenkins +@ExtendWith(MockitoExtension.class) public class WebhookManagerTest { public static final GitSCM GIT_SCM = new GitSCM("ssh://git@github.com/dummy/dummy.git"); public static final URL HOOK_ENDPOINT = endpoint("http://hook.endpoint/"); public static final URL ANOTHER_HOOK_ENDPOINT = endpoint("http://another.url/"); - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; @Spy private WebhookManager manager = forHookUrl(HOOK_ENDPOINT); @@ -87,15 +88,20 @@ public class WebhookManagerTest { @Captor ArgumentCaptor> captor; + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jenkins = rule; + } + @Test - public void shouldDoNothingOnNoAdminRights() throws Exception { + void shouldDoNothingOnNoAdminRights() throws Exception { manager.unregisterFor(nonactive, newArrayList(active)); verify(manager, never()).withAdminAccess(); verify(manager, never()).fetchHooks(); } @Test - public void shouldSearchBothWebAndServiceHookOnNonActiveName() throws Exception { + void shouldSearchBothWebAndServiceHookOnNonActiveName() throws Exception { doReturn(newArrayList(repo)).when(nonactive).resolve(any(Predicate.class)); when(repo.hasAdminAccess()).thenReturn(true); @@ -107,7 +113,7 @@ public void shouldSearchBothWebAndServiceHookOnNonActiveName() throws Exception } @Test - public void shouldSearchOnlyServiceHookOnActiveName() throws Exception { + void shouldSearchOnlyServiceHookOnActiveName() throws Exception { doReturn(newArrayList(repo)).when(active).resolve(any(Predicate.class)); when(repo.hasAdminAccess()).thenReturn(true); @@ -120,7 +126,7 @@ public void shouldSearchOnlyServiceHookOnActiveName() throws Exception { @Test @WithoutJenkins - public void shouldMatchAdminAccessWhenTrue() throws Exception { + void shouldMatchAdminAccessWhenTrue() throws Exception { when(repo.hasAdminAccess()).thenReturn(true); assertThat("has admin access", manager.withAdminAccess().apply(repo), is(true)); @@ -128,7 +134,7 @@ public void shouldMatchAdminAccessWhenTrue() throws Exception { @Test @WithoutJenkins - public void shouldMatchAdminAccessWhenFalse() throws Exception { + void shouldMatchAdminAccessWhenFalse() throws Exception { when(repo.hasAdminAccess()).thenReturn(false); assertThat("has no admin access", manager.withAdminAccess().apply(repo), is(false)); @@ -136,7 +142,7 @@ public void shouldMatchAdminAccessWhenFalse() throws Exception { @Test @WithoutJenkins - public void shouldMatchWebHook() { + void shouldMatchWebHook() { lenient().when(repo.hasAdminAccess()).thenReturn(false); GHHook hook = hook(HOOK_ENDPOINT, PUSH); @@ -146,7 +152,7 @@ public void shouldMatchWebHook() { @Test @WithoutJenkins - public void shouldNotMatchOtherUrlWebHook() { + void shouldNotMatchOtherUrlWebHook() { lenient().when(repo.hasAdminAccess()).thenReturn(false); GHHook hook = hook(ANOTHER_HOOK_ENDPOINT, PUSH); @@ -156,7 +162,7 @@ public void shouldNotMatchOtherUrlWebHook() { } @Test - public void shouldMergeEventsOnRegisterNewAndDeleteOldOnes() throws IOException { + void shouldMergeEventsOnRegisterNewAndDeleteOldOnes() throws IOException { doReturn(newArrayList(repo)).when(nonactive).resolve(any(Predicate.class)); when(repo.hasAdminAccess()).thenReturn(true); Predicate del = spy(Predicate.class); @@ -172,7 +178,7 @@ public void shouldMergeEventsOnRegisterNewAndDeleteOldOnes() throws IOException } @Test - public void shouldNotReplaceAlreadyRegisteredHook() throws IOException { + void shouldNotReplaceAlreadyRegisteredHook() throws IOException { doReturn(newArrayList(repo)).when(nonactive).resolve(any(Predicate.class)); when(repo.hasAdminAccess()).thenReturn(true); @@ -185,8 +191,8 @@ public void shouldNotReplaceAlreadyRegisteredHook() throws IOException { } @Test - @Issue( "JENKINS-62116" ) - public void shouldNotReplaceAlreadyRegisteredHookWithMoreEvents() throws IOException { + @Issue("JENKINS-62116") + void shouldNotReplaceAlreadyRegisteredHookWithMoreEvents() throws IOException { doReturn(newArrayList(repo)).when(nonactive).resolve(any(Predicate.class)); when(repo.hasAdminAccess()).thenReturn(true); @@ -200,7 +206,7 @@ public void shouldNotReplaceAlreadyRegisteredHookWithMoreEvents() throws IOExcep @Test - public void shouldNotAddPushEventByDefaultForProjectWithoutTrigger() throws IOException { + void shouldNotAddPushEventByDefaultForProjectWithoutTrigger() throws IOException { FreeStyleProject project = jenkins.createFreeStyleProject(); project.setScm(GIT_SCM); @@ -209,7 +215,7 @@ public void shouldNotAddPushEventByDefaultForProjectWithoutTrigger() throws IOEx } @Test - public void shouldAddPushEventByDefault() throws IOException { + void shouldAddPushEventByDefault() throws IOException { FreeStyleProject project = jenkins.createFreeStyleProject(); project.addTrigger(new GitHubPushTrigger()); project.setScm(GIT_SCM); @@ -219,7 +225,7 @@ public void shouldAddPushEventByDefault() throws IOException { } @Test - public void shouldReturnNullOnGettingEmptyEventsListToSubscribe() throws IOException { + void shouldReturnNullOnGettingEmptyEventsListToSubscribe() throws IOException { doReturn(newArrayList(repo)).when(active).resolve(any(Predicate.class)); when(repo.hasAdminAccess()).thenReturn(true); @@ -229,7 +235,7 @@ public void shouldReturnNullOnGettingEmptyEventsListToSubscribe() throws IOExcep } @Test - public void shouldSelectOnlyHookManagedCreds() { + void shouldSelectOnlyHookManagedCreds() { GitHubServerConfig conf = new GitHubServerConfig(""); conf.setManageHooks(false); GitHubPlugin.configuration().getConfigs().add(conf); @@ -239,7 +245,7 @@ public void shouldSelectOnlyHookManagedCreds() { } @Test - public void shouldNotSelectCredsWithCustomHost() { + void shouldNotSelectCredsWithCustomHost() { GitHubServerConfig conf = new GitHubServerConfig(""); conf.setApiUrl(ANOTHER_HOOK_ENDPOINT.toString()); conf.setManageHooks(false); @@ -250,7 +256,7 @@ public void shouldNotSelectCredsWithCustomHost() { } @Test - public void shouldSendSecretIfDefined() throws Exception { + void shouldSendSecretIfDefined() throws Exception { String secretText = "secret_text"; storeSecretIn(GitHubPlugin.configuration(), secretText); diff --git a/src/test/java/org/jenkinsci/plugins/github/webhook/subscriber/DefaultPushGHEventListenerTest.java b/src/test/java/org/jenkinsci/plugins/github/webhook/subscriber/DefaultPushGHEventListenerTest.java index b83e762f7..0a20c01a5 100644 --- a/src/test/java/org/jenkinsci/plugins/github/webhook/subscriber/DefaultPushGHEventListenerTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/webhook/subscriber/DefaultPushGHEventListenerTest.java @@ -7,21 +7,23 @@ import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.plugins.git.GitSCM; -import java.util.Collections; -import java.util.List; import jenkins.model.Jenkins; import org.jenkinsci.plugins.github.extension.GHSubscriberEvent; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; -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.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.github.GHEvent; import org.mockito.MockedStatic; import org.mockito.Mockito; +import java.util.Collections; +import java.util.List; + import static com.cloudbees.jenkins.GitHubWebHookFullTest.classpath; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -35,24 +37,29 @@ /** * @author lanwen (Merkushev Kirill) */ +@WithJenkins public class DefaultPushGHEventListenerTest { public static final GitSCM GIT_SCM_FROM_RESOURCE = new GitSCM("ssh://git@github.com/lanwen/test.git"); public static final String TRIGGERED_BY_USER_FROM_RESOURCE = "lanwen"; - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; + + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jenkins = rule; + } @Test @WithoutJenkins - public void shouldBeNotApplicableForProjectWithoutTrigger() { + void shouldBeNotApplicableForProjectWithoutTrigger() { FreeStyleProject prj = mock(FreeStyleProject.class); assertThat(new DefaultPushGHEventSubscriber().isApplicable(prj), is(false)); } @Test @WithoutJenkins - public void shouldBeApplicableForProjectWithTrigger() { + void shouldBeApplicableForProjectWithTrigger() { FreeStyleProject prj = mock(FreeStyleProject.class); when(prj.getTriggers()).thenReturn( Collections.singletonMap(new GitHubPushTrigger.DescriptorImpl(), new GitHubPushTrigger())); @@ -61,7 +68,7 @@ public void shouldBeApplicableForProjectWithTrigger() { @Test @WithoutJenkins - public void shouldParsePushPayload() { + void shouldParsePushPayload() { GitHubPushTrigger trigger = mock(GitHubPushTrigger.class); FreeStyleProject prj = mock(FreeStyleProject.class); @@ -96,7 +103,7 @@ public void shouldParsePushPayload() { @Test @Issue("JENKINS-27136") - public void shouldReceivePushHookOnWorkflow() throws Exception { + void shouldReceivePushHookOnWorkflow() throws Exception { WorkflowJob job = jenkins.getInstance().createProject(WorkflowJob.class, "test-workflow-job"); GitHubPushTrigger trigger = mock(GitHubPushTrigger.class); @@ -119,7 +126,7 @@ public void shouldReceivePushHookOnWorkflow() throws Exception { @Test @Issue("JENKINS-27136") - public void shouldNotReceivePushHookOnWorkflowWithNoBuilds() throws Exception { + void shouldNotReceivePushHookOnWorkflowWithNoBuilds() throws Exception { WorkflowJob job = jenkins.getInstance().createProject(WorkflowJob.class, "test-workflow-job"); GitHubPushTrigger trigger = mock(GitHubPushTrigger.class); diff --git a/src/test/java/org/jenkinsci/plugins/github/webhook/subscriber/PingGHEventSubscriberTest.java b/src/test/java/org/jenkinsci/plugins/github/webhook/subscriber/PingGHEventSubscriberTest.java index 4d6ae5587..1e29ce021 100644 --- a/src/test/java/org/jenkinsci/plugins/github/webhook/subscriber/PingGHEventSubscriberTest.java +++ b/src/test/java/org/jenkinsci/plugins/github/webhook/subscriber/PingGHEventSubscriberTest.java @@ -1,43 +1,49 @@ package org.jenkinsci.plugins.github.webhook.subscriber; import hudson.model.FreeStyleProject; -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.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.github.GHEvent; import static com.cloudbees.jenkins.GitHubWebHookFullTest.classpath; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import org.jvnet.hudson.test.Issue; /** * @author lanwen (Merkushev Kirill) */ -public class PingGHEventSubscriberTest { +@WithJenkins +class PingGHEventSubscriberTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; + + @BeforeEach + void setUp(JenkinsRule rule) throws Exception { + jenkins = rule; + } @Test - public void shouldBeNotApplicableForProjects() throws Exception { + void shouldBeNotApplicableForProjects() throws Exception { FreeStyleProject prj = jenkins.createFreeStyleProject(); assertThat(new PingGHEventSubscriber().isApplicable(prj), is(false)); } @Test - public void shouldParsePingPayload() throws Exception { + void shouldParsePingPayload() throws Exception { injectedPingSubscr().onEvent(GHEvent.PING, classpath("payloads/ping.json")); } @Issue("JENKINS-30626") @Test @WithoutJenkins - public void shouldParseOrgPingPayload() throws Exception { + void shouldParseOrgPingPayload() throws Exception { new PingGHEventSubscriber().onEvent(GHEvent.PING, classpath("payloads/orgping.json")); } - + private PingGHEventSubscriber injectedPingSubscr() { PingGHEventSubscriber pingSubsc = new PingGHEventSubscriber(); jenkins.getInstance().getInjector().injectMembers(pingSubsc); diff --git a/src/test/resources/org/jenkinsci/plugins/github/test/GHMockRule/repos-repo.json b/src/test/resources/org/jenkinsci/plugins/github/test/GitHubMockExtension/repos-repo.json similarity index 100% rename from src/test/resources/org/jenkinsci/plugins/github/test/GHMockRule/repos-repo.json rename to src/test/resources/org/jenkinsci/plugins/github/test/GitHubMockExtension/repos-repo.json diff --git a/src/test/resources/org/jenkinsci/plugins/github/test/GHMockRule/user.json b/src/test/resources/org/jenkinsci/plugins/github/test/GitHubMockExtension/user.json similarity index 100% rename from src/test/resources/org/jenkinsci/plugins/github/test/GHMockRule/user.json rename to src/test/resources/org/jenkinsci/plugins/github/test/GitHubMockExtension/user.json From 4fe0138c891644cb3ad8d9a258b6c85ed26f887b Mon Sep 17 00:00:00 2001 From: strangelookingnerd <49242855+strangelookingnerd@users.noreply.github.com> Date: Mon, 27 Jan 2025 20:37:39 +0100 Subject: [PATCH 2/3] Bump plugin-pom --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2d0137060..b29642f54 100755 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.jenkins-ci.plugins plugin - 5.2 + 5.6 From e46fdea949aca62022e98b0f64e2d4c8ebeb0dca Mon Sep 17 00:00:00 2001 From: strangelookingnerd <49242855+strangelookingnerd@users.noreply.github.com> Date: Mon, 27 Jan 2025 20:43:24 +0100 Subject: [PATCH 3/3] Fix typo --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b29642f54..7d3dc04a4 100755 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.jenkins-ci.plugins plugin - 5.6 + 5.6