11package 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+
327import com .offbytwo .jenkins .JenkinsServer ;
428import com .offbytwo .jenkins .model .Artifact ;
529import com .offbytwo .jenkins .model .BuildWithDetails ;
1135import org .eclipse .jgit .dircache .DirCache ;
1236import org .eclipse .jgit .lib .StoredConfig ;
1337import org .eclipse .jgit .revwalk .RevCommit ;
14- import org .eclipse .jgit .transport .PushResult ;
1538import org .eclipse .jgit .transport .RefSpec ;
1639import org .eclipse .jgit .transport .UsernamePasswordCredentialsProvider ;
1740import org .junit .Rule ;
2245import org .slf4j .Logger ;
2346import 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
4350public 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 ("\n The file was modified by the test application : " + ft .format (dNow ) + " \n " );
279+ String outString = "\n The 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 ) {
0 commit comments