Python six.moves.http_client.FORBIDDEN Examples

The following are 16 code examples of six.moves.http_client.FORBIDDEN(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module six.moves.http_client , or try the search function .
Example #1
Source File: test_inquiries.py    From st2 with Apache License 2.0 6 votes vote down vote up
def test_respond_restrict_users(self):
        """Test that Inquiries can reject responses from users not in a list
        """

        # Default user for tests is "stanley", which is not in the 'users' list
        # Should be rejected
        post_resp = self._do_create_inquiry(INQUIRY_2, RESULT_2)
        inquiry_id = self._get_inquiry_id(post_resp)
        response = {"continue": True}
        put_resp = self._do_respond(inquiry_id, response, expect_errors=True)
        self.assertEqual(put_resp.status_int, http_client.FORBIDDEN)
        self.assertIn('does not have permission to respond', put_resp.json['faultstring'])

        # Responding as a use in the list should be accepted
        old_user = cfg.CONF.system_user.user
        cfg.CONF.system_user.user = "foo"
        post_resp = self._do_create_inquiry(INQUIRY_2, RESULT_2)
        inquiry_id = self._get_inquiry_id(post_resp)
        response = {"continue": True}
        put_resp = self._do_respond(inquiry_id, response)
        self.assertEqual(response, put_resp.json.get("response"))

        # Clean up
        cfg.CONF.system_user.user = old_user 
Example #2
Source File: restclient.py    From treadmill with Apache License 2.0 6 votes vote down vote up
def _handle_error(url, response):
    """Handle response status codes."""
    handlers = {
        http_client.NOT_FOUND: NotFoundError(
            'Resource not found: {}'.format(url)
        ),
        # XXX: Correct code is CONFLICT. Support invalid FOUND during
        #      migration.
        http_client.FOUND: AlreadyExistsError(
            'Resource already exists: {}'.format(url)
        ),
        http_client.CONFLICT: AlreadyExistsError(
            'Resource already exists: {}'.format(url)
        ),
        http_client.TOO_MANY_REQUESTS: TooManyRequestsError(response),
        http_client.FAILED_DEPENDENCY: ValidationError(response),
        # XXX: Correct code is FORBIDDEN. Support invalid UNAUTHORIZED during
        #      migration.
        http_client.UNAUTHORIZED: NotAuthorizedError(response),
        http_client.FORBIDDEN: NotAuthorizedError(response),
        http_client.BAD_REQUEST: BadRequestError(response),
    }

    if response.status_code in handlers:
        raise handlers[response.status_code] 
Example #3
Source File: test_reply_handling.py    From suds with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_empty_reply():
    client = testutils.client_from_wsdl(_wsdl__simple_f, faults=False)
    def f(status=None, description=None):
        inject = dict(reply=suds.byte_str(), status=status,
            description=description)
        return client.service.f(__inject=inject)
    status, reason = f()
    assert status == http_client.OK
    assert reason is None
    status, reason = f(http_client.OK)
    assert status == http_client.OK
    assert reason is None
    status, reason = f(http_client.INTERNAL_SERVER_ERROR)
    assert status == http_client.INTERNAL_SERVER_ERROR
    assert reason == "injected reply"
    status, reason = f(http_client.FORBIDDEN)
    assert status == http_client.FORBIDDEN
    assert reason == "injected reply"
    status, reason = f(http_client.FORBIDDEN, "kwack")
    assert status == http_client.FORBIDDEN
    assert reason == "kwack" 
Example #4
Source File: test_files_handler.py    From colabtools with Apache License 2.0 5 votes vote down vote up
def testExistingDirectory(self):
    os.makedirs(os.path.join(self.temp_dir, 'some/existing/dir'))
    response = self.fetch('/files/some/existing/dir')
    self.assertEqual(http_client.FORBIDDEN, response.code) 
Example #5
Source File: test_files_handler.py    From colabtools with Apache License 2.0 5 votes vote down vote up
def testDoesNotAllowRequestsOutsideOfRootDir(self):
    # Based on existing tests:
    # https://github.com/jupyter/notebook/blob/f5fa0c180e92d35b4cbfa1cc20b41e9d1d9dfabe/notebook/services/contents/tests/test_manager.py#L173
    with open(os.path.join(self.temp_dir, '..', 'foo'), 'w') as f:
      f.write('foo')
    with open(os.path.join(self.temp_dir, '..', 'bar'), 'w') as f:
      f.write('bar')

    response = self.fetch('/files/../foo')
    self.assertEqual(http_client.FORBIDDEN, response.code)
    response = self.fetch('/files/foo/../../../bar')
    self.assertEqual(http_client.FORBIDDEN, response.code)
    response = self.fetch('/files/foo/../../bar')
    self.assertEqual(http_client.FORBIDDEN, response.code) 
Example #6
Source File: test_extensions.py    From masakari with Apache License 2.0 5 votes vote down vote up
def test_extensions_expected_error_from_list(self):
        @extensions.expected_errors((http.NOT_FOUND, http.FORBIDDEN))
        def fake_func():
            raise webob.exc.HTTPNotFound()

        self.assertRaises(webob.exc.HTTPNotFound, fake_func) 
Example #7
Source File: test_wsgi.py    From masakari with Apache License 2.0 5 votes vote down vote up
def test_resource_not_authorized(self):
        class Controller(object):
            def index(self, req):
                raise exception.Forbidden()

        req = webob.Request.blank('/tests')
        app = fakes.TestRouter(Controller())
        response = req.get_response(app)
        self.assertEqual(response.status_int, http.FORBIDDEN) 
Example #8
Source File: test_kvps.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_get_all_user_query_param_can_only_be_used_with_rbac(self):
        resp = self.app.get('/v1/keys?user=foousera', expect_errors=True)

        expected_error = '"user" attribute can only be provided by admins when RBAC is enabled'
        self.assertEqual(resp.status_int, http_client.FORBIDDEN)
        self.assertEqual(resp.json['faultstring'], expected_error) 
Example #9
Source File: test_kvps.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_get_one_user_query_param_can_only_be_used_with_rbac(self):
        resp = self.app.get('/v1/keys/keystone_endpoint?user=foousera', expect_errors=True)

        expected_error = '"user" attribute can only be provided by admins when RBAC is enabled'
        self.assertEqual(resp.status_int, http_client.FORBIDDEN)
        self.assertEqual(resp.json['faultstring'], expected_error) 
Example #10
Source File: test_auth_api_keys.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_get_all_invalid_limit_too_large_none_admin(self):
        # limit > max_page_size, but user is not admin
        resp = self.app.get('/v1/apikeys?offset=2&limit=1000', expect_errors=True)
        self.assertEqual(resp.status_int, http_client.FORBIDDEN)
        self.assertEqual(resp.json['faultstring'],
                         'Limit "1000" specified, maximum value is "100"') 
Example #11
Source File: test_actions.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_get_all_invalid_limit_too_large_none_admin(self):
        # limit > max_page_size, but user is not admin
        resp = self.app.get('/v1/actions?limit=1000', expect_errors=True)
        self.assertEqual(resp.status_int, http_client.FORBIDDEN)
        self.assertEqual(resp.json['faultstring'], 'Limit "1000" specified, maximum value is'
                         ' "100"') 
Example #12
Source File: transfer.py    From apitools with Apache License 2.0 5 votes vote down vote up
def __ProcessResponse(self, response):
        """Process response (by updating self and writing to self.stream)."""
        if response.status_code not in self._ACCEPTABLE_STATUSES:
            # We distinguish errors that mean we made a mistake in setting
            # up the transfer versus something we should attempt again.
            if response.status_code in (http_client.FORBIDDEN,
                                        http_client.NOT_FOUND):
                raise exceptions.HttpError.FromResponse(response)
            else:
                raise exceptions.TransferRetryError(response.content)
        if response.status_code in (http_client.OK,
                                    http_client.PARTIAL_CONTENT):
            try:
                self.stream.write(six.ensure_binary(response.content))
            except TypeError:
                self.stream.write(six.ensure_text(response.content))
            self.__progress += response.length
            if response.info and 'content-encoding' in response.info:
                # TODO(craigcitro): Handle the case where this changes over a
                # download.
                self.__encoding = response.info['content-encoding']
        elif response.status_code == http_client.NO_CONTENT:
            # It's important to write something to the stream for the case
            # of a 0-byte download to a file, as otherwise python won't
            # create the file.
            self.stream.write('')
        return response 
Example #13
Source File: restclient_test.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def test_get_401(self, resp_mock):
        """Test treadmill.restclient.get UNAUTHORIZED (401)"""
        # XXX: Correct code in FORBIDDEN. Support invalid UNAUTHORIZED during
        #      migration.
        resp_mock.return_value.status_code = http_client.UNAUTHORIZED
        resp_mock.return_value.json.return_value = {}

        with self.assertRaises(restclient.NotAuthorizedError):
            restclient.get('http://foo.com', '/') 
Example #14
Source File: restclient_test.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def test_get_403(self, resp_mock):
        """Test treadmill.restclient.get FORBIDDEN (403)"""
        resp_mock.return_value.status_code = http_client.FORBIDDEN
        resp_mock.return_value.json.return_value = {}

        with self.assertRaises(restclient.NotAuthorizedError):
            restclient.get('http://foo.com', '/') 
Example #15
Source File: exc.py    From python-egnyte with MIT License 5 votes vote down vote up
def __init__(self, values=None, ok_statuses=(http_client.OK, ), ignored_errors=None):
        super(ErrorMapping, self).__init__({
            http_client.BAD_REQUEST: RequestError,
            http_client.UNAUTHORIZED: NotAuthorized,
            http_client.FORBIDDEN: InsufficientPermissions,
            http_client.NOT_FOUND: NotFound,
            http_client.CONFLICT: DuplicateRecordExists,
            http_client.REQUEST_ENTITY_TOO_LARGE: FileSizeExceedsLimit,
            http_client.SEE_OTHER: Redirected,
        })
        if values:
            self.update(values)
        if ignored_errors:
            self.ignored_errors = recursive_tuple(ignored_errors)
        self.ok_statuses = ok_statuses 
Example #16
Source File: test_core.py    From osbs-client with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_watch_response_hiccup(self, fail, openshift):
        class MockResponse(object):
            def __init__(self, status, lines=None, content=None):
                self.status_code = status
                self.lines = lines or []
                self.content = content

            def iter_lines(self):
                return self.lines

            def json(self):
                return json.loads(self.content)

        test_json = json.dumps({"object": "test", "type": "test"}).encode('utf-8')
        bad_response = MockResponse(http_client.FORBIDDEN, None, "failure")
        good_response = MockResponse(http_client.OK, [test_json])
        fresh_response = MockResponse(http_client.OK, content='"test"')
        flexmock(time).should_receive('sleep').and_return(None)
        if fail:
            (flexmock(openshift)
                .should_receive('_get')
                .and_return(bad_response, bad_response, bad_response, bad_response, good_response)
                .one_by_one())
            with pytest.raises(OsbsResponseException) as exc:
                for changetype, obj in openshift.watch_resource("builds", 12):
                    continue
            assert str(exc.value).startswith('failure')
        else:
            (flexmock(openshift)
                .should_receive('_get')
                .and_return(good_response, fresh_response,
                            bad_response,
                            good_response, fresh_response)
                .one_by_one())

            yielded = 0
            expected = [
                (None, 'test'),    # fresh object
                ('test', 'test'),  # update
                (None, 'test'),    # fresh object after reconnect
                ('test', 'test'),  # update
            ]
            for (changetype, obj), (exp_changetype, exp_obj) in zip(
                    openshift.watch_resource("builds", 12), expected):
                yielded += 1
                assert changetype == exp_changetype
                assert obj == exp_obj

            assert yielded == len(expected)