def build_job(host, jobname, options): """ Trigger build for an existing job. If the wait option is specified, wait until build completion :returns: A boolean value indicating success: * If wait: ``True`` if build was successful, ``False`` otherwise * If not wait: ``True`` if HTTP status code is not an error code """ print ("Start building job '{0}'".format(jobname)) jenkins = Jenkins(host, proxies=get_proxy(options), auth=get_auth(options)) try: response = jenkins.build(jobname, wait=options['--wait']) if options['--wait']: result = response['result'] print('Result = "{0}"'.format(result)) return result == 'SUCCESS' else: print("Build '%s' started" % jobname) return response.status_code < 400 except (jobs.JobInexistent, jobs.JobNotBuildable) as error: print("Error:", error.msg) return False
def list_jobs(host, options, color=True, raw=False): """ List all jobs """ if raw: FORMAT = "{1}" position = 0 elif color: FORMAT = "\033[{0}m{1}\033[0m" position = 0 else: FORMAT = "{0:<10} {1}" position = 1 if not raw: print ("All jobs in {0}".format(host)) jenkins = Jenkins(host, proxies=get_proxy(options), auth=get_auth(options)) joblist = jenkins.all_jobs() for name, color in joblist: if '_' in color: color = color.split('_')[0] building = True else: building = False prefix = '' if raw else '* ' if building else ' ' out = COLOR_MEANING[color][position] print(prefix + FORMAT.format(out, name))
def create_job(host, jobname, options): """ Create a new job """ data = get_variables(options["-D"]) print( """ Creating job '{0}' from template '{1}' with: {2} """.format( jobname, options["<template>"], data ) ) jenkins = Jenkins(host, proxies=get_proxy(options), auth=get_auth(options)) try: response = jenkins.create_copy(jobname, options["<template>"], **data) if response.status_code == 200 and options["--build"]: print("Triggering build.") jenkins.build(jobname) print("Job URL: {0}".format(jenkins.job_url(jobname))) return response.status_code < 400 except jobs.JobExists as error: print("Error:", error.msg) return False
def delete_jobs(host, jobnames): """ Delete existing jobs. """ for jobname in jobnames: print ("Deleting job '{0}'".format(jobname)) jenkins = Jenkins(host) response = jenkins.delete(jobname) print(response.status_code)
def delete_job(host, jobname): """ Delete an existing job """ print ("Deleting job '{0}'".format(jobname)) jenkins = Jenkins(host) response = jenkins.delete(jobname) print('Status: {0}'.format(response.status_code))
def delete_jobs(host, jobnames, options): """ Delete existing jobs. """ jenkins = Jenkins(host, auth=get_auth(options)) for jobname in jobnames: print ("Deleting job '{0}'".format(jobname)) response = jenkins.delete(jobname) print(response.status_code)
def delete_jobs(host, jobnames, options): """ Delete existing jobs. """ jenkins = Jenkins(host, auth=get_auth(options)) for jobname in jobnames: print("Deleting job '{0}'".format(jobname)) response = jenkins.delete(jobname) print(response.status_code)
def __init__(self): self.jenkins_url = jenkins_config.get('url') self.user = jenkins_config.get('user') self.password = jenkins_config.get('password') if self.jenkins_url is not None: try: self.jenkins = Jenkins(self.jenkins_url, auth=(self.user, self.password)) except Exception as e: log_error(e)
def main(): url = sys.argv[1] jobname = sys.argv[2] jenkins = Jenkins(url) result = jenkins.build(jobname, wait=True) print('id=' + result['id']) if result['result'] == 'SUCCESS': sys.exit(0) else: sys.exit(1)
class TestJenkins(TestCase): def setUp(self): super(TestJenkins, self).setUp() self.jenkins = Jenkins('http://jenkins') def test_all_jobs(self, requests): response = {'jobs': [{'name': 'job1', 'color': 'blue'}]} requests.get.return_value = mock_response(response) jobs = self.jenkins.all_jobs() requests.get.assert_called_once_with('http://jenkins/api/python', verify=True, auth=None) self.assertEqual(jobs, [('job1', 'blue')]) def test_get_job_url(self, *args): url = self.jenkins.job_url('job123') self.assertEqual('http://jenkins/job/job123', url) def test_last_result(self, requests, *args): second_response = Mock(status_code=200) second_response.content = "{'result': 23}" requests.get.side_effect = [ mock_response('job_info.txt'), second_response ] response = self.jenkins.last_result('name') self.assertEqual(23, response['result']) self.assertEqual( (('https://builds.apache.org/job/Solr-Trunk/1783/api/python',), {'auth': None, 'verify': True}), requests.get.call_args_list[1] ) @data( ('job_info', 'job/{0}/api/python'), ('last_build_info', 'job/{0}/lastBuild/api/python'), ('last_build_report', 'job/{0}/lastBuild/testReport/api/python'), ('last_success', 'job/{0}/lastSuccessfulBuild/api/python'), ('get_config_xml', 'job/{0}/config.xml'), ) def test_get_methods_with_jobname(self, case, requests): method, url = case requests.get.return_value = mock_response('{0}.txt'.format(method)) response = getattr(self.jenkins, method)('name') requests.get.assert_called_once_with( 'http://jenkins/' + url.format('name'), verify=True, auth=None) getattr(self, 'checks_{0}'.format(method))(response)
def delete_jobs(host, jobnames, options): """ Delete existing jobs. """ jenkins = Jenkins(host, proxies=get_proxy(options), auth=get_auth(options)) for jobname in jobnames: print("Deleting job '{0}'".format(jobname)) try: response = jenkins.delete(jobname) if response.status_code == 200: print "Job '%s' deleted" % jobname except jobs.JobInexistent as error: print "Error: %s" % error.msg except (jobs.HttpForbidden, jobs.HttpUnauthorized): pass
def delete_jobs(host, jobnames, options): """ Delete existing jobs. """ jenkins = Jenkins(host, proxies=get_proxy(options), auth=get_auth(options)) for jobname in jobnames: print ("Deleting job '{0}'".format(jobname)) try: response = jenkins.delete(jobname) if response.status_code == 200: print("Job '%s' deleted" % jobname) except jobs.JobInexistent as error: print("Error:", error.msg) print("Error:", error.msg) except (jobs.HttpForbidden, jobs.HttpUnauthorized): pass
def create_job(host, jobname, options): """ Create a new job """ data = get_variables(options) print (""" Creating job '{0}' from template '{1}' with: {2} """.format(jobname, options.template, data)) jenkins = Jenkins(host) response = jenkins.create_copy(jobname, options.template, **data) if response.status_code == 200 and options.build: print('Triggering build.') jenkins.build(jobname) return response.status_code
def __init__(self): self.jenkins_url = jenkins_config.get('url') self.user = jenkins_config.get('user') self.password = jenkins_config.get('password') if self.jenkins_url is not None: try: self.jenkins = Jenkins( self.jenkins_url, auth=(self.user, self.password)) except Exception as e: log_error(e)
def run_jenkins(host, jobname, options): spliteq = lambda x: x.split("=") data = dict(map(spliteq, options.D)) print( """ Creating job '{0}' from template '{1}' with: {2} """.format( jobname, options.template, data ) ) jenkins = Jenkins(host) response = jenkins.create_copy(jobname, options.template, **data) print("Status: {0}".format(response.status_code)) if response.status_code == 200 and options.build: print("Triggering build.") j.build(jobname)
def list_jobs(host): """ List all jobs """ COLOR = "\033[{0}m" COLORCODE = { 'blue': '1;34', 'red': '1;31', 'yellow': '1;33', 'aborted': '1;37', 'disabled': '0;37', 'grey': '1;37', } print ("All jobs in {0}".format(host)) jenkins = Jenkins(host) jobs = jenkins.all_jobs() for name, color in jobs: print(COLOR.format(COLORCODE[color.split('_')[0]]) + name)
def list_jobs(host, color=True): """ List all jobs """ if color: FORMAT = "\033[{0}m{1}\033[0m" position = 0 else: FORMAT = "{0:<10} {1}" position = 1 print ("All jobs in {0}".format(host)) jenkins = Jenkins(host) jobs = jenkins.all_jobs() for name, color in jobs: if '_' in color: color = color.split('_')[0] building = True else: building = False prefix = '* ' if building else ' ' out = COLOR_MEANING[color][position] print(prefix + FORMAT.format(out, name))
def build_job(host, jobname, options): """ Trigger build for an existing job. If the wait option is specified, wait until build completion :returns: A boolean value indicating success: * If wait: ``True`` if build was successful, ``False`` otherwise * If not wait: ``True`` if HTTP status code is not an error code """ print("Start building job '{0}'".format(jobname)) jenkins = Jenkins(host, auth=get_auth(options)) response = jenkins.build(jobname, wait=options.wait) if options.wait: result = response['result'] print('Result = "{0}"'.format(result)) return result == 'SUCCESS' else: return response.status_code < 400
def build_job(host, jobname, options): """ Trigger build for an existing job. If the wait option is specified, wait until build completion :returns: A boolean value indicating success: * If wait: ``True`` if build was successful, ``False`` otherwise * If not wait: ``True`` if HTTP status code is not an error code """ print ("Start building job '{0}'".format(jobname)) jenkins = Jenkins(host, auth=get_auth(options)) response = jenkins.build(jobname, wait=options.wait) if options.wait: result = response['result'] print('Result = "{0}"'.format(result)) return result == 'SUCCESS' else: return response.status_code < 400
def create_job(host, jobname, options): """ Create a new job """ data = get_variables(options['-D']) print (""" Creating job '{0}' from template '{1}' with: {2} """.format(jobname, options['<template>'], data)) jenkins = Jenkins(host, proxies=get_proxy(options), auth=get_auth(options)) try: response = jenkins.create_copy(jobname, options['<template>'], **data) if response.status_code == 200 and options['--build']: print('Triggering build.') jenkins.build(jobname) print ('Job URL: {0}'.format(jenkins.job_url(jobname))) return response.status_code < 400 except jobs.JobExists as error: print("Error:", error.msg) return False
class jenkins: def __init__(self): self.jenkins_url = jenkins_config.get('url') self.user = jenkins_config.get('user') self.password = jenkins_config.get('password') if self.jenkins_url is not None: try: self.jenkins = Jenkins( self.jenkins_url, auth=(self.user, self.password)) except Exception as e: log_error(e) def help(self, req, resp): h = ''' jenkins CI ops jenkins create_copy -j job -t template -r repo -b branch -p package ops jenkins result -j job ops jenkins info -t template ops jenkins build -j job ops jenkins enable -j job ops jenkins disable -j job ops jenkins delete -j job ''' return h def result(self, req, resp): job = req.get_param(name='j') if job is None: return '-j(job) need' return self.jenkins.last_result(job)['result'] def info(self, req, resp): template = req.get_param(name='t') if template is None: return '-t(template) need' return self.jenkins.get_config_xml(template) def create_copy(self, req, resp): job = req.get_param(name='j') template = req.get_param(name='t') repo = req.get_param(name='r') branch = req.get_param(name='b') package = req.get_param(name='p') if job is None: return '-j(job) need' if template is None: return '-t(template) need' if repo is None: return '-r(repo) need' if branch is None: return '-b(branch) need' if package is None: return '-p(package) need' return self.jenkins.create_copy( job, template, repo=repo, branch=branch, package=package) def build(self, req, resp): job = req.get_param(name='j') if job is None: return '-j(job) need' return self.jenkins.build(job) def enable(self, req, resp): job = req.get_param(name='j') if job is None: return '-j(job) need' return self.jenkins.enable(job) def disable(self, req, resp): job = req.get_param(name='j') if job is None: return '-j(job) need' return self.jenkins.disable(job) def delete(self, req, resp): job = req.get_param(name='j') if job is None: return '-j(job) need' return self.jenkins.delete(job)
class jenkins: def __init__(self): self.jenkins_url = jenkins_config.get('url') self.user = jenkins_config.get('user') self.password = jenkins_config.get('password') if self.jenkins_url is not None: try: self.jenkins = Jenkins(self.jenkins_url, auth=(self.user, self.password)) except Exception as e: log_error(e) def help(self, req, resp): h = ''' jenkins CI ops jenkins create_copy -j job -t template -r repo -b branch -p package ops jenkins result -j job ops jenkins info -t template ops jenkins build -j job ops jenkins enable -j job ops jenkins disable -j job ops jenkins delete -j job ''' return h def result(self, req, resp): job = req.get_param(name='j') if job is None: return '-j(job) need' return self.jenkins.last_result(job)['result'] def info(self, req, resp): template = req.get_param(name='t') if template is None: return '-t(template) need' return self.jenkins.get_config_xml(template) def create_copy(self, req, resp): job = req.get_param(name='j') template = req.get_param(name='t') repo = req.get_param(name='r') branch = req.get_param(name='b') package = req.get_param(name='p') if job is None: return '-j(job) need' if template is None: return '-t(template) need' if repo is None: return '-r(repo) need' if branch is None: return '-b(branch) need' if package is None: return '-p(package) need' return self.jenkins.create_copy(job, template, repo=repo, branch=branch, package=package) def build(self, req, resp): job = req.get_param(name='j') if job is None: return '-j(job) need' return self.jenkins.build(job) def enable(self, req, resp): job = req.get_param(name='j') if job is None: return '-j(job) need' return self.jenkins.enable(job) def disable(self, req, resp): job = req.get_param(name='j') if job is None: return '-j(job) need' return self.jenkins.disable(job) def delete(self, req, resp): job = req.get_param(name='j') if job is None: return '-j(job) need' return self.jenkins.delete(job)
__author__ = 'Dmitry' import jenkins j = jenkins.Jenkins('http://tdw-deploy-tool.dbdc.luxoft.com:8080/jenkins/') j.get_jobs() j.create_job('empty', jenkins.EMPTY_CONFIG_XML) from autojenkins import Jenkins j = Jenkins('http://tdw-deploy-tool.dbdc.luxoft.com:8080/jenkins/') j.get_config_xml('Test-run') j = Jenkins('http://jenkins.pe.local')
import os,sys sys.path.extend(os.path.dirname(os.path.realpath(__file__))) #http://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html date_regexp = re.compile("(\d+-\d+-\d+)") jobHash = {} if __name__ == '__main__': j = Jenkins('http://135.251.224.94:8080/') jobs = j.all_jobs() print(jobs) for job, color in jobs: if color in ['red', 'blue', 'yellow']: full_info = j.job_info(job) last_build = j.last_build_info(job) when = datetime.fromtimestamp(last_build['timestamp'] / 1000) else: when = '(unknown)' print("{0!s:<19} {1:<6} {2}".format(when, color, job)) #print "Build!" #j.build("CodeWarrior_Build_Test") #print "Waiting"
from autojenkins import Jenkins if __name__ == '__main__': j = Jenkins('http://jenkins.pe.local') # dir = path.dirname(path.dirname(__file__)) # config_file = path.join(dir, 'templates/story-dev-job.xml') response = j.delete('aaa') response = j.create_copy('aaa', 'template', repo='mbf-warehouse-screens', branch='us544_login', package='warehouse_screens') print(response.status_code) if response.status_code == 200: j.build('aaa')
from datetime import datetime from autojenkins import Jenkins import re #http://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html date_regexp = re.compile("(\d+-\d+-\d+)") jobHash = {} if __name__ == '__main__': j = Jenkins('http://172.24.186.185:8081') jobs = j.all_jobs() #print(jobs) for myjob in jobs: print myjob for jobname, jobstatus in jobs: dateflag = date_regexp.search(jobname) if dateflag: datestamp = dateflag.groups()[0] #print "Jobname=%-90s Date=%-20s Status=%-10s" % ( jobname, datestamp, jobstatus ) if jobHash.has_key(datestamp): jobHash[datestamp].append(jobname) else: jobHash[datestamp] = [] jobHash[datestamp].append(jobname) for key in sorted(jobHash.keys()): if cmp(key, "2014-11-08") == 1: continue
#epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True ########NEW FILE######## __FILENAME__ = build_wait from autojenkins import Jenkins j = Jenkins('http://jenkins.live') result = j.build('mbf-order-dcs-us677_merge_dev_carles', wait=True) print('Result = ' + result['result']) ########NEW FILE######## __FILENAME__ = demo_run from datetime import datetime from autojenkins import Jenkins if __name__ == '__main__': j = Jenkins('https://builds.apache.org') jobs = j.all_jobs() print(jobs) for job, color in jobs:
from autojenkins import Jenkins import re #http://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html date_regexp = re.compile("(\d+-\d+-\d+)") jobHash = {} if __name__ == '__main__': j = Jenkins('http://172.24.186.185:8081') jobs = j.all_jobs() #print(jobs) for myjob in jobs: print myjob for jobname, jobstatus in jobs: dateflag = date_regexp.search(jobname) if dateflag: datestamp = dateflag.groups()[0] #print "Jobname=%-90s Date=%-20s Status=%-10s" % ( jobname, datestamp, jobstatus ) if jobHash.has_key(datestamp): jobHash[datestamp].append(jobname) else: jobHash[datestamp] = [] jobHash[datestamp].append(jobname)
from datetime import datetime from autojenkins import Jenkins if __name__ == '__main__': j = Jenkins('https://builds.apache.org') jobs = j.all_jobs() print(jobs) for job, color in jobs: if color in ['red', 'blue', 'yellow']: full_info = j.job_info(job) last_build = j.last_build_info(job) when = datetime.fromtimestamp(last_build['timestamp'] / 1000) else: when = '(unknown)' print("{0!s:<19} {1:<6} {2}".format(when, color, job))
def setUp(self): super(TestJenkins, self).setUp() self.jenkins = Jenkins('http://jenkins')
#!/usr/bin/python import time from autojenkins import Jenkins j = Jenkins('http://192.168.1.216:8080/') # Create a new job. j.create_copy('my-new-job', 'Selenium-Test', repo='my-repo', branch='my-branch') newjob = j.job_info('my-new-job') while newjob != 'null': print 'Job Created Successfully' break else: time.sleep(1)
from autojenkins import Jenkins j = Jenkins('http://jenkins.live') result = j.build('mbf-order-dcs-us677_merge_dev_carles', wait=True) print('Result = ' + result['result'])
class TestJenkins(TestCase): def setUp(self): super(TestJenkins, self).setUp() self.jenkins = Jenkins('http://jenkins') def test_all_jobs(self, requests): response = {'jobs': [{'name': 'job1', 'color': 'blue'}]} requests.get.return_value = mock_response(response) jobs = self.jenkins.all_jobs() requests.get.assert_called_once_with('http://jenkins/api/python', verify=True, auth=None) self.assertEqual(jobs, [('job1', 'blue')]) def test_get_job_url(self, *args): url = self.jenkins.job_url('job123') self.assertEqual('http://jenkins/job/job123', url) def test_last_result(self, requests, *args): second_response = Mock(status_code=200) second_response.content = "{'result': 23}" requests.get.side_effect = [ mock_response('job_info.txt'), second_response ] response = self.jenkins.last_result('name') self.assertEqual(23, response['result']) self.assertEqual( (('https://builds.apache.org/job/Solr-Trunk/1783/api/python',), {'auth': None, 'verify': True}), requests.get.call_args_list[1] ) @data( ('job_info', 'job/{0}/api/python'), ('last_build_info', 'job/{0}/lastBuild/api/python'), ('last_build_report', 'job/{0}/lastBuild/testReport/api/python'), ('last_success', 'job/{0}/lastSuccessfulBuild/api/python'), ('get_config_xml', 'job/{0}/config.xml'), ) def test_get_methods_with_jobname(self, case, requests): method, url = case requests.get.return_value = mock_response('{0}.txt'.format(method)) response = getattr(self.jenkins, method)('name') requests.get.assert_called_once_with( 'http://jenkins/' + url.format('name'), verify=True, auth=None) getattr(self, 'checks_{0}'.format(method))(response) def test_build_info(self, requests): url = 'job/name/3/api/python' requests.get.return_value = mock_response('last_build_info.txt') self.jenkins.build_info('name', 3) requests.get.assert_called_once_with( 'http://jenkins/' + url, verify=True, auth=None) def check_result(self, response, route, value): for key in route: response = response[key] self.assertEqual(response, value) def check_results(self, response, values): for route, value in values: self.check_result(response, route, value) def checks_job_info(self, response): self.check_results( response, [(('color',), 'red'), (('lastSuccessfulBuild', 'number'), 1778), (('lastSuccessfulBuild', 'url'), 'https://builds.apache.org/job/Solr-Trunk/1778/'), ]) def checks_last_build_info(self, response): self.check_results( response, [(('timestamp',), 1330941036216L), (('number',), 1783), (('result',), 'FAILURE'), (('changeSet', 'kind'), 'svn'), ]) def checks_last_build_report(self, response): self.check_results( response, [(('duration',), 692.3089), (('failCount',), 1), (('suites', 0, 'name'), 'org.apache.solr.BasicFunctionalityTest'), ]) def checks_last_success(self, response): self.check_results( response, [(('result',), 'SUCCESS'), (('building',), False), (('artifacts', 0, 'displayPath'), 'apache-solr-4.0-2012-02-29_09-07-30-src.tgz'), ]) def checks_get_config_xml(self, response): self.assertTrue(response.startswith('<?xml')) self.assertTrue(response.endswith('</project>')) # TODO: test job creation, and set_config_xml def test_create(self, requests): requests.post.return_value = mock_response() config_xml = path.join(fixture_path, 'create_copy.txt') self.jenkins.create('job', config_xml, value='2') CFG = "<value>2</value><disabled>true</disabled>" requests.post.assert_called_once_with( 'http://jenkins/createItem', auth=None, headers={'Content-Type': 'application/xml'}, params={'name': 'job'}, data=CFG, verify=True) def test_create_copy(self, requests): requests.get.return_value = mock_response('create_copy.txt') requests.post.return_value = mock_response() self.jenkins.create_copy('job', 'template', value='2') CFG = "<value>2</value><disabled>false</disabled>" requests.post.assert_called_once_with( 'http://jenkins/createItem', auth=None, headers={'Content-Type': 'application/xml'}, params={'name': 'job'}, data=CFG, verify=True) def test_transfer(self, requests): requests.get.return_value = mock_response('transfer.txt') requests.post.return_value = mock_response() self.jenkins.transfer('job', 'http://jenkins2') CFG = load_fixture('transfer.txt') requests.post.assert_called_once_with( 'http://jenkins2/createItem', auth=None, headers={'Content-Type': 'application/xml'}, params={'name': 'job'}, data=CFG, verify=True) @data( ('build', 'job/{0}/build'), ('delete', 'job/{0}/doDelete'), ('enable', 'job/{0}/enable'), ('disable', 'job/{0}/disable'), ) def test_post_methods_with_jobname_no_data(self, case, requests): method, url = case # Jenkins API post methods return status 302 upon success requests.post.return_value = mock_response(status=302) response = getattr(self.jenkins, method)('name') self.assertEqual(302, response.status_code) requests.post.assert_called_once_with( 'http://jenkins/' + url.format('name'), auth=None, verify=True) def test_set_config_xml(self, requests): requests.post.return_value = Mock(status_code=200) CFG = '<config>x</config>' response = self.jenkins.set_config_xml('name', CFG) # return value is a pass-trough self.assertEqual(requests.post.return_value, response) requests.post.assert_called_once_with( 'http://jenkins/job/name/config.xml', headers={'Content-Type': 'application/xml'}, data=CFG, auth=None, verify=True) @patch('autojenkins.jobs.time') @patch('autojenkins.jobs.Jenkins.last_result') @patch('autojenkins.jobs.Jenkins.wait_for_build') def test_build_with_wait(self, wait_for_build, last_result, time, requests): """Test building a job synchronously""" requests.post.return_value = mock_response(status=302) last_result.return_value = {'result': 'HELLO'} result = self.jenkins.build('name', wait=True) self.assertEqual({'result': 'HELLO'}, result) requests.post.assert_called_once_with( 'http://jenkins/job/name/build', auth=None, verify=True) last_result.assert_called_once_with('name') time.sleep.assert_called_once_with(10) @patch('autojenkins.jobs.time') @patch('autojenkins.jobs.sys') @patch('autojenkins.jobs.Jenkins.is_building') def test_wait_for_build(self, is_building, sys, time, requests): is_building.side_effect = [True, True, False] self.jenkins.wait_for_build('name') self.assertEqual(3, is_building.call_count) self.assertEqual(2, time.sleep.call_count) self.assertEqual(((3,), {}), time.sleep.call_args) @patch('autojenkins.jobs.Jenkins.last_result') @data(True, False) def test_is_building(self, building, last_result, _): last_result.return_value = {'building': building} result = self.jenkins.is_building('name') last_result.assert_called_once_with('name') self.assertEqual(building, result) def test_404_raises_http_not_found(self, requests): http404_response = Mock() http404_response.status_code = 404 requests.get.return_value = http404_response with self.assertRaises(HttpNotFoundError): self.jenkins.last_build_info('job123') def test_500_raises_http_error(self, requests): http500_response = Mock() http500_response.status_code = 500 requests.get.return_value = http500_response with self.assertRaises(HttpStatusError): self.jenkins.last_build_info('job123')
from autojenkins import Jenkins if __name__ == '__main__': """ j = Jenkins('http://jenkins.pe.local') # dir = path.dirname(path.dirname(__file__)) # config_file = path.join(dir, 'templates/story-dev-job.xml') response = j.delete('aaa') response = j.create_copy('aaa', 'template', repo='mbf-warehouse-screens', branch='us544_login', package='warehouse_screens') print(response.status_code) if response.status_code == 200: j.build('aaa') """ # j = Jenkins('https://builds.apache.org') j = Jenkins('http://jenkins.pe.local') jobs = j.all_jobs() print(jobs) for job, color in jobs: if color in ['red', 'blue', 'yellow']: full_info = j.job_info(job) last_build = j.last_build_info(job) when = datetime.fromtimestamp(last_build['timestamp'] / 1000) else: when = '(unknown)' print("{0!s:<19} {1:<6} {2}".format(when, color, job))
#!/usr/bin/python import time from autojenkins import Jenkins j = Jenkins('http://192.168.1.216:8080/') # Build new job. print "Building Job" j.build('my-new-job') while j.job_info('my-new-job')['color'] == 'notbuilt' or j.job_info('my-new-job')['color'] == 'notbuilt_anime': #print j.job_info('my-new-job')['color'] time.sleep(1) if j.job_info('my-new-job')['color'] == 'blue' or j.job_info('my-new-job')['color'] == 'yellow' or j.job_info('my-new-job')['color'] == 'red': #print j.job_info('my-new-job')['color'] print 'Build Completed' break if j.last_result('my-new-job')['result'] == 'SUCCESS': print 'Job was built successfully' else: print 'Build failed'
from autojenkins import Jenkins import time # configure jenkins URL j = Jenkins('http://jenkins:8080', auth=('admin', 'admin')) job = 'FirstPythonJob_unittest' # Trigger manual build and get results #run job j.build(job) #get last result info jobstatus = j.last_result(job)['result'] x = str(jobstatus) # Check Job status and do something when completed / failed etc.. while x == "None": print("Job ", job, "is still building") time.sleep(5) x = j.last_result(job)['result'] x = str(x) if x != "None": print("Job Status is:", x) print "***** Printing Jenkins console output *****" time.sleep(2.5) print j.console_text(job, build_number='lastBuild') else: pass