def test_simple(self, jenkins_mock):
        jenkins_mock.side_effect = [
            json.dumps(
                {'_class': 'com.cloudbees.hudson.plugins.folder.Folder'}),
            jenkins.NotFoundException(),
            None,
            json.dumps(
                {'_class': 'com.cloudbees.hudson.plugins.folder.Folder'}),
            json.dumps({'id': 'Test Credential'}),
        ]

        self.j.create_credential('Test Folder', self.config_xml)
        self.assertEqual(
            jenkins_mock.call_args_list[1][0][0].url,
            self.make_url(
                'job/Test%20Folder/credentials/store/folder/'
                'domain/_/credential/Test%20Credential/api/json?depth=0'))

        self.assertEqual(
            jenkins_mock.call_args_list[2][0][0].url,
            self.make_url('job/Test%20Folder/credentials/store/folder/'
                          'domain/_/createCredentials'))

        self.assertEqual(
            jenkins_mock.call_args_list[4][0][0].url,
            self.make_url(
                'job/Test%20Folder/credentials/store/folder/'
                'domain/_/credential/Test%20Credential/api/json?depth=0'))
        self._check_requests(jenkins_mock.call_args_list)
Exemple #2
0
def jenkins_request_with_headers(jenkins_server, req):
    """
    We need to get the headers in addition to the body answer
    to get the location from them
    This function uses jenkins_request method from python-jenkins library
    with just the return call changed

    :param jenkins_server: The server to query
    :param req: The request to execute
    :return: Dict containing the response body (key body)
        and the headers coming along (headers)
    """
    try:
        response = jenkins_server.jenkins_request(req)
        response_body = response.content
        response_headers = response.headers
        if response_body is None:
            raise jenkins.EmptyResponseException(
                "Error communicating with server[%s]: "
                "empty response" % jenkins_server.server)
        return {'body': response_body.decode('utf-8'), 'headers': response_headers}
    except HTTPError as e:
        # Jenkins's funky authentication means its nigh impossible to distinguish errors.
        if e.code in [401, 403, 500]:
            raise JenkinsException(
                'Error in request. Possibly authentication failed [%s]: %s' % (e.code, e.msg)
            )
        elif e.code == 404:
            raise jenkins.NotFoundException('Requested item could not be found')
        else:
            raise
    except socket.timeout as e:
        raise jenkins.TimeoutException('Error in request: %s' % e)
    except URLError as e:
        raise JenkinsException('Error in request: %s' % e.reason)
Exemple #3
0
 def jenkins_request_with_headers(self,
                                  jenkins_server,
                                  req,
                                  add_crumb=True):
     """
     We need to get the headers in addition to the body answer
     to get the location from them
     This function is just a copy of the one present in python-jenkins library
     with just the return call changed
     :param jenkins_server: The server to query
     :param req: The request to execute
     :param add_crumb: Boolean to indicate if it should add crumb to the request
     :return:
     """
     try:
         # if jenkins_server.auth:
         #     req.add_header('Authorization', jenkins_server.auth)
         # if add_crumb:
         #     jenkins_server.maybe_add_crumb(req)
         base64string = base64.b64encode(
             '%s:%s' % (self.connection.login, self.connection.password))
         self.log.info("base64string -> %s", base64string)
         req.add_header("Authorization", "Basic %s" % base64string)
         response = urlopen(req, timeout=jenkins_server.timeout)
         response_body = response.read()
         response_headers = response.info()
         if response_body is None:
             raise jenkins.EmptyResponseException(
                 "Error communicating with server[%s]: "
                 "empty response" % jenkins_server.server)
         return {
             'body': response_body.decode('utf-8'),
             'headers': response_headers
         }
     except HTTPError as e:
         # Jenkins's funky authentication means its nigh impossible to
         # distinguish errors.
         if e.code in [401, 403, 500]:
             # six.moves.urllib.error.HTTPError provides a 'reason'
             # attribute for all python version except for ver 2.6
             # Falling back to HTTPError.msg since it contains the
             # same info as reason
             raise JenkinsException(
                 'Error in request. ' +
                 'Possibly authentication failed [%s]: %s' %
                 (e.code, e.msg))
         elif e.code == 404:
             raise jenkins.NotFoundException(
                 'Requested item could not be found')
         else:
             raise
     except socket.timeout as e:
         raise jenkins.TimeoutException('Error in request: %s' % e)
     except URLError as e:
         # python 2.6 compatibility to ensure same exception raised
         # since URLError wraps a socket timeout on python 2.6.
         if str(e.reason) == "timed out":
             raise jenkins.TimeoutException('Error in request: %s' %
                                            e.reason)
         raise JenkinsException('Error in request: %s' % e.reason)
    def test_failed(self, jenkins_mock):
        jenkins_mock.side_effect = [
            json.dumps(
                {'_class': 'com.cloudbees.hudson.plugins.folder.Folder'}),
            jenkins.NotFoundException(),
            None,
            json.dumps(
                {'_class': 'com.cloudbees.hudson.plugins.folder.Folder'}),
            None,
        ]

        with self.assertRaises(jenkins.JenkinsException) as context_manager:
            self.j.create_credential('Test Folder', self.config_xml)
        self.assertEqual(
            jenkins_mock.call_args_list[1][0][0].url,
            self.make_url(
                'job/Test%20Folder/credentials/store/folder/'
                'domain/_/credential/Test%20Credential/api/json?depth=0'))
        self.assertEqual(
            jenkins_mock.call_args_list[2][0][0].url,
            self.make_url('job/Test%20Folder/credentials/store/'
                          'folder/domain/_/createCredentials'))
        self.assertEqual(
            jenkins_mock.call_args_list[4][0][0].url,
            self.make_url(
                'job/Test%20Folder/credentials/store/folder/'
                'domain/_/credential/Test%20Credential/api/json?depth=0'))
        self.assertEqual(
            str(context_manager.exception),
            'create[Test Credential] failed in the domain[_] of [Test Folder]')
        self._check_requests(jenkins_mock.call_args_list)
Exemple #5
0
    def test_failed(self, jenkins_mock):
        jenkins_mock.side_effect = [
            jenkins.NotFoundException(),
            None,
            jenkins.NotFoundException(),
        ]

        with self.assertRaises(jenkins.JenkinsException) as context_manager:
            self.j.create_view(u'TestView', self.config_xml)
        self.assertEqual(jenkins_mock.call_args_list[0][0][0].get_full_url(),
                         self.make_url('view/TestView/api/json?tree=name'))
        self.assertEqual(jenkins_mock.call_args_list[1][0][0].get_full_url(),
                         self.make_url('createView?name=TestView'))
        self.assertEqual(str(context_manager.exception),
                         'create[TestView] failed')
        self._check_requests(jenkins_mock.call_args_list)
Exemple #6
0
class JenkinsCancelQueueTest(JenkinsTestBase):

    @patch.object(jenkins.Jenkins, 'jenkins_open')
    def test_simple(self, jenkins_mock):
        job_name_to_return = {u'name': 'TestJob'}
        jenkins_mock.return_value = json.dumps(job_name_to_return)

        self.j.cancel_queue(52)

        self.assertEqual(
            jenkins_mock.call_args[0][0].get_full_url(),
            self.make_url('queue/cancelItem?id=52'))
        self._check_requests(jenkins_mock.call_args_list)

    @patch.object(jenkins.Jenkins, 'jenkins_open',
                  side_effect=jenkins.NotFoundException('not found'))
    def test_notfound(self, jenkins_mock):
        job_name_to_return = {u'name': 'TestJob'}
        jenkins_mock.return_value = json.dumps(job_name_to_return)

        self.j.cancel_queue(52)

        self.assertEqual(
            jenkins_mock.call_args[0][0].get_full_url(),
            self.make_url('queue/cancelItem?id=52'))
        self._check_requests(jenkins_mock.call_args_list)
Exemple #7
0
    def test_view_missing(self, jenkins_mock):
        jenkins_mock.side_effect = jenkins.NotFoundException()

        with self.assertRaises(jenkins.JenkinsException) as context_manager:
            self.j.assert_view_exists('NonExistent')
        self.assertEqual(str(context_manager.exception),
                         'view[NonExistent] does not exist')
        self._check_requests(jenkins_mock.call_args_list)
    def test_promotion_missing(self, jenkins_mock):
        jenkins_mock.side_effect = jenkins.NotFoundException()

        with self.assertRaises(jenkins.JenkinsException) as context_manager:
            self.j.assert_promotion_exists('NonExistent', 'TestJob')
        self.assertEqual(
            str(context_manager.exception),
            'promotion[NonExistent] does not exist for job[TestJob]')
        self._check_requests(jenkins_mock.call_args_list)
Exemple #9
0
    def test_credential_missing(self, jenkins_mock):
        jenkins_mock.side_effect = [
            json.dumps({'_class': 'com.cloudbees.hudson.plugins.folder.Folder'}),
            jenkins.NotFoundException()
        ]

        self.assertEqual(self.j.credential_exists('NonExistent', 'TestFolder'),
                         False)
        self._check_requests(jenkins_mock.call_args_list)
Exemple #10
0
    def test_return_none(self, jenkins_mock):
        jenkins_mock.side_effect = jenkins.NotFoundException()

        job_name = self.j.get_job_name(u'TestJob')

        self.assertEqual(job_name, None)
        self.assertEqual(jenkins_mock.call_args[0][0].url,
                         self.make_url('job/TestJob/api/json?tree=name'))
        self._check_requests(jenkins_mock.call_args_list)
Exemple #11
0
    def test_return_none(self, jenkins_mock):
        jenkins_mock.side_effect = jenkins.NotFoundException()

        view_name = self.j.get_view_name(u'TestView')

        self.assertEqual(view_name, None)
        self.assertEqual(jenkins_mock.call_args[0][0].get_full_url(),
                         self.make_url('view/TestView/api/json?tree=name'))
        self._check_requests(jenkins_mock.call_args_list)
Exemple #12
0
    def test_failed_in_folder(self, jenkins_mock):
        jenkins_mock.side_effect = [
            jenkins.NotFoundException(),
            None,
            jenkins.NotFoundException(),
        ]

        with self.assertRaises(jenkins.JenkinsException) as context_manager:
            self.j.create_job(u'a Folder/TestJob', self.config_xml)
        self.assertEqual(
            jenkins_mock.call_args_list[0][0][0].url,
            self.make_url('job/a%20Folder/job/TestJob/api/json?tree=name'))
        self.assertEqual(
            jenkins_mock.call_args_list[1][0][0].url,
            self.make_url('job/a%20Folder/createItem?name=TestJob'))
        self.assertEqual(
            str(context_manager.exception),
            'create[a Folder/TestJob] failed')
        self._check_requests(jenkins_mock.call_args_list)
Exemple #13
0
    def test_simple(self, jenkins_mock):
        jenkins_mock.side_effect = [
            None,
            jenkins.NotFoundException(),
        ]

        self.j.delete_view(u'Test View')

        self.assertEqual(jenkins_mock.call_args_list[0][0][0].get_full_url(),
                         self.make_url('view/Test%20View/doDelete'))
        self._check_requests(jenkins_mock.call_args_list)
Exemple #14
0
    def test_simple(self, jenkins_mock):
        jenkins_mock.side_effect = jenkins.NotFoundException()
        request = jenkins.Request(self.make_url('job/TestJob'))

        self.j.maybe_add_crumb(request)

        self.assertEqual(jenkins_mock.call_args[0][0].get_full_url(),
                         self.make_url('crumbIssuer/api/json'))
        self.assertFalse(self.j.crumb)
        self.assertFalse('.crumb' in request.headers)
        self._check_requests(jenkins_mock.call_args_list)
    def test_failed(self, jenkins_mock):
        jenkins_mock.side_effect = [
            jenkins.NotFoundException(),
            None,
            jenkins.NotFoundException(),
        ]

        with self.assertRaises(jenkins.JenkinsException) as context_manager:
            self.j.create_promotion(u'TestPromotion', 'TestJob',
                                    self.config_xml)
        self.assertEqual(
            jenkins_mock.call_args_list[0][0][0].get_full_url(),
            self.make_url('job/TestJob/promotion/process/'
                          'TestPromotion/api/json?tree=name'))
        self.assertEqual(
            jenkins_mock.call_args_list[1][0][0].get_full_url(),
            self.make_url('job/TestJob/promotion/'
                          'createProcess?name=TestPromotion'))
        self.assertEqual(str(context_manager.exception),
                         'create[TestPromotion] at job[TestJob] failed')
        self._check_requests(jenkins_mock.call_args_list)
Exemple #16
0
    def test_simple(self, jenkins_mock):
        jenkins_mock.side_effect = [
            jenkins.NotFoundException(),
            None,
            json.dumps({'name': 'Test View'}),
        ]

        self.j.create_view(u'Test View', self.config_xml)

        self.assertEqual(jenkins_mock.call_args_list[1][0][0].get_full_url(),
                         self.make_url('createView?name=Test%20View'))
        self._check_requests(jenkins_mock.call_args_list)
    def test_return_none(self, jenkins_mock):
        jenkins_mock.side_effect = jenkins.NotFoundException()

        promotion_name = self.j.get_promotion_name(u'TestPromotion',
                                                   u'Test Job')

        self.assertEqual(promotion_name, None)
        self.assertEqual(
            jenkins_mock.call_args[0][0].get_full_url(),
            self.make_url('job/Test%20Job/promotion/process/'
                          'TestPromotion/api/json?tree=name'))
        self._check_requests(jenkins_mock.call_args_list)
Exemple #18
0
    def validate_job_name(self):
        matches = self.get_all_matching_jobs(self.name)
        if not matches:
            raise jenkins.NotFoundException(
                "No job found by name {}".format(JOB_NAME))
        if len(matches) > 1:
            raise MultipleMatches(
                "Multiple match found: {}, be specific ".format(matches))

        url = matches[0]
        self.name = url[url.index('job') + 4:]
        self._info = self.get_job_info(self.name)
Exemple #19
0
    def test_in_folder(self, jenkins_mock):
        jenkins_mock.side_effect = [
            None,
            jenkins.NotFoundException(),
        ]

        self.j.delete_job(u'a Folder/Test Job')

        self.assertEqual(
            jenkins_mock.call_args_list[0][0][0].url,
            self.make_url('job/a%20Folder/job/Test%20Job/doDelete'))
        self._check_requests(jenkins_mock.call_args_list)
Exemple #20
0
    def test_credential_missing(self, jenkins_mock):
        jenkins_mock.side_effect = [
            json.dumps({'_class': 'com.cloudbees.hudson.plugins.folder.Folder'}),
            jenkins.NotFoundException()
        ]

        with self.assertRaises(jenkins.JenkinsException) as context_manager:
            self.j.assert_credential_exists('NonExistent', 'TestFoler')
        self.assertEqual(
            str(context_manager.exception),
            'credential[NonExistent] does not exist'
            ' in the domain[_] of [TestFoler]')
        self._check_requests(jenkins_mock.call_args_list)
    def test_simple(self, jenkins_mock):
        jenkins_mock.side_effect = [
            None,
            jenkins.NotFoundException(),
        ]

        self.j.delete_promotion(u'Test Promotion', 'TestJob')

        self.assertEqual(
            jenkins_mock.call_args_list[0][0][0].get_full_url(),
            self.make_url('job/TestJob/promotion/process/'
                          'Test%20Promotion/doDelete'))
        self._check_requests(jenkins_mock.call_args_list)
Exemple #22
0
    def test_in_folder(self, jenkins_mock):
        jenkins_mock.side_effect = [
            jenkins.NotFoundException(),
            None,
            json.dumps({'name': 'Test Job'}),
        ]

        self.j.create_job(u'a Folder/Test Job', self.config_xml)

        self.assertEqual(
            jenkins_mock.call_args_list[1][0][0].url,
            self.make_url('job/a%20Folder/createItem?name=Test%20Job'))
        self._check_requests(jenkins_mock.call_args_list)
Exemple #23
0
    def test_job_unknown(self, mock_jenkins):
        self.mock_client.get_job_info.side_effect = jenkins.NotFoundException()
        mock_jenkins.return_value = self.mock_client

        status = cabot_jenkins.get_job_status(self.mock_config, 'unknown-job')

        expected = {
            'active': None,
            'succeeded': None,
            'job_number': None,
            'blocked_build_time': None,
            'status_code': 404
        }
        self.assertEqual(status, expected)
Exemple #24
0
    def test_failed(self, jenkins_mock):
        jenkins_mock.side_effect = [
            None,
            jenkins.NotFoundException(),
        ]

        with self.assertRaises(jenkins.JenkinsException) as context_manager:
            self.j.copy_job(u'TestJob', u'TestJob_2')
        self.assertEqual(
            jenkins_mock.call_args_list[0][0][0].url,
            self.make_url('createItem?name=TestJob_2&mode=copy&from=TestJob'))
        self.assertEqual(str(context_manager.exception),
                         'create[TestJob_2] failed')
        self._check_requests(jenkins_mock.call_args_list)
Exemple #25
0
    def test_failed(self, jenkins_mock):
        jenkins_mock.side_effect = [
            None,
            jenkins.NotFoundException(),
        ]

        with self.assertRaises(jenkins.JenkinsException) as context_manager:
            self.j.rename_job(u'TestJob', u'TestJob_2')
        self.assertEqual(
            jenkins_mock.call_args_list[0][0][0].url,
            self.make_url('job/TestJob/doRename?newName=TestJob_2'))
        self.assertEqual(str(context_manager.exception),
                         'rename[TestJob_2] failed')
        self._check_requests(jenkins_mock.call_args_list)
    def test_simple(self, jenkins_mock):
        jenkins_mock.side_effect = [
            jenkins.NotFoundException(),
            None,
            json.dumps({'name': 'Test Promotion'}),
        ]

        self.j.create_promotion(u'Test Promotion', 'Test Job', self.config_xml)

        self.assertEqual(
            jenkins_mock.call_args_list[1][0][0].get_full_url(),
            self.make_url('job/Test%20Job/promotion/'
                          'createProcess?name=Test%20Promotion'))
        self._check_requests(jenkins_mock.call_args_list)
Exemple #27
0
    def test_extended_dir_simple(self, jenkins_mock):
        jenkins_mock.side_effect = [
            None,
            jenkins.NotFoundException(),
        ]

        self.j.delete_view(u'Test Extended/Test Dir/Test View')

        self.assertEqual(
            jenkins_mock.call_args_list[0][0][0].url,
            self.make_url(
                'job/Test%20Extended/job/Test%20Dir/view/Test%20View/doDelete')
        )
        self._check_requests(jenkins_mock.call_args_list)
Exemple #28
0
    def test_simple(self, jenkins_mock):
        jenkins_mock.side_effect = [
            True,
            json.dumps({'_class': 'com.cloudbees.hudson.plugins.folder.Folder'}),
            jenkins.NotFoundException(),
        ]

        self.j.delete_credential(u'Test Credential', 'TestFolder')

        self.assertEqual(
            jenkins_mock.call_args_list[0][0][0].url,
            self.make_url('job/TestFolder/credentials/store/folder/domain/'
                          '_/credential/Test%20Credential/config.xml'))
        self._check_requests(jenkins_mock.call_args_list)
Exemple #29
0
def jenkins_request_with_headers(jenkins_server, req):
    """
    We need to get the headers in addition to the body answer
    to get the location from them
    This function uses jenkins_request method from python-jenkins library
    with just the return call changed

    :param jenkins_server: The server to query
    :param req: The request to execute
    :return: Dict containing the response body (key body)
        and the headers coming along (headers)
    """
    try:
        response = jenkins_server.jenkins_request(req)
        response_body = response.content
        response_headers = response.headers
        if response_body is None:
            raise jenkins.EmptyResponseException(
                "Error communicating with server[%s]: "
                "empty response" % jenkins_server.server)
        return {
            'body': response_body.decode('utf-8'),
            'headers': response_headers
        }
    except HTTPError as e:
        # Jenkins's funky authentication means its nigh impossible to
        # distinguish errors.
        if e.code in [401, 403, 500]:
            # six.moves.urllib.error.HTTPError provides a 'reason'
            # attribute for all python version except for ver 2.6
            # Falling back to HTTPError.msg since it contains the
            # same info as reason
            raise JenkinsException('Error in request. ' +
                                   'Possibly authentication failed [%s]: %s' %
                                   (e.code, e.msg))
        elif e.code == 404:
            raise jenkins.NotFoundException(
                'Requested item could not be found')
        else:
            raise
    except socket.timeout as e:
        raise jenkins.TimeoutException('Error in request: %s' % e)
    except URLError as e:
        # python 2.6 compatibility to ensure same exception raised
        # since URLError wraps a socket timeout on python 2.6.
        if str(e.reason) == "timed out":
            raise jenkins.TimeoutException('Error in request: %s' % e.reason)
        raise JenkinsException('Error in request: %s' % e.reason)
Exemple #30
0
    def test_extended_dir_simple(self, jenkins_mock):
        jenkins_mock.side_effect = [
            jenkins.NotFoundException(),
            None,
            json.dumps({'name': 'Test View'}),
        ]

        self.j.create_view(u'Test Extended/Test Dir/Test View',
                           self.config_xml)

        self.assertEqual(
            jenkins_mock.call_args_list[1][0][0].url,
            self.make_url(
                'job/Test%20Extended/job/Test%20Dir/createView?name=Test%20View'
            ))
        self._check_requests(jenkins_mock.call_args_list)