def test_json(self, request):
        request().content = '{}'
        resp = make_rest_api_call(
            'GET', 'http://something.com/path/to/resource.json')
        self.assertEqual(resp, {})
        request.assert_called_with(
            'GET', 'http://something.com/path/to/resource.json',
            headers=None,
            timeout=None)

        # Test JSON Error
        e = HTTPError('error')
        e.response = MagicMock()
        e.response.status_code = 404
        e.response.content = '''{
            "error": "description",
            "code": "Error Code"
        }'''
        request().raise_for_status.side_effect = e

        self.assertRaises(
            SoftLayerAPIError,
            make_rest_api_call,
            'GET',
            'http://something.com/path/to/resource.json')
示例#2
0
def _get_error_base(mocker):
    base_err = HTTPError()
    mock_response = mocker.MagicMock(spec=Response)
    base_err.response = mock_response
    request = mocker.MagicMock(spec=Request)
    request.body = '{"test":"body"}'
    base_err.response.request = request
    return base_err
示例#3
0
 def side_effect(*args, **kwargs):
     base_err = HTTPError()
     base_err.response = mocker.MagicMock(spec=Response)
     base_err.response.text = """
         [{"name":"CUSTOM_KEY_INVALID","description":"An error has
         occurred. See server logs for more information.","objects":[]}]
     """
     raise Py42InternalServerError(base_err)
示例#4
0
    def raise_for_status(self, allow_redirects=True):
        """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""

        if self.error:
            raise HTTPError(self.error)

        if (self.status_code >= 300) and (self.status_code < 400) and not allow_redirects:
            http_error = HTTPError('%s Redirection' % (self.status_code))
            http_error.response = self
            raise http_error

        elif (self.status_code >= 400) and (self.status_code < 500):
            http_error = HTTPError('%s Client Error' % (self.status_code))
            http_error.response = self
            raise http_error

        elif (self.status_code >= 500) and (self.status_code < 600):
            http_error = HTTPError('%s Server Error' % (self.status_code))
            http_error.response = self
            raise http_error
示例#5
0
    def raise_for_status(self, allow_redirects=True):
        """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""

        if self.error:
            raise HTTPError(self.error)

        if (self.status_code >= 300) and (self.status_code < 400) and not allow_redirects:
            http_error = HTTPError('%s Redirection' % (self.status_code))
            http_error.response = self
            raise http_error

        elif (self.status_code >= 400) and (self.status_code < 500):
            http_error = HTTPError('%s Client Error' % (self.status_code))
            http_error.response = self
            raise http_error

        elif (self.status_code >= 500) and (self.status_code < 600):
            http_error = HTTPError('%s Server Error' % (self.status_code))
            http_error.response = self
            raise http_error
 def invalid_virtual_address(target):
     setup_target(target)
     bigip = make_bigip()
     http_error = HTTPError('foo')
     http_error.response = Mock()
     http_error.response.status_code = 400
     BigIPResourceHelper.load.side_effect = http_error
     target.split_addr_port.return_value = \
         tuple([bigip.lb_id, bigip.vip_port])
     expected = []
     assert target.get_virtual_service_insertion(
         bigip, partition=bigip.partition) == expected
 def invalid_virtual_address(target):
     setup_target(target)
     bigip = make_bigip()
     http_error = HTTPError('foo')
     http_error.response = Mock()
     http_error.response.status_code = 400
     BigIPResourceHelper.load.side_effect = http_error
     target.split_addr_port.return_value = \
         tuple([bigip.lb_id, bigip.vip_port])
     expected = []
     assert target.get_virtual_service_insertion(
         bigip, partition=bigip.partition) == expected
示例#8
0
    def test_should_not_retry_on_404_response(self):
        with mock.patch(
                "gentoo_build_publisher.publisher.Jenkins.download_artifact"
        ) as download_artifact_mock:
            error = HTTPError()
            error.response = mock.Mock()
            error.response.status_code = 404
            download_artifact_mock.side_effect = error

            with mock.patch.object(pull_build, "retry") as retry_mock:
                pull_build.s("tango.197").apply()

        retry_mock.assert_not_called()
    def __raise_for_status(self, status_code, reason):
        http_error_msg = ''

        if 400 <= status_code < 500:
            http_error_msg = '%s Client Error: %s' % (status_code, reason)

        elif 500 <= status_code < 600:
            http_error_msg = '%s Server Error: %s' % (status_code, reason)

        if http_error_msg:
            http_error = HTTPError(http_error_msg)
            http_error.response = self
            raise http_error
    def test_text(self, request):
        request().text = "content"
        resp = make_rest_api_call("GET", "http://something.com/path/to/resource.txt")
        self.assertEqual(resp, "content")
        request.assert_called_with("GET", "http://something.com/path/to/resource.txt", headers=None, timeout=None)

        # Test Text Error
        e = HTTPError("error")
        e.response = MagicMock()
        e.response.status_code = 404
        e.response.content = "Error Code"
        request().raise_for_status.side_effect = e

        self.assertRaises(SoftLayerAPIError, make_rest_api_call, "GET", "http://something.com/path/to/resource.txt")
 def positive_w_exception(target):
     setup_target(target)
     bigip = make_bigip()
     http_error = HTTPError('foo')
     http_error.response = Mock()
     http_error.response.status_code = 404
     bigip.tm.ltm.virtual_address_s.virtual_address.load.side_effect = \
         http_error
     target.split_addr_port.return_value = \
         tuple([bigip.lb_id, bigip.vip_port])
     expected = \
         [{bigip.name: dict(address=bigip.lb_id,
                            netmask=bigip.netmask,
                            protocol=bigip.protocol,
                            port=bigip.vip_port)}]
     assert target.get_virtual_service_insertion(
         bigip, partition=bigip.partition) == expected
示例#12
0
 def positive_w_exception(target):
     setup_target(target)
     bigip = make_bigip()
     http_error = HTTPError('foo')
     http_error.response = Mock()
     http_error.response.status_code = 404
     bigip.tm.ltm.virtual_address_s.virtual_address.load.side_effect = \
         http_error
     target.split_addr_port.return_value = \
         tuple([bigip.lb_id, bigip.vip_port])
     expected = \
         [{bigip.name: dict(address=bigip.lb_id,
                            netmask=bigip.netmask,
                            protocol=bigip.protocol,
                            port=bigip.vip_port)}]
     assert target.get_virtual_service_insertion(
         bigip, partition=bigip.partition) == expected
示例#13
0
    def raise_for_status(self, allow_redirects=True):
        """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""

        if self.status_code == 304:
            return
        elif self.error:
            http_error = HTTPError(self.error)
        elif (self.status_code >= 300) and (self.status_code < 400) and not allow_redirects:
            http_error = HTTPError('{0!s} Redirection'.format((self.status_code)))
        elif (self.status_code >= 400) and (self.status_code < 500):
            http_error = HTTPError('{0!s} Client Error'.format((self.status_code)))
        elif (self.status_code >= 500) and (self.status_code < 600):
            http_error = HTTPError('{0!s} Server Error'.format((self.status_code)))
        else:
            return

        http_error.response = self
        raise http_error
    def test_purge_orphaned_health_monitor(self, standalone_builder,
                                           fully_mocked_target, mock_logger,
                                           service_with_health_monitor,
                                           mock_resource_helper):
        svc = service_with_health_monitor
        builder = standalone_builder
        target = fully_mocked_target

        def main_path(target, builder, svc, resource_helper):
            bigip = Mock()
            hostnames = ['foodoozoo']
            bigip.hostname = hostnames[0]
            builder.mock_get_all_bigips(target, return_value=[bigip])
            li_id = svc['healthmonitors'][0]['id']
            t_id = svc['healthmonitors'][0]['tenant_id']
            target.purge_orphaned_health_monitor(t_id, li_id, hostnames)
            builder.check_mocks(target)
            assert resource_helper.return_value.load.call_count
            assert resource_helper.call_count == 4

        def error(target, svc, builder, resource_helper, logger, error):
            bigip = Mock()
            hostnames = ['foodoozoo']
            bigip.hostname = hostnames[0]
            builder.mock_get_all_bigips(target, return_value=[bigip])
            li_id = svc['healthmonitors'][0]['id']
            t_id = svc['healthmonitors'][0]['tenant_id']
            resource_helper.return_value.load.side_effect = error
            target.purge_orphaned_health_monitor(t_id, li_id, hostnames)

        main_path(target, builder, svc, mock_resource_helper)
        mock_resource_helper.reset_mock()
        response = Mock()
        response.status_code = 404
        http_error = HTTPError("foo")
        http_error.response = response
        error(target, svc, builder, mock_resource_helper, self.logger,
              http_error)
        assert self.logger.exception.call_count
        self.logger.reset_mock()
        error(target, svc, builder, mock_resource_helper, self.logger,
              Exception)
        assert self.logger.exception.call_count
示例#15
0
    def raise_for_status(self, allow_redirects=True):
        """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""

        if self.status_code == 304:
            return
        elif self.error:
            if self.traceback:
                six.reraise(Exception, Exception(self.error), Traceback.from_string(self.traceback).as_traceback())
            http_error = HTTPError(self.error)
        elif (self.status_code >= 300) and (self.status_code < 400) and not allow_redirects:
            http_error = HTTPError('%s Redirection' % (self.status_code))
        elif (self.status_code >= 400) and (self.status_code < 500):
            http_error = HTTPError('%s Client Error' % (self.status_code))
        elif (self.status_code >= 500) and (self.status_code < 600):
            http_error = HTTPError('%s Server Error' % (self.status_code))
        else:
            return

        http_error.response = self
        raise http_error
示例#16
0
    def raise_for_status(self, allow_redirects=True):
        """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""

        if self.status_code == 304:
            return
        elif self.error:
            if self.traceback:
                six.reraise(Exception, Exception(self.error), Traceback.from_string(self.traceback).as_traceback())
            http_error = HTTPError(self.error)
        elif (self.status_code >= 300) and (self.status_code < 400) and not allow_redirects:
            http_error = HTTPError('%s Redirection' % (self.status_code))
        elif (self.status_code >= 400) and (self.status_code < 500):
            http_error = HTTPError('%s Client Error' % (self.status_code))
        elif (self.status_code >= 500) and (self.status_code < 600):
            http_error = HTTPError('%s Server Error' % (self.status_code))
        else:
            return

        http_error.response = self
        raise http_error
    def test_text(self, request):
        request().text = 'content'
        resp = make_rest_api_call(
            'GET', 'http://something.com/path/to/resource.txt')
        self.assertEqual(resp, 'content')
        request.assert_called_with(
            'GET', 'http://something.com/path/to/resource.txt',
            headers=None,
            timeout=None)

        # Test Text Error
        e = HTTPError('error')
        e.response = MagicMock()
        e.response.status_code = 404
        e.response.content = 'Error Code'
        request().raise_for_status.side_effect = e

        self.assertRaises(
            SoftLayerAPIError,
            make_rest_api_call,
            'GET',
            'http://something.com/path/to/resource.txt')
示例#18
0
def test_that_raise_for_status_extends_error_message():
    inner_response = MagicMock()
    inner_response.text = '{"foo": "bar", "spam": ["eggs"]}'

    error = HTTPError('Something went wrong.')
    error.response = inner_response

    inner_response.raise_for_status.side_effect = error

    response = Response(inner_response)
    with pytest.raises(HTTPError):
        response.raise_for_status()

    inner_response.raise_for_status.assert_called_once_with()
    assert error.args == (
        'Something went wrong.\n'
        '{\n'
        '    "foo": "bar",' + (' ' if six.PY2 else '') + '\n'
        '    "spam": [\n'
        '        "eggs"\n'
        '    ]\n'
        '}',
    )
示例#19
0
 def mock_update_failed_response(self, mock_error_response):
     http_error = HTTPError(UPDATE_ERROR_RESPONSE)
     http_error.response = mock_error_response
     http_error.response.text = UPDATE_ERROR_RESPONSE
     return http_error
示例#20
0
    def test_validate_signature(self):
        """Check validate signature"""
        data = {
            "data": {
                "external_ids": ['SignedChain'],
                "dblock": {
                    "height": 10000
                },
                "content": "123"
            }
        }
        result = ValidateSignatureUtil.validate_signature(
            data, True, self.request_handler)
        self.assertEqual("not_signed/invalid_chain_format", result)

        data = {
            "data": {
                "external_ids": [
                    'SignedChain',
                    '0x01',
                    '171e5851451ce6f2d9730c1537da4375feb442870d835c54a1bca8ffa7e2bda7',
                    'idpub',
                    '779229d23cdb7380869e63e5156a5497170bceec139b37e7af2a4d1aae14d053d19f7626e08d4bbb003d4b05d941f43402f1288af2ff0391a2dee4abf0919b07',
                    '2019-01-18T14:17:50Z',
                ],
                "dblock": {
                    "height": 10000
                },
                "content":
                "123"
            }
        }
        result = ValidateSignatureUtil.validate_signature(
            data, True, self.request_handler)
        self.assertEqual("not_signed/invalid_chain_format", result)

        data = {
            "data": {
                "external_ids": [
                    'SignedChain',
                    '0x01',
                    '171e5851451ce6f2d9730c1537da4375feb442870d835c54a1bca8ffa7e2bda7',
                    'idpub3NegGMKn2CDcx3A9JkpoMm2jE9KxchxqHTmXPvJnmUJGizfrb7',
                    '779229d23cdb7380869e63e5156a5497170bceec139b37e7af2a4d1aae14d053d19f7626e08d4bbb003d4b05d941ty3402f1288af2ff0391a2dee4abf0919b07',
                    '2019-01-18T14:17:50Z',
                ],
                "dblock": {
                    "height": 10000
                },
                "content":
                "123"
            }
        }
        result = ValidateSignatureUtil.validate_signature(
            data, True, self.request_handler)
        self.assertEqual("not_signed/invalid_chain_format", result)

        data = {
            "data": {
                "external_ids": [
                    'SignedChain',
                    '0x01',
                    '171e5851451ce6f2d9730c1537da4375feb442870d835c54a1bca8ffa7e2bda7',
                    'idpub3NegGMKn2CDcx3A9JkpoMm2jE9KxchxqHTmXPvJnmUJGizfrb7',
                    '779229d23cdb7380869e63e5156a5497170bceec139b37e7af2a4d1aae14d053d19f7626e08d4bbb003d4b05d941f43402f1288af2ff0391a2dee4abf0919b07',
                    '2019-01-18T14:17:50Z',
                ],
                "dblock": {
                    "height": 10000
                },
                "content":
                "123"
            }
        }

        with patch(
                "factom_sdk.request_handler.request_handler.requests.request"
        ) as mock_get:
            mock_error = HTTPError()
            mock_error.response = Mock()
            mock_error.response.status_code = 404
            mock_get.side_effect = mock_error
            response = ValidateSignatureUtil.validate_signature(
                data, True, self.request_handler)
            self.assertEqual("key_not_found", response)

        with self.assertRaises(HTTPError) as cm:
            with patch(
                    "factom_sdk.request_handler.request_handler.requests.request"
            ) as mock_get:
                mock_error = HTTPError()
                mock_error.response = Mock()
                mock_error.response.status_code = 500
                mock_get.side_effect = mock_error
                ValidateSignatureUtil.validate_signature(
                    data, True, self.request_handler)
        self.assertTrue("" in str(cm.exception))

        with patch(
                "factom_sdk.request_handler.request_handler.requests.request"
        ) as mock_get:
            json = {
                "data": {
                    "key": "123",
                    "retired_height": 1001,
                    "activated_height": 1001,
                }
            }
            mock_get.return_value.ok = True
            mock_get.return_value.json.return_value = json
            response = ValidateSignatureUtil.validate_signature(
                data, True, self.request_handler)
            self.assertEqual("retired_key", response)

        data = {
            "data": {
                "external_ids": [
                    'SignedEntry',
                    '0x01',
                    '171e5851451ce6f2d9730c1537da4375feb442870d835c54a1bca8ffa7e2bda7',
                    'idpub3NegGMKn2CDcx3A9JkpoMm2jE9KxchxqHTmXPvJnmUJGizfrb7',
                    '779229d23cdb7380869e63e5156a5497170bceec139b37e7af2a4d1aae14d053d19f7626e08d4bbb003d4b05d941f43402f1288af2ff0391a2dee4abf0919b07',
                    '2019-01-18T14:17:50Z',
                ],
                "dblock": {
                    "height": 1000
                },
                "content":
                "123"
            }
        }

        with patch(
                "factom_sdk.request_handler.request_handler.requests.request"
        ) as mock_get:
            json = {
                "data": {
                    "key": "123",
                    "retired_height": 900,
                    "activated_height": 1001,
                }
            }
            mock_get.return_value.ok = True
            mock_get.return_value.json.return_value = json
            response = ValidateSignatureUtil.validate_signature(
                data, False, self.request_handler)
            self.assertEqual("retired_key", response)

        with patch(
                "factom_sdk.request_handler.request_handler.requests.request"
        ) as mock_get:
            json = {
                "data": {
                    "key":
                    "idpub3NegGMKn2CDcx3A9JkpoMm2jE9KxchxqHTmXPvJnmUJGizfrb7",
                    "retired_height": 1001,
                    "activated_height": 900,
                }
            }
            mock_get.return_value.ok = True
            mock_get.return_value.json.return_value = json
            response = ValidateSignatureUtil.validate_signature(
                data, False, self.request_handler)
            self.assertEqual("invalid_signature", response)
示例#21
0
 def raise_for_status(self):
     if self.status_code == 200:
         return
     error = HTTPError()
     error.response = self
     raise error
示例#22
0
 def mock_add_same_event_multiple_times(self, mock_error_response):
     http_error = HTTPError(ADDED_SAME_EVENT_AGAIN_ERROR)
     http_error.response = mock_error_response
     http_error.response.text = ADDED_SAME_EVENT_AGAIN_ERROR
     return http_error
示例#23
0
 def mock_name_exists_response(self, mock_error_response):
     http_error = HTTPError(NAME_EXISTS_ERROR_MSG)
     http_error.response = mock_error_response
     http_error.response.text = NAME_EXISTS_ERROR_MSG
     return http_error
示例#24
0
 def side_effect(org_id):
     err = HTTPError()
     err.response = mock.Mock(status_code=403)
     raise TembaAPIError(caused_by=err)
示例#25
0
def user_already_added_response(mocker):
    mock_response = mocker.MagicMock(spec=Response)
    mock_response.text = "USER_ALREADY_IN_HOLD"
    http_error = HTTPError()
    http_error.response = mock_response
    return Py42BadRequestError(http_error)
示例#26
0
 def mock_unknown_error(self, mock_error_response):
     http_error = HTTPError(UNKNOWN_ERROR)
     http_error.response = mock_error_response
     http_error.response.text = UNKNOWN_ERROR
     return http_error
示例#27
0
 def mock_description_too_long_response(self, mock_error_response):
     http_error = HTTPError(DESCRIPTION_TOO_LONG_ERROR_MSG)
     http_error.response = mock_error_response
     http_error.response.text = DESCRIPTION_TOO_LONG_ERROR_MSG
     return http_error