Skip to content

Commit d613177

Browse files
committed
Modified IT for branch filter
1 parent 131834c commit d613177

File tree

5 files changed

+173
-77
lines changed

5 files changed

+173
-77
lines changed

src/test/java/org/jenkinsci/plugins/gogs/GogsConfigHandler.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,20 @@ void createEmptyRepo(String projectName) throws IOException {
193193
}
194194
}
195195

196+
void removeRepo(String projectName) throws IOException {
197+
Executor executor = getExecutor();
198+
String gogsHookConfigUrl = getGogsServer_apiUrl() + "repos/" + this.gogsServer_user + "/" + projectName;
199+
Request request = Request.Delete(gogsHookConfigUrl);
200+
201+
if (this.gogsAccessToken != null) {
202+
request.addHeader("Authorization", "token " + this.gogsAccessToken);
203+
}
204+
205+
int result = executor.execute(request).returnResponse().getStatusLine().getStatusCode();
206+
if (result != 204) {
207+
throw new IOException("Repository deletion call did not return the expected value (returned " + result + ")");
208+
}
209+
}
196210

197211
/**
198212
* Gets a Executor object. The Executor object allows to cache the authentication data.

src/test/java/org/jenkinsci/plugins/gogs/GogsWebHook_IT.java

Lines changed: 123 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,29 @@
11
package org.jenkinsci.plugins.gogs;
22

3+
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_BRANCH_SECTION;
4+
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_REMOTE_SECTION;
5+
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_USER_SECTION;
6+
import static org.jenkinsci.plugins.gogs.JenkinsHandler.waitUntilJenkinsHasBeenStartedUp;
7+
import static org.junit.Assert.assertEquals;
8+
import static org.junit.Assert.fail;
9+
10+
import java.io.BufferedWriter;
11+
import java.io.File;
12+
import java.io.FileWriter;
13+
import java.io.IOException;
14+
import java.io.InputStream;
15+
import java.io.StringReader;
16+
import java.io.Writer;
17+
import java.net.URI;
18+
import java.net.URISyntaxException;
19+
import java.nio.charset.Charset;
20+
import java.nio.file.Files;
21+
import java.text.SimpleDateFormat;
22+
import java.util.Date;
23+
import java.util.List;
24+
import java.util.Properties;
25+
import java.util.concurrent.TimeoutException;
26+
327
import com.offbytwo.jenkins.JenkinsServer;
428
import com.offbytwo.jenkins.model.Artifact;
529
import com.offbytwo.jenkins.model.BuildWithDetails;
@@ -11,7 +35,6 @@
1135
import org.eclipse.jgit.dircache.DirCache;
1236
import org.eclipse.jgit.lib.StoredConfig;
1337
import org.eclipse.jgit.revwalk.RevCommit;
14-
import org.eclipse.jgit.transport.PushResult;
1538
import org.eclipse.jgit.transport.RefSpec;
1639
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
1740
import org.junit.Rule;
@@ -22,35 +45,18 @@
2245
import org.slf4j.Logger;
2346
import org.slf4j.LoggerFactory;
2447

25-
import java.io.*;
26-
import java.net.URI;
27-
import java.net.URISyntaxException;
28-
import java.nio.charset.Charset;
29-
import java.nio.file.Files;
30-
import java.text.SimpleDateFormat;
31-
import java.util.Date;
32-
import java.util.List;
33-
import java.util.Properties;
34-
import java.util.concurrent.TimeoutException;
35-
36-
import static org.eclipse.jgit.lib.ConfigConstants.*;
37-
import static org.jenkinsci.plugins.gogs.JenkinsHandler.waitUntilJenkinsHasBeenStartedUp;
38-
import static org.junit.Assert.assertEquals;
39-
import static org.junit.Assert.fail;
40-
4148
//FIXME: the test should run in sequence
4249

4350
public class GogsWebHook_IT {
44-
public static final String JENKINS_URL = "http://localhost:8080/";
45-
public static final String JENKINS_USER = "butler";
46-
public static final String JENKINS_PASSWORD = "butler";
47-
public static final String GOGS_URL = "http://localhost:3000";
48-
public static final String GOGS_USER = "butler";
49-
public static final String GOGS_PASSWORD = "butler";
50-
public static final String WEBHOOK_URL = "http://localhost:8080/job/testRep1/build?delay=0";
51-
public static final String JSON_COMMANDFILE_PATH = "target/test-classes/Gogs-config-json/";
52-
public static final String JENKINS_CONFIGS_PATH = "target/test-classes/Jenkins-config/";
53-
public static final String JENKINS_JOB_NAME = "test project";
51+
private static final String JENKINS_URL = "http://localhost:8080/";
52+
private static final String JENKINS_USER = "butler";
53+
private static final String JENKINS_PASSWORD = "butler";
54+
private static final String GOGS_URL = "http://localhost:3000";
55+
private static final String GOGS_USER = "butler";
56+
private static final String GOGS_PASSWORD = "butler";
57+
private static final String JSON_COMMANDFILE_PATH = "target/test-classes/Gogs-config-json/";
58+
private static final String JENKINS_CONFIGS_PATH = "target/test-classes/Jenkins-config/";
59+
private static final String JENKINS_JOB_NAME = "test project";
5460
final Logger log = LoggerFactory.getLogger(GogsWebHook_IT.class);
5561

5662
@Rule
@@ -63,13 +69,50 @@ protected void starting(Description description) {
6369

6470
@Test
6571
public void smokeTest_build_masterBranch() throws Exception {
72+
final String projectName = "testRep1";
73+
74+
doItTest(JENKINS_JOB_NAME,
75+
projectName,
76+
"test-project.xml",
77+
"webHookDefinition.json",
78+
null);
79+
}
80+
81+
@Test
82+
public void smokeTest_build_testBranch() throws Exception {
83+
final String projectName = "testRep2";
84+
doItTest(JENKINS_JOB_NAME + "2",
85+
projectName,
86+
"test-project-branch.xml",
87+
"webHookDefinition_branch.json",
88+
"test");
89+
}
90+
91+
/**
92+
* Do integration tests
93+
*
94+
* @param jenkinsJobName Jenkins jobname
95+
* @param projectName Gogs project name
96+
* @param jenkinsXML XML file name with Jenkins job definition
97+
* @param webhookDefinition JSON file with webhook definition
98+
* @param branch Branch name to do test on (null means master)
99+
* @throws Exception Something unexpected went wrong
100+
*/
101+
private void doItTest(final String jenkinsJobName,
102+
final String projectName,
103+
final String jenkinsXML,
104+
final String webhookDefinition,
105+
final String branch) throws Exception {
106+
// Default refspec is master
107+
StringBuilder refSpec = new StringBuilder("refs/heads/master:refs/heads/");
108+
66109
//Instantiate the Gogs Handler object and wait for the server to be available
67110
GogsConfigHandler gogsServer = new GogsConfigHandler(GOGS_URL, GOGS_USER, GOGS_PASSWORD);
68111
gogsServer.waitForServer(12, 5);
69112

70113
//Create the test repository on the server
71114
try {
72-
gogsServer.createEmptyRepo("testRep1");
115+
gogsServer.createEmptyRepo(projectName);
73116
} catch (IOException e) {
74117
//check for the exist message;
75118
if (e.getMessage().contains("422")) {
@@ -87,50 +130,52 @@ public void smokeTest_build_masterBranch() throws Exception {
87130
StoredConfig config = git.getRepository().getConfig();
88131
config.setString(CONFIG_USER_SECTION, null, "name", "Automated Test");
89132
config.setString(CONFIG_USER_SECTION, null, "email", "test@test.org");
90-
config.setString(CONFIG_REMOTE_SECTION, "origin", "url", "http://localhost:3000/butler/testRep1.git");
133+
config.setString(CONFIG_REMOTE_SECTION, "origin", "url", "http://localhost:3000/butler/"+projectName+".git");
91134
config.setString(CONFIG_REMOTE_SECTION, "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
92135
config.setString(CONFIG_BRANCH_SECTION, "master", "remote", "origin");
93136
config.setString(CONFIG_BRANCH_SECTION, "master", "merge", "refs/heads/master");
94137
config.save();
95138

96-
97139
//add the files located there and commit them
98140
Status status = git.status().call();
99141
DirCache index = git.add().addFilepattern(".").call();
100142
RevCommit commit = git.commit().setMessage("Repos initialization").call();
101143
log.info("Commit" + commit.getName());
102144

103-
104145
//push
105146
UsernamePasswordCredentialsProvider user2 = new UsernamePasswordCredentialsProvider("butler", "butler");
106147

107-
RefSpec spec = new RefSpec("refs/heads/master:refs/heads/master");
108-
Iterable<PushResult> resultIterable = git.push()
109-
.setRemote("origin")
110-
.setCredentialsProvider(user2)
111-
.setRefSpecs(spec)
112-
.call();
148+
if (branch == null) {
149+
refSpec.append("master");
150+
} else {
151+
refSpec.append(branch);
152+
}
113153

114-
//Setup the Jenkins job
154+
RefSpec spec = new RefSpec(refSpec.toString());
155+
git.push()
156+
.setRemote("origin")
157+
.setCredentialsProvider(user2)
158+
.setRefSpecs(spec)
159+
.setPushAll()
160+
.call();
115161

162+
//Setup the Jenkins job
116163
JenkinsServer jenkins = new JenkinsServer(new URI(JENKINS_URL), JENKINS_USER, JENKINS_PASSWORD);
117-
118164
waitUntilJenkinsHasBeenStartedUp(jenkins);
119165

120-
121166
//Check if the job exist. If not create it.
122-
Job job = jenkins.getJob(JENKINS_JOB_NAME);
167+
Job job = jenkins.getJob(jenkinsJobName);
123168
if (job == null) {
124169
//Read the job configuration into a string
125-
File jenkinsConfigFile = new File(JENKINS_CONFIGS_PATH + "test-project.xml");
170+
File jenkinsConfigFile = new File(JENKINS_CONFIGS_PATH + jenkinsXML);
126171
byte[] encoded = Files.readAllBytes(jenkinsConfigFile.toPath());
127172
String configXml = new String(encoded, Charset.defaultCharset());
128173

129-
jenkins.createJob(JENKINS_JOB_NAME, configXml);
174+
jenkins.createJob(jenkinsJobName, configXml);
130175
}
131176

132177
//Get the expected build number
133-
JobWithDetails jobAtIntitalState = jenkins.getJob(JENKINS_JOB_NAME);
178+
JobWithDetails jobAtIntitalState = jenkins.getJob(jenkinsJobName);
134179
int expectedBuildNbr = jobAtIntitalState.getNextBuildNumber();
135180
log.info("Next build number: " + expectedBuildNbr);
136181

@@ -139,21 +184,21 @@ public void smokeTest_build_masterBranch() throws Exception {
139184

140185
//Wait for the job to complete
141186
long timeOut = 60000L;
142-
waitForBuildToComplete(jenkins, expectedBuildNbr, timeOut);
187+
waitForBuildToComplete(jenkins, expectedBuildNbr, timeOut, jenkinsJobName);
143188

144189
//Get the data we stored in the marker file and check it
145-
Properties markerAsProperty = loadMarkerArtifactAsProperty(jenkins);
190+
Properties markerAsProperty = loadMarkerArtifactAsProperty(jenkins, jenkinsJobName);
146191
String buildedCommit = markerAsProperty.getProperty("GIT_COMMIT");
147-
assertEquals("Not the expected GIT commit", commit.getName(), buildedCommit);
148192

193+
assertEquals("Not the expected GIT commit", commit.getName(), buildedCommit);
149194

150195
//add the trigger to Gogs
151-
File jsonCommandFile = new File(JSON_COMMANDFILE_PATH + "webHookDefinition.json");
152-
int hookId = gogsServer.createWebHook(jsonCommandFile, "testRep1");
196+
File jsonCommandFile = new File(JSON_COMMANDFILE_PATH + webhookDefinition);
197+
int hookId = gogsServer.createWebHook(jsonCommandFile, projectName);
153198
log.info("Created hook with ID " + hookId);
154199

155200
//Get what is the next build number of the test jenkins job
156-
jobAtIntitalState = jenkins.getJob(JENKINS_JOB_NAME);
201+
jobAtIntitalState = jenkins.getJob(jenkinsJobName);
157202
expectedBuildNbr = jobAtIntitalState.getNextBuildNumber();
158203

159204
//change the source file
@@ -164,34 +209,37 @@ public void smokeTest_build_masterBranch() throws Exception {
164209
RevCommit commitForHook = git.commit().setMessage("Small test modification").call();
165210
log.info("Commit" + commitForHook.getName());
166211
git.push()
167-
.setRemote("origin")
168-
.setCredentialsProvider(user2)
169-
.setRefSpecs(spec)
170-
.call();
212+
.setRemote("origin")
213+
.setCredentialsProvider(user2)
214+
.setRefSpecs(spec)
215+
.setPushAll()
216+
.call();
171217

172-
//wait for the build
173-
waitForBuildToComplete(jenkins, expectedBuildNbr, timeOut);
174-
175-
//Get the data we stored in the marker file and check it
176-
Properties hookMarkerAsProperty = loadMarkerArtifactAsProperty(jenkins);
177-
String hookBuildedCommit = hookMarkerAsProperty.getProperty("GIT_COMMIT");
178-
assertEquals("Not the expected GIT commit", commitForHook.getName(), hookBuildedCommit);
179-
180-
//Cleanup - remove the hook we created
181-
gogsServer.removeHook("demoApp", hookId);
218+
try {
219+
//wait for the build
220+
waitForBuildToComplete(jenkins, expectedBuildNbr, timeOut, jenkinsJobName);
221+
222+
//Get the data we stored in the marker file and check it
223+
Properties hookMarkerAsProperty = loadMarkerArtifactAsProperty(jenkins, jenkinsJobName);
224+
String hookBuildedCommit = hookMarkerAsProperty.getProperty("GIT_COMMIT");
225+
assertEquals("Not the expected GIT commit", commitForHook.getName(), hookBuildedCommit);
226+
} finally {
227+
// Cleanup the mess we made
228+
gogsServer.removeHook(projectName, hookId);
229+
gogsServer.removeRepo(projectName);
230+
}
182231
}
183232

184-
185233
/**
186234
* Loads the marker file of the last build (archived during the build)
187235
*
188236
* @param jenkins the jenkins instance we want to load from
189237
* @return the marker file loaded as a property file (so that it can be easily queried)
190238
* @throws IOException Something unexpected went wrong when querying the Jenkins server
191-
* @throws URISyntaxException Something uunexpected went wrong loading the marker as a property
239+
* @throws URISyntaxException Something unexpected went wrong loading the marker as a property
192240
*/
193-
private Properties loadMarkerArtifactAsProperty(JenkinsServer jenkins) throws IOException, URISyntaxException {
194-
JobWithDetails detailedJob = jenkins.getJob(JENKINS_JOB_NAME);
241+
private Properties loadMarkerArtifactAsProperty(JenkinsServer jenkins, String jobName) throws IOException, URISyntaxException {
242+
JobWithDetails detailedJob = jenkins.getJob(jobName);
195243
BuildWithDetails lastBuild = detailedJob.getLastBuild().details();
196244
int buildNbr = lastBuild.getNumber();
197245
boolean isBuilding = lastBuild.isBuilding();
@@ -223,13 +271,13 @@ private Properties loadMarkerArtifactAsProperty(JenkinsServer jenkins) throws IO
223271
* @param fileName the source file to modify
224272
* @throws IOException something went wrong when updating the file
225273
*/
226-
private void changeTheSourceFile(String fileName) throws IOException {
274+
private void changeTheSourceFile(@SuppressWarnings("SameParameterValue") String fileName) throws IOException {
227275
Writer output;
228-
boolean openInAppendMode = true;
229-
output = new BufferedWriter(new FileWriter(fileName, openInAppendMode));
276+
output = new BufferedWriter(new FileWriter(fileName, true));
230277
Date dNow = new Date();
231278
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
232-
output.append("\nThe file was modified by the test application : " + ft.format(dNow) + " \n");
279+
String outString = "\nThe file was modified by the test application : " + ft.format(dNow) + " \n";
280+
output.append(outString);
233281
output.close();
234282
}
235283

@@ -243,9 +291,9 @@ private void changeTheSourceFile(String fileName) throws IOException {
243291
* @throws TimeoutException we exeeded the timeout period.
244292
* @throws IOException an unexpected error occurred while communicating with Jenkins
245293
*/
246-
private void waitForBuildToComplete(JenkinsServer jenkins, int expectedBuildNbr, long timeOut) throws InterruptedException, TimeoutException, IOException {
294+
private void waitForBuildToComplete(JenkinsServer jenkins, int expectedBuildNbr, long timeOut, String jobname) throws InterruptedException, TimeoutException, IOException {
247295
boolean buildCompleted = false;
248-
Long timeoutCounter = 0L;
296+
long timeoutCounter = 0L;
249297
while (!buildCompleted) {
250298
Thread.sleep(2000);
251299
timeoutCounter = timeoutCounter + 2000L;
@@ -254,7 +302,7 @@ private void waitForBuildToComplete(JenkinsServer jenkins, int expectedBuildNbr,
254302
}
255303
//When the build is in the queue, the nextbuild number didn't change.
256304
//When it changed, It might still be running.
257-
JobWithDetails wrkJobData = jenkins.getJob(JENKINS_JOB_NAME);
305+
JobWithDetails wrkJobData = jenkins.getJob(jobname);
258306
int newNextNbr = wrkJobData.getNextBuildNumber();
259307
log.info("New Next Nbr:" + newNextNbr);
260308
if (expectedBuildNbr != newNextNbr) {

src/test/resources/Gogs-config-json/webHookDefinition.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"type":"gogs",
33
"config":
44
{
5-
"url":"http://jenkins:8080/job/test%20project/build?delay=0",
5+
"url":"http://jenkins:8080/gogs-webhook/?job=test%20project",
66
"content_type":"json"
77
},
88
"events":["create","push","pull_request"],

src/test/resources/Gogs-config-json/webHookDefinition_1.json renamed to src/test/resources/Gogs-config-json/webHookDefinition_branch.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"type":"gogs",
33
"config":
44
{
5-
"url":"http://localhost:8080/job/demoapp/build?delay=0",
5+
"url":"http://jenkins:8080/gogs-webhook/?job=test%20project2&branch=test",
66
"content_type":"json"
77
},
88
"events":["create","push","pull_request"],

0 commit comments

Comments
 (0)