コード例 #1
0
    def test_server_metadata_update_forbidden(self):
        server = mock.Mock()
        res_server = mock.Mock()
        res_server.metadata = {
            'k1': 'v1',
            'forbidden_key': 'forbidden_data',
            'k2': 'v2'
        }
        self.compute.get_server_metadata.return_value = res_server
        self.compute.delete_server_metadata.side_effect = [
            None, sdk_exc.HttpException(http_status=403), None
        ]
        self.compute.set_server_metadata.side_effect = [
            None, sdk_exc.HttpException(http_status=403), None
        ]

        d = nova_v2.NovaClient(self.conn_params)
        d.server_metadata_update(server, {'k3': 'v3', 'k4': 'v4', 'k5': 'v5'})
        self.compute.set_server_metadata.assert_has_calls([
            mock.call(server, k3='v3'),
            mock.call(server, k4='v4'),
            mock.call(server, k5='v5')
        ],
                                                          any_order=True)
        self.compute.delete_server_metadata.assert_has_calls([
            mock.call(server, ['k1']),
            mock.call(server, ['forbidden_key']),
            mock.call(server, ['k2'])
        ],
                                                             any_order=True)
コード例 #2
0
    def authorize(self):
        """Authorize this Connection

        **NOTE**: This method is optional. When an application makes a call
                  to any OpenStack service, this method allows you to request
                  a token manually before attempting to do anything else.

        :returns: A string token.

        :raises:`~openstack.exceptions.HttpException` if the authorization
                fails due to reasons like the credentials provided are unable
                to be authorized or the `auth_plugin` argument is missing,
                etc.
        """
        try:
            headers = self.session.get_auth_headers()
        except ksa_exc.AuthorizationFailure as ex:
            raise exceptions.HttpException("Authentication Failure",
                                           six.text_type(ex),
                                           status_code=401)
        except ksa_exc.MissingAuthPlugin as ex:
            raise exceptions.HttpException("Bad Request",
                                           six.text_type(ex),
                                           status_code=400)
        except Exception as ex:
            raise exceptions.HttpException("Unknown exception",
                                           six.text_type(ex),
                                           status_code=500)

        return headers.get('X-Auth-Token') if headers else None
コード例 #3
0
    def test_send_notification_409_error(
        self, mock_password, mock_session, mock_connection):

        mock_conn = mock.Mock()
        mock_conn.instance_ha.return_value = mock.Mock()
        mock_conn.instance_ha.create_notification.return_value = mock.Mock()
        mock_connection.return_value = mock_conn

        # TODO(samP): Remove attribute check and else case if
        # openstacksdk is bumped up from '>=0.9.19' to '>=0.10.0'
        # in global-requirements.
        if hasattr(exceptions.HttpException(), 'status_code'):
            response = FakeResponse(status_code=409)
            status_ex = exceptions.HttpException(response=response)
        else:
            status_ex = exceptions.HttpException(http_status=409)

        mock_conn.instance_ha.create_notification.side_effect = status_ex
        notifier = masakari.SendNotification()
        notifier.send_notification(
            self.api_retry_max, self.api_retry_interval, self.event)

        mock_conn.instance_ha.create_notification.assert_called_once_with(
            type=self.event['notification']['type'],
            hostname=self.event['notification']['hostname'],
            generated_time=self.event['notification']['generated_time'],
            payload=self.event['notification']['payload'])
コード例 #4
0
    def test_send_notification_500_error(self, mock_password, mock_session,
        mock_service_description, mock_connection, mock_sleep):

        mock_conn = mock.Mock()
        mock_client = mock.Mock()
        mock_conn.ha.proxy_class.return_value = mock_client
        mock_connection.return_value = mock_conn

        # TODO(samP): Remove attribute check and else case if
        # openstacksdk is bumped up from '>=0.9.19' to '>=0.10.0'
        # in global-requirements.
        if hasattr(exceptions.HttpException(), 'status_code'):
            response = FakeResponse(status_code=500)
            status_ex = exceptions.HttpException(response=response)
        else:
            status_ex = exceptions.HttpException(http_status=500)

        mock_client.create_notification.side_effect = status_ex
        mock_sleep.return_value = None

        notifier = masakari.SendNotification()
        notifier.send_notification(
            self.api_retry_max, self.api_retry_interval, self.event)

        mock_client.create_notification.assert_called_with(
            type=self.event['notification']['type'],
            hostname=self.event['notification']['hostname'],
            generated_time=self.event['notification']['generated_time'],
            payload=self.event['notification']['payload'])
        self.assertEqual(self.api_retry_max + 1,
                         mock_client.create_notification.call_count)
コード例 #5
0
 def test_is_bad_request(self):
     self.assertTrue(
         self.plugin.is_bad_request(
             exceptions.HttpException(http_status=400)))
     self.assertFalse(self.plugin.is_bad_request(Exception))
     self.assertFalse(
         self.plugin.is_bad_request(
             exceptions.HttpException(http_status=404)))
コード例 #6
0
 def test_unicode_message(self):
     unicode_message = u"Event: No item found for does_not_exist©"
     http_exception = exceptions.HttpException(message=unicode_message)
     try:
         http_exception.__unicode__()
     except Exception:
         self.fail("HttpException unicode message error")
コード例 #7
0
 def test_validate_false(self):
     self.mock_get_profile.side_effect = exceptions.ResourceNotFound(
         'PROFILE_ID')
     self.assertFalse(self.constraint.validate("PROFILE_ID", self.ctx))
     self.mock_get_profile.side_effect = exceptions.HttpException(
         'PROFILE_ID')
     self.assertFalse(self.constraint.validate("PROFILE_ID", self.ctx))
コード例 #8
0
 def test_validate_false(self):
     self.mock_get_cluster.side_effect = exceptions.ResourceNotFound(
         'CLUSTER_ID')
     self.assertFalse(self.constraint.validate("CLUSTER_ID", self.ctx))
     self.mock_get_cluster.side_effect = exceptions.HttpException(
         'CLUSTER_ID')
     self.assertFalse(self.constraint.validate("CLUSTER_ID", self.ctx))
コード例 #9
0
 def page(cls,
          session,
          limit=None,
          marker=None,
          path_args=None,
          **params):
     raise exceptions.HttpException("exception")
コード例 #10
0
    def test_send_notification_500_error(self, mock_auth, mock_session,
                                         mock_connection, mock_sleep):

        mock_conn = mock.Mock()
        mock_conn.instance_ha.return_value = mock.Mock()
        mock_conn.instance_ha.create_notification.return_value = mock.Mock()
        mock_connection.return_value = mock_conn

        response = FakeResponse(status_code=500)
        status_ex = exceptions.HttpException(response=response)

        mock_conn.instance_ha.create_notification.side_effect = status_ex
        mock_sleep.return_value = None

        notifier = masakari.SendNotification()
        notifier.send_notification(self.api_retry_max, self.api_retry_interval,
                                   self.event)

        mock_conn.instance_ha.create_notification.assert_called_with(
            type=self.event['notification']['type'],
            hostname=self.event['notification']['hostname'],
            generated_time=self.event['notification']['generated_time'],
            payload=self.event['notification']['payload'])
        self.assertEqual(self.api_retry_max + 1,
                         mock_conn.instance_ha.create_notification.call_count)
コード例 #11
0
    def test_nada(self):
        self.mock_get.side_effect = [
            exceptions.HttpException(404, 'not found'),
            FakeResponse({FakeResource.resources_key: []})
        ]

        self.assertEqual(None, FakeResource.find(self.mock_session, self.NAME))
コード例 #12
0
 def test_is_not_found(self):
     self.assertFalse(
         self.plugin.is_not_found(
             exceptions.HttpException(http_status=400)))
     self.assertFalse(self.plugin.is_not_found(Exception))
     self.assertTrue(
         self.plugin.is_not_found(
             exceptions.NotFoundException(http_status=404)))
コード例 #13
0
    def test_no_name(self):
        self.mock_get.side_effect = [
            exceptions.HttpException(404, 'not found'),
            FakeResponse({FakeResource.resources_key: [self.matrix]})
        ]
        FakeResource.name_attribute = None

        self.assertEqual(None, FakeResource.find(self.mock_session, self.NAME))
コード例 #14
0
    def test_nada_not_ignored(self):
        self.mock_get.side_effect = [
            exceptions.HttpException(404, 'not found'),
            FakeResponse({FakeResource.resources_key: []})
        ]

        self.assertRaises(exceptions.ResourceNotFound, FakeResource.find,
                          self.mock_session, self.NAME, ignore_missing=False)
コード例 #15
0
ファイル: test_event.py プロジェクト: numvc/LuxoftBot
 def test_event_list_sort_invalid_direction(self):
     kwargs = copy.deepcopy(self.defaults)
     kwargs['sort'] = 'name:bad_direction'
     arglist = ['--sort', 'name:bad_direction']
     parsed_args = self.check_parser(self.cmd, arglist, [])
     self.mock_client.events.side_effect = sdk_exc.HttpException()
     self.assertRaises(sdk_exc.HttpException, self.cmd.take_action,
                       parsed_args)
コード例 #16
0
 def test_profile_list_sort_invalid_key(self):
     kwargs = copy.deepcopy(self.defaults)
     kwargs['sort'] = 'bad_key'
     arglist = ['--sort', 'bad_key']
     parsed_args = self.check_parser(self.cmd, arglist, [])
     self.mock_client.profiles.side_effect = sdk_exc.HttpException()
     self.assertRaises(sdk_exc.HttpException, self.cmd.take_action,
                       parsed_args)
コード例 #17
0
ファイル: test_proxy.py プロジェクト: useitcloud/openstacksdk
    def test_delete_HttpException(self):
        self.res.delete.side_effect = exceptions.HttpException(message="test",
                                                               http_status=500)

        self.assertRaises(exceptions.HttpException,
                          self.sot._delete,
                          DeleteableResource,
                          self.res,
                          ignore_missing=False)
コード例 #18
0
 def test_node_list_sort_invalid_direction(self):
     self.mock_client.nodes = mock.Mock(return_value=self.response)
     kwargs = copy.deepcopy(self.defaults)
     kwargs['sort'] = 'name:bad_direction'
     arglist = ['--sort', 'name:bad_direction']
     parsed_args = self.check_parser(self.cmd, arglist, [])
     self.mock_client.nodes.side_effect = sdk_exc.HttpException()
     self.assertRaises(sdk_exc.HttpException, self.cmd.take_action,
                       parsed_args)
コード例 #19
0
    def test_dups(self):
        dup = {'id': 'Larry'}
        self.mock_get.side_effect = [
            exceptions.HttpException(404, 'not found'),
            FakeResponse({FakeResource.resources_key: [self.matrix, dup]})
        ]

        self.assertRaises(exceptions.DuplicateResource, FakeResource.find,
                          self.mock_session, self.NAME)
コード例 #20
0
    def test_find_project_with_generic_exception(self):
        sdk_connection = mock.Mock()
        sdk_find_project = sdk_connection.identity.find_project
        exc = exceptions.HttpException()
        # Some value other than 403.
        exc.status_code = 499
        sdk_find_project.side_effect = exc

        with testtools.ExpectedException(exceptions.HttpException):
            cli_identity.find_project(sdk_connection, 'project1')
コード例 #21
0
    def test_dups(self):
        dupe = self.matrix.copy()
        dupe['id'] = 'different'
        self.mock_get.side_effect = [
            # Raise a 404 first so we get out of the ID search and into name.
            exceptions.HttpException(404, 'not found'),
            FakeResponse({FakeResource.resources_key: [self.matrix, dupe]})
        ]

        self.assertRaises(exceptions.DuplicateResource, FakeResource.find,
                          self.mock_session, self.NAME)
コード例 #22
0
    def test_name(self):
        self.mock_get.side_effect = [
            exceptions.HttpException(404, 'not found'),
            FakeResponse({FakeResource.resources_key: [self.matrix]})
        ]

        result = FakeResource.find(self.mock_session,
                                   self.NAME,
                                   path_args=fake_arguments)

        self.assertEqual(self.NAME, result.name)
        self.assertEqual(self.PROP, result.prop)
コード例 #23
0
    def test_find_project_with_forbidden_exception(self):
        sdk_connection = mock.Mock()
        sdk_find_project = sdk_connection.identity.find_project
        exc = exceptions.HttpException()
        exc.status_code = 403
        sdk_find_project.side_effect = exc

        ret = cli_identity.find_project(sdk_connection, 'project1')

        self.assertIsInstance(ret, project.Project)
        self.assertEqual('project1', ret.id)
        self.assertEqual('project1', ret.name)
コード例 #24
0
 def test_policy_delete_not_attached(self):
     policy = self._create_policy(self.t)
     self.senlin_mock.get_policy.side_effect = [
         exceptions.ResourceNotFound('SenlinPolicy'),
     ]
     self.senlin_mock.detach_policy_from_cluster.side_effect = [
         exceptions.HttpException(http_status=400),
     ]
     scheduler.TaskRunner(policy.delete)()
     self.senlin_mock.detach_policy_from_cluster.assert_called_once_with(
         'c1_id', policy.resource_id)
     self.senlin_mock.delete_policy.assert_called_once_with(
         policy.resource_id)
コード例 #25
0
ファイル: session.py プロジェクト: 571451370/devstack_mitaka
 def map_exceptions_wrapper(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except _exceptions.HttpError as e:
         if e.http_status == 404:
             raise exceptions.NotFoundException(
                 message=e.message, details=e.details,
                 response=e.response, request_id=e.request_id,
                 url=e.url, method=e.method,
                 http_status=e.http_status, cause=e)
         else:
             raise exceptions.HttpException(
                 message=e.message, details=e.details,
                 response=e.response, request_id=e.request_id,
                 url=e.url, method=e.method,
                 http_status=e.http_status, cause=e)
     except _exceptions.ClientException as e:
         raise exceptions.SDKException(message=e.message, cause=e)
コード例 #26
0
 def test_find_not_found(self):
     sess = mock.Mock()
     sess.get = mock.MagicMock()
     sess.get.side_effect = exceptions.HttpException("404")
     sot = keypair.Keypair()
     self.assertEqual(None, sot.find(sess, "kato"))
コード例 #27
0
ファイル: test_lbaasv2.py プロジェクト: ragilsetian/kuryr-k8s
 def test_ensure_with_internalservererror(self):
     self._verify_ensure_with_exception(
         os_exc.HttpException(http_status=500))
コード例 #28
0
    def request(self, method, url, redirect=None, **kwargs):
        """Send a request

        :param string method: Request HTTP method
        :param string url: Request URL
        :param boolean/integer redirect: (integer) The maximum number of
                                         redirections followed in a request.
                                         (boolean) No redirections if False,
                                         requests.Session handles redirection
                                         if True. (optional)

        The following additional kw args are supported:
        :param object json: Request body to be encoded as JSON
                            Overwrites ``data`` argument if present
        :param string accept: Set the ``Accept`` header; overwrites
                                  any value that may be in the headers dict.
                                  Header is omitted if ``None``.
        :param string user_agent: Set the ``User-Agent`` header; overwrites
                                  any value that may be in the headers dict.
                                  Header is omitted if ``None``.

        Remaining kw args from requests.Session.request() supported

        """

        headers = kwargs.setdefault('headers', {})

        # JSON-encode the data in json arg if present
        # Overwrites any existing 'data' value
        json_data = kwargs.pop('json', None)
        if json_data is not None:
            kwargs['data'] = json.dumps(json_data)
            headers['Content-Type'] = JSON

        # Set User-Agent header if user_agent arg included, or
        # fall through the default chain as described above
        if 'user_agent' in kwargs:
            headers['User-Agent'] = kwargs.pop('user_agent')
        elif self._user_agent:
            headers.setdefault('User-Agent', self._user_agent)
        else:
            headers.setdefault('User-Agent', DEFAULT_USER_AGENT)

        if redirect is None:
            redirect = self._redirect

        if isinstance(redirect, bool) and redirect:
            # Fall back to requests redirect handling
            kwargs['allow_redirects'] = True
        else:
            # Force disable requests redirect handling, we will manage
            # redirections below
            kwargs['allow_redirects'] = False
        if 'accept' in kwargs:
            accept = kwargs.pop('accept')
        else:
            accept = self._accept
        if accept:
            headers.setdefault('Accept', accept)

        self._log_request(method, url, **kwargs)

        resp = self._send_request(method, url, redirect, **kwargs)

        self._log_response(resp)

        try:
            resp.raise_for_status()
        except requests.RequestException as e:
            raise exceptions.HttpException(six.text_type(e), details=resp.text)
        if accept == JSON:
            try:
                resp.body = resp.json()
            except ValueError as e:
                # this may be simplejson.decode.JSONDecodeError
                # Re-raise into our own exception
                raise exceptions.InvalidResponse(response=resp.text)

        return resp
コード例 #29
0
 def _do_raise(self, *args, **kwargs):
     raise exceptions.HttpException(*args, **kwargs)
コード例 #30
0
    def request(self, method, url, redirect=None, **kwargs):
        """Send a request

        Perform an HTTP request. The following arguments differ from
        ``requests.Session``:

        :param string method: Request HTTP method
        :param string url: Request URL
        :param boolean/integer redirect: (integer) The maximum number of
                                         redirections followed in a request.
                                         (boolean) No redirections if False,
                                         requests.Session handles redirection
                                         if True. (optional)

        The following additional kw args are supported:

        :param object json: Request body to be encoded as JSON
                            Overwrites ``data`` argument if present
        :param string accept: Set the ``Accept`` header; overwrites
                                  any value that may be in the headers dict.
                                  Header is omitted if ``None``.
        :param string user_agent: Prepend an additional value to the existing
                                  ``User-Agent`` header.

        Remaining kw args from requests.Session.request() supported

        """

        headers = kwargs.setdefault('headers', {})

        # JSON-encode the data in json arg if present
        # Overwrites any existing 'data' value
        json_data = kwargs.pop('json', None)
        if json_data is not None:
            kwargs['data'] = json.dumps(json_data)
            headers['Content-Type'] = JSON

        # Prepend the caller's user_agent to User-Agent header if included,
        # or use the default that this transport was created with.
        # Note: Only attempt to work with strings and avoid needlessly
        # concatenating an empty string.
        user_agent = kwargs.pop('user_agent', None)
        if isinstance(user_agent, six.string_types) and user_agent != '':
            headers['User-Agent'] = '%s %s' % (user_agent, self._user_agent)
        elif 'User-Agent' in headers:
            # If they've specified their own headers with a User-Agent,
            # use that directly.
            pass
        else:
            headers.setdefault('User-Agent', self._user_agent)

        if redirect is None:
            redirect = self._redirect

        if isinstance(redirect, bool) and redirect:
            # Fall back to requests redirect handling
            kwargs['allow_redirects'] = True
        else:
            # Force disable requests redirect handling, we will manage
            # redirections below
            kwargs['allow_redirects'] = False
        if 'accept' in kwargs:
            accept = kwargs.pop('accept')
        else:
            accept = self._accept
        if accept:
            headers.setdefault('Accept', accept)

        self._log_request(method, url, **kwargs)

        resp = self._send_request(method, url, redirect, **kwargs)

        self._log_response(resp)

        try:
            resp.raise_for_status()
        except requests.RequestException as e:
            raise exceptions.HttpException(
                six.text_type(e),
                details=self._parse_error_response(resp),
                status_code=resp.status_code)
        if accept == JSON:
            try:
                resp.body = resp.json()
            except ValueError as e:
                # this may be simplejson.decode.JSONDecodeError
                # Re-raise into our own exception
                raise exceptions.InvalidResponse(response=resp.text)

        return resp