(5);
+
+ for (GHCommitState state : GHCommitState.values()) {
+ String envVar = String.format("ghprb%sMessage", state.name());
+ String message = envVars.get(envVar);
+ statusMessages.add(new GhprbBuildResultMessage(state, message));
+ }
+
+ String context = envVars.get("commitStatusContext");
+
+ if (StringUtils.isEmpty(context)) {
+ context = jobName;
+ }
+
+ statusUpdater = new GhprbSimpleStatus(envVars.get("ghprbCommitStatusContext"), envVars.get("ghprbStatusUrl"), envVars.get("ghprbTriggeredStatus"), envVars.get("ghprbStartedStatus"), statusMessages);
+
+ String credentialsId = envVars.get("ghprbCredentialsId");
+ String repoName = envVars.get("ghprbGhRepository");
+
+ GhprbGitHubAuth auth = GhprbTrigger.getDscp().getGitHubAuth(credentialsId);
+ try {
+ GitHub gh = auth.getConnection(build.getProject());
+ repo = gh.getRepository(repoName);
+ return true;
+ } catch (Exception e) {
+ logger.log(Level.SEVERE, "Unable to connect to GitHub repo", e);
+ return false;
+ }
+
+ }
+
+ // Sets the status as pending when the job starts and then calls the createCommitStatus method to send it to GitHub
+ @Override
+ public Environment setUpEnvironment(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, BuildListener listener) {
+ if (updateEnvironmentVars(build, listener)) {
+ logger.log(Level.FINE, "Job: " + build.getFullDisplayName() + " Attempting to send GitHub commit status");
+
+ try {
+ statusUpdater.onEnvironmentSetup(build, listener, repo);
+ } catch (GhprbCommitStatusException e) {
+ e.printStackTrace();
+ }
+ }
+
+ return new Environment(){};
+ }
+
+ @Override
+ public void onStarted(AbstractBuild, ?> build, TaskListener listener) {
+ if (!updateEnvironmentVars(build, listener)) {
+ return;
+ }
+
+ try {
+ statusUpdater.onBuildStart(build, listener, repo);
+ } catch (GhprbCommitStatusException e) {
+ e.printStackTrace();
+ }
+ }
+
+ // Sets the status to the build result when the job is done, and then calls the createCommitStatus method to send it to GitHub
+ @Override
+ public void onCompleted(AbstractBuild, ?> build, TaskListener listener) {
+ if (!updateEnvironmentVars(build, listener)) {
+ return;
+ }
+
+ try {
+ statusUpdater.onBuildComplete(build, listener, repo);
+ } catch (GhprbCommitStatusException e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbGitHubAuth/config.groovy b/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbGitHubAuth/config.groovy
index 6aefeca56..8bd491efb 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbGitHubAuth/config.groovy
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbGitHubAuth/config.groovy
@@ -5,6 +5,10 @@ f.entry(title:_("GitHub Server API URL"), field:"serverAPIUrl") {
f.textbox()
}
+f.entry(title:_("Jenkins URL override"), field:"jenkinsUrl") {
+ f.textbox()
+}
+
f.entry(title:_("Shared secret"), field:"secret") {
f.password()
}
@@ -12,7 +16,7 @@ f.entry(title:_("Shared secret"), field:"secret") {
f.entry(title:_("Credentials"), field:"credentialsId") {
c.select(onchange="""{
var self = this.targetElement ? this.targetElement : this;
- var r = findPreviousFormItem(self,'serverAPIUrl');
+ var r = findPreviousFormItem(self,'serverAPIUrl','credentialsId');
r.onchange(r);
self = null;
r = null;
@@ -20,12 +24,46 @@ f.entry(title:_("Credentials"), field:"credentialsId") {
}
f.advanced(title:_("Test Credentials")) {
- f.entry(title:_("Test Credentials")) {
- f.validateButton(title:_("Connect to API"), progress:_("Connecting..."), with:"serverAPIUrl,credentialsId", method:"testGithubAccess")
- f.entry(title:_("Repository owner/name"), field:"repo") {
+ f.optionalBlock(title:_("Test basic connection to GitHub")) {
+ f.entry() {
+ f.validateButton(title:_("Connect to API"), progress:_("Connecting..."), with:"serverAPIUrl,credentialsId", method:"testGithubAccess")
+ }
+ }
+
+ f.entry(title:_("Repository owner/name"), field:"repo") {
+ f.textbox()
+ }
+ f.optionalBlock(title:_("Test Permissions to a Repository")) {
+ f.entry() {
+ f.validateButton(title:_("Check repo permissions"), progress:_("Checking..."), with:"serverAPIUrl,credentialsId,repo", method:"checkRepoAccess")
+ }
+ }
+ f.optionalBlock(title:_("Test adding comment to Pull Request")) {
+ f.entry(title:_("Issue ID"), field:"issueId") {
+ f.number()
+ }
+ f.entry(title:_("Comment to post"), field:"message1") {
+ f.textbox()
+ }
+ f.validateButton(title:_("Comment to issue"), progress:_("Commenting..."), with:"serverAPIUrl,credentialsId,repo,issueId,message1", method:"testComment")
+ }
+ f.optionalBlock(title:_("Test updating commit status")) {
+ f.entry(title:_("Commit SHA"), field:"sha1") {
+ f.textbox()
+ }
+ f.entry(title:_("Commit State"), field:"state") {
+ f.select()
+ }
+ f.entry(title:_("Status url"), field:"url") {
+ f.textbox()
+ }
+ f.entry(title:_("Message to post"), field:"message2") {
+ f.textbox()
+ }
+ f.entry(title:_("Context for the status"), field:"context") {
f.textbox()
}
- f.validateButton(title:_("Check repo permissions"), progress:_("Connecting..."), with:"serverAPIUrl,credentialsId,repo", method:"checkRepoAccess")
+ f.validateButton(title:_("Update status"), progress:_("Updating..."), with:"serverAPIUrl,credentialsId,repo,sha1,state,url,message2,context", method:"testUpdateStatus")
}
}
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbGitHubAuth/help-jenkinsUrl.html b/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbGitHubAuth/help-jenkinsUrl.html
new file mode 100644
index 000000000..361b94778
--- /dev/null
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbGitHubAuth/help-jenkinsUrl.html
@@ -0,0 +1,3 @@
+
+ Use this to override the Jenkins URL that GitHub should call.
+
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbPullRequestMerge/config.jelly b/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbPullRequestMerge/config.jelly
index d36347b90..c720ee69c 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbPullRequestMerge/config.jelly
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbPullRequestMerge/config.jelly
@@ -2,13 +2,16 @@
-
-
-
+
+
+
+
+
+
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbPullRequestMerge/global.jelly b/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbPullRequestMerge/global.jelly
index acb0a3d2e..2f5c4993a 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbPullRequestMerge/global.jelly
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbPullRequestMerge/global.jelly
@@ -3,9 +3,6 @@
-
-
-
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbPullRequestMerge/help-onlyTriggerPhrase.html b/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbPullRequestMerge/help-onlyTriggerPhrase.html
deleted file mode 100644
index 6a5ba1cec..000000000
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/GhprbPullRequestMerge/help-onlyTriggerPhrase.html
+++ /dev/null
@@ -1,4 +0,0 @@
-
- When checked, only commenting the trigger phrase in the pull request will trigger a build.
- All other methods of triggering a pull request build are disabled.
-
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/builds/GhprbCancelBuildsOnUpdate/config.jelly b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/builds/GhprbCancelBuildsOnUpdate/config.jelly
new file mode 100644
index 000000000..eb333a89f
--- /dev/null
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/builds/GhprbCancelBuildsOnUpdate/config.jelly
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildLog/config.jelly b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildLog/config.jelly
index 3b79b49b7..22345540d 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildLog/config.jelly
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildLog/config.jelly
@@ -1,5 +1,5 @@
-
+
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildResultMessage/help-message.html b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildResultMessage/help-message.html
index a86712a55..f06228927 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildResultMessage/help-message.html
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildResultMessage/help-message.html
@@ -1,3 +1,5 @@
The message that is appended to a comment when a build finishes with the desired build status.
-
\ No newline at end of file
+ If no status updates should be made when a build finishes with the indicated
+ build status, use "--none--" to alert the trigger.
+
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildStatus/config.jelly b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildStatus/config.jelly
index dcb6b0fe5..0ab4c2b80 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildStatus/config.jelly
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildStatus/config.jelly
@@ -1,5 +1,5 @@
-
+
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildStatus/help-messages.html b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildStatus/help-messages.html
index f99a6a9ce..3c224a0f9 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildStatus/help-messages.html
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/comments/GhprbBuildStatus/help-messages.html
@@ -1,5 +1,5 @@
- Global: Sets a default for each job, but won't be used by default.
+ Global: Sets a default for each job, if the job setup has no entries then this is used.
- Add a text message to the comment appended to the pull request on build completion.
+ Add a text message to the comment posted to the pull request on build completion.
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/config.jelly b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/config.jelly
index 93b5fe8b8..d883f91dd 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/config.jelly
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/config.jelly
@@ -1,17 +1,17 @@
-
+
-
+
-
+
-
+
-
+
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-completedStatus.html b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-completedStatus.html
index 8095eedc4..9d4442d6a 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-completedStatus.html
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-completedStatus.html
@@ -1,4 +1,4 @@
- Use a custom status for when a build is completed.
+ Use a custom status on the commit for when a build is completed.
If the field is left blank then the default value is used instead.
-
\ No newline at end of file
+
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-startedStatus.html b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-startedStatus.html
index 4b6235478..b4e1c9fbb 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-startedStatus.html
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-startedStatus.html
@@ -1,4 +1,5 @@
Use a custom status for when a build is started.
If the field is left blank then the default value is used instead.
-
\ No newline at end of file
+ If no status updates should be made when a build is started, use "--none--" to alert the trigger.
+
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-statusUrl.html b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-statusUrl.html
index af04b3035..82c957c7c 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-statusUrl.html
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-statusUrl.html
@@ -1,3 +1,4 @@
Use a custom url instead of the Jenkins job url.
+ If the desired url should be blank, use "--none--" to alert the trigger to use a blank url.
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-triggeredStatus.html b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-triggeredStatus.html
index f942bd38c..4c32d7185 100644
--- a/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-triggeredStatus.html
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatus/help-triggeredStatus.html
@@ -1,4 +1,5 @@
Use a custom status for when a build is triggered.
If the field is left blank then the default value is used instead.
-
\ No newline at end of file
+ If no status updates should be made when a build is triggered, use "--none--" to alert the trigger.
+
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/config.jelly b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/config.jelly
new file mode 100644
index 000000000..d883f91dd
--- /dev/null
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/config.jelly
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-commitStatusContext.html b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-commitStatusContext.html
new file mode 100644
index 000000000..f9f488e71
--- /dev/null
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-commitStatusContext.html
@@ -0,0 +1,4 @@
+
+
Context:
+ A string label to differentiate this status from the status of other systems. Default: "default"
+
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-completedStatus.html b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-completedStatus.html
new file mode 100644
index 000000000..0301c9968
--- /dev/null
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-completedStatus.html
@@ -0,0 +1,4 @@
+
+ Use a custom status on the commit for when a build is completed.
+ If the field is left blank then the default value is used instead.
+
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-startedStatus.html b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-startedStatus.html
new file mode 100644
index 000000000..4b6235478
--- /dev/null
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-startedStatus.html
@@ -0,0 +1,4 @@
+
+ Use a custom status for when a build is started.
+ If the field is left blank then the default value is used instead.
+
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-statusUrl.html b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-statusUrl.html
new file mode 100644
index 000000000..82c957c7c
--- /dev/null
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-statusUrl.html
@@ -0,0 +1,4 @@
+
+ Use a custom url instead of the Jenkins job url.
+ If the desired url should be blank, use "--none--" to alert the trigger to use a blank url.
+
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-triggeredStatus.html b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-triggeredStatus.html
new file mode 100644
index 000000000..f942bd38c
--- /dev/null
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help-triggeredStatus.html
@@ -0,0 +1,4 @@
+
+ Use a custom status for when a build is triggered.
+ If the field is left blank then the default value is used instead.
+
\ No newline at end of file
diff --git a/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help.html b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help.html
new file mode 100644
index 000000000..664d45aec
--- /dev/null
+++ b/src/main/resources/org/jenkinsci/plugins/ghprb/upstream/GhprbUpstreamStatus/help.html
@@ -0,0 +1,8 @@
+
+ Allows you to set a custom context and message on a pull request pulled using GHPRB.
+
This will add the context and message to the pull request found in the upstream job NOT on any pull requests taken on this job
+
To add a custom context and message on any pull requests on THIS job see the GHPRB section in the Build Triggers section
+
+
IMPORTANT:
+
This will only work if you configure a upstream job that uses the Github Pull Request Builder Plugin
+
\ No newline at end of file
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/GeneralTest.java b/src/test/java/org/jenkinsci/plugins/ghprb/GeneralTest.java
new file mode 100644
index 000000000..7a62ce65e
--- /dev/null
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/GeneralTest.java
@@ -0,0 +1,72 @@
+package org.jenkinsci.plugins.ghprb;
+
+import static org.fest.assertions.Assertions.assertThat;
+
+import java.util.List;
+
+import org.jenkinsci.plugins.ghprb.extensions.build.GhprbCancelBuildsOnUpdate;
+import org.jenkinsci.plugins.ghprb.extensions.comments.GhprbBuildLog;
+import org.jenkinsci.plugins.ghprb.extensions.comments.GhprbBuildResultMessage;
+import org.jenkinsci.plugins.ghprb.extensions.comments.GhprbBuildStatus;
+import org.jenkinsci.plugins.ghprb.extensions.comments.GhprbCommentFile;
+import org.jenkinsci.plugins.ghprb.extensions.status.GhprbSimpleStatus;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.runners.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class GeneralTest {
+
+ private void checkClassForGetters(Class> clazz) {
+ List errors = GhprbTestUtil.checkClassForGetters(clazz);
+ assertThat(errors).isEmpty();
+ }
+
+ @Test
+ public void checkTriggerForGetters() {
+ checkClassForGetters(GhprbTrigger.class);
+ }
+
+ @Test
+ public void checkTriggerDescriptorForGetters() {
+ checkClassForGetters(GhprbTrigger.DescriptorImpl.class);
+ }
+
+ @Test
+ public void checkPullRequestMergeForGetters() {
+ checkClassForGetters(GhprbPullRequestMerge.class);
+ }
+
+ @Test
+ public void checkBuildLogForGetters() {
+ checkClassForGetters(GhprbBuildLog.class);
+ }
+
+
+ @Test
+ public void checkBuildResultMessageForGetters() {
+ checkClassForGetters(GhprbBuildResultMessage.class);
+ }
+
+ @Test
+ public void checkBuildStatusForGetters() {
+ checkClassForGetters(GhprbBuildStatus.class);
+ }
+
+ @Test
+ public void checkCommentFileForGetters() {
+ checkClassForGetters(GhprbCommentFile.class);
+ }
+
+
+ @Test
+ public void checkSimpleStatusForGetters() {
+ checkClassForGetters(GhprbSimpleStatus.class);
+ }
+
+ @Test
+ public void checkCancelBuildsOnUpdateForGetters() {
+ checkClassForGetters(GhprbCancelBuildsOnUpdate.class);
+ }
+
+}
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbIT.java b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbIT.java
index e79527e8d..155437197 100644
--- a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbIT.java
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbIT.java
@@ -1,10 +1,8 @@
package org.jenkinsci.plugins.ghprb;
-import com.coravy.hudson.plugins.github.GithubProjectProperty;
import com.google.common.collect.Lists;
import hudson.model.FreeStyleProject;
-import hudson.plugins.git.GitSCM;
import org.joda.time.DateTime;
import org.junit.Before;
@@ -16,17 +14,13 @@
import org.kohsuke.github.GHIssueComment;
import org.kohsuke.stapler.RequestImpl;
import org.mockito.Mock;
+import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import static com.google.common.collect.Lists.newArrayList;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.any;
@RunWith(MockitoJUnitRunner.class)
public class GhprbIT extends GhprbITBaseTestCase {
@@ -36,38 +30,23 @@ public class GhprbIT extends GhprbITBaseTestCase {
@Mock
private RequestImpl req;
+ @Mock
+ private GHIssueComment comment;
+
+
+ private FreeStyleProject project;
+
@Before
- public void setUp() throws Exception {
- // GhprbTestUtil.mockGithubUserPage();
- super.beforeTest();
+ public void setUp() throws Exception {// GIVEN
+ project = jenkinsRule.createFreeStyleProject("PRJ");
+ super.beforeTest(null, null, project);
}
@Test
public void shouldBuildTriggersOnNewPR() throws Exception {
- // GIVEN
- FreeStyleProject project = jenkinsRule.createFreeStyleProject("PRJ");
- GhprbTrigger trigger = GhprbTestUtil.getTrigger(null);
- given(commitPointer.getSha()).willReturn("sha");
- GhprbTestUtil.setupGhprbTriggerDescriptor(null);
- project.addProperty(new GithubProjectProperty("https://github.com/user/dropwizard"));
given(ghPullRequest.getNumber()).willReturn(1);
-
- // Creating spy on ghprb, configuring repo
- Ghprb ghprb = spy(trigger.createGhprb(project));
- doReturn(ghprbGitHub).when(ghprb).getGitHub();
- ghprb.getRepository().setHelper(ghprb);
-
- // Configuring and adding Ghprb trigger
- project.addTrigger(trigger);
-
- // Configuring Git SCM
- GitSCM scm = GhprbTestUtil.provideGitSCM();
- project.setScm(scm);
-
- trigger.start(project, true);
- trigger.setHelper(ghprb);
-
+
GhprbTestUtil.triggerRunAndWait(10, trigger, project);
assertThat(project.getBuilds().toArray().length).isEqualTo(1);
@@ -76,22 +55,11 @@ public void shouldBuildTriggersOnNewPR() throws Exception {
@Test
public void shouldBuildTriggersOnUpdatingNewCommitsPR() throws Exception {
// GIVEN
- FreeStyleProject project = jenkinsRule.createFreeStyleProject("PRJ");
- GhprbTrigger trigger = GhprbTestUtil.getTrigger(null);
- given(commitPointer.getSha()).willReturn("sha").willReturn("sha").willReturn("newOne").willReturn("newOne");
+ given(commitPointer.getSha()).willReturn("sha").willReturn("newOne").willReturn("newOne");
given(ghPullRequest.getComments()).willReturn(Lists. newArrayList());
- GhprbTestUtil.setupGhprbTriggerDescriptor(null);
- project.addProperty(new GithubProjectProperty("https://github.com/user/dropwizard"));
+
given(ghPullRequest.getNumber()).willReturn(2).willReturn(2).willReturn(3).willReturn(3);
- Ghprb ghprb = spy(trigger.createGhprb(project));
- doReturn(ghprbGitHub).when(ghprb).getGitHub();
- trigger.start(project, true);
- trigger.setHelper(ghprb);
- ghprb.getRepository().setHelper(ghprb);
- project.addTrigger(trigger);
- GitSCM scm = GhprbTestUtil.provideGitSCM();
- project.setScm(scm);
-
+
GhprbTestUtil.triggerRunAndWait(10, trigger, project);
assertThat(project.getBuilds().toArray().length).isEqualTo(2);
@@ -100,29 +68,17 @@ public void shouldBuildTriggersOnUpdatingNewCommitsPR() throws Exception {
@Test
public void shouldBuildTriggersOnUpdatingRetestMessagePR() throws Exception {
// GIVEN
- FreeStyleProject project = jenkinsRule.createFreeStyleProject("PRJ");
- GhprbTrigger trigger = GhprbTestUtil.getTrigger(null);
-
- given(commitPointer.getSha()).willReturn("sha");
-
- GHIssueComment comment = mock(GHIssueComment.class);
+ GhprbTestUtil.triggerRunAndWait(10, trigger, project);
+ assertThat(project.getBuilds().toArray().length).isEqualTo(1);
+
given(comment.getBody()).willReturn("retest this please");
given(comment.getUpdatedAt()).willReturn(new DateTime().plusDays(1).toDate());
given(comment.getUser()).willReturn(ghUser);
+
given(ghPullRequest.getComments()).willReturn(newArrayList(comment));
given(ghPullRequest.getNumber()).willReturn(5).willReturn(5);
- GhprbTestUtil.setupGhprbTriggerDescriptor(null);
- project.addProperty(new GithubProjectProperty("https://github.com/user/dropwizard"));
-
- Ghprb ghprb = spy(trigger.createGhprb(project));
- doReturn(ghprbGitHub).when(ghprb).getGitHub();
- trigger.start(project, true);
- trigger.setHelper(ghprb);
- ghprb.getRepository().setHelper(ghprb);
- project.addTrigger(trigger);
- GitSCM scm = GhprbTestUtil.provideGitSCM();
- project.setScm(scm);
+
GhprbTestUtil.triggerRunAndWait(10, trigger, project);
assertThat(project.getBuilds().toArray().length).isEqualTo(2);
}
@@ -131,35 +87,26 @@ public void shouldBuildTriggersOnUpdatingRetestMessagePR() throws Exception {
@Test
public void shouldNotBuildDisabledBuild() throws Exception {
// GIVEN
- FreeStyleProject project = jenkinsRule.createFreeStyleProject("PRJ");
- GhprbTrigger trigger = GhprbTestUtil.getTrigger(null);
-
+
given(commitPointer.getSha()).willReturn("sha");
- GHIssueComment comment = mock(GHIssueComment.class);
given(comment.getBody()).willReturn("retest this please");
given(comment.getUpdatedAt()).willReturn(new DateTime().plusDays(1).toDate());
given(comment.getUser()).willReturn(ghUser);
given(ghPullRequest.getComments()).willReturn(newArrayList(comment));
given(ghPullRequest.getNumber()).willReturn(5);
- GhprbTestUtil.setupGhprbTriggerDescriptor(null);
- project.addProperty(new GithubProjectProperty("https://github.com/user/dropwizard"));
-
- Ghprb ghprb = spy(trigger.createGhprb(project));
- doReturn(ghprbGitHub).when(ghprb).getGitHub();
- trigger.start(project, true);
- trigger.setHelper(ghprb);
- ghprb.getRepository().setHelper(ghprb);
- project.addTrigger(trigger);
- GitSCM scm = GhprbTestUtil.provideGitSCM();
- project.setScm(scm);
project.disable();
GhprbTestUtil.triggerRunAndWait(10, trigger, project);
assertThat(project.getBuilds().toArray().length).isEqualTo(0);
- verify(ghRepository, times(0)).createCommitStatus(any(String.class), any(GHCommitState.class), any(String.class), any(String.class));
+ Mockito.verify(ghRepository, Mockito.times(0)).createCommitStatus(any(String.class), any(GHCommitState.class), any(String.class), any(String.class));
+ }
+
+ @Test
+ public void triggerIsRemovedFromListWhenProjectChanges() {
+
}
}
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbITBaseTestCase.java b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbITBaseTestCase.java
index c0bb1a97b..30c85304a 100644
--- a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbITBaseTestCase.java
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbITBaseTestCase.java
@@ -1,11 +1,17 @@
package org.jenkinsci.plugins.ghprb;
import static com.google.common.collect.Lists.newArrayList;
-import static org.kohsuke.github.GHIssueState.OPEN;
import static org.mockito.BDDMockito.given;
+import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
+
+import java.util.Map;
+
+import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
+import hudson.model.TaskListener;
+import hudson.plugins.git.GitSCM;
import org.joda.time.DateTime;
import org.kohsuke.github.GHCommitPointer;
@@ -16,6 +22,9 @@
import org.kohsuke.github.GitHub;
import org.mockito.Mock;
import org.mockito.Mockito;
+import org.kohsuke.github.GHIssueState;
+
+import com.coravy.hudson.plugins.github.GithubProjectProperty;
/**
* @author mdelapenya (Manuel de la Peña)
@@ -33,43 +42,77 @@ public abstract class GhprbITBaseTestCase {
@Mock
protected GHUser ghUser;
@Mock
- protected GitHub gitHub;
+ protected Ghprb helper;
+ @Mock
+ protected GhprbPullRequest ghprbPullRequest;
+
+ protected GhprbBuilds builds;
+
+ protected GhprbTrigger trigger;
// Stubs
protected GHRateLimit ghRateLimit = new GHRateLimit();
- protected void beforeTest() throws Exception {
- given(ghprbGitHub.get()).willReturn(gitHub);
- given(gitHub.getRateLimit()).willReturn(ghRateLimit);
+ protected void beforeTest(Map globalConfig, Map triggerConfig, AbstractProject, ?> project) throws Exception {
+ project.addProperty(new GithubProjectProperty("https://github.com/user/dropwizard"));
+ GhprbTestUtil.setupGhprbTriggerDescriptor(globalConfig);
+
+ trigger = GhprbTestUtil.getTrigger(triggerConfig);
+
+ GitHub gitHub = trigger.getGitHub();
+
given(gitHub.getRepository(anyString())).willReturn(ghRepository);
+
+ given(ghPullRequest.getHead()).willReturn(commitPointer);
+ given(ghPullRequest.getUser()).willReturn(ghUser);
+
given(commitPointer.getRef()).willReturn("ref");
+ given(commitPointer.getSha()).willReturn("sha");
+
given(ghRepository.getName()).willReturn("dropwizard");
GhprbTestUtil.mockPR(ghPullRequest, commitPointer, new DateTime(), new DateTime().plusDays(1));
+
- given(ghRepository.getPullRequests(eq(OPEN))).willReturn(newArrayList(ghPullRequest)).willReturn(newArrayList(ghPullRequest));
+ given(ghRepository.getPullRequests(eq(GHIssueState.OPEN))).willReturn(newArrayList(ghPullRequest)).willReturn(newArrayList(ghPullRequest));
+ given(ghRepository.getPullRequest(Mockito.anyInt())).willReturn(ghPullRequest);
- given(ghPullRequest.getUser()).willReturn(ghUser);
given(ghUser.getEmail()).willReturn("email@email.com");
given(ghUser.getLogin()).willReturn("user");
ghRateLimit.remaining = GhprbTestUtil.INITIAL_RATE_LIMIT;
GhprbTestUtil.mockCommitList(ghPullRequest);
- }
+
- protected void setRepositoryHelper(Ghprb ghprb) {
- ghprb.getRepository().setHelper(ghprb);
- }
+ GhprbRepository repo = Mockito.spy(new GhprbRepository("user/dropwizard", trigger));
+ Mockito.doReturn(ghRepository).when(repo).getGitHubRepo();
+ Mockito.doNothing().when(repo).addComment(Mockito.anyInt(), Mockito.anyString(), any(AbstractBuild.class), any(TaskListener.class));
+ Mockito.doReturn(ghprbPullRequest).when(repo).getPullRequest(Mockito.anyInt());
+
+ Mockito.doReturn(repo).when(trigger).getRepository();
- protected void setTriggerHelper(GhprbTrigger trigger, Ghprb ghprb) {
- trigger.setHelper(ghprb);
- }
+ builds = new GhprbBuilds(trigger, repo);
- protected Ghprb spyCreatingGhprb(GhprbTrigger trigger, AbstractProject, ?> project) {
+ // Creating spy on ghprb, configuring repo
+ given(helper.getGitHub()).willReturn(ghprbGitHub);
+ given(helper.getTrigger()).willReturn(trigger);
+ given(helper.isWhitelisted(ghUser)).willReturn(true);
+ given(helper.getBuilds()).willReturn(builds);
+
+
+ Mockito.doCallRealMethod().when(trigger).run();
- return Mockito.spy(trigger.createGhprb(project));
- }
+ // Configuring and adding Ghprb trigger
+ project.addTrigger(trigger);
+
+ // Configuring Git SCM
+ GitSCM scm = GhprbTestUtil.provideGitSCM();
+ project.setScm(scm);
+
+ trigger.start(project, true);
+ trigger.setHelper(helper);
+ }
}
\ No newline at end of file
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbPullRequestMergeTest.java b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbPullRequestMergeTest.java
index ff56c0b08..c9d17ac3f 100644
--- a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbPullRequestMergeTest.java
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbPullRequestMergeTest.java
@@ -26,6 +26,7 @@
import org.kohsuke.github.GHPullRequest;
import org.kohsuke.github.GHPullRequestCommitDetail;
import org.kohsuke.github.GHPullRequestCommitDetail.Commit;
+import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GHUser;
import org.kohsuke.github.GitUser;
import org.kohsuke.github.PagedIterable;
@@ -44,6 +45,8 @@
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class GhprbPullRequestMergeTest {
@@ -64,11 +67,15 @@ public class GhprbPullRequestMergeTest {
@Mock
private GHUser triggerSender;
@Mock
+ private GHUser prCreator;
+ @Mock
private GhprbCause cause;
@Mock
private Ghprb helper;
@Mock
private GhprbRepository repo;
+ @Mock
+ private GHRepository ghRepo;
@Mock
private StreamBuildListener listener;
@@ -86,6 +93,9 @@ public class GhprbPullRequestMergeTest {
private final String committerName = "committer";
private final String nonCommitterName = "noncommitter";
+
+ private final String committerEmail = "committer@mail.com";
+ private final String nonCommitterEmail = "noncommitter@mail.com";
private final String mergeComment = "merge";
@@ -99,13 +109,22 @@ public void beforeTest() throws Exception {
triggerValues.put("adminlist", adminList);
triggerValues.put("triggerPhrase", triggerPhrase);
- GhprbTrigger trigger = spy(GhprbTestUtil.getTrigger(triggerValues));
+ GhprbTrigger trigger = GhprbTestUtil.getTrigger(triggerValues);
+ Mockito.doReturn(repo).when(trigger).getRepository();
ConcurrentMap pulls = new ConcurrentHashMap(1);
+
pulls.put(pullId, pullRequest);
Map> jobs = new HashMap>(1);
jobs.put("project", pulls);
+ Mockito.doReturn(project).when(trigger).getActualProject();
+ Mockito.doReturn(repo).when(trigger).getRepository();
+ repo.addPullRequests(pulls);
+ Mockito.doReturn(pullRequest).when(repo).getPullRequest(pullId);
+ Mockito.doReturn(pr).when(repo).getActualPullRequest(pullId);
+
+
GithubProjectProperty projectProperty = new GithubProjectProperty("https://github.com/jenkinsci/ghprb-plugin");
DescriptorImpl descriptor = trigger.getDescriptor();
@@ -123,7 +142,7 @@ public void beforeTest() throws Exception {
given(build.getResult()).willReturn(Result.SUCCESS);
given(build.getParent()).willCallRealMethod();
- given(pullRequest.getPullRequest()).willReturn(pr);
+ given(pullRequest.getPullRequest(Mockito.anyBoolean())).willReturn(pr);
given(cause.getPullID()).willReturn(pullId);
given(cause.isMerged()).willReturn(true);
@@ -143,9 +162,8 @@ public void beforeTest() throws Exception {
jobsField.setAccessible(true);
jobsField.set(descriptor, jobs);
- helper = spy(new Ghprb(project, trigger, pulls));
+ helper = spy(new Ghprb(trigger));
trigger.setHelper(helper);
- given(helper.getRepository()).willReturn(repo);
given(helper.isBotUser(any(GHUser.class))).willReturn(false);
}
@@ -155,10 +173,14 @@ public void afterClass() {
}
@SuppressWarnings("unchecked")
- private void setupConditions(String triggerLogin, String committerName, String comment) throws IOException {
+ private void setupConditions(String prUserLogin, String triggerLogin, String committerName, String committerEmail, String comment) throws IOException {
given(triggerSender.getLogin()).willReturn(triggerLogin);
given(triggerSender.getName()).willReturn(committerName);
+ given(triggerSender.getEmail()).willReturn(committerEmail);
given(committer.getName()).willReturn(this.committerName);
+
+ given(prCreator.getLogin()).willReturn(prUserLogin);
+ given(pr.getUser()).willReturn(prCreator);
PagedIterator itr = Mockito.mock(PagedIterator.class);
PagedIterable pagedItr = Mockito.mock(PagedIterable.class);
@@ -178,129 +200,173 @@ private void setupConditions(String triggerLogin, String committerName, String c
given(cause.getCommentBody()).willReturn(comment);
}
-
- private GhprbPullRequestMerge setupMerger(boolean onlyTriggerPhrase, boolean onlyAdminsMerge, boolean disallowOwnCode) {
- GhprbPullRequestMerge merger = spy(new GhprbPullRequestMerge(mergeComment, onlyTriggerPhrase, onlyAdminsMerge, disallowOwnCode));
+
+ private void setupConditions(String triggerLogin, String committerName, String committerEmail, String comment) throws IOException {
+ setupConditions(nonCommitterName, triggerLogin, committerName, committerEmail, comment);
+ }
+
+ private GhprbPullRequestMerge setupMerger(
+ boolean onlyAdminsMerge,
+ boolean disallowOwnCode,
+ boolean failOnNonMerge,
+ boolean deleteOnMerge
+ ) {
+
+ GhprbPullRequestMerge merger = spy(new GhprbPullRequestMerge(
+ mergeComment,
+ onlyAdminsMerge,
+ disallowOwnCode,
+ failOnNonMerge,
+ deleteOnMerge));
merger.setHelper(helper);
+ Mockito.reset(pr);
return merger;
}
+ private GhprbPullRequestMerge setupMerger(
+ boolean onlyAdminsMerge,
+ boolean disallowOwnCode) {
+ return setupMerger(onlyAdminsMerge, disallowOwnCode, false, false);
+ }
+
@Test
public void testApproveMerge() throws Exception {
- boolean onlyTriggerPhrase = false;
boolean onlyAdminsMerge = false;
boolean disallowOwnCode = false;
- GhprbPullRequestMerge merger = setupMerger(onlyTriggerPhrase, onlyAdminsMerge, disallowOwnCode);
+ GhprbPullRequestMerge merger = setupMerger(onlyAdminsMerge, disallowOwnCode);
- setupConditions(nonAdminLogin, committerName, triggerPhrase);
+ setupConditions(nonAdminLogin, committerName, committerEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(1)).merge(mergeComment);
- setupConditions(adminLogin, nonCommitterName, triggerPhrase);
+ setupConditions(adminLogin, nonCommitterName, nonCommitterEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(2)).merge(mergeComment);
- setupConditions(adminLogin, committerName, nonTriggerPhrase);
+ setupConditions(adminLogin, committerName, committerEmail, nonTriggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(2)).merge(mergeComment);
- setupConditions(nonAdminLogin, nonCommitterName, triggerPhrase);
+ setupConditions(nonAdminLogin, nonCommitterName, nonCommitterEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(3)).merge(mergeComment);
- setupConditions(nonAdminLogin, nonCommitterName, nonTriggerPhrase);
+ setupConditions(nonAdminLogin, nonCommitterName, nonCommitterEmail, nonTriggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(3)).merge(mergeComment);
- setupConditions(adminLogin, nonCommitterName, nonTriggerPhrase);
+ setupConditions(adminLogin, nonCommitterName, nonCommitterEmail, nonTriggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(3)).merge(mergeComment);
- setupConditions(nonAdminLogin, nonCommitterName, nonTriggerPhrase);
+ setupConditions(nonAdminLogin, nonCommitterName, nonCommitterEmail, nonTriggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(3)).merge(mergeComment);
- setupConditions(adminLogin, committerName, triggerPhrase);
+ setupConditions(adminLogin, committerName, committerEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(4)).merge(mergeComment);
}
@Test
public void testAdminMerge() throws Exception {
- boolean onlyTriggerPhrase = false;
boolean onlyAdminsMerge = true;
boolean disallowOwnCode = false;
- GhprbPullRequestMerge merger = setupMerger(onlyTriggerPhrase, onlyAdminsMerge, disallowOwnCode);
+ GhprbPullRequestMerge merger = setupMerger(onlyAdminsMerge, disallowOwnCode);
- setupConditions(adminLogin, committerName, triggerPhrase);
+ setupConditions(adminLogin, committerName, committerEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(1)).merge(mergeComment);
- setupConditions(nonAdminLogin, committerName, triggerPhrase);
+ setupConditions(nonAdminLogin, committerName, committerEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(false);
+ verify(pr, times(1)).merge(mergeComment);
}
@Test
public void testTriggerMerge() throws Exception {
- boolean onlyTriggerPhrase = true;
boolean onlyAdminsMerge = false;
boolean disallowOwnCode = false;
- GhprbPullRequestMerge merger = setupMerger(onlyTriggerPhrase, onlyAdminsMerge, disallowOwnCode);
+ GhprbPullRequestMerge merger = setupMerger(onlyAdminsMerge, disallowOwnCode);
- setupConditions(adminLogin, committerName, triggerPhrase);
+ setupConditions(adminLogin, committerName, committerEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(1)).merge(mergeComment);
- setupConditions(adminLogin, committerName, nonTriggerPhrase);
- assertThat(merger.perform(build, null, listener)).isEqualTo(false);
+ setupConditions(adminLogin, committerName, committerEmail, nonTriggerPhrase);
+ assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(1)).merge(mergeComment);
}
@Test
public void testOwnCodeMerge() throws Exception {
- boolean onlyTriggerPhrase = false;
boolean onlyAdminsMerge = false;
boolean disallowOwnCode = true;
- GhprbPullRequestMerge merger = setupMerger(onlyTriggerPhrase, onlyAdminsMerge, disallowOwnCode);
+ GhprbPullRequestMerge merger = setupMerger(onlyAdminsMerge, disallowOwnCode);
- setupConditions(adminLogin, nonCommitterName, triggerPhrase);
+ setupConditions(adminLogin, nonCommitterName, nonCommitterEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(1)).merge(mergeComment);
- setupConditions(adminLogin, committerName, triggerPhrase);
+ setupConditions(adminLogin, committerName, committerEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(false);
+ verify(pr, times(1)).merge(mergeComment);
}
@Test
public void testDenyMerge() throws Exception {
- boolean onlyTriggerPhrase = true;
boolean onlyAdminsMerge = true;
boolean disallowOwnCode = true;
- GhprbPullRequestMerge merger = setupMerger(onlyTriggerPhrase, onlyAdminsMerge, disallowOwnCode);
+ GhprbPullRequestMerge merger = setupMerger(onlyAdminsMerge, disallowOwnCode);
- setupConditions(nonAdminLogin, nonCommitterName, triggerPhrase);
+ setupConditions(nonAdminLogin, nonAdminLogin, nonCommitterName, nonCommitterEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(false);
+ verify(pr, times(0)).merge(mergeComment);
- setupConditions(adminLogin, committerName, triggerPhrase);
+ setupConditions(nonAdminLogin, adminLogin, committerName, committerEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(false);
+ verify(pr, times(0)).merge(mergeComment);
- setupConditions(adminLogin, nonCommitterName, nonTriggerPhrase);
- assertThat(merger.perform(build, null, listener)).isEqualTo(false);
+ setupConditions(nonAdminLogin, adminLogin, nonCommitterName, nonCommitterEmail, nonTriggerPhrase);
+ assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(0)).merge(mergeComment);
- setupConditions(nonAdminLogin, nonCommitterName, triggerPhrase);
+ setupConditions(nonAdminLogin, nonAdminLogin, nonCommitterName, nonCommitterEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(false);
+ verify(pr, times(0)).merge(mergeComment);
- setupConditions(nonAdminLogin, nonCommitterName, nonTriggerPhrase);
- assertThat(merger.perform(build, null, listener)).isEqualTo(false);
+ setupConditions(nonAdminLogin, nonAdminLogin, nonCommitterName, nonCommitterEmail, nonTriggerPhrase);
+ assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(0)).merge(mergeComment);
- setupConditions(adminLogin, committerName, nonTriggerPhrase);
- assertThat(merger.perform(build, null, listener)).isEqualTo(false);
+ setupConditions(nonAdminLogin, adminLogin, committerName, committerEmail, nonTriggerPhrase);
+ assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(0)).merge(mergeComment);
- setupConditions(nonAdminLogin, committerName, nonTriggerPhrase);
+ setupConditions(nonAdminLogin, nonAdminLogin, committerName, committerEmail, nonTriggerPhrase);
+ assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(0)).merge(mergeComment);
+
+ setupConditions(adminLogin, adminLogin, nonCommitterName, nonCommitterEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(false);
+ verify(pr, times(0)).merge(mergeComment);
- setupConditions(adminLogin, nonCommitterName, triggerPhrase);
+ setupConditions(nonAdminLogin, adminLogin, nonCommitterName, nonCommitterEmail, triggerPhrase);
assertThat(merger.perform(build, null, listener)).isEqualTo(true);
+ verify(pr, times(1)).merge(mergeComment);
+
}
}
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbPullRequestTest.java b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbPullRequestTest.java
index fccf277d3..e34a4c18d 100644
--- a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbPullRequestTest.java
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbPullRequestTest.java
@@ -1,11 +1,14 @@
package org.jenkinsci.plugins.ghprb;
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kohsuke.github.GHCommitPointer;
import org.kohsuke.github.GHPullRequest;
+import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GHUser;
import org.mockito.Mock;
+import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.IOException;
@@ -14,6 +17,7 @@
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
@@ -33,33 +37,54 @@ public class GhprbPullRequestTest {
private Ghprb helper;
@Mock
private GhprbRepository repo;
-
- @Test
- public void testConstructorWhenAuthorIsWhitelisted() throws IOException {
- // GIVEN
- GHUser ghUser = mock(GHUser.class);
- GHCommitPointer head = mock(GHCommitPointer.class);
- GHCommitPointer base = mock(GHCommitPointer.class);
+ @Mock
+ private GHCommitPointer head, base;
+ @Mock
+ private GhprbRepository ghprbRepository;
+ @Mock
+ private GHUser ghUser;
+ @Mock
+ private GhprbBuilds builds;
+
+ @Before
+ public void setup() throws IOException {
given(head.getSha()).willReturn("some sha");
given(base.getRef()).willReturn("some ref");
// Mocks for GHPullRequest
given(pr.getNumber()).willReturn(10);
+ given(pr.getCreatedAt()).willReturn(new Date());
given(pr.getUpdatedAt()).willReturn(new Date());
given(pr.getTitle()).willReturn("title");
given(pr.getHead()).willReturn(head);
given(pr.getBase()).willReturn(base);
- given(pr.getUser()).willReturn(ghUser);
+
given(ghUser.getEmail()).willReturn("email");
-
+
+ given(ghprbRepository.getActualPullRequest(10)).willReturn(pr);
+ given(ghprbRepository.getName()).willReturn("name");
+
+ given(pr.getHead()).willReturn(head);
+ given(pr.getUser()).willReturn(ghUser);
+
+ // Mocks for Ghprb
+ given(helper.isWhitelisted(ghUser)).willReturn(true);
+ given(helper.getBuilds()).willReturn(builds);
+
+ doNothing().when(builds).build(any(GhprbPullRequest.class), any(GHUser.class), anyString());
+
// Mocks for GhprbRepository
given(repo.getName()).willReturn("repoName");
- // Mocks for Ghprb
- given(helper.isWhitelisted(ghUser)).willReturn(true);
+ // Mocks for GhprbRepository
+ doNothing().when(repo).addComment(Mockito.anyInt(), anyString());
+ }
+
+ @Test
+ public void testConstructorWhenAuthorIsWhitelisted() throws IOException {
// WHEN
- GhprbPullRequest ghprbPullRequest = new GhprbPullRequest(pr, helper, repo);
+ GhprbPullRequest ghprbPullRequest = new GhprbPullRequest(pr, helper, repo, false);
// THEN
assertThat(ghprbPullRequest.getId()).isEqualTo(10);
@@ -72,75 +97,66 @@ public void testConstructorWhenAuthorIsWhitelisted() throws IOException {
@Test
public void testInitRepoNameNull() throws IOException {
- // GIVEN
- GHUser ghUser = mock(GHUser.class);
- GHCommitPointer head = mock(GHCommitPointer.class);
- GHCommitPointer base = mock(GHCommitPointer.class);
-
- // Mocks for GHPullRequest
- given(pr.getNumber()).willReturn(10);
- given(pr.getUpdatedAt()).willReturn(new Date());
- given(pr.getTitle()).willReturn("title");
- given(pr.getHead()).willReturn(head);
- given(pr.getBase()).willReturn(base);
- given(head.getSha()).willReturn("some sha");
- given(base.getRef()).willReturn("some ref");
- given(pr.getUser()).willReturn(ghUser);
- given(ghUser.getEmail()).willReturn("email");
- // Mocks for GhprbRepository
given(repo.getName()).willReturn(null);
- doNothing().when(repo).addComment(eq(10), anyString());
- // Mocks for Ghprb
- given(helper.isWhitelisted(ghUser)).willReturn(true);
-
- GhprbPullRequest ghprbPullRequest = new GhprbPullRequest(pr, helper, repo);
- GhprbRepository ghprbRepository = mock(GhprbRepository.class);
- given(ghprbRepository.getName()).willReturn("name");
+ GhprbPullRequest ghprbPullRequest = new GhprbPullRequest(pr, helper, repo, false);
// WHEN
ghprbPullRequest.init(helper, ghprbRepository);
// THEN
- verify(ghprbRepository, times(1)).getName();
+ verify(pr, times(1)).getHead();
+ verify(pr, times(1)).getBase();
+ verify(pr, times(1)).getNumber();
+ verify(pr, times(1)).getCreatedAt();
+ verify(pr, times(3)).getUser();
+ Mockito.verifyNoMoreInteractions(pr);
}
@Test
public void testInitRepoNameNotNull() throws IOException {
- // GIVEN
- GHUser ghUser = mock(GHUser.class);
- GHCommitPointer head = mock(GHCommitPointer.class);
- GHCommitPointer base = mock(GHCommitPointer.class);
-
- // Mocks for GHPullRequest
- given(pr.getNumber()).willReturn(10);
- given(pr.getUpdatedAt()).willReturn(new Date());
- given(pr.getTitle()).willReturn("title");
- given(pr.getHead()).willReturn(head);
- given(pr.getBase()).willReturn(base);
- given(head.getSha()).willReturn("some sha");
- given(base.getRef()).willReturn("some ref");
- given(pr.getUser()).willReturn(ghUser);
- given(ghUser.getEmail()).willReturn("email");
// Mocks for GhprbRepository
given(repo.getName()).willReturn("name");
doNothing().when(repo).addComment(eq(10), anyString());
- // Mocks for Ghprb
- given(helper.isWhitelisted(ghUser)).willReturn(true);
-
- GhprbPullRequest ghprbPullRequest = new GhprbPullRequest(pr, helper, repo);
- GhprbRepository ghprbRepository = mock(GhprbRepository.class);
- given(ghprbRepository.getName()).willReturn("name");
+ GhprbPullRequest ghprbPullRequest = new GhprbPullRequest(pr, helper, repo, false);
// WHEN
ghprbPullRequest.init(helper, ghprbRepository);
// THEN
verify(ghprbRepository, never()).getName();
+ Mockito.verifyNoMoreInteractions(ghprbRepository);
+ }
+
+ @Test
+ public void authorRepoGitUrlShouldBeNullWhenNoRepository() throws Exception {
+ // GIVEN
+
+ GhprbPullRequest ghprbPullRequest = new GhprbPullRequest(pr, helper, repo, false);
+
+ // WHEN
+ ghprbPullRequest.init(helper, ghprbRepository);
+
+ // THEN
+ assertThat(ghprbPullRequest.getAuthorRepoGitUrl()).isEqualTo("");
}
+ @Test
+ public void authorRepoGitUrlShouldBeSetWhenRepository() throws Exception {
+ // GIVEN
+ String expectedAuthorRepoGitUrl = "https://github.com/jenkinsci/ghprb-plugin";
+ GHRepository repository = mock(GHRepository.class);
+ given(repository.gitHttpTransportUrl()).willReturn(expectedAuthorRepoGitUrl);
+
+ given(head.getRepository()).willReturn(repository);
+
+ GhprbPullRequest ghprbPullRequest = new GhprbPullRequest(pr, helper, repo, false);
+
+ // THEN
+ assertThat(ghprbPullRequest.getAuthorRepoGitUrl()).isEqualTo(expectedAuthorRepoGitUrl);
+ }
}
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbRepositoryTest.java b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbRepositoryTest.java
index 8011fdae5..3a519f8ae 100644
--- a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbRepositoryTest.java
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbRepositoryTest.java
@@ -24,9 +24,14 @@
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
+import com.coravy.hudson.plugins.github.GithubProjectProperty;
+
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
+
+import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
+import hudson.model.TaskListener;
import hudson.model.queue.QueueTaskFuture;
import java.io.FileNotFoundException;
@@ -48,7 +53,6 @@
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
-import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.reset;
@@ -65,8 +69,7 @@
@RunWith(MockitoJUnitRunner.class)
public class GhprbRepositoryTest {
- private static final String TEST_USER_NAME = "test-user";
- private static final String TEST_REPO_NAME = "test-repo";
+ private static final String TEST_REPO_NAME = "test-user/test-repo";
private static final Date UPDATE_DATE = new Date();
private static final String msg = "Build triggered. sha1 is merged.";
@@ -99,16 +102,29 @@ public class GhprbRepositoryTest {
public JenkinsRule jenkinsRule = new JenkinsRule();
@Before
- @SuppressWarnings("unused")
public void setUp() throws Exception {
AbstractProject, ?> project = jenkinsRule.createFreeStyleProject("GhprbRepoTest");
- trigger = spy(GhprbTestUtil.getTrigger(null));
- doReturn(mock(QueueTaskFuture.class)).when(trigger).startJob(any(GhprbCause.class), any(GhprbRepository.class));
+ project.addProperty(new GithubProjectProperty("https://github.com/" + TEST_REPO_NAME));
+ trigger = GhprbTestUtil.getTrigger(null);
+ doReturn(gt).when(trigger).getGitHub();
+
+ given(gt.getRepository(anyString())).willReturn(ghRepository);
+
+ trigger.start(project, true);
+ trigger.setHelper(helper);
+
+
+ pulls = new ConcurrentHashMap();
+
+
+ doReturn(mock(QueueTaskFuture.class)).when(trigger).scheduleBuild(any(GhprbCause.class), any(GhprbRepository.class));
initGHPRWithTestData();
+
+ given(ghPullRequest.getUser()).willReturn(ghUser);
// Mock github API
given(helper.getGitHub()).willReturn(gitHub);
- given(gitHub.get()).willReturn(gt);
+ given(helper.getTrigger()).willReturn(trigger);
given(gt.getRepository(anyString())).willReturn(ghRepository);
// Mock rate limit
@@ -118,9 +134,13 @@ public void setUp() throws Exception {
}
- private void addSimpleStatus() throws IOException {
+ private void addSimpleStatus() {
GhprbSimpleStatus status = new GhprbSimpleStatus("default");
- trigger.getExtensions().remove(GhprbSimpleStatus.class);
+ try {
+ trigger.getExtensions().remove(GhprbSimpleStatus.class);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
trigger.getExtensions().add(status);
}
@@ -130,6 +150,7 @@ public void testCheckMethodWhenUsingGitHubEnterprise() throws IOException {
given(gt.getRateLimit()).willThrow(new FileNotFoundException());
List ghPullRequests = createListWithMockPR();
given(ghRepository.getPullRequests(eq(GHIssueState.OPEN))).willReturn(ghPullRequests);
+ given(ghRepository.getPullRequest(ghPullRequest.getId())).willReturn(ghPullRequest);
mockHeadAndBase();
mockCommitList();
@@ -145,7 +166,7 @@ public void testCheckMethodWhenUsingGitHubEnterprise() throws IOException {
ghprbRepository.check();
// THEN
- verifyGetGithub(1);
+ verifyGetGithub(2, 0);
}
@Test
@@ -153,13 +174,16 @@ public void testCheckMethodWithOnlyExistingPRs() throws IOException {
// GIVEN
List ghPullRequests = createListWithMockPR();
given(ghRepository.getPullRequests(eq(GHIssueState.OPEN))).willReturn(ghPullRequests);
+ given(ghRepository.getPullRequest(Mockito.anyInt())).willReturn(ghPullRequest);
+ doReturn(ghRepository).when(ghprbRepository).getGitHubRepo();
mockHeadAndBase();
mockCommitList();
given(helper.ifOnlyTriggerPhrase()).willReturn(true);
pulls.put(1, ghprbPullRequest);
+ ghprbRepository.addPullRequests(pulls);
given(ghPullRequest.getUpdatedAt()).willReturn(UPDATE_DATE);
given(ghPullRequest.getNumber()).willReturn(1);
@@ -168,23 +192,25 @@ public void testCheckMethodWithOnlyExistingPRs() throws IOException {
ghprbRepository.check();
// THEN
- verifyGetGithub(1);
+ verifyGetGithub(2, 1);
/** GH Repo verifications */
verify(ghRepository, only()).getPullRequests(OPEN); // Call to Github API
verifyNoMoreInteractions(ghRepository);
/** GH PR verifications */
- verify(ghPullRequest, times(3)).getHead();
- verify(ghPullRequest, times(1)).getBase();
+ verify(ghPullRequest, times(2)).getHead();
verify(ghPullRequest, times(2)).getNumber();
verify(ghPullRequest, times(1)).getUpdatedAt();
- verify(ghPullRequest, times(1)).getBody();
+ verify(ghPullRequest, times(1)).getCreatedAt();
+ verify(ghPullRequest, times(1)).getUser();
+ verify(ghPullRequest, times(1)).getBase();
verifyNoMoreInteractions(ghPullRequest);
verify(helper).ifOnlyTriggerPhrase();
verify(helper).getWhiteListTargetBranches();
- verify(helper, times(3)).isProjectDisabled();
+ verify(helper, times(2)).isProjectDisabled();
+ verify(helper).checkSkipBuild(eq(ghPullRequest));
verifyNoMoreInteractions(helper);
verifyNoMoreInteractions(gt);
@@ -211,7 +237,9 @@ public void testCheckMethodWithNewPR() throws IOException {
given(ghPullRequest.getUser()).willReturn(ghUser);
given(ghPullRequest.getHtmlUrl()).willReturn(new URL("https://github.com/org/repo/pull/100"));
given(ghPullRequest.getApiURL()).willReturn(new URL("https://github.com/org/repo/pull/100"));
-
+ given(ghPullRequest.getId()).willReturn(100);
+ given(ghRepository.getPullRequest(ghPullRequest.getId())).willReturn(ghPullRequest);
+
given(ghUser.getEmail()).willReturn("email");
given(helper.ifOnlyTriggerPhrase()).willReturn(false);
@@ -222,33 +250,36 @@ public void testCheckMethodWithNewPR() throws IOException {
ghprbRepository.check();
// THEN
-
- verifyGetGithub(1);
+ verifyGetGithub(2, 1);
verifyNoMoreInteractions(gt);
/** GH PR verifications */
verify(builds, times(1)).build(any(GhprbPullRequest.class), any(GHUser.class), any(String.class));
verify(ghRepository, times(1)).getPullRequests(OPEN); // Call to Github API
- verify(ghRepository, times(1)).createCommitStatus(eq("head sha"), eq(PENDING), isNull(String.class), eq(msg), eq("default")); // Call to Github API
+ verify(ghRepository, times(1)).createCommitStatus(eq("head sha"), eq(PENDING), eq(""), eq(msg), eq("default")); // Call to Github API
+ verify(ghRepository, times(1)).getPullRequest(Mockito.anyInt());
verifyNoMoreInteractions(ghRepository);
verify(ghPullRequest, times(1)).getTitle();
- verify(ghPullRequest, times(2)).getUser();
+ verify(ghPullRequest, times(6)).getUser();
verify(ghPullRequest, times(1)).getMergeable(); // Call to Github API
- verify(ghPullRequest, times(8)).getHead();
- verify(ghPullRequest, times(3)).getBase();
+ verify(ghPullRequest, times(7)).getHead();
+ verify(ghPullRequest, times(4)).getBase();
verify(ghPullRequest, times(5)).getNumber();
- verify(ghPullRequest, times(3)).getUpdatedAt();
+ verify(ghPullRequest, times(2)).getUpdatedAt();
+ verify(ghPullRequest, times(1)).getCreatedAt();
verify(ghPullRequest, times(1)).getHtmlUrl();
verify(ghPullRequest, times(1)).listCommits();
- verify(ghPullRequest, times(2)).getBody();
+ verify(ghPullRequest, times(1)).getBody();
+ verify(ghPullRequest, times(1)).getId();
verifyNoMoreInteractions(ghPullRequest);
verify(helper, times(1)).isWhitelisted(eq(ghUser)); // Call to Github API
verify(helper, times(2)).ifOnlyTriggerPhrase();
verify(helper, times(1)).getBuilds();
verify(helper, times(2)).getWhiteListTargetBranches();
- verify(helper, times(5)).isProjectDisabled();
+ verify(helper, times(4)).isProjectDisabled();
+ verify(helper, times(2)).checkSkipBuild(eq(ghPullRequest));
verifyNoMoreInteractions(helper);
verify(ghUser, times(1)).getEmail(); // Call to Github API
@@ -272,19 +303,22 @@ public void testCheckMethodWhenPrWasUpdatedWithNonKeyPhrase() throws IOException
mockCommitList();
GhprbBuilds builds = mockBuilds();
- Date now = new Date();
+ Date later = new DateTime().plusHours(3).toDate();
Date tomorrow = new DateTime().plusDays(1).toDate();
given(ghRepository.getPullRequests(eq(GHIssueState.OPEN))).willReturn(ghPullRequests);
- given(ghPullRequest.getUpdatedAt()).willReturn(now).willReturn(now).willReturn(tomorrow);
+
+ given(ghPullRequest.getUpdatedAt()).willReturn(later).willReturn(tomorrow);
given(ghPullRequest.getNumber()).willReturn(100);
given(ghPullRequest.getMergeable()).willReturn(true);
given(ghPullRequest.getTitle()).willReturn("title");
given(ghPullRequest.getUser()).willReturn(ghUser);
given(ghPullRequest.getHtmlUrl()).willReturn(new URL("https://github.com/org/repo/pull/100"));
given(ghPullRequest.getApiURL()).willReturn(new URL("https://github.com/org/repo/pull/100"));
-
+ given(ghPullRequest.getId()).willReturn(100);
+ given(ghRepository.getPullRequest(ghPullRequest.getId())).willReturn(ghPullRequest);
+
given(ghUser.getEmail()).willReturn("email");
given(ghUser.getLogin()).willReturn("login");
@@ -299,27 +333,30 @@ public void testCheckMethodWhenPrWasUpdatedWithNonKeyPhrase() throws IOException
ghprbRepository.check(); // PR was updated
// THEN
- verifyGetGithub(2);
+ verifyGetGithub(2, 1);
verifyNoMoreInteractions(gt);
/** GH PR verifications */
verify(builds, times(1)).build(any(GhprbPullRequest.class), any(GHUser.class), any(String.class));
verify(ghRepository, times(2)).getPullRequests(eq(OPEN)); // Call to Github API
- verify(ghRepository, times(1)).createCommitStatus(eq("head sha"), eq(PENDING), isNull(String.class), eq(msg), eq("default")); // Call to Github API
+ verify(ghRepository, times(1)).createCommitStatus(eq("head sha"), eq(PENDING), eq(""), eq(msg), eq("default")); // Call to Github API
+ verify(ghRepository, times(1)).getPullRequest(Mockito.anyInt());
verifyNoMoreInteractions(ghRepository);
- verify(ghPullRequest, times(2)).getTitle();
- verify(ghPullRequest, times(2)).getUser();
+ verify(ghPullRequest, times(1)).getTitle();
+ verify(ghPullRequest, times(6)).getUser();
verify(ghPullRequest, times(1)).getMergeable(); // Call to Github API
- verify(ghPullRequest, times(8)).getHead();
- verify(ghPullRequest, times(3)).getBase();
+ verify(ghPullRequest, times(9)).getHead();
+ verify(ghPullRequest, times(6)).getBase();
verify(ghPullRequest, times(5)).getNumber();
verify(ghPullRequest, times(1)).getHtmlUrl();
- verify(ghPullRequest, times(3)).getUpdatedAt();
+ verify(ghPullRequest, times(2)).getUpdatedAt();
+ verify(ghPullRequest, times(1)).getCreatedAt();
- verify(ghPullRequest, times(1)).getComments();
+ verify(ghPullRequest, times(2)).getComments();
verify(ghPullRequest, times(1)).listCommits();
- verify(ghPullRequest, times(2)).getBody();
+ verify(ghPullRequest, times(1)).getBody();
+ verify(ghPullRequest, times(1)).getId();
verifyNoMoreInteractions(ghPullRequest);
verify(helper, times(1)).isWhitelisted(eq(ghUser)); // Call to Github API
@@ -332,15 +369,19 @@ public void testCheckMethodWhenPrWasUpdatedWithNonKeyPhrase() throws IOException
verify(helper).isOktotestPhrase(eq("comment body"));
verify(helper).isRetestPhrase(eq("comment body"));
verify(helper).isTriggerPhrase(eq("comment body"));
- verify(helper, times(6)).isProjectDisabled();
+ verify(helper, times(4)).isProjectDisabled();
+ verify(helper, times(2)).checkSkipBuild(eq(ghPullRequest));
verifyNoMoreInteractions(helper);
verify(ghUser, times(1)).getEmail(); // Call to Github API
verify(ghUser, times(1)).getLogin();
+ verify(ghUser, times(1)).getName();
verifyNoMoreInteractions(ghUser);
}
- private List createListWithMockPR() {
+ private List createListWithMockPR() throws IOException {
+
+ given(ghPullRequest.getCreatedAt()).willReturn(new Date());
List ghPullRequests = new ArrayList();
ghPullRequests.add(ghPullRequest);
return ghPullRequests;
@@ -357,15 +398,17 @@ public void testCheckMethodWhenPrWasUpdatedWithRetestPhrase() throws IOException
mockCommitList();
GhprbBuilds builds = mockBuilds();
- given(ghRepository.getPullRequests(eq(GHIssueState.OPEN))).willReturn(ghPullRequests);
- given(ghPullRequest.getUpdatedAt()).willReturn(now).willReturn(now).willReturn(tomorrow);
+ given(ghPullRequest.getUpdatedAt()).willReturn(now).willReturn(tomorrow);
given(ghPullRequest.getNumber()).willReturn(100);
given(ghPullRequest.getMergeable()).willReturn(true);
given(ghPullRequest.getTitle()).willReturn("title");
given(ghPullRequest.getUser()).willReturn(ghUser);
given(ghPullRequest.getHtmlUrl()).willReturn(new URL("https://github.com/org/repo/pull/100"));
given(ghPullRequest.getApiURL()).willReturn(new URL("https://github.com/org/repo/pull/100"));
-
+ given(ghPullRequest.getId()).willReturn(100);
+ given(ghRepository.getPullRequest(ghPullRequest.getId())).willReturn(ghPullRequest);
+ given(ghRepository.getPullRequests(eq(GHIssueState.OPEN))).willReturn(ghPullRequests);
+
given(ghUser.getEmail()).willReturn("email");
given(ghUser.getLogin()).willReturn("login");
@@ -381,7 +424,7 @@ public void testCheckMethodWhenPrWasUpdatedWithRetestPhrase() throws IOException
ghprbRepository.check(); // PR was updated
// THEN
- verifyGetGithub(2);
+ verifyGetGithub(2, 1);
verifyNoMoreInteractions(gt);
/** GH PR verifications */
@@ -389,18 +432,21 @@ public void testCheckMethodWhenPrWasUpdatedWithRetestPhrase() throws IOException
verifyNoMoreInteractions(builds);
verify(ghRepository, times(2)).getPullRequests(eq(OPEN)); // Call to Github API
- verify(ghRepository, times(2)).createCommitStatus(eq("head sha"), eq(PENDING), isNull(String.class), eq(msg), eq("default")); // Call to Github API
+ verify(ghRepository, times(2)).createCommitStatus(eq("head sha"), eq(PENDING), eq(""), eq(msg), eq("default")); // Call to Github API
+ verify(ghRepository, times(1)).getPullRequest(Mockito.anyInt());
verifyNoMoreInteractions(ghRepository);
verify(ghPullRequest, times(2)).getTitle();
- verify(ghPullRequest, times(2)).getUser();
+ verify(ghPullRequest, times(7)).getUser();
verify(ghPullRequest, times(2)).getMergeable(); // Call to Github API
- verify(ghPullRequest, times(8)).getHead();
- verify(ghPullRequest, times(3)).getBase();
+ verify(ghPullRequest, times(10)).getHead();
+ verify(ghPullRequest, times(6)).getBase();
verify(ghPullRequest, times(5)).getNumber();
- verify(ghPullRequest, times(3)).getUpdatedAt();
- verify(ghPullRequest, times(1)).getHtmlUrl();
+ verify(ghPullRequest, times(2)).getUpdatedAt();
+ verify(ghPullRequest, times(1)).getCreatedAt();
+ verify(ghPullRequest, times(2)).getHtmlUrl();
+ verify(ghPullRequest, times(1)).getId();
verify(ghPullRequest, times(1)).getComments();
verify(ghPullRequest, times(2)).listCommits();
@@ -416,11 +462,13 @@ public void testCheckMethodWhenPrWasUpdatedWithRetestPhrase() throws IOException
verify(helper).isOktotestPhrase(eq("test this please"));
verify(helper).isRetestPhrase(eq("test this please"));
verify(helper).isAdmin(eq(ghUser));
- verify(helper, times(6)).isProjectDisabled();
+ verify(helper, times(4)).isProjectDisabled();
+ verify(helper, times(2)).checkSkipBuild(eq(ghPullRequest));
verifyNoMoreInteractions(helper);
verify(ghUser, times(1)).getEmail(); // Call to Github API
verify(ghUser, times(1)).getLogin();
+ verify(ghUser, times(1)).getName();
verifyNoMoreInteractions(ghUser);
verify(builds, times(2)).build(any(GhprbPullRequest.class), any(GHUser.class), any(String.class));
@@ -459,18 +507,18 @@ public void testCheckMethodWithNoPR() throws IOException {
// GIVEN
List ghPullRequests = new ArrayList();
given(ghRepository.getPullRequests(eq(GHIssueState.OPEN))).willReturn(ghPullRequests);
+ given(ghRepository.getPullRequest(ghPullRequest.getId())).willReturn(ghPullRequest);
// WHEN
ghprbRepository.check();
- verify(helper).isProjectDisabled();
+ verify(trigger).isActive();
// THEN
- verifyGetGithub(1);
+ verifyGetGithub(2, 1);
verifyNoMoreInteractions(gt);
verify(ghRepository, times(1)).getPullRequests(OPEN); // Call to Github API
- verifyNoMoreInteractions(ghRepository);
- verifyZeroInteractions(helper);
+ verifyNoMoreInteractions(helper, ghRepository);
}
@Test
@@ -482,9 +530,8 @@ public void testExceedRateLimit() throws IOException {
ghprbRepository.check();
// THEN
- verify(helper, only()).getGitHub();
- verify(gitHub, only()).get();
- verify(gt, only()).getRateLimit();
+ verify(trigger, times(2)).getGitHub();
+ verifyGetGithub(2, 0);
verifyZeroInteractions(ghRepository);
verifyZeroInteractions(gitHub);
verifyZeroInteractions(gt);
@@ -497,9 +544,16 @@ public void testSignature() throws IOException, InvalidKeyException, NoSuchAlgor
String actualSignature = createSHA1Signature(actualSecret, body);
String fakeSignature = createSHA1Signature("abc", body);
+ GhprbGitHubAuth ghAuth = Mockito.spy(new GhprbGitHubAuth("", "", "", "", "", actualSecret));
+ doReturn(true).when(trigger).isActive();
+
+ doReturn(ghAuth).when(trigger).getGitHubApiAuth();
+
Assert.assertFalse(actualSignature.equals(fakeSignature));
- Assert.assertTrue(GhprbWebHook.checkSignature(body, actualSignature, actualSecret));
- Assert.assertFalse(GhprbWebHook.checkSignature(body, fakeSignature, actualSecret));
+ Assert.assertTrue(actualSecret.equals(ghAuth.getSecret()));
+
+ Assert.assertTrue(trigger.matchSignature(body, actualSignature));
+ Assert.assertFalse(trigger.matchSignature(body, fakeSignature));
}
private String createSHA1Signature(String secret, String body) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
@@ -527,10 +581,15 @@ private void initGHPRWithTestData() throws IOException {
given(ghPullRequest.getHead()).willReturn(head);
given(head.getSha()).willReturn("head sha");
- pulls = new ConcurrentHashMap();
- ghprbRepository = new GhprbRepository(TEST_USER_NAME, TEST_REPO_NAME, helper, pulls);
- ghprbPullRequest = new GhprbPullRequest(ghPullRequest, helper, ghprbRepository);
+ ghprbRepository = spy(new GhprbRepository(TEST_REPO_NAME, trigger));
+ Mockito.doNothing().when(ghprbRepository).addComment(Mockito.anyInt(), anyString());
+ Mockito.doNothing().when(ghprbRepository).addComment(Mockito.anyInt(), anyString(), any(AbstractBuild.class), any(TaskListener.class));
+
+ doReturn(ghprbRepository).when(trigger).getRepository();
+
+ ghprbPullRequest = new GhprbPullRequest(ghPullRequest, helper, ghprbRepository, false);
+
// Reset mocks not to mix init data invocations with tests
reset(ghPullRequest, ghUser, helper, head, base);
}
@@ -540,10 +599,9 @@ private void increaseRateLimitToDefaults() {
}
// Verifications
- private void verifyGetGithub(int callsCount) throws IOException {
- verify(helper, times(callsCount)).getGitHub();
- verify(gitHub, times(callsCount)).get(); // Call to Github API (once, than cached)
- verify(gt, times(1)).getRepository(anyString()); // Call to Github API
+ private void verifyGetGithub(int callsCount, int repoTimes) throws IOException {
+ verify(trigger, times(callsCount)).getGitHub();
verify(gt, times(callsCount)).getRateLimit();
+ verify(gt, times(repoTimes)).getRepository(anyString());
}
}
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbRootActionTest.java b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbRootActionTest.java
index 033fc2fc3..afcb41968 100644
--- a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbRootActionTest.java
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbRootActionTest.java
@@ -7,6 +7,7 @@
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
+import java.io.Reader;
import java.io.StringReader;
import java.net.URLEncoder;
@@ -17,13 +18,15 @@
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import org.kohsuke.github.GHCommitPointer;
+import org.kohsuke.github.GHEventPayload.IssueComment;
+import org.kohsuke.github.GHIssueComment;
import org.kohsuke.github.GHPullRequest;
-import org.kohsuke.github.GHRateLimit;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GHUser;
import org.kohsuke.github.GitHub;
import org.kohsuke.stapler.StaplerRequest;
import org.mockito.Mock;
+import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.coravy.hudson.plugins.github.GithubProjectProperty;
@@ -54,10 +57,6 @@ public class GhprbRootActionTest {
@Mock
protected GHUser ghUser;
- protected GitHub gitHub;
- // Stubs
- protected GHRateLimit ghRateLimit = new GHRateLimit();
-
@Rule
public JenkinsRule jenkinsRule = new JenkinsRule();
@@ -66,13 +65,18 @@ public class GhprbRootActionTest {
private StaplerRequest req;
private BufferedReader br;
+
+ private GhprbTrigger trigger;
+
+
+ private final int prId = 1;
@Before
public void setup() throws Exception {
- gitHub = spy(GitHub.connectAnonymously());
- given(ghprbGitHub.get()).willReturn(gitHub);
- given(gitHub.getRateLimit()).willReturn(ghRateLimit);
- doReturn(ghRepository).when(gitHub).getRepository(anyString());
+ trigger = GhprbTestUtil.getTrigger();
+ GitHub gitHub = trigger.getGitHub();
+
+ given(gitHub.getRepository(anyString())).willReturn(ghRepository);
given(commitPointer.getRef()).willReturn("ref");
given(ghRepository.getName()).willReturn("dropwizard");
@@ -83,8 +87,8 @@ public void setup() throws Exception {
given(ghPullRequest.getUser()).willReturn(ghUser);
given(ghUser.getEmail()).willReturn("email@email.com");
given(ghUser.getLogin()).willReturn("user");
+ given(ghUser.getName()).willReturn("User");
- ghRateLimit.remaining = GhprbTestUtil.INITIAL_RATE_LIMIT;
GhprbTestUtil.mockCommitList(ghPullRequest);
}
@@ -93,28 +97,35 @@ public void setup() throws Exception {
public void testUrlEncoded() throws Exception {
// GIVEN
FreeStyleProject project = jenkinsRule.createFreeStyleProject("testUrlEncoded");
- GhprbTrigger trigger = spy(GhprbTestUtil.getTrigger(null));
+
+ doReturn(project).when(trigger).getActualProject();
+ doReturn(true).when(trigger).getUseGitHubHooks();
+
given(commitPointer.getSha()).willReturn("sha1");
GhprbTestUtil.setupGhprbTriggerDescriptor(null);
project.addProperty(new GithubProjectProperty("https://github.com/user/dropwizard"));
- given(ghPullRequest.getNumber()).willReturn(1);
- Ghprb ghprb = spy(trigger.createGhprb(project));
+ given(ghPullRequest.getId()).willReturn(prId);
+ given(ghPullRequest.getNumber()).willReturn(prId);
+ given(ghRepository.getPullRequest(prId)).willReturn(ghPullRequest);
+ Ghprb ghprb = spy(new Ghprb(trigger));
doReturn(ghprbGitHub).when(ghprb).getGitHub();
+ doReturn(true).when(ghprb).isAdmin(Mockito.any(GHUser.class));
+
trigger.start(project, true);
trigger.setHelper(ghprb);
- ghprb.getRepository().setHelper(ghprb);
+
project.addTrigger(trigger);
GitSCM scm = GhprbTestUtil.provideGitSCM();
project.setScm(scm);
GhprbTestUtil.triggerRunAndWait(10, trigger, project);
- assertThat(project.getBuilds().toArray().length).isEqualTo(1);
-
- doReturn(gitHub).when(trigger).getGitHub();
+ assertThat(project.getBuilds().toArray().length).isEqualTo(0);
BufferedReader br = new BufferedReader(new StringReader(
"payload=" + URLEncoder.encode(GhprbTestUtil.PAYLOAD, "UTF-8")));
+
+
given(req.getContentType()).willReturn("application/x-www-form-urlencoded");
given(req.getParameter("payload")).willReturn(GhprbTestUtil.PAYLOAD);
@@ -122,27 +133,44 @@ public void testUrlEncoded() throws Exception {
given(req.getReader()).willReturn(br);
given(req.getCharacterEncoding()).willReturn("UTF-8");
+
+ StringReader brTest = new StringReader(GhprbTestUtil.PAYLOAD);
+
+ IssueComment issueComment = spy(GitHub.connectAnonymously().parseEventPayload(brTest, IssueComment.class));
+ brTest.close();
+
+ GHIssueComment ghIssueComment = spy(issueComment.getComment());
+
+ Mockito.when(issueComment.getComment()).thenReturn(ghIssueComment);
+ Mockito.when(ghIssueComment.getUser()).thenReturn(ghUser);
+
+
+ given(trigger.getGitHub().parseEventPayload(Mockito.any(Reader.class), Mockito.eq(IssueComment.class))).willReturn(issueComment);
+
GhprbRootAction ra = new GhprbRootAction();
ra.doIndex(req, null);
GhprbTestUtil.waitForBuildsToFinish(project);
- assertThat(project.getBuilds().toArray().length).isEqualTo(2);
+ assertThat(project.getBuilds().toArray().length).isEqualTo(1);
}
@Test
public void disabledJobsDontBuild() throws Exception {
// GIVEN
FreeStyleProject project = jenkinsRule.createFreeStyleProject("disabledJobsDontBuild");
- GhprbTrigger trigger = spy(GhprbTestUtil.getTrigger(null));
+ doReturn(project).when(trigger).getActualProject();
+
given(commitPointer.getSha()).willReturn("sha1");
GhprbTestUtil.setupGhprbTriggerDescriptor(null);
project.addProperty(new GithubProjectProperty("https://github.com/user/dropwizard"));
- given(ghPullRequest.getNumber()).willReturn(1);
- Ghprb ghprb = spy(trigger.createGhprb(project));
+ given(ghPullRequest.getId()).willReturn(prId);
+ given(ghPullRequest.getNumber()).willReturn(prId);
+ given(ghRepository.getPullRequest(prId)).willReturn(ghPullRequest);
+ Ghprb ghprb = spy(new Ghprb(trigger));
doReturn(ghprbGitHub).when(ghprb).getGitHub();
trigger.start(project, true);
trigger.setHelper(ghprb);
- ghprb.getRepository().setHelper(ghprb);
+
project.addTrigger(trigger);
GitSCM scm = GhprbTestUtil.provideGitSCM();
project.setScm(scm);
@@ -153,8 +181,6 @@ public void disabledJobsDontBuild() throws Exception {
project.disable();
- doReturn(gitHub).when(trigger).getGitHub();
-
BufferedReader br = new BufferedReader(new StringReader(
"payload=" + URLEncoder.encode(GhprbTestUtil.PAYLOAD, "UTF-8")));
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbTestUtil.java b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbTestUtil.java
index 381ea1b02..e7410d653 100644
--- a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbTestUtil.java
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbTestUtil.java
@@ -15,16 +15,28 @@
package org.jenkinsci.plugins.ghprb;
import static com.google.common.collect.Lists.newArrayList;
+import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
import java.net.URL;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import org.codehaus.plexus.util.StringUtils;
import org.joda.time.DateTime;
+import org.junit.Test;
import org.kohsuke.github.GHCommitPointer;
import org.kohsuke.github.GHPullRequest;
+import org.kohsuke.github.GHRateLimit;
+import org.kohsuke.github.GitHub;
import org.kohsuke.github.PagedIterable;
import org.kohsuke.github.PagedIterator;
import org.kohsuke.stapler.BindInterceptor;
@@ -37,6 +49,7 @@
import hudson.plugins.git.UserRemoteConfig;
import net.sf.json.JSONObject;
import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.spy;
public class GhprbTestUtil {
@@ -345,6 +358,11 @@ public static GitSCM provideGitSCM() {
null);
}
+
+ public static GhprbTrigger getTrigger() throws Exception {
+ return getTrigger(null);
+ }
+
public static GhprbTrigger getTrigger(Map values) throws Exception {
setupReq();
if (values == null) {
@@ -369,7 +387,15 @@ public static GhprbTrigger getTrigger(Map values) throws Excepti
defaults.put(next.getKey(), next.getValue());
}
- GhprbTrigger trigger = req.bindJSON(GhprbTrigger.class, defaults);
+ GhprbTrigger trigger = spy(req.bindJSON(GhprbTrigger.class, defaults));
+
+ GHRateLimit limit = new GHRateLimit();
+ limit.remaining = INITIAL_RATE_LIMIT;
+
+ GitHub github = Mockito.mock(GitHub.class);
+ given(github.getRateLimit()).willReturn(limit);
+
+ Mockito.doReturn(github).when(trigger).getGitHub();
return trigger;
}
@@ -388,6 +414,40 @@ public static void triggerRunAndWait(int numOfTriggers, GhprbTrigger trigger, Ab
}
}
+
+
+ public static List checkClassForGetters(Class> clazz) {
+ Field[] fields = clazz.getDeclaredFields();
+ List xmlFields = new ArrayList();
+ List errors = new ArrayList();
+
+ for (Field field : fields) {
+ int modifiers = field.getModifiers();
+ if (modifiers == (Modifier.PRIVATE) || modifiers == (Modifier.PRIVATE | Modifier.FINAL)) {
+ xmlFields.add(field);
+ }
+ }
+
+ for (Field field : xmlFields) {
+ String getter = "get" + StringUtils.capitalise(field.getName());
+ try {
+ Method method = clazz.getDeclaredMethod(getter);
+ int modifier = method.getModifiers();
+ if (!Modifier.isPublic(modifier)) {
+ errors.add(getter + " is not a public method");
+ }
+ } catch (Exception e) {
+ String wrongGetter = "is" + StringUtils.capitalise(field.getName());
+ try {
+ clazz.getDeclaredMethod(wrongGetter);
+ errors.add("Setter is using the wrong name, is " + wrongGetter + " and should be " + getter);
+ } catch(Exception err) {
+ errors.add("Missing " + getter);
+ }
+ }
+ }
+ return errors;
+ }
private GhprbTestUtil() {}
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbTriggerTest.java b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbTriggerTest.java
index 0022e0412..b7853f827 100644
--- a/src/test/java/org/jenkinsci/plugins/ghprb/GhprbTriggerTest.java
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/GhprbTriggerTest.java
@@ -5,16 +5,23 @@
import static org.mockito.Mockito.*;
import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
+import org.jenkinsci.plugins.ghprb.extensions.GhprbExtension;
+import org.jenkinsci.plugins.ghprb.extensions.GhprbGlobalDefault;
+import org.jenkinsci.plugins.ghprb.extensions.build.GhprbCancelBuildsOnUpdate;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.kohsuke.github.GHIssue;
+import org.jvnet.hudson.test.JenkinsRule;
+import org.kohsuke.github.GHPullRequest;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@@ -24,42 +31,119 @@
@RunWith(MockitoJUnitRunner.class)
public class GhprbTriggerTest {
+ @Rule
+ public JenkinsRule jenkinsRule = new JenkinsRule();
+
@Mock
private GhprbPullRequest pr;
+
+ @Mock
+ private Ghprb helper;
+
+ @Test
+ public void testGlobalExtensions() throws Exception {
+ GhprbTrigger.getDscp().getExtensions().add(new GhprbCancelBuildsOnUpdate(false));
+
+ GhprbTrigger trigger = GhprbTestUtil.getTrigger();
+
+ for (GhprbExtension ext : trigger.getDescriptor().getExtensions()) {
+ if (ext instanceof GhprbGlobalDefault) {
+ assertThat(trigger.getExtensions().contains(ext));
+ }
+ }
+ }
@Test
public void testCheckSkipBuild() throws Exception {
- GHIssue issue = mock(GHIssue.class);
-
- String[] comments = { "Some dumb comment\r\nThat shouldn't match", "[skip ci]" };
- String[] phraseArray = { "\\[skip\\W+ci\\]", "skip ci" };
-
- Method checkSkip = GhprbPullRequest.class.getDeclaredMethod("checkSkipBuild", GHIssue.class);
+ GHPullRequest issue = mock(GHPullRequest.class);
+
+ boolean skipBuild = false;
+ boolean build = true;
+
+ String nonMatch = "Some dumb comment\r\nThat shouldn't match";
+ String multiLine = "This is a multiline skip\r\n[skip ci]";
+ String justSkipCi = "skip ci";
+ String fullSkipCi = "[skip ci]";
+
+ Map> stringsToTest = new HashMap>(10);
+
+ Map comment = new HashMap(5);
+ comment.put(nonMatch, build);
+ comment.put(multiLine, skipBuild);
+ comment.put(justSkipCi, build);
+ comment.put(fullSkipCi, skipBuild);
+ stringsToTest.put(".*\\[skip\\W+ci\\].*", comment);
+
+ comment = new HashMap(5);
+ comment.put(nonMatch, build);
+ comment.put(multiLine, build);
+ comment.put(justSkipCi, build);
+ comment.put(fullSkipCi, skipBuild);
+ stringsToTest.put("\\[skip ci\\]", comment);
+
+ comment = new HashMap(5);
+ comment.put(nonMatch, build);
+ comment.put(multiLine, skipBuild);
+ comment.put(justSkipCi, skipBuild);
+ comment.put(fullSkipCi, skipBuild);
+ stringsToTest.put("\\[skip ci\\]\n.*\\[skip\\W+ci\\].*\nskip ci", comment);
+
+ Method checkSkip = GhprbPullRequest.class.getDeclaredMethod("checkSkipBuild");
checkSkip.setAccessible(true);
+
+
+ Field prField = GhprbPullRequest.class.getDeclaredField("pr");
+ prField.setAccessible(true);
+ prField.set(pr, issue);
Field shouldRun = GhprbPullRequest.class.getDeclaredField("shouldRun");
shouldRun.setAccessible(true);
+
+ Field prHelper = GhprbPullRequest.class.getDeclaredField("helper");
+ prHelper.setAccessible(true);
+ prHelper.set(pr, helper);
+
+ for (Entry> skipMap : stringsToTest.entrySet()) {
+ String skipPhrases = skipMap.getKey();
- for (String phraseString : phraseArray) {
- for (String comment : comments) {
+ Set phrases = new HashSet(Arrays.asList(skipPhrases.split("[\\r\\n]+")));
- Set phrases = new HashSet(Arrays.asList(phraseString.split("[\\r\\n]+")));
- given(issue.getBody()).willReturn(comment);
- given(pr.getSkipBuildPhrases()).willReturn(phrases);
- boolean isMatch = false;
- for (String phrase : phrases) {
- isMatch = Pattern.matches(phrase, comment);
- if (isMatch) {
+ given(helper.getSkipBuildPhrases()).willReturn(phrases);
+
+ for (Entry skipResults : skipMap.getValue().entrySet()) {
+ String nextComment = skipResults.getKey();
+ Boolean shouldBuild = skipResults.getValue();
+
+ given(issue.getBody()).willReturn(nextComment);
+ String skipPhrase = "";
+
+ for (String skipBuildPhrase : phrases) {
+ skipBuildPhrase = skipBuildPhrase.trim();
+ Pattern skipBuildPhrasePattern = Ghprb.compilePattern(skipBuildPhrase);
+
+ if (skipBuildPhrasePattern.matcher(nextComment).matches()) {
+ skipPhrase = skipBuildPhrase;
break;
}
}
+
+ given(helper.checkSkipBuild(issue)).willReturn(skipPhrase);
+
shouldRun.set(pr, true);
- checkSkip.invoke(pr, issue);
- assertThat(shouldRun.get(pr)).isEqualTo(!isMatch);
+ checkSkip.invoke(pr);
+ String errorMessage = String.format("Comment does %scontain skip phrase \n(\n%s\n)\n[\n%s\n]", shouldBuild ? "not ": "", nextComment, skipPhrases);
+
+ if (shouldBuild) {
+ assertThat(skipPhrase).overridingErrorMessage(errorMessage).isEmpty();
+ } else {
+ assertThat(skipPhrase).overridingErrorMessage(errorMessage).isNotEmpty();
+ }
+
+ assertThat(shouldRun.get(pr)).overridingErrorMessage(errorMessage).isEqualTo(shouldBuild);
}
}
-
}
+
}
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatusTest.java b/src/test/java/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatusTest.java
index 9396c4d2b..212546b46 100644
--- a/src/test/java/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatusTest.java
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/extensions/status/GhprbSimpleStatusTest.java
@@ -1,9 +1,13 @@
package org.jenkinsci.plugins.ghprb.extensions.status;
import org.jenkinsci.plugins.ghprb.GhprbPullRequest;
+import org.jenkinsci.plugins.ghprb.GhprbTestUtil;
import org.jenkinsci.plugins.ghprb.GhprbTrigger;
+import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.jvnet.hudson.test.JenkinsRule;
import org.kohsuke.github.GHCommitState;
import org.kohsuke.github.GHRepository;
import org.mockito.Mock;
@@ -19,13 +23,22 @@
@RunWith(MockitoJUnitRunner.class)
public class GhprbSimpleStatusTest {
+ @Rule
+ public JenkinsRule jenkinsRule = new JenkinsRule();
+
@Mock
private GHRepository ghRepository;
@Mock
private GhprbPullRequest ghprbPullRequest;
- @Mock
+
private GhprbTrigger trigger;
+
+ @Before
+ public void setUp() throws Exception {
+ trigger = GhprbTestUtil.getTrigger(null);
+ }
+
@Test
public void testMergedMessage() throws Exception {
String mergedMessage = "Build triggered. sha1 is merged.";
@@ -33,13 +46,11 @@ public void testMergedMessage() throws Exception {
given(ghprbPullRequest.isMergeable()).willReturn(true);
GhprbSimpleStatus status = spy(new GhprbSimpleStatus("default"));
- status.onBuildTriggered(trigger, ghprbPullRequest, ghRepository);
+ status.onBuildTriggered(trigger.getActualProject(), "sha", true, 1, ghRepository);
- verify(ghRepository).createCommitStatus(eq("sha"), eq(GHCommitState.PENDING), isNull(String.class), eq(mergedMessage), eq("default"));
+ verify(ghRepository).createCommitStatus(eq("sha"), eq(GHCommitState.PENDING), eq(""), eq(mergedMessage), eq("default"));
verifyNoMoreInteractions(ghRepository);
- verify(ghprbPullRequest).getHead();
- verify(ghprbPullRequest).isMergeable();
verifyNoMoreInteractions(ghprbPullRequest);
}
@@ -50,13 +61,11 @@ public void testMergeConflictMessage() throws Exception {
given(ghprbPullRequest.isMergeable()).willReturn(false);
GhprbSimpleStatus status = spy(new GhprbSimpleStatus("default"));
- status.onBuildTriggered(trigger, ghprbPullRequest, ghRepository);
+ status.onBuildTriggered(trigger.getActualProject(), "sha", false, 1, ghRepository);
- verify(ghRepository).createCommitStatus(eq("sha"), eq(GHCommitState.PENDING), isNull(String.class), eq(mergedMessage), eq("default"));
+ verify(ghRepository).createCommitStatus(eq("sha"), eq(GHCommitState.PENDING), eq(""), eq(mergedMessage), eq("default"));
verifyNoMoreInteractions(ghRepository);
- verify(ghprbPullRequest).getHead();
- verify(ghprbPullRequest).isMergeable();
verifyNoMoreInteractions(ghprbPullRequest);
}
@@ -67,13 +76,11 @@ public void testDoesNotSendEmptyContext() throws Exception {
given(ghprbPullRequest.isMergeable()).willReturn(false);
GhprbSimpleStatus status = spy(new GhprbSimpleStatus(""));
- status.onBuildTriggered(trigger, ghprbPullRequest, ghRepository);
+ status.onBuildTriggered(trigger.getActualProject(), "sha", false, 1, ghRepository);
- verify(ghRepository).createCommitStatus(eq("sha"), eq(GHCommitState.PENDING), isNull(String.class), eq(mergedMessage), isNull(String.class));
+ verify(ghRepository).createCommitStatus(eq("sha"), eq(GHCommitState.PENDING), eq(""), eq(mergedMessage), isNull(String.class));
verifyNoMoreInteractions(ghRepository);
- verify(ghprbPullRequest).getHead();
- verify(ghprbPullRequest).isMergeable();
verifyNoMoreInteractions(ghprbPullRequest);
}
}
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/manager/impl/GhprbDefaultBuildManagerTest.java b/src/test/java/org/jenkinsci/plugins/ghprb/manager/impl/GhprbDefaultBuildManagerTest.java
index 3045eb833..ed12d6ffc 100644
--- a/src/test/java/org/jenkinsci/plugins/ghprb/manager/impl/GhprbDefaultBuildManagerTest.java
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/manager/impl/GhprbDefaultBuildManagerTest.java
@@ -2,20 +2,16 @@
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
-import static org.mockito.Mockito.doReturn;
import java.util.HashMap;
import java.util.Map;
-import com.coravy.hudson.plugins.github.GithubProjectProperty;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixProject;
-import org.jenkinsci.plugins.ghprb.Ghprb;
import org.jenkinsci.plugins.ghprb.GhprbITBaseTestCase;
import org.jenkinsci.plugins.ghprb.GhprbTestUtil;
-import org.jenkinsci.plugins.ghprb.GhprbTrigger;
import org.jenkinsci.plugins.ghprb.manager.GhprbBuildManager;
import org.jenkinsci.plugins.ghprb.manager.factory.GhprbBuildManagerFactoryUtil;
import org.junit.Before;
@@ -33,17 +29,25 @@ public class GhprbDefaultBuildManagerTest extends GhprbITBaseTestCase {
@Rule
public JenkinsRule jenkinsRule = new JenkinsRule();
+
+ private MatrixProject project;
@Before
public void setUp() throws Exception {
// GhprbTestUtil.mockGithubUserPage();
- super.beforeTest();
+ project = jenkinsRule.createMatrixProject("MTXPRJ");
+
+ Map config = new HashMap(1);
+
+ config.put("publishedURL", "defaultPublishedURL");
+ super.beforeTest(config, null, project);
}
@Test
public void shouldCalculateUrlFromDefault() throws Exception {
+
// GIVEN
- MatrixProject project = givenThatGhprbHasBeenTriggeredForAMatrixProject();
+ givenThatGhprbHasBeenTriggeredForAMatrixProject();
// THEN
assertThat(project.getBuilds().toArray().length).isEqualTo(1);
@@ -57,44 +61,14 @@ public void shouldCalculateUrlFromDefault() throws Exception {
assertThat(buildManager.calculateBuildUrl("defaultPublishedURL")).isEqualTo("defaultPublishedURL/" + matrixBuild.getUrl());
}
- private MatrixProject givenThatGhprbHasBeenTriggeredForAMatrixProject() throws Exception {
- MatrixProject project = jenkinsRule.createMatrixProject("MTXPRJ");
-
- GhprbTrigger trigger = GhprbTestUtil.getTrigger(null);
-
+ private void givenThatGhprbHasBeenTriggeredForAMatrixProject() throws Exception {
given(commitPointer.getSha()).willReturn("sha");
- Map config = new HashMap(1);
- config.put("publishedURL", "defaultPublishedURL");
-
- GhprbTestUtil.setupGhprbTriggerDescriptor(config);
-
-
- project.addProperty(new GithubProjectProperty("https://github.com/user/dropwizard"));
-
given(ghPullRequest.getNumber()).willReturn(1);
- // Creating spy on ghprb, configuring repo
- Ghprb ghprb = spyCreatingGhprb(trigger, project);
-
- doReturn(ghprbGitHub).when(ghprb).getGitHub();
-
- setRepositoryHelper(ghprb);
-
given(ghRepository.getPullRequest(1)).willReturn(ghPullRequest);
- // Configuring and adding Ghprb trigger
- project.addTrigger(trigger);
-
- // Configuring Git SCM
- project.setScm(GhprbTestUtil.provideGitSCM());
-
- trigger.start(project, true);
-
- setTriggerHelper(trigger, ghprb);
-
GhprbTestUtil.triggerRunAndWait(10, trigger, project);
- return project;
}
}
\ No newline at end of file
diff --git a/src/test/java/org/jenkinsci/plugins/ghprb/manager/impl/downstreambuilds/BuildFlowBuildManagerTest.java b/src/test/java/org/jenkinsci/plugins/ghprb/manager/impl/downstreambuilds/BuildFlowBuildManagerTest.java
index 99810ca93..603e3e650 100644
--- a/src/test/java/org/jenkinsci/plugins/ghprb/manager/impl/downstreambuilds/BuildFlowBuildManagerTest.java
+++ b/src/test/java/org/jenkinsci/plugins/ghprb/manager/impl/downstreambuilds/BuildFlowBuildManagerTest.java
@@ -3,19 +3,15 @@
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
-import static org.mockito.Mockito.doReturn;
import com.cloudbees.plugins.flow.BuildFlow;
import com.cloudbees.plugins.flow.FlowRun;
import com.cloudbees.plugins.flow.JobInvocation;
-import com.coravy.hudson.plugins.github.GithubProjectProperty;
import java.util.Iterator;
-import org.jenkinsci.plugins.ghprb.Ghprb;
import org.jenkinsci.plugins.ghprb.GhprbITBaseTestCase;
import org.jenkinsci.plugins.ghprb.GhprbTestUtil;
-import org.jenkinsci.plugins.ghprb.GhprbTrigger;
import org.jenkinsci.plugins.ghprb.manager.GhprbBuildManager;
import org.jenkinsci.plugins.ghprb.manager.factory.GhprbBuildManagerFactoryUtil;
import org.jenkinsci.plugins.ghprb.rules.JenkinsRuleWithBuildFlow;
@@ -35,16 +31,39 @@ public class BuildFlowBuildManagerTest extends GhprbITBaseTestCase {
@Rule
public JenkinsRuleWithBuildFlow jenkinsRule = new JenkinsRuleWithBuildFlow();
+
+ private BuildFlow buildFlowProject;
@Before
public void setUp() throws Exception {
- super.beforeTest();
+
+ buildFlowProject = jenkinsRule.createBuildFlowProject();
+
+ jenkinsRule.createFreeStyleProject("downstreamProject1");
+ jenkinsRule.createFreeStyleProject("downstreamProject2");
+ jenkinsRule.createFreeStyleProject("downstreamProject3");
+
+ StringBuilder dsl = new StringBuilder();
+
+ dsl.append("parallel (");
+ dsl.append(" { build(\"downstreamProject1\") },");
+ dsl.append(" { build(\"downstreamProject2\") }");
+ dsl.append(")");
+ dsl.append("{ build(\"downstreamProject3\") }");
+
+ buildFlowProject.setDsl(dsl.toString());
+
+ given(ghPullRequest.getNumber()).willReturn(1);
+ given(ghRepository.getPullRequest(1)).willReturn(ghPullRequest);
+
+ super.beforeTest(null, null, buildFlowProject);
}
@Test
public void shouldCalculateUrlWithDownstreamBuilds() throws Exception {
// GIVEN
- BuildFlow buildFlowProject = givenThatGhprbHasBeenTriggeredForABuildFlowProject();
+
+ GhprbTestUtil.triggerRunAndWait(10, trigger, buildFlowProject);
// THEN
assertThat(buildFlowProject.getBuilds().toArray().length).isEqualTo(1);
@@ -84,55 +103,4 @@ public void shouldCalculateUrlWithDownstreamBuilds() throws Exception {
assertThat(buildManager.calculateBuildUrl(null)).isEqualTo(expectedUrl.toString());
}
- private BuildFlow givenThatGhprbHasBeenTriggeredForABuildFlowProject() throws Exception {
-
- BuildFlow buildFlowProject = jenkinsRule.createBuildFlowProject();
-
- jenkinsRule.createFreeStyleProject("downstreamProject1");
- jenkinsRule.createFreeStyleProject("downstreamProject2");
- jenkinsRule.createFreeStyleProject("downstreamProject3");
-
- StringBuilder dsl = new StringBuilder();
-
- dsl.append("parallel (");
- dsl.append(" { build(\"downstreamProject1\") },");
- dsl.append(" { build(\"downstreamProject2\") }");
- dsl.append(")");
- dsl.append("{ build(\"downstreamProject3\") }");
-
- buildFlowProject.setDsl(dsl.toString());
-
- GhprbTrigger trigger = GhprbTestUtil.getTrigger(null);
-
- given(commitPointer.getSha()).willReturn("sha");
- GhprbTestUtil.setupGhprbTriggerDescriptor(null);
-
- buildFlowProject.addProperty(new GithubProjectProperty("https://github.com/user/dropwizard"));
-
- given(ghPullRequest.getNumber()).willReturn(1);
-
- // Creating spy on ghprb, configuring repo
- Ghprb ghprb = spyCreatingGhprb(trigger, buildFlowProject);
-
- doReturn(ghprbGitHub).when(ghprb).getGitHub();
-
- setRepositoryHelper(ghprb);
-
- given(ghRepository.getPullRequest(1)).willReturn(ghPullRequest);
-
- // Configuring and adding Ghprb trigger
- buildFlowProject.addTrigger(trigger);
-
- // Configuring Git SCM
- buildFlowProject.setScm(GhprbTestUtil.provideGitSCM());
-
- trigger.start(buildFlowProject, true);
-
- setTriggerHelper(trigger, ghprb);
-
- GhprbTestUtil.triggerRunAndWait(10, trigger, buildFlowProject);
-
- return buildFlowProject;
- }
-
}