blob: d9da0eef9116d9a193d3cd8671072b37e0be2851 [file] [log] [blame]
James E. Blairb0fcae42012-07-17 11:12:10 -07001#!/usr/bin/env python
2
3# Copyright 2012 Hewlett-Packard Development Company, L.P.
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may
6# not use this file except in compliance with the License. You may obtain
7# a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14# License for the specific language governing permissions and limitations
15# under the License.
16
17import unittest
18import ConfigParser
19import os
20import Queue
James E. Blair8cc15a82012-08-01 11:17:57 -070021import hashlib
James E. Blairb0fcae42012-07-17 11:12:10 -070022import logging
James E. Blair8cc15a82012-08-01 11:17:57 -070023import random
James E. Blairb0fcae42012-07-17 11:12:10 -070024import json
25import threading
26import time
27import pprint
28import re
James E. Blair8cc15a82012-08-01 11:17:57 -070029import urllib2
30import urlparse
James E. Blair4886cc12012-07-18 15:39:41 -070031import shutil
32import git
James E. Blairb0fcae42012-07-17 11:12:10 -070033
34import zuul
35import zuul.scheduler
36import zuul.launcher.jenkins
37import zuul.trigger.gerrit
38
39FIXTURE_DIR = os.path.join(os.path.dirname(__file__),
40 'fixtures')
41CONFIG = ConfigParser.ConfigParser()
42CONFIG.read(os.path.join(FIXTURE_DIR, "zuul.conf"))
43
44CONFIG.set('zuul', 'layout_config',
45 os.path.join(FIXTURE_DIR, "layout.yaml"))
46
47logging.basicConfig(level=logging.DEBUG)
48
49
James E. Blair8cc15a82012-08-01 11:17:57 -070050def random_sha1():
51 return hashlib.sha1(str(random.random())).hexdigest()
52
53
James E. Blair4886cc12012-07-18 15:39:41 -070054class ChangeReference(git.Reference):
55 _common_path_default = "refs/changes"
56 _points_to_commits_only = True
57
58
59def init_repo(project):
60 parts = project.split('/')
61 path = os.path.join("/tmp/zuul-test/upstream", *parts[:-1])
62 if not os.path.exists(path):
63 os.makedirs(path)
64 path = os.path.join("/tmp/zuul-test/upstream", project)
65 repo = git.Repo.init(path)
66
67 fn = os.path.join(path, 'README')
68 f = open(fn, 'w')
69 f.write("test\n")
70 f.close()
71 repo.index.add([fn])
72 repo.index.commit('initial commit')
James E. Blairc6294a52012-08-17 10:19:48 -070073 master = repo.create_head('master')
James E. Blair4886cc12012-07-18 15:39:41 -070074 repo.create_tag('init')
75
James E. Blairc6294a52012-08-17 10:19:48 -070076 mp = repo.create_head('mp')
77 repo.head.reference = mp
78 f = open(fn, 'a')
79 f.write("test mp\n")
80 f.close()
81 repo.index.add([fn])
82 repo.index.commit('mp commit')
83
84 repo.head.reference = master
85 repo.head.reset(index=True, working_tree=True)
86 repo.git.clean('-x', '-f', '-d')
87
James E. Blair4886cc12012-07-18 15:39:41 -070088
James E. Blair973721f2012-08-15 10:19:43 -070089def add_fake_change_to_repo(project, branch, change_num, patchset, msg, fn):
James E. Blair4886cc12012-07-18 15:39:41 -070090 path = os.path.join("/tmp/zuul-test/upstream", project)
91 repo = git.Repo(path)
92 ref = ChangeReference.create(repo, '1/%s/%s' % (change_num,
93 patchset),
94 'refs/tags/init')
95 repo.head.reference = ref
96 repo.head.reset(index=True, working_tree=True)
97 repo.git.clean('-x', '-f', '-d')
98
99 path = os.path.join("/tmp/zuul-test/upstream", project)
James E. Blair973721f2012-08-15 10:19:43 -0700100 fn = os.path.join(path, fn)
James E. Blair4886cc12012-07-18 15:39:41 -0700101 f = open(fn, 'w')
James E. Blair973721f2012-08-15 10:19:43 -0700102 f.write("test %s %s %s\n" % (branch, change_num, patchset))
James E. Blair4886cc12012-07-18 15:39:41 -0700103 f.close()
104 repo.index.add([fn])
James E. Blairdaabed22012-08-15 15:38:57 -0700105 return repo.index.commit(msg)
James E. Blair4886cc12012-07-18 15:39:41 -0700106
107
108def ref_has_change(ref, change):
109 path = os.path.join("/tmp/zuul-test/git", change.project)
110 repo = git.Repo(path)
111 for commit in repo.iter_commits(ref):
112 if commit.message.strip() == ('%s-1' % change.subject):
113 return True
114 return False
115
116
117def job_has_changes(*args):
118 job = args[0]
119 commits = args[1:]
120 project = job.parameters['ZUUL_PROJECT']
121 path = os.path.join("/tmp/zuul-test/git", project)
122 repo = git.Repo(path)
123 ref = job.parameters['ZUUL_REF']
124 repo_messages = [c.message.strip() for c in repo.iter_commits(ref)]
125 commit_messages = ['%s-1' % commit.subject for commit in commits]
126 print 'checking that job %s has changes:' % ref
127 print ' commit messages:', commit_messages
128 print ' repo messages :', repo_messages
129 for msg in commit_messages:
130 if msg not in repo_messages:
131 return False
132 return True
133
134
James E. Blairb0fcae42012-07-17 11:12:10 -0700135class FakeChange(object):
James E. Blair8c803f82012-07-31 16:25:42 -0700136 categories = {'APRV': ('Approved', -1, 1),
137 'CRVW': ('Code-Review', -2, 2),
138 'VRFY': ('Verified', -2, 2)}
James E. Blairb0fcae42012-07-17 11:12:10 -0700139
James E. Blair8cc15a82012-08-01 11:17:57 -0700140 def __init__(self, gerrit, number, project, branch, subject, status='NEW'):
141 self.gerrit = gerrit
James E. Blaird466dc42012-07-31 10:42:56 -0700142 self.reported = 0
James E. Blair8c803f82012-07-31 16:25:42 -0700143 self.queried = 0
James E. Blairb0fcae42012-07-17 11:12:10 -0700144 self.patchsets = []
James E. Blairb0fcae42012-07-17 11:12:10 -0700145 self.number = number
146 self.project = project
147 self.branch = branch
148 self.subject = subject
149 self.latest_patchset = 0
James E. Blair8c803f82012-07-31 16:25:42 -0700150 self.depends_on_change = None
151 self.needed_by_changes = []
James E. Blairb0fcae42012-07-17 11:12:10 -0700152 self.data = {
153 'branch': branch,
154 'comments': [],
155 'commitMessage': subject,
156 'createdOn': time.time(),
James E. Blair8cc15a82012-08-01 11:17:57 -0700157 'id': 'I' + random_sha1(),
James E. Blairb0fcae42012-07-17 11:12:10 -0700158 'lastUpdated': time.time(),
159 'number': str(number),
160 'open': True,
161 'owner': {'email': 'user@example.com',
162 'name': 'User Name',
163 'username': 'username'},
164 'patchSets': self.patchsets,
165 'project': project,
166 'status': status,
167 'subject': subject,
James E. Blair8c803f82012-07-31 16:25:42 -0700168 'submitRecords': [],
James E. Blairb0fcae42012-07-17 11:12:10 -0700169 'url': 'https://hostname/%s' % number}
170
171 self.addPatchset()
James E. Blair8c803f82012-07-31 16:25:42 -0700172 self.data['submitRecords'] = self.getSubmitRecords()
James E. Blairb0fcae42012-07-17 11:12:10 -0700173
174 def addPatchset(self, files=None):
175 self.latest_patchset += 1
James E. Blairdaabed22012-08-15 15:38:57 -0700176 if files:
177 fn = files[0]
178 else:
179 fn = '%s-%s' % (self.branch, self.number)
180 msg = self.subject + '-' + str(self.latest_patchset)
181 c = add_fake_change_to_repo(self.project, self.branch,
182 self.number, self.latest_patchset,
183 msg, fn)
James E. Blairb0fcae42012-07-17 11:12:10 -0700184 d = {'approvals': [],
185 'createdOn': time.time(),
186 'files': [{'file': '/COMMIT_MSG',
187 'type': 'ADDED'},
188 {'file': 'README',
189 'type': 'MODIFIED'}],
James E. Blair8c803f82012-07-31 16:25:42 -0700190 'number': str(self.latest_patchset),
James E. Blairb0fcae42012-07-17 11:12:10 -0700191 'ref': 'refs/changes/1/%s/%s' % (self.number,
192 self.latest_patchset),
James E. Blairdaabed22012-08-15 15:38:57 -0700193 'revision': c.hexsha,
James E. Blairb0fcae42012-07-17 11:12:10 -0700194 'uploader': {'email': 'user@example.com',
195 'name': 'User name',
196 'username': 'user'}}
197 self.data['currentPatchSet'] = d
198 self.patchsets.append(d)
James E. Blair8c803f82012-07-31 16:25:42 -0700199 self.data['submitRecords'] = self.getSubmitRecords()
James E. Blairb0fcae42012-07-17 11:12:10 -0700200
201 def addApproval(self, category, value):
James E. Blair8c803f82012-07-31 16:25:42 -0700202 approval = {'description': self.categories[category][0],
203 'type': category,
204 'value': str(value)}
205 self.patchsets[-1]['approvals'].append(approval)
206 event = {'approvals': [approval],
James E. Blairb0fcae42012-07-17 11:12:10 -0700207 'author': {'email': 'user@example.com',
208 'name': 'User Name',
209 'username': 'username'},
210 'change': {'branch': self.branch,
211 'id': 'Iaa69c46accf97d0598111724a38250ae76a22c87',
212 'number': str(self.number),
213 'owner': {'email': 'user@example.com',
214 'name': 'User Name',
215 'username': 'username'},
216 'project': self.project,
217 'subject': self.subject,
218 'topic': 'master',
219 'url': 'https://hostname/459'},
220 'comment': '',
221 'patchSet': self.patchsets[-1],
222 'type': 'comment-added'}
James E. Blair8c803f82012-07-31 16:25:42 -0700223 self.data['submitRecords'] = self.getSubmitRecords()
James E. Blairb0fcae42012-07-17 11:12:10 -0700224 return json.loads(json.dumps(event))
225
James E. Blair8c803f82012-07-31 16:25:42 -0700226 def getSubmitRecords(self):
227 status = {}
228 for cat in self.categories.keys():
229 status[cat] = 0
230
231 for a in self.patchsets[-1]['approvals']:
232 cur = status[a['type']]
233 cat_min, cat_max = self.categories[a['type']][1:]
234 new = int(a['value'])
235 if new == cat_min:
236 cur = new
237 elif abs(new) > abs(cur):
238 cur = new
239 status[a['type']] = cur
240
241 labels = []
242 ok = True
243 for typ, cat in self.categories.items():
244 cur = status[typ]
245 cat_min, cat_max = cat[1:]
246 if cur == cat_min:
247 value = 'REJECT'
248 ok = False
249 elif cur == cat_max:
250 value = 'OK'
251 else:
252 value = 'NEED'
253 ok = False
254 labels.append({'label': cat[0], 'status': value})
255 if ok:
256 return [{'status': 'OK'}]
257 return [{'status': 'NOT_READY',
258 'labels': labels}]
259
260 def setDependsOn(self, other, patchset):
261 self.depends_on_change = other
262 d = {'id': other.data['id'],
263 'number': other.data['number'],
264 'ref': other.patchsets[patchset - 1]['ref']
265 }
266 self.data['dependsOn'] = [d]
267
268 other.needed_by_changes.append(self)
269 needed = other.data.get('neededBy', [])
270 d = {'id': self.data['id'],
271 'number': self.data['number'],
272 'ref': self.patchsets[patchset - 1]['ref'],
273 'revision': self.patchsets[patchset - 1]['revision']
274 }
275 needed.append(d)
276 other.data['neededBy'] = needed
277
James E. Blairb0fcae42012-07-17 11:12:10 -0700278 def query(self):
James E. Blair8c803f82012-07-31 16:25:42 -0700279 self.queried += 1
280 d = self.data.get('dependsOn')
281 if d:
282 d = d[0]
283 if (self.depends_on_change.patchsets[-1]['ref'] == d['ref']):
284 d['isCurrentPatchSet'] = True
285 else:
286 d['isCurrentPatchSet'] = False
James E. Blairb0fcae42012-07-17 11:12:10 -0700287 return json.loads(json.dumps(self.data))
288
289 def setMerged(self):
290 self.data['status'] = 'MERGED'
291 self.open = False
James E. Blairdaabed22012-08-15 15:38:57 -0700292
293 path = os.path.join("/tmp/zuul-test/upstream", self.project)
294 repo = git.Repo(path)
295 repo.heads[self.branch].commit = \
296 repo.commit(self.patchsets[-1]['revision'])
James E. Blairb0fcae42012-07-17 11:12:10 -0700297
James E. Blaird466dc42012-07-31 10:42:56 -0700298 def setReported(self):
299 self.reported += 1
300
James E. Blairb0fcae42012-07-17 11:12:10 -0700301
302class FakeGerrit(object):
303 def __init__(self, *args, **kw):
304 self.event_queue = Queue.Queue()
305 self.fixture_dir = os.path.join(FIXTURE_DIR, 'gerrit')
306 self.change_number = 0
307 self.changes = {}
308
309 def addFakeChange(self, project, branch, subject):
310 self.change_number += 1
James E. Blair8cc15a82012-08-01 11:17:57 -0700311 c = FakeChange(self, self.change_number, project, branch, subject)
James E. Blairb0fcae42012-07-17 11:12:10 -0700312 self.changes[self.change_number] = c
313 return c
314
315 def addEvent(self, data):
316 return self.event_queue.put(data)
317
318 def getEvent(self):
319 return self.event_queue.get()
320
321 def eventDone(self):
322 self.event_queue.task_done()
323
324 def review(self, project, changeid, message, action):
James E. Blaird466dc42012-07-31 10:42:56 -0700325 number, ps = changeid.split(',')
326 change = self.changes[int(number)]
James E. Blairb0fcae42012-07-17 11:12:10 -0700327 if 'submit' in action:
James E. Blairb0fcae42012-07-17 11:12:10 -0700328 change.setMerged()
James E. Blaird466dc42012-07-31 10:42:56 -0700329 if message:
330 change.setReported()
James E. Blairb0fcae42012-07-17 11:12:10 -0700331
332 def query(self, number):
333 change = self.changes[int(number)]
334 return change.query()
335
336 def startWatching(self, *args, **kw):
337 pass
338
339
340class FakeJenkinsEvent(object):
341 def __init__(self, name, number, parameters, phase, status=None):
342 data = {'build':
343 {'full_url': 'https://server/job/%s/%s/' % (name, number),
344 'number': number,
345 'parameters': parameters,
346 'phase': phase,
347 'url': 'job/%s/%s/' % (name, number)},
348 'name': name,
349 'url': 'job/%s/' % name}
350 if status:
351 data['build']['status'] = status
352 self.body = json.dumps(data)
353
354
355class FakeJenkinsJob(threading.Thread):
356 log = logging.getLogger("zuul.test")
357
358 def __init__(self, jenkins, callback, name, number, parameters):
359 threading.Thread.__init__(self)
360 self.jenkins = jenkins
361 self.callback = callback
362 self.name = name
363 self.number = number
364 self.parameters = parameters
365 self.wait_condition = threading.Condition()
366 self.waiting = False
James E. Blaird466dc42012-07-31 10:42:56 -0700367 self.aborted = False
368 self.canceled = False
369 self.created = time.time()
James E. Blairb0fcae42012-07-17 11:12:10 -0700370
371 def release(self):
372 self.wait_condition.acquire()
373 self.wait_condition.notify()
374 self.waiting = False
375 self.log.debug("Job %s released" % (self.parameters['UUID']))
376 self.wait_condition.release()
377
378 def isWaiting(self):
379 self.wait_condition.acquire()
380 if self.waiting:
381 ret = True
382 else:
383 ret = False
384 self.wait_condition.release()
385 return ret
386
387 def _wait(self):
388 self.wait_condition.acquire()
389 self.waiting = True
390 self.log.debug("Job %s waiting" % (self.parameters['UUID']))
391 self.wait_condition.wait()
392 self.wait_condition.release()
393
394 def run(self):
395 self.jenkins.fakeEnqueue(self)
396 if self.jenkins.hold_jobs_in_queue:
397 self._wait()
398 self.jenkins.fakeDequeue(self)
James E. Blaird466dc42012-07-31 10:42:56 -0700399 if self.canceled:
400 self.jenkins.all_jobs.remove(self)
401 return
James E. Blairb0fcae42012-07-17 11:12:10 -0700402 self.callback.jenkins_endpoint(FakeJenkinsEvent(
403 self.name, self.number, self.parameters,
404 'STARTED'))
405 if self.jenkins.hold_jobs_in_build:
406 self._wait()
407 self.log.debug("Job %s continuing" % (self.parameters['UUID']))
James E. Blairb02a3bb2012-07-30 17:49:55 -0700408
409 result = 'SUCCESS'
James E. Blairdaabed22012-08-15 15:38:57 -0700410 if ('ZUUL_REF' in self.parameters) and self.jenkins.fakeShouldFailTest(
James E. Blairb02a3bb2012-07-30 17:49:55 -0700411 self.name,
James E. Blair4886cc12012-07-18 15:39:41 -0700412 self.parameters['ZUUL_REF']):
James E. Blairb02a3bb2012-07-30 17:49:55 -0700413 result = 'FAILURE'
James E. Blaird466dc42012-07-31 10:42:56 -0700414 if self.aborted:
415 result = 'ABORTED'
James E. Blairb02a3bb2012-07-30 17:49:55 -0700416
James E. Blairb0fcae42012-07-17 11:12:10 -0700417 self.jenkins.fakeAddHistory(name=self.name, number=self.number,
James E. Blairb02a3bb2012-07-30 17:49:55 -0700418 result=result)
James E. Blairb0fcae42012-07-17 11:12:10 -0700419 self.callback.jenkins_endpoint(FakeJenkinsEvent(
420 self.name, self.number, self.parameters,
James E. Blairb02a3bb2012-07-30 17:49:55 -0700421 'COMPLETED', result))
James E. Blairb0fcae42012-07-17 11:12:10 -0700422 self.callback.jenkins_endpoint(FakeJenkinsEvent(
423 self.name, self.number, self.parameters,
James E. Blairb02a3bb2012-07-30 17:49:55 -0700424 'FINISHED', result))
James E. Blairb0fcae42012-07-17 11:12:10 -0700425 self.jenkins.all_jobs.remove(self)
426
427
428class FakeJenkins(object):
429 log = logging.getLogger("zuul.test")
430
431 def __init__(self, *args, **kw):
432 self.queue = []
433 self.all_jobs = []
434 self.job_counter = {}
James E. Blaird466dc42012-07-31 10:42:56 -0700435 self.queue_counter = 0
James E. Blairb0fcae42012-07-17 11:12:10 -0700436 self.job_history = []
437 self.hold_jobs_in_queue = False
438 self.hold_jobs_in_build = False
James E. Blairb02a3bb2012-07-30 17:49:55 -0700439 self.fail_tests = {}
James E. Blairb0fcae42012-07-17 11:12:10 -0700440
441 def fakeEnqueue(self, job):
442 self.queue.append(job)
443
444 def fakeDequeue(self, job):
445 self.queue.remove(job)
446
447 def fakeAddHistory(self, **kw):
448 self.job_history.append(kw)
449
450 def fakeRelease(self, regex=None):
451 all_jobs = self.all_jobs[:]
452 self.log.debug("releasing jobs %s (%s)" % (regex, len(self.all_jobs)))
453 for job in all_jobs:
454 if not regex or re.match(regex, job.name):
455 self.log.debug("releasing job %s" % (job.parameters['UUID']))
456 job.release()
457 else:
458 self.log.debug("not releasing job %s" % (
459 job.parameters['UUID']))
460 self.log.debug("done releasing jobs %s (%s)" % (regex,
461 len(self.all_jobs)))
462
463 def fakeAllWaiting(self, regex=None):
464 all_jobs = self.all_jobs[:]
465 for job in all_jobs:
466 self.log.debug("job %s %s" % (job.parameters['UUID'],
467 job.isWaiting()))
468 if not job.isWaiting():
469 return False
470 return True
471
James E. Blairb02a3bb2012-07-30 17:49:55 -0700472 def fakeAddFailTest(self, name, change):
473 l = self.fail_tests.get(name, [])
474 l.append(change)
475 self.fail_tests[name] = l
476
James E. Blair4886cc12012-07-18 15:39:41 -0700477 def fakeShouldFailTest(self, name, ref):
James E. Blairb02a3bb2012-07-30 17:49:55 -0700478 l = self.fail_tests.get(name, [])
479 for change in l:
James E. Blair4886cc12012-07-18 15:39:41 -0700480 if ref_has_change(ref, change):
James E. Blairb02a3bb2012-07-30 17:49:55 -0700481 return True
482 return False
483
James E. Blairb0fcae42012-07-17 11:12:10 -0700484 def build_job(self, name, parameters):
485 count = self.job_counter.get(name, 0)
486 count += 1
487 self.job_counter[name] = count
James E. Blaird466dc42012-07-31 10:42:56 -0700488
489 queue_count = self.queue_counter
490 self.queue_counter += 1
James E. Blairb0fcae42012-07-17 11:12:10 -0700491 job = FakeJenkinsJob(self, self.callback, name, count, parameters)
James E. Blaird466dc42012-07-31 10:42:56 -0700492 job.queue_id = queue_count
493
James E. Blairb0fcae42012-07-17 11:12:10 -0700494 self.all_jobs.append(job)
495 job.start()
496
James E. Blaird466dc42012-07-31 10:42:56 -0700497 def stop_build(self, name, number):
498 for job in self.all_jobs:
499 if job.name == name and job.number == number:
500 job.aborted = True
501 job.release()
502 return
503
504 def cancel_queue(self, id):
505 for job in self.queue:
506 if job.queue_id == id:
507 job.canceled = True
508 job.release()
509 return
510
511 def get_queue_info(self):
512 items = []
513 for job in self.queue:
514 paramstr = ''
515 paramlst = []
516 d = {'actions': [{'parameters': paramlst},
517 {'causes': [{'shortDescription':
518 'Started by user Jenkins',
519 'userId': 'jenkins',
520 'userName': 'Jenkins'}]}],
521 'blocked': False,
522 'buildable': True,
523 'buildableStartMilliseconds': (job.created * 1000) + 5,
524 'id': job.queue_id,
525 'inQueueSince': (job.created * 1000),
526 'params': paramstr,
527 'stuck': False,
528 'task': {'color': 'blue',
529 'name': job.name,
530 'url': 'https://server/job/%s/' % job.name},
531 'why': 'Waiting for next available executor'}
532 for k, v in job.parameters.items():
533 paramstr += "\n(StringParameterValue) %s='%s'" % (k, v)
534 pd = {'name': k, 'value': v}
535 paramlst.append(pd)
536 items.append(d)
537 return items
538
James E. Blairb0fcae42012-07-17 11:12:10 -0700539 def set_build_description(self, *args, **kw):
540 pass
541
542
543class FakeJenkinsCallback(zuul.launcher.jenkins.JenkinsCallback):
544 def start(self):
545 pass
546
547
James E. Blair8cc15a82012-08-01 11:17:57 -0700548class FakeURLOpener(object):
549 def __init__(self, fake_gerrit, url):
550 self.fake_gerrit = fake_gerrit
551 self.url = url
552
553 def read(self):
554 res = urlparse.urlparse(self.url)
555 path = res.path
556 project = '/'.join(path.split('/')[2:-2])
James E. Blair8cc15a82012-08-01 11:17:57 -0700557 ret = ''
James E. Blairdaabed22012-08-15 15:38:57 -0700558 path = os.path.join("/tmp/zuul-test/upstream", project)
559 repo = git.Repo(path)
560 for ref in repo.refs:
561 ret += ref.object.hexsha + '\t' + ref.path + '\n'
James E. Blair8cc15a82012-08-01 11:17:57 -0700562 return ret
563
564
James E. Blair4886cc12012-07-18 15:39:41 -0700565class FakeGerritTrigger(zuul.trigger.gerrit.Gerrit):
566 def getGitUrl(self, project):
567 return "/tmp/zuul-test/upstream/%s" % project
568
569
James E. Blairb0fcae42012-07-17 11:12:10 -0700570class testScheduler(unittest.TestCase):
571 log = logging.getLogger("zuul.test")
572
573 def setUp(self):
James E. Blair4886cc12012-07-18 15:39:41 -0700574 if os.path.exists("/tmp/zuul-test"):
575 shutil.rmtree("/tmp/zuul-test")
576 os.makedirs("/tmp/zuul-test")
577 os.makedirs("/tmp/zuul-test/upstream")
578 os.makedirs("/tmp/zuul-test/git")
579
580 # For each project in config:
581 init_repo("org/project")
582 init_repo("org/project1")
583 init_repo("org/project2")
James E. Blairb0fcae42012-07-17 11:12:10 -0700584 self.config = CONFIG
585 self.sched = zuul.scheduler.Scheduler()
586
587 def jenkinsFactory(*args, **kw):
588 self.fake_jenkins = FakeJenkins()
589 return self.fake_jenkins
590
591 def jenkinsCallbackFactory(*args, **kw):
592 self.fake_jenkins_callback = FakeJenkinsCallback(*args, **kw)
593 return self.fake_jenkins_callback
594
James E. Blair8cc15a82012-08-01 11:17:57 -0700595 def URLOpenerFactory(*args, **kw):
596 args = [self.fake_gerrit] + list(args)
597 return FakeURLOpener(*args, **kw)
598
James E. Blairb0fcae42012-07-17 11:12:10 -0700599 zuul.launcher.jenkins.ExtendedJenkins = jenkinsFactory
600 zuul.launcher.jenkins.JenkinsCallback = jenkinsCallbackFactory
James E. Blair8cc15a82012-08-01 11:17:57 -0700601 urllib2.urlopen = URLOpenerFactory
James E. Blairb0fcae42012-07-17 11:12:10 -0700602 self.jenkins = zuul.launcher.jenkins.Jenkins(self.config, self.sched)
603 self.fake_jenkins.callback = self.fake_jenkins_callback
604
605 zuul.lib.gerrit.Gerrit = FakeGerrit
606
James E. Blair4886cc12012-07-18 15:39:41 -0700607 self.gerrit = FakeGerritTrigger(self.config, self.sched)
James E. Blair8cc15a82012-08-01 11:17:57 -0700608 self.gerrit.replication_timeout = 1.5
609 self.gerrit.replication_retry_interval = 0.5
James E. Blairb0fcae42012-07-17 11:12:10 -0700610 self.fake_gerrit = self.gerrit.gerrit
611
612 self.sched.setLauncher(self.jenkins)
613 self.sched.setTrigger(self.gerrit)
614
615 self.sched.start()
616 self.sched.reconfigure(self.config)
617 self.sched.resume()
618
619 def tearDown(self):
620 self.jenkins.stop()
621 self.gerrit.stop()
622 self.sched.stop()
623 self.sched.join()
James E. Blair4886cc12012-07-18 15:39:41 -0700624 #shutil.rmtree("/tmp/zuul-test")
James E. Blairb0fcae42012-07-17 11:12:10 -0700625
626 def waitUntilSettled(self):
627 self.log.debug("Waiting until settled...")
628 start = time.time()
629 while True:
630 if time.time() - start > 10:
631 print 'queue status:',
632 print self.sched.trigger_event_queue.empty(),
633 print self.sched.result_event_queue.empty(),
634 print self.fake_gerrit.event_queue.empty(),
635 raise Exception("Timeout waiting for Zuul to settle")
636 self.fake_gerrit.event_queue.join()
637 self.sched.queue_lock.acquire()
638 if (self.sched.trigger_event_queue.empty() and
639 self.sched.result_event_queue.empty() and
640 self.fake_gerrit.event_queue.empty() and
641 self.fake_jenkins.fakeAllWaiting()):
642 self.sched.queue_lock.release()
643 self.log.debug("...settled.")
644 return
645 self.sched.queue_lock.release()
646 self.sched.wake_event.wait(0.1)
647
James E. Blaird466dc42012-07-31 10:42:56 -0700648 def countJobResults(self, jobs, result):
649 jobs = filter(lambda x: x['result'] == result, jobs)
650 return len(jobs)
651
James E. Blairb0fcae42012-07-17 11:12:10 -0700652 def test_jobs_launched(self):
653 "Test that jobs are launched and a change is merged"
654 A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
James E. Blair8c803f82012-07-31 16:25:42 -0700655 A.addApproval('CRVW', 2)
James E. Blairb0fcae42012-07-17 11:12:10 -0700656 self.fake_gerrit.addEvent(A.addApproval('APRV', 1))
657 self.waitUntilSettled()
658 jobs = self.fake_jenkins.job_history
659 job_names = [x['name'] for x in jobs]
660 assert 'project-merge' in job_names
661 assert 'project-test1' in job_names
662 assert 'project-test2' in job_names
663 assert jobs[0]['result'] == 'SUCCESS'
664 assert jobs[1]['result'] == 'SUCCESS'
665 assert jobs[2]['result'] == 'SUCCESS'
666 assert A.data['status'] == 'MERGED'
James E. Blaird466dc42012-07-31 10:42:56 -0700667 assert A.reported == 2
James E. Blairb0fcae42012-07-17 11:12:10 -0700668
669 def test_parallel_changes(self):
670 "Test that changes are tested in parallel and merged in series"
671 self.fake_jenkins.hold_jobs_in_build = True
672 A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
673 B = self.fake_gerrit.addFakeChange('org/project', 'master', 'B')
674 C = self.fake_gerrit.addFakeChange('org/project', 'master', 'C')
James E. Blair8c803f82012-07-31 16:25:42 -0700675 A.addApproval('CRVW', 2)
676 B.addApproval('CRVW', 2)
677 C.addApproval('CRVW', 2)
James E. Blairb0fcae42012-07-17 11:12:10 -0700678
679 self.fake_gerrit.addEvent(A.addApproval('APRV', 1))
680 self.fake_gerrit.addEvent(B.addApproval('APRV', 1))
681 self.fake_gerrit.addEvent(C.addApproval('APRV', 1))
682
683 self.waitUntilSettled()
684 jobs = self.fake_jenkins.all_jobs
685 assert len(jobs) == 1
686 assert jobs[0].name == 'project-merge'
James E. Blair4886cc12012-07-18 15:39:41 -0700687 assert job_has_changes(jobs[0], A)
James E. Blairb0fcae42012-07-17 11:12:10 -0700688
689 self.fake_jenkins.fakeRelease('.*-merge')
690 self.waitUntilSettled()
691 assert len(jobs) == 3
692 assert jobs[0].name == 'project-test1'
James E. Blair4886cc12012-07-18 15:39:41 -0700693 assert job_has_changes(jobs[0], A)
James E. Blairb0fcae42012-07-17 11:12:10 -0700694 assert jobs[1].name == 'project-test2'
James E. Blair4886cc12012-07-18 15:39:41 -0700695 assert job_has_changes(jobs[1], A)
James E. Blairb0fcae42012-07-17 11:12:10 -0700696 assert jobs[2].name == 'project-merge'
James E. Blair4886cc12012-07-18 15:39:41 -0700697 assert job_has_changes(jobs[2], A, B)
James E. Blairb0fcae42012-07-17 11:12:10 -0700698
699 self.fake_jenkins.fakeRelease('.*-merge')
700 self.waitUntilSettled()
701 assert len(jobs) == 5
702 assert jobs[0].name == 'project-test1'
James E. Blair4886cc12012-07-18 15:39:41 -0700703 assert job_has_changes(jobs[0], A)
James E. Blairb0fcae42012-07-17 11:12:10 -0700704 assert jobs[1].name == 'project-test2'
James E. Blair4886cc12012-07-18 15:39:41 -0700705 assert job_has_changes(jobs[1], A)
James E. Blairb0fcae42012-07-17 11:12:10 -0700706
707 assert jobs[2].name == 'project-test1'
James E. Blair4886cc12012-07-18 15:39:41 -0700708 assert job_has_changes(jobs[2], A, B)
James E. Blairb0fcae42012-07-17 11:12:10 -0700709 assert jobs[3].name == 'project-test2'
James E. Blair4886cc12012-07-18 15:39:41 -0700710 assert job_has_changes(jobs[3], A, B)
James E. Blairb0fcae42012-07-17 11:12:10 -0700711
712 assert jobs[4].name == 'project-merge'
James E. Blair4886cc12012-07-18 15:39:41 -0700713 assert job_has_changes(jobs[4], A, B, C)
James E. Blairb0fcae42012-07-17 11:12:10 -0700714
715 self.fake_jenkins.fakeRelease('.*-merge')
716 self.waitUntilSettled()
717 assert len(jobs) == 6
718 assert jobs[0].name == 'project-test1'
James E. Blair4886cc12012-07-18 15:39:41 -0700719 assert job_has_changes(jobs[0], A)
James E. Blairb0fcae42012-07-17 11:12:10 -0700720 assert jobs[1].name == 'project-test2'
James E. Blair4886cc12012-07-18 15:39:41 -0700721 assert job_has_changes(jobs[1], A)
James E. Blairb0fcae42012-07-17 11:12:10 -0700722
723 assert jobs[2].name == 'project-test1'
James E. Blair4886cc12012-07-18 15:39:41 -0700724 assert job_has_changes(jobs[2], A, B)
James E. Blairb0fcae42012-07-17 11:12:10 -0700725 assert jobs[3].name == 'project-test2'
James E. Blair4886cc12012-07-18 15:39:41 -0700726 assert job_has_changes(jobs[3], A, B)
James E. Blairb0fcae42012-07-17 11:12:10 -0700727
728 assert jobs[4].name == 'project-test1'
James E. Blair4886cc12012-07-18 15:39:41 -0700729 assert job_has_changes(jobs[4], A, B, C)
James E. Blairb0fcae42012-07-17 11:12:10 -0700730 assert jobs[5].name == 'project-test2'
James E. Blair4886cc12012-07-18 15:39:41 -0700731 assert job_has_changes(jobs[5], A, B, C)
James E. Blairb0fcae42012-07-17 11:12:10 -0700732
733 self.fake_jenkins.hold_jobs_in_build = False
734 self.fake_jenkins.fakeRelease()
735 self.waitUntilSettled()
736 assert len(jobs) == 0
737
738 jobs = self.fake_jenkins.job_history
739 assert len(jobs) == 9
740 assert A.data['status'] == 'MERGED'
741 assert B.data['status'] == 'MERGED'
742 assert C.data['status'] == 'MERGED'
James E. Blaird466dc42012-07-31 10:42:56 -0700743 assert A.reported == 2
744 assert B.reported == 2
745 assert C.reported == 2
James E. Blairb02a3bb2012-07-30 17:49:55 -0700746
747 def test_failed_changes(self):
748 "Test that a change behind a failed change is retested"
749 A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
750 B = self.fake_gerrit.addFakeChange('org/project', 'master', 'B')
James E. Blair8c803f82012-07-31 16:25:42 -0700751 A.addApproval('CRVW', 2)
752 B.addApproval('CRVW', 2)
James E. Blairb02a3bb2012-07-30 17:49:55 -0700753
754 self.fake_gerrit.addEvent(A.addApproval('APRV', 1))
755 self.fake_gerrit.addEvent(B.addApproval('APRV', 1))
756
James E. Blair4886cc12012-07-18 15:39:41 -0700757 self.fake_jenkins.fakeAddFailTest('project-test1', A)
James E. Blairb02a3bb2012-07-30 17:49:55 -0700758
759 self.waitUntilSettled()
760 jobs = self.fake_jenkins.job_history
761 assert len(jobs) > 6
762 assert A.data['status'] == 'NEW'
763 assert B.data['status'] == 'MERGED'
James E. Blaird466dc42012-07-31 10:42:56 -0700764 assert A.reported == 2
765 assert B.reported == 2
James E. Blairb02a3bb2012-07-30 17:49:55 -0700766
767 def test_independent_queues(self):
768 "Test that changes end up in the right queues"
769 self.fake_jenkins.hold_jobs_in_build = True
770 A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
771 B = self.fake_gerrit.addFakeChange('org/project1', 'master', 'B')
772 C = self.fake_gerrit.addFakeChange('org/project2', 'master', 'C')
James E. Blair8c803f82012-07-31 16:25:42 -0700773 A.addApproval('CRVW', 2)
774 B.addApproval('CRVW', 2)
775 C.addApproval('CRVW', 2)
James E. Blairb02a3bb2012-07-30 17:49:55 -0700776
777 self.fake_gerrit.addEvent(A.addApproval('APRV', 1))
778 self.fake_gerrit.addEvent(B.addApproval('APRV', 1))
779 self.fake_gerrit.addEvent(C.addApproval('APRV', 1))
780
781 jobs = self.fake_jenkins.all_jobs
782 self.waitUntilSettled()
783
784 # There should be one merge job at the head of each queue running
785 assert len(jobs) == 2
786 assert jobs[0].name == 'project-merge'
James E. Blair4886cc12012-07-18 15:39:41 -0700787 assert job_has_changes(jobs[0], A)
James E. Blairb02a3bb2012-07-30 17:49:55 -0700788 assert jobs[1].name == 'project1-merge'
James E. Blair4886cc12012-07-18 15:39:41 -0700789 assert job_has_changes(jobs[1], B)
James E. Blairb02a3bb2012-07-30 17:49:55 -0700790
791 # Release the current merge jobs
792 self.fake_jenkins.fakeRelease('.*-merge')
793 self.waitUntilSettled()
794 # Release the merge job for project2 which is behind project1
795 self.fake_jenkins.fakeRelease('.*-merge')
796 self.waitUntilSettled()
797
798 # All the test jobs should be running:
799 # project1 (3) + project2 (3) + project (2) = 8
800 assert len(jobs) == 8
801
802 self.fake_jenkins.fakeRelease()
803 self.waitUntilSettled()
804 assert len(jobs) == 0
805
806 jobs = self.fake_jenkins.job_history
807 assert len(jobs) == 11
808 assert A.data['status'] == 'MERGED'
809 assert B.data['status'] == 'MERGED'
810 assert C.data['status'] == 'MERGED'
James E. Blaird466dc42012-07-31 10:42:56 -0700811 assert A.reported == 2
812 assert B.reported == 2
813 assert C.reported == 2
814
815 def test_failed_change_at_head(self):
816 "Test that if a change at the head fails, jobs behind it are canceled"
817 self.fake_jenkins.hold_jobs_in_build = True
818
819 A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
820 B = self.fake_gerrit.addFakeChange('org/project', 'master', 'B')
821 C = self.fake_gerrit.addFakeChange('org/project', 'master', 'C')
James E. Blair8c803f82012-07-31 16:25:42 -0700822 A.addApproval('CRVW', 2)
823 B.addApproval('CRVW', 2)
824 C.addApproval('CRVW', 2)
James E. Blaird466dc42012-07-31 10:42:56 -0700825
James E. Blair4886cc12012-07-18 15:39:41 -0700826 self.fake_jenkins.fakeAddFailTest('project-test1', A)
James E. Blaird466dc42012-07-31 10:42:56 -0700827
828 self.fake_gerrit.addEvent(A.addApproval('APRV', 1))
829 self.fake_gerrit.addEvent(B.addApproval('APRV', 1))
830 self.fake_gerrit.addEvent(C.addApproval('APRV', 1))
831
832 self.waitUntilSettled()
833 jobs = self.fake_jenkins.all_jobs
834 finished_jobs = self.fake_jenkins.job_history
835
836 assert len(jobs) == 1
837 assert jobs[0].name == 'project-merge'
James E. Blair4886cc12012-07-18 15:39:41 -0700838 assert job_has_changes(jobs[0], A)
James E. Blaird466dc42012-07-31 10:42:56 -0700839
840 self.fake_jenkins.fakeRelease('.*-merge')
841 self.waitUntilSettled()
842 self.fake_jenkins.fakeRelease('.*-merge')
843 self.waitUntilSettled()
844 self.fake_jenkins.fakeRelease('.*-merge')
845 self.waitUntilSettled()
846
847 assert len(jobs) == 6
848 assert jobs[0].name == 'project-test1'
849 assert jobs[1].name == 'project-test2'
850 assert jobs[2].name == 'project-test1'
851 assert jobs[3].name == 'project-test2'
852 assert jobs[4].name == 'project-test1'
853 assert jobs[5].name == 'project-test2'
854
855 jobs[0].release()
856 self.waitUntilSettled()
857
858 assert len(jobs) == 1 # project-test2
859 assert self.countJobResults(finished_jobs, 'ABORTED') == 4
860
861 self.fake_jenkins.hold_jobs_in_build = False
862 self.fake_jenkins.fakeRelease()
863 self.waitUntilSettled()
864
865 assert len(jobs) == 0
866 assert len(finished_jobs) == 15
867 assert A.data['status'] == 'NEW'
868 assert B.data['status'] == 'MERGED'
869 assert C.data['status'] == 'MERGED'
870 assert A.reported == 2
871 assert B.reported == 2
872 assert C.reported == 2
873
874 def test_failed_change_at_head_with_queue(self):
875 "Test that if a change at the head fails, queued jobs are canceled"
876 self.fake_jenkins.hold_jobs_in_queue = True
877
878 A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
879 B = self.fake_gerrit.addFakeChange('org/project', 'master', 'B')
880 C = self.fake_gerrit.addFakeChange('org/project', 'master', 'C')
James E. Blair8c803f82012-07-31 16:25:42 -0700881 A.addApproval('CRVW', 2)
882 B.addApproval('CRVW', 2)
883 C.addApproval('CRVW', 2)
James E. Blaird466dc42012-07-31 10:42:56 -0700884
James E. Blair4886cc12012-07-18 15:39:41 -0700885 self.fake_jenkins.fakeAddFailTest('project-test1', A)
James E. Blaird466dc42012-07-31 10:42:56 -0700886
887 self.fake_gerrit.addEvent(A.addApproval('APRV', 1))
888 self.fake_gerrit.addEvent(B.addApproval('APRV', 1))
889 self.fake_gerrit.addEvent(C.addApproval('APRV', 1))
890
891 self.waitUntilSettled()
892 jobs = self.fake_jenkins.all_jobs
893 finished_jobs = self.fake_jenkins.job_history
894 queue = self.fake_jenkins.queue
895
896 assert len(jobs) == 1
897 assert len(queue) == 1
898 assert jobs[0].name == 'project-merge'
James E. Blair4886cc12012-07-18 15:39:41 -0700899 assert job_has_changes(jobs[0], A)
James E. Blaird466dc42012-07-31 10:42:56 -0700900
901 self.fake_jenkins.fakeRelease('.*-merge')
902 self.waitUntilSettled()
903 self.fake_jenkins.fakeRelease('.*-merge')
904 self.waitUntilSettled()
905 self.fake_jenkins.fakeRelease('.*-merge')
906 self.waitUntilSettled()
907
908 assert len(jobs) == 6
909 assert len(queue) == 6
910 assert jobs[0].name == 'project-test1'
911 assert jobs[1].name == 'project-test2'
912 assert jobs[2].name == 'project-test1'
913 assert jobs[3].name == 'project-test2'
914 assert jobs[4].name == 'project-test1'
915 assert jobs[5].name == 'project-test2'
916
917 jobs[0].release()
918 self.waitUntilSettled()
919
920 assert len(jobs) == 1 # project-test2
921 assert len(queue) == 1
922 assert self.countJobResults(finished_jobs, 'ABORTED') == 0
923
924 self.fake_jenkins.hold_jobs_in_queue = False
925 self.fake_jenkins.fakeRelease()
926 self.waitUntilSettled()
927
928 assert len(jobs) == 0
929 assert len(finished_jobs) == 11
930 assert A.data['status'] == 'NEW'
931 assert B.data['status'] == 'MERGED'
932 assert C.data['status'] == 'MERGED'
933 assert A.reported == 2
934 assert B.reported == 2
935 assert C.reported == 2
James E. Blair8c803f82012-07-31 16:25:42 -0700936
937 def test_patch_order(self):
938 "Test that dependent patches are tested in the right order"
939 A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
940 B = self.fake_gerrit.addFakeChange('org/project', 'master', 'B')
941 C = self.fake_gerrit.addFakeChange('org/project', 'master', 'C')
942 A.addApproval('CRVW', 2)
943 B.addApproval('CRVW', 2)
944 C.addApproval('CRVW', 2)
945
946 M2 = self.fake_gerrit.addFakeChange('org/project', 'master', 'M2')
947 M1 = self.fake_gerrit.addFakeChange('org/project', 'master', 'M1')
948 M2.setMerged()
949 M1.setMerged()
950
951 # C -> B -> A -> M1 -> M2
952 # M2 is here to make sure it is never queried. If it is, it
953 # means zuul is walking down the entire history of merged
954 # changes.
955
956 C.setDependsOn(B, 1)
957 B.setDependsOn(A, 1)
958 A.setDependsOn(M1, 1)
959 M1.setDependsOn(M2, 1)
960
961 self.fake_gerrit.addEvent(C.addApproval('APRV', 1))
962
963 self.waitUntilSettled()
964
965 assert A.data['status'] == 'NEW'
966 assert B.data['status'] == 'NEW'
967 assert C.data['status'] == 'NEW'
968
969 self.fake_gerrit.addEvent(B.addApproval('APRV', 1))
970 self.fake_gerrit.addEvent(A.addApproval('APRV', 1))
971
972 self.waitUntilSettled()
973 assert M2.queried == 0
974 assert A.data['status'] == 'MERGED'
975 assert B.data['status'] == 'MERGED'
976 assert C.data['status'] == 'MERGED'
977 assert A.reported == 2
978 assert B.reported == 2
979 assert C.reported == 2
980
981 def test_can_merge(self):
James E. Blair4886cc12012-07-18 15:39:41 -0700982 "Test whether a change is ready to merge"
James E. Blair8c803f82012-07-31 16:25:42 -0700983 # TODO: move to test_gerrit (this is a unit test!)
984 A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
James E. Blair4aea70c2012-07-26 14:23:24 -0700985 a = self.sched.trigger.getChange(1, 2)
986 mgr = self.sched.pipelines['gate'].manager
987 assert not self.sched.trigger.canMerge(a, mgr.getSubmitAllowNeeds())
James E. Blair8c803f82012-07-31 16:25:42 -0700988
989 A.addApproval('CRVW', 2)
James E. Blair4aea70c2012-07-26 14:23:24 -0700990 a = self.sched.trigger.getChange(1, 2)
991 assert not self.sched.trigger.canMerge(a, mgr.getSubmitAllowNeeds())
James E. Blair8c803f82012-07-31 16:25:42 -0700992
993 A.addApproval('APRV', 1)
James E. Blair4aea70c2012-07-26 14:23:24 -0700994 a = self.sched.trigger.getChange(1, 2)
995 assert self.sched.trigger.canMerge(a, mgr.getSubmitAllowNeeds())
James E. Blair8c803f82012-07-31 16:25:42 -0700996
997 return True
James E. Blair4886cc12012-07-18 15:39:41 -0700998
999 def test_build_configuration(self):
1000 "Test that zuul merges the right commits for testing"
1001 self.fake_jenkins.hold_jobs_in_queue = True
1002 A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
1003 B = self.fake_gerrit.addFakeChange('org/project', 'master', 'B')
1004 C = self.fake_gerrit.addFakeChange('org/project', 'master', 'C')
1005 A.addApproval('CRVW', 2)
1006 B.addApproval('CRVW', 2)
1007 C.addApproval('CRVW', 2)
1008 self.fake_gerrit.addEvent(A.addApproval('APRV', 1))
1009 self.fake_gerrit.addEvent(B.addApproval('APRV', 1))
1010 self.fake_gerrit.addEvent(C.addApproval('APRV', 1))
1011 self.waitUntilSettled()
1012
1013 jobs = self.fake_jenkins.all_jobs
1014
1015 self.fake_jenkins.fakeRelease('.*-merge')
1016 self.waitUntilSettled()
1017 self.fake_jenkins.fakeRelease('.*-merge')
1018 self.waitUntilSettled()
1019 self.fake_jenkins.fakeRelease('.*-merge')
1020 self.waitUntilSettled()
1021 ref = jobs[-1].parameters['ZUUL_REF']
1022 self.fake_jenkins.hold_jobs_in_queue = False
1023 self.fake_jenkins.fakeRelease()
James E. Blair973721f2012-08-15 10:19:43 -07001024 self.waitUntilSettled()
James E. Blair4886cc12012-07-18 15:39:41 -07001025
1026 path = os.path.join("/tmp/zuul-test/git/org/project")
1027 repo = git.Repo(path)
1028 repo_messages = [c.message.strip() for c in repo.iter_commits(ref)]
1029 repo_messages.reverse()
1030 print ' repo messages :', repo_messages
1031 correct_messages = ['initial commit', 'A-1', 'B-1', 'C-1']
1032 assert repo_messages == correct_messages
James E. Blair973721f2012-08-15 10:19:43 -07001033
1034 def test_build_configuration_conflict(self):
1035 "Test that merge conflicts are handled"
1036 self.fake_jenkins.hold_jobs_in_queue = True
1037 A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
1038 A.addPatchset(['conflict'])
1039 B = self.fake_gerrit.addFakeChange('org/project', 'master', 'B')
1040 B.addPatchset(['conflict'])
1041 C = self.fake_gerrit.addFakeChange('org/project', 'master', 'C')
1042 A.addApproval('CRVW', 2)
1043 B.addApproval('CRVW', 2)
1044 C.addApproval('CRVW', 2)
1045 self.fake_gerrit.addEvent(A.addApproval('APRV', 1))
1046 self.fake_gerrit.addEvent(B.addApproval('APRV', 1))
1047 self.fake_gerrit.addEvent(C.addApproval('APRV', 1))
1048 self.waitUntilSettled()
1049
1050 jobs = self.fake_jenkins.all_jobs
1051
1052 self.fake_jenkins.fakeRelease('.*-merge')
1053 self.waitUntilSettled()
1054 self.fake_jenkins.fakeRelease('.*-merge')
1055 self.waitUntilSettled()
1056 self.fake_jenkins.fakeRelease('.*-merge')
1057 self.waitUntilSettled()
1058 ref = jobs[-1].parameters['ZUUL_REF']
1059 self.fake_jenkins.hold_jobs_in_queue = False
1060 self.fake_jenkins.fakeRelease()
1061 self.waitUntilSettled()
1062
1063 assert A.data['status'] == 'MERGED'
1064 assert B.data['status'] == 'NEW'
1065 assert C.data['status'] == 'MERGED'
1066 assert A.reported == 2
1067 assert B.reported == 2
1068 assert C.reported == 2
James E. Blairdaabed22012-08-15 15:38:57 -07001069
1070 def test_post(self):
1071 "Test that post jobs run"
1072 e = {"type": "ref-updated",
1073 "submitter": {"name": "User Name"},
1074 "refUpdate": {"oldRev":
1075 "90f173846e3af9154517b88543ffbd1691f31366",
1076 "newRev":
1077 "d479a0bfcb34da57a31adb2a595c0cf687812543",
1078 "refName": "master", "project": "org/project"}}
1079 self.fake_gerrit.addEvent(e)
1080 self.waitUntilSettled()
1081
1082 jobs = self.fake_jenkins.job_history
1083 job_names = [x['name'] for x in jobs]
1084 assert len(jobs) == 1
1085 assert 'project-post' in job_names
James E. Blairc6294a52012-08-17 10:19:48 -07001086
1087 def test_build_configuration_branch(self):
1088 "Test that the right commits are on alternate branches"
1089 self.fake_jenkins.hold_jobs_in_queue = True
1090 A = self.fake_gerrit.addFakeChange('org/project', 'mp', 'A')
1091 B = self.fake_gerrit.addFakeChange('org/project', 'mp', 'B')
1092 C = self.fake_gerrit.addFakeChange('org/project', 'mp', 'C')
1093 A.addApproval('CRVW', 2)
1094 B.addApproval('CRVW', 2)
1095 C.addApproval('CRVW', 2)
1096 self.fake_gerrit.addEvent(A.addApproval('APRV', 1))
1097 self.fake_gerrit.addEvent(B.addApproval('APRV', 1))
1098 self.fake_gerrit.addEvent(C.addApproval('APRV', 1))
1099 self.waitUntilSettled()
1100
1101 jobs = self.fake_jenkins.all_jobs
1102
1103 self.fake_jenkins.fakeRelease('.*-merge')
1104 self.waitUntilSettled()
1105 self.fake_jenkins.fakeRelease('.*-merge')
1106 self.waitUntilSettled()
1107 self.fake_jenkins.fakeRelease('.*-merge')
1108 self.waitUntilSettled()
1109 ref = jobs[-1].parameters['ZUUL_REF']
1110 self.fake_jenkins.hold_jobs_in_queue = False
1111 self.fake_jenkins.fakeRelease()
1112 self.waitUntilSettled()
1113
1114 path = os.path.join("/tmp/zuul-test/git/org/project")
1115 repo = git.Repo(path)
1116 repo_messages = [c.message.strip() for c in repo.iter_commits(ref)]
1117 repo_messages.reverse()
1118 print ' repo messages :', repo_messages
1119 correct_messages = ['initial commit', 'mp commit', 'A-1', 'B-1', 'C-1']
1120 assert repo_messages == correct_messages
1121
1122 def test_build_configuration_branch_interaction(self):
1123 "Test that switching between branches works"
1124 self.test_build_configuration()
1125 self.test_build_configuration_branch()
1126 # C has been merged, undo that
1127 path = os.path.join("/tmp/zuul-test/upstream", "org/project")
1128 repo = git.Repo(path)
1129 repo.heads.master.commit = repo.commit('init')
1130 self.test_build_configuration()
1131
1132 def test_build_configuration_multi_branch(self):
1133 "Test that dependent changes on multiple branches are merged"
1134 self.fake_jenkins.hold_jobs_in_queue = True
1135 A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
1136 B = self.fake_gerrit.addFakeChange('org/project', 'mp', 'B')
1137 C = self.fake_gerrit.addFakeChange('org/project', 'master', 'C')
1138 A.addApproval('CRVW', 2)
1139 B.addApproval('CRVW', 2)
1140 C.addApproval('CRVW', 2)
1141 self.fake_gerrit.addEvent(A.addApproval('APRV', 1))
1142 self.fake_gerrit.addEvent(B.addApproval('APRV', 1))
1143 self.fake_gerrit.addEvent(C.addApproval('APRV', 1))
1144 self.waitUntilSettled()
1145
1146 jobs = self.fake_jenkins.all_jobs
1147
1148 self.fake_jenkins.fakeRelease('.*-merge')
1149 self.waitUntilSettled()
1150 ref_mp = jobs[-1].parameters['ZUUL_REF']
1151 self.fake_jenkins.fakeRelease('.*-merge')
1152 self.waitUntilSettled()
1153 self.fake_jenkins.fakeRelease('.*-merge')
1154 self.waitUntilSettled()
1155 ref_master = jobs[-1].parameters['ZUUL_REF']
1156 self.fake_jenkins.hold_jobs_in_queue = False
1157 self.fake_jenkins.fakeRelease()
1158 self.waitUntilSettled()
1159
1160 path = os.path.join("/tmp/zuul-test/git/org/project")
1161 repo = git.Repo(path)
1162
1163 repo_messages = [c.message.strip()
1164 for c in repo.iter_commits(ref_master)]
1165 repo_messages.reverse()
1166 print ' repo messages :', repo_messages
1167 correct_messages = ['initial commit', 'A-1', 'C-1']
1168 assert repo_messages == correct_messages
1169
1170 repo_messages = [c.message.strip()
1171 for c in repo.iter_commits(ref_mp)]
1172 repo_messages.reverse()
1173 print ' repo messages :', repo_messages
1174 correct_messages = ['initial commit', 'mp commit', 'B-1']
1175 assert repo_messages == correct_messages