def test_get_build_by_params_not_found(jenkins, monkeypatch, mocker): build_params = { 'param1': 'value1' } fake_builds = ( mocker.Mock(get_params=lambda: {}), mocker.Mock(get_params=lambda: {}), mocker.Mock(get_params=lambda: {}) ) build_call_count = [0] def fake_get_build(cls, number): # pylint: disable=unused-argument build_call_count[0] += 1 return fake_builds[number - 1] monkeypatch.setattr(Job, 'get_first_buildnumber', lambda x: 1) monkeypatch.setattr(Job, 'get_last_buildnumber', lambda x: 3) monkeypatch.setattr(Job, 'get_build', fake_get_build) mocker.spy(Build, 'get_params') mocker.spy(Job, 'get_build') job = Job('http://localhost/jobs/foo', 'foo', jenkins) with pytest.raises(NoBuildData): job.get_build_by_params(build_params) assert job.get_build.call_count == 3 assert build_call_count[0] == 3
def test_nobuilds_get_last_build(self, _poll): # Bare minimum build dict, we only testing dissapearance of 'builds' _poll.return_value = {"name": "foo"} j = Job('http://halob:8080/job/foo/', 'foo', self.J) with self.assertRaises(NoBuildData): j.get_last_build()
def test_nobuilds_get_build_dict(self): j = Job('http://halob:8080/job/look_ma_no_builds/', 'look_ma_no_builds', self.J) ret = j.get_build_dict() self.assertTrue(isinstance(ret, dict)) self.assertEquals(len(ret), 0)
def test_incomplete_builds_list_will_call_jenkins_twice(self): # The job data contains only one build, so we expect that the # remaining jobs will be fetched automatically, and to have two calls # to the Jenkins API TestJobGetAllBuilds.__get_data_call_count = 0 self.j = Job('http://halob:8080/job/foo/', 'foo', self.J) self.assertEquals(TestJobGetAllBuilds.__get_data_call_count, 2)
def test_get_build_by_params_not_found(jenkins, monkeypatch, mocker): build_params = {'param1': 'value1'} fake_builds = (mocker.Mock(get_params=lambda: {}), mocker.Mock(get_params=lambda: {}), mocker.Mock(get_params=lambda: {})) build_call_count = [0] def fake_get_build(cls, number): # pylint: disable=unused-argument build_call_count[0] += 1 return fake_builds[number - 1] monkeypatch.setattr(Job, 'get_first_buildnumber', lambda x: 1) monkeypatch.setattr(Job, 'get_last_buildnumber', lambda x: 3) monkeypatch.setattr(Job, 'get_build', fake_get_build) mocker.spy(Build, 'get_params') mocker.spy(Job, 'get_build') job = Job('http://localhost/jobs/foo', 'foo', jenkins) with pytest.raises(NoBuildData): job.get_build_by_params(build_params) assert job.get_build.call_count == 3 assert build_call_count[0] == 3
def test_nobuilds_get_revision_dict(jenkins, monkeypatch): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return {"name": "foo"} monkeypatch.setattr(Job, '_poll', fake_poll) job = Job('http://halob:8080/job/foo/', 'foo', jenkins) with pytest.raises(NoBuildData): job.get_revision_dict()
def disable(j, name): """ disabled a job """ job_url = "%s/job/%s" % (j.baseurl, name) job = Job(job_url, name, j) result = job.disable() print("result: %s" % result.status_code)
def test_empty_field__add_missing_builds(self, get_data): url = 'http://halob:8080/job/foo/%s' % config.JENKINS_API data = TestJob.URL_DATA[url].copy() data.update({'firstBuild': None}) get_data.return_value = data j = Job('http://halob:8080/job/foo/', 'foo', self.J) initial_call_count = get_data.call_count j._add_missing_builds(data) self.assertEquals(get_data.call_count, initial_call_count)
def test_nobuilds_get_build_dict(self): j = Job( 'http://halob:8080/job/look_ma_no_builds/', 'look_ma_no_builds', self.J) ret = j.get_build_dict() self.assertTrue(isinstance(ret, dict)) self.assertEqual(len(ret), 0)
def test_empty_field__add_missing_builds(self, get_data): url = "http://halob:8080/job/foo/%s" % config.JENKINS_API data = TestJob.URL_DATA[url].copy() data.update({"firstBuild": None}) get_data.return_value = data j = Job("http://halob:8080/job/foo/", "foo", self.J) initial_call_count = get_data.call_count j._add_missing_builds(data) self.assertEquals(get_data.call_count, initial_call_count)
def test_get_params_list(self, get_data): url = "http://halob:8080/job/foo/%s" % config.JENKINS_API get_data.return_value = TestJob.URL_DATA[url].copy() j = Job("http://halob:8080/job/foo/", "foo", self.J) params = j.get_params_list() self.assertIsInstance(params, list) self.assertEquals(len(params), 2) self.assertEquals(params, ["param1", "param2"])
def __getitem__(self, job_name): if job_name in self: job_data = [job_row for job_row in self._data if job_row['name'] == job_name or Job.get_full_name_from_url_and_baseurl( job_row['url'], self.jenkins.baseurl) == job_name][0] return Job(job_data['url'], job_data['name'], self.jenkins) else: raise UnknownJob(job_name)
def test_get_params_list(self, get_data): url = 'http://halob:8080/job/foo/%s' % config.JENKINS_API get_data.return_value = TestJob.URL_DATA[url].copy() j = Job('http://halob:8080/job/foo/', 'foo', self.J) params = j.get_params_list() self.assertIsInstance(params, list) self.assertEquals(len(params), 2) self.assertEquals(params, ['param1', 'param2'])
def test__add_missing_builds_no_builds(self, get_data): url = 'http://halob:8080/job/foo/%s' % config.JENKINS_API data = TestJob.URL_DATA[url].copy() get_data.return_value = data j = Job('http://halob:8080/job/foo/', 'foo', self.J) initial_call_count = get_data.call_count mock_data = TestJob.URL_DATA[url].copy() mock_data['builds'] = None j._add_missing_builds(mock_data) self.assertEquals(initial_call_count, get_data.call_count)
def test__add_missing_builds_no_first_build(self, get_data): url = "http://halob:8080/job/foo/%s" % config.JENKINS_API data = TestJob.URL_DATA[url].copy() get_data.return_value = data j = Job("http://halob:8080/job/foo/", "foo", self.J) initial_call_count = get_data.call_count mock_data = TestJob.URL_DATA[url].copy() mock_data["firstBuild"] = None j._add_missing_builds(mock_data) self.assertEquals(initial_call_count, get_data.call_count)
def iterkeys(self): """ Iterate over the names of all available jobs """ if len(self._data) == 0: self._data = self.poll().get('jobs', []) for row in self._data: yield row['name'] if row['name'] != Job.get_full_name_from_url_and_baseurl( row['url'], self.jenkins.baseurl): yield Job.get_full_name_from_url_and_baseurl( row['url'], self.jenkins.baseurl)
def iterkeys(self): """ Iterate over the names of all available jobs """ if not self._data: self._data = self.poll().get('jobs', []) for row in self._data: yield row['name'] if row['name'] != \ Job.get_full_name_from_url_and_baseurl(row['url'], self.jenkins.baseurl): yield Job.get_full_name_from_url_and_baseurl( row['url'], self.jenkins.baseurl)
def getLastBuildInfo(self,server): try: job_obj=Job(server.baseurl+"/job/"+self.data['builddf']['Name'],self.data['builddf']['Name'],server) last_bd=job_obj.get_last_build_or_none() self.logger.debug("The last build at %s is %s" % (server.baseurl, last_bd.name)) except Exception, details: #sys.stderr.write('ERROR: %s \n' % details) #sys.exit(1) #x=inspect.stack() if 'test_' in inspect.stack()[1][3] or 'test_' in inspect.stack()[2][3]: raise else: #print Exception,details self.logger.error('ERROR: %s \n' % details,exc_info=True) sys.exit(1)
def aget_job(self, name): self.load() url = self.rest.job(name) try: data = yield from url.api.python.aget() except aiohttp.errors.HttpProcessingError as e: if 404 == e.code: raise UnknownJob() raise instance = JenkinsJob(data['url'], data['name'], self._instance) instance._data = data payload = yield from url('config.xml').aget() instance._config = payload.data return Job.factory(instance)
def job(jenkins, monkeypatch): def fake_get_data(cls, url, tree=None): # pylint: disable=unused-argument return JOB_DATA monkeypatch.setattr(JenkinsBase, 'get_data', fake_get_data) return Job('http://localhost:800/view/Buildampel/job/Fahrzeug-Server/', 'Fahrzeug-Server', jenkins)
def test_incomplete_builds_list_will_call_jenkins_twice(self): # The job data contains only one build, so we expect that the # remaining jobs will be fetched automatically, and to have two calls # to the Jenkins API TestJobGetAllBuilds.__get_data_call_count = 0 self.j = Job('http://halob:8080/job/foo/', 'foo', self.J) self.assertEqual(TestJobGetAllBuilds.__get_data_call_count, 2)
def test__add_missing_builds_not_all_loaded(self, get_data): url = 'http://halob:8080/job/foo/%s' % config.JENKINS_API data = TestJob.URL_DATA[url].copy() get_data.return_value = data j = Job('http://halob:8080/job/foo/', 'foo', self.J) # to test this function we change data to not have one build # and set it to mark that firstBuild was not loaded # in that condition function will call j.get_data # and will use syntetic field 'allBuilds' to # repopulate 'builds' field with all builds mock_data = TestJob.URL_DATA[url].copy() mock_data['firstBuild'] = {'number': 1} del mock_data['builds'][-1] self.assertEquals(len(mock_data['builds']), 2) new_data = j._add_missing_builds(mock_data) self.assertEquals(len(new_data['builds']), 3)
def test_get_json_for_single_param(self): params = {"B": "one two three"} expected = '{"parameter": {"name": "B", "value": "one two three"}, "statusCode": "303", "redirectTo": "."}' self.assertJsonEqual( Job.mk_json_from_build_parameters(params), expected )
def job_with_diff_baseurl(monkeypatch, jenkins_with_diff_baseurl): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return configs.JOB_DATA monkeypatch.setattr(Job, '_poll', fake_poll) fake_job = Job('http://localhost', 'Fake_Job', jenkins_with_diff_baseurl) return fake_job
def get_jobs(self): """ Fetch all the build-names on this Jenkins server. """ for info in self._data["jobs"]: yield info["name"], \ Job(info["url"], info["name"], jenkins_obj=self)
def __getitem__(self, job_name): if job_name in self: job_data = [job_row for job_row in self._data if job_row['name'] == job_name][0] return Job(job_data['url'], job_data['name'], self.jenkins) else: raise UnknownJob(job_name)
def job(monkeypatch, jenkins): def fake_poll(cls, tree=None): # pylint: disable=unused-argument return configs.JOB_DATA monkeypatch.setattr(Job, '_poll', fake_poll) fake_job = Job('http://', 'Fake_Job', jenkins) return fake_job
def test_get_json_for_many_params(self): params = {"B": "Honey", "A": "Boo", "C": 2} expected = '{"parameter": [{"name": "A", "value": "Boo"}, {"name": "B", "value": "Honey"}, {"name": "C", "value": "2"}], "statusCode": "303", "redirectTo": "."}' self.assertJsonEqual( Job.mk_json_from_build_parameters(params), expected )
def job(jenkins, monkeypatch): def fake_get_data(cls, url, tree=None): # pylint: disable=unused-argument return configs.JOB_DATA monkeypatch.setattr(JenkinsBase, 'get_data', fake_get_data) new_job = Job('http://halob:8080/job/foo/', 'foo', jenkins) return new_job
def get_jobs(self): """ Fetch all the build-names on this Jenkins server. """ jobs = self.poll(tree='jobs[name,url,color]')['jobs'] for info in jobs: yield info["name"], \ Job(info["url"], info["name"], jenkins_obj=self)
def get_job_by_url(self, url, job_name): """ Get a job by url :param url: jobs' url :param jobname: name of the job, str :return: Job obj """ return Job(url, job_name, self)
def itervalues(self): """ Iterate over all available jobs """ if not self._data: self._data = self.poll().get('jobs', []) for row in self._data: yield Job(row['url'], row['name'], self.jenkins)
def test_get_json_for_many_params(): params = {"B": "Honey", "A": "Boo", "C": 2} expected = ('{"parameter": [{"name": "A", "value": "Boo"}, ' '{"name": "B", "value": "Honey"}, ' '{"name": "C", "value": "2"}], ' '"statusCode": "303", "redirectTo": "."}') json_equal(Job.mk_json_from_build_parameters(params), expected)
def job_tree_empty(jenkins, monkeypatch): def fake_get_data(cls, url, tree=None): # pylint: disable=unused-argument return {} monkeypatch.setattr(Job, 'get_data', fake_get_data) new_job = Job('http://halob:8080/job/foo/', 'foo', jenkins) return new_job
def get_builds_from_build_ids(job: Job, build_id_list): build_dto_list = [] for build_id in build_id_list: print("Build id " + str(build_id)) build = job.get_build(build_id) build_dto = BuildDto(build.get_number(), build.get_status(), build.get_timestamp()) build_dto_list.append(build_dto) return JobDto(job.name, build_dto_list)
def __getitem__(self, job_name): for row in self.jenkins._data.get('jobs', []): if row['name'] == job_name: return Job( row['url'], row['name'], self.jenkins) raise UnknownJob(job_name)
def iteritems(self): try: it = self.get_job_dict().iteritems() except AttributeError: # Python3 it = self.get_job_dict().items() for name, url in it: yield name, Job(url, name, self.jenkins_obj)
def __getitem__(self, jobname): """ Get a job by name :param jobname: name of job, str :return: Job obj """ for info in self._data["jobs"]: if info["name"] == jobname: return Job(info["url"], info["name"], jenkins_obj=self) raise UnknownJob(jobname)
def test__add_missing_builds_not_all_loaded(jenkins, monkeypatch): def fake_get_data(cls, url, tree): # pylint: disable=unused-argument return configs.JOB_DATA.copy() monkeypatch.setattr(JenkinsBase, 'get_data', fake_get_data) job = Job('http://halob:8080/job/foo/', 'foo', jenkins) # to test this function we change data to not have one build # and set it to mark that firstBuild was not loaded # in that condition function will call j.get_data # and will use syntetic field 'allBuilds' to # repopulate 'builds' field with all builds mock_data = configs.JOB_DATA.copy() mock_data['firstBuild'] = {'number': 1} del mock_data['builds'][-1] job._data = mock_data assert len(mock_data['builds']) == 2 new_data = job._add_missing_builds(mock_data) assert len(new_data['builds']) == 3
def test_poll_cache(self, _poll): # only gets called once in interval j = Job('http://halob:8080/job/foo/', 'foo', self.J, poll_cache_timeout=1) for i in range(2): j.poll() self.assertEquals(_poll.call_count, 1) j.poll(True) # test force poll self.assertEquals(_poll.call_count, 2) # ensure it gets called again after cache timeout _poll.reset_mock() time.sleep(1.1) j.poll() self.assertTrue(_poll.called) # ensure it is disabled by default _poll.reset_mock() for i in range(2): self.j.poll() self.assertEquals(_poll.call_count, 2) self.assertIsNone(self.j.poll_cache_expires)
class TestHgJob(unittest.TestCase): JOB_DATA = { "actions": [], "description": "test job", "displayName": "foo", "displayNameOrNull": None, "name": "foo", "url": "http://*****:*****@mock.patch.object(JenkinsBase, 'get_data', fakeGetData) def setUp(self): self.J = mock.MagicMock() # Jenkins object self.j = Job('http://*****:*****@1.42"> <source>http://cm5/hg/sandbox/v01.0/int</source> <modules/> <branch>testme</branch> <clean>false</clean> <browser class="hudson.plugins.mercurial.browser.HgWeb"> <url>http://cm5/hg/sandbox/v01.0/int/</url> </browser> </scm> </project> ''' return config_node def configtree_with_default_branch(self): config_node = ''' <project> <scm class="hudson.plugins.mercurial.MercurialSCM" plugin="[email protected]"> <source>http://cm5/hg/sandbox/v01.0/int</source> <modules/> <clean>false</clean> <browser class="hudson.plugins.mercurial.browser.HgWeb"> <url>http://cm5/hg/sandbox/v01.0/int/</url> </browser> </scm> </project> ''' return config_node @mock.patch.object(Job, 'get_config', configtree_with_branch) def test_hg_attributes(self): expected_url = ['http://cm5/hg/sandbox/v01.0/int'] self.assertEquals(self.j.get_scm_type(), 'hg') self.assertEquals(self.j.get_scm_url(), expected_url) self.assertEquals(self.j.get_scm_branch(), ['testme']) @mock.patch.object(Job, 'get_config', configtree_with_default_branch) def test_hg_attributes_default_branch(self): self.assertEquals(self.j.get_scm_branch(), ['default'])
class TestJob(unittest.TestCase): JOB_DATA = { "actions": [], "description": "test job", "displayName": "foo", "displayNameOrNull": None, "name": "foo", "url": "http://*****:*****@mock.patch.object(JenkinsBase, 'get_data', fakeGetData) def setUp(self): self.J = mock.MagicMock() # Jenkins object self.j = Job('http://*****:*****@mock.patch.object(JenkinsBase, 'get_data', fakeGetData) def test_wrong_field__build_id_for_type(self): with self.assertRaises(AssertionError): self.j._buildid_for_type('wrong') @mock.patch.object(JenkinsBase, 'get_data', fakeGetData) def test_get_last_good_buildnumber(self): ret = self.j.get_last_good_buildnumber() self.assertTrue(ret, 3) @mock.patch.object(JenkinsBase, 'get_data', fakeGetData) def test_get_last_failed_buildnumber(self): with self.assertRaises(NoBuildData): self.j.get_last_failed_buildnumber() @mock.patch.object(JenkinsBase, 'get_data', fakeGetData) def test_get_last_buildnumber(self): ret = self.j.get_last_buildnumber() self.assertEquals(ret, 4) @mock.patch.object(JenkinsBase, 'get_data', fakeGetData) def test_get_last_completed_buildnumber(self): ret = self.j.get_last_completed_buildnumber() self.assertEquals(ret, 3) def test_get_build_dict(self): ret = self.j.get_build_dict() self.assertTrue(isinstance(ret, dict)) self.assertEquals(len(ret), 4) @mock.patch.object(Job, '_poll') def test_nobuilds_get_build_dict(self, _poll): # Bare minimum build dict, we only testing dissapearance of 'builds' _poll.return_value = {"name": "foo"} j = Job('http://*****:*****@mock.patch.object(Job, '_poll') def test_nobuilds_get_revision_dict(self, _poll): # Bare minimum build dict, we only testing dissapearance of 'builds' _poll.return_value = {"name": "foo"} j = Job('http://*****:*****@mock.patch.object(Job, '_poll') def test_nobuilds_get_last_build(self, _poll): # Bare minimum build dict, we only testing dissapearance of 'builds' _poll.return_value = {"name": "foo"} j = Job('http://halob:8080/job/foo/', 'foo', self.J) with self.assertRaises(NoBuildData): j.get_last_build()
def setUp(self): self.J = mock.MagicMock() # Jenkins object self.j = Job('http://halob:8080/job/foo/', 'foo', self.J)
class TestJob(unittest.TestCase): JOB_DATA = {'actions': [None, {}], 'buildable': True, 'builds': [{'number': 106, 'url': 'http://*****:*****@mock.patch.object(JenkinsBase, 'get_data', fakeGetData) #@mock.patch.object(Job, '_add_missing_builds', fake_add_missing_builds) def setUp(self): self.J = mock.MagicMock() # Jenkins object self.j = Job('http://*****:*****@mock.patch.object(JenkinsBase, 'get_data', fakeGetData) def test_get_last_good_buildnumber(self): ret = self.j.get_last_good_buildnumber() self.assertTrue(ret, 3) @mock.patch.object(JenkinsBase, 'get_data', fakeGetData) def test_has_params(self): self.assertFalse(self.j.has_params())
def test_complete_builds_list_will_call_jenkins_once(self): # The job data contains all builds, so we will not gather remaining # builds TestJobGetAllBuilds.__get_data_call_count = 0 self.j = Job('http://halob:8080/job/fullfoo/', 'fullfoo', self.J) self.assertEqual(TestJobGetAllBuilds.__get_data_call_count, 1)
def setUp(self): TestJobGetAllBuilds.__get_data_call_count = 0 self.J = mock.MagicMock() # Jenkins object self.j = Job('http://halob:8080/job/foo/', 'foo', self.J)
def test_get_params(self, get_data): url = 'http://halob:8080/job/foo/%s' % config.JENKINS_API get_data.return_value = TestJob.URL_DATA[url].copy() j = Job('http://halob:8080/job/foo/', 'foo', self.J) params = list(j.get_params()) self.assertEquals(len(params), 2)
def setUp(self): self.J = mock.MagicMock() # Jenkins object self.j = Job("http://halob:8080/job/foo/", "foo", self.J)
class TestJobGetAllBuilds(unittest.TestCase): # this job has builds JOB1_DATA = { "actions": [], "description": "test job", "displayName": "foo", "displayNameOrNull": None, "name": "foo", "url": "http://*****:*****@mock.patch.object(JenkinsBase, 'get_data', fakeGetDataTree) def setUp(self): TestJobGetAllBuilds.__get_data_call_count = 0 self.J = mock.MagicMock() # Jenkins object self.j = Job('http://*****:*****@mock.patch.object(JenkinsBase, 'get_data', fakeGetDataTree) def test_get_build_dict(self): # The job data contains only one build, so we expect that the # remaining jobs will be fetched automatically ret = self.j.get_build_dict() self.assertTrue(isinstance(ret, dict)) self.assertEqual(len(ret), 4) @mock.patch.object(JenkinsBase, 'get_data', fakeGetDataTree) def test_incomplete_builds_list_will_call_jenkins_twice(self): # The job data contains only one build, so we expect that the # remaining jobs will be fetched automatically, and to have two calls # to the Jenkins API TestJobGetAllBuilds.__get_data_call_count = 0 self.J.lazy = False self.j = Job('http://*****:*****@mock.patch.object(JenkinsBase, 'get_data', fakeGetDataTree) def test_lazy_builds_list_will_not_call_jenkins_twice(self): # The job data contains only one build, so we expect that the # remaining jobs will be fetched automatically, and to have two calls # to the Jenkins API TestJobGetAllBuilds.__get_data_call_count = 0 self.J.lazy = True self.j = Job('http://*****:*****@mock.patch.object(JenkinsBase, 'get_data', fakeGetDataTree) def test_complete_builds_list_will_call_jenkins_once(self): # The job data contains all builds, so we will not gather remaining # builds TestJobGetAllBuilds.__get_data_call_count = 0 self.j = Job('http://*****:*****@mock.patch.object(JenkinsBase, 'get_data', fakeGetDataTree) def test_nobuilds_get_build_dict(self): j = Job( 'http://*****:*****@mock.patch.object(JenkinsBase, 'get_data', fakeGetDataTree) def test_get_build_ids(self): # The job data contains only one build, so we expect that the # remaining jobs will be fetched automatically ret = list(self.j.get_build_ids()) self.assertTrue(isinstance(ret, list)) self.assertEqual(len(ret), 4)