Python six.moves.http_client.BAD_REQUEST Examples

The following are 30 code examples of six.moves.http_client.BAD_REQUEST(). 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_policies.py    From st2 with Apache License 2.0 6 votes vote down vote up
def test_put_sys_pack(self):
        instance = self.__create_instance()
        instance['pack'] = 'core'

        post_resp = self.__do_post(instance)
        self.assertEqual(post_resp.status_int, http_client.CREATED)

        updated_input = post_resp.json
        updated_input['enabled'] = not updated_input['enabled']
        put_resp = self.__do_put(self.__get_obj_id(post_resp), updated_input)
        self.assertEqual(put_resp.status_int, http_client.BAD_REQUEST)
        self.assertEqual(put_resp.json['faultstring'],
                         "Resources belonging to system level packs can't be manipulated")

        # Clean up manually since API won't delete object in sys pack.
        Policy.delete(Policy.get_by_id(self.__get_obj_id(post_resp))) 
Example #2
Source File: test__client.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def test__token_endpoint_request_internal_failure_error():
    request = make_request(
        {"error_description": "internal_failure"}, status=http_client.BAD_REQUEST
    )

    with pytest.raises(exceptions.RefreshError):
        _client._token_endpoint_request(
            request, "http://example.com", {"error_description": "internal_failure"}
        )

    request = make_request(
        {"error": "internal_failure"}, status=http_client.BAD_REQUEST
    )

    with pytest.raises(exceptions.RefreshError):
        _client._token_endpoint_request(
            request, "http://example.com", {"error": "internal_failure"}
        ) 
Example #3
Source File: test__upload.py    From google-resumable-media-python with Apache License 2.0 6 votes vote down vote up
def test__process_recover_response_bad_status(self):
        upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
        _fix_up_virtual(upload)

        upload._invalid = True

        response = _make_response(status_code=http_client.BAD_REQUEST)
        with pytest.raises(common.InvalidResponse) as exc_info:
            upload._process_recover_response(response)

        error = exc_info.value
        assert error.response is response
        assert len(error.args) == 4
        assert error.args[1] == response.status_code
        assert error.args[3] == resumable_media.PERMANENT_REDIRECT
        # Make sure still invalid.
        assert upload.invalid 
Example #4
Source File: test_download.py    From google-resumable-media-python with Apache License 2.0 6 votes vote down vote up
def test_extra_headers(self, authorized_transport, secret_file):
        blob_name, data, headers = secret_file
        # Create the actual download object.
        media_url = utils.DOWNLOAD_URL_TEMPLATE.format(blob_name=blob_name)
        download = self._make_one(media_url, headers=headers)
        # Consume the resource.
        response = download.consume(authorized_transport)
        assert response.status_code == http_client.OK
        assert response.content == data
        check_tombstoned(download, authorized_transport)
        # Attempt to consume the resource **without** the headers.
        download_wo = self._make_one(media_url)
        with pytest.raises(common.InvalidResponse) as exc_info:
            download_wo.consume(authorized_transport)

        check_error_response(exc_info, http_client.BAD_REQUEST, ENCRYPTED_ERR)
        check_tombstoned(download_wo, authorized_transport) 
Example #5
Source File: test_release_resources.py    From rotest with MIT License 6 votes vote down vote up
def test_try_to_release_not_owned_resource(self):
        """Assert that trying to release unowned resource fails."""
        resources = DemoResourceData.objects.filter(
            name='available_resource1')

        resource, = resources
        resource.owner = "unknown_user"
        resource.save()

        SESSIONS[self.token].resources = [resource]

        response, _ = self.requester(json_data={
            "resources": ["available_resource1"],
            "token": self.token
        })
        # refresh from db
        resources = DemoResourceData.objects.filter(
            name='available_resource1')

        resource, = resources
        self.assertEqual(response.status_code, http_client.BAD_REQUEST)
        self.assertEqual(resource.owner, "unknown_user") 
Example #6
Source File: test_lock_resources.py    From rotest with MIT License 6 votes vote down vote up
def test_invalid_resource_field(self):
        """Assert invalid resource field filter requested."""
        response, _ = self.requester(
            json_data={
                "descriptors": [
                    {
                        "type": "rotest.management.models.ut_models."
                                "DemoResourceData",
                        "properties": {
                            "invalid_field": "field1"
                        }
                    }
                ],
                "timeout": 0,
                "token": self.token
            })
        self.assertEqual(response.status_code, http_client.BAD_REQUEST) 
Example #7
Source File: test_api_validation.py    From karbor with Apache License 2.0 6 votes vote down vote up
def check_validation_error(self, method, body, expected_detail, req=None):
        if not req:
            req = FakeRequest()
        try:
            method(body=body, req=req,)
        except exception.ValidationError as ex:
            self.assertEqual(http.BAD_REQUEST, ex.kwargs['code'])
            if isinstance(expected_detail, list):
                self.assertIn(ex.kwargs['detail'], expected_detail,
                              'Exception details did not match expected')
            elif not re.match(expected_detail, ex.kwargs['detail']):
                self.assertEqual(expected_detail, ex.kwargs['detail'],
                                 'Exception details did not match expected')
        except Exception as ex:
            self.fail('An unexpected exception happens: %s' % ex)
        else:
            self.fail('Any exception did not happen.') 
Example #8
Source File: test_run.py    From column with GNU General Public License v3.0 6 votes vote down vote up
def _test_bad_payload(self):
        response = self.app.post(
            '/runs',
            data=json.dumps(dict(inventory_file='localhost,',
                                 options={'connection': 'local'})),
            content_type='application/json')
        self.assertEqual(http_client.BAD_REQUEST, response.status_code)

        pb = 'tests/fixtures/playbooks/hello_world_with_fail.yml'
        response = self.app.post(
            '/runs',
            data=json.dumps(dict(playbook_path=pb,
                                 inventory_file='localhost,',
                                 options={'connection': 'local',
                                          'bad_option': 'bad'})),
            content_type='application/json')
        self.assertEqual(http_client.BAD_REQUEST, response.status_code) 
Example #9
Source File: annotator.py    From python-stanford-corenlp with MIT License 6 votes vote down vote up
def do_GET(self):
            """
            Handle a ping request
            """
            if not self.path.endswith("/"): self.path += "/"
            if self.path == "/ping/":
                msg = "pong".encode("UTF-8")

                self.send_response(HTTPStatus.OK)
                self.send_header("Content-Type", "text/application")
                self.send_header("Content-Length", len(msg))
                self.end_headers()
                self.wfile.write(msg)
            else:
                self.send_response(HTTPStatus.BAD_REQUEST)
                self.end_headers() 
Example #10
Source File: test_reply_handling.py    From suds with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_reply_error_without_detail_with_fault(monkeypatch):
    monkeypatch.delitem(locals(), "e", False)

    client = testutils.client_from_wsdl(_wsdl__simple_f, faults=True)

    for http_status in (http_client.OK, http_client.INTERNAL_SERVER_ERROR):
        inject = dict(reply=_fault_reply__without_detail, status=http_status)
        e = pytest.raises(suds.WebFault, client.service.f, __inject=inject)
        try:
            e = e.value
            _test_fault(e.fault, False)
            assert e.document.__class__ is suds.sax.document.Document
            assert str(e) == "Server raised fault: 'Dummy error.'"
        finally:
            del e  # explicitly break circular reference chain in Python 3

    inject = dict(reply=_fault_reply__with_detail,
        status=http_client.BAD_REQUEST, description="quack-quack")
    e = pytest.raises(Exception, client.service.f, __inject=inject).value
    try:
        assert e.__class__ is Exception
        assert e.args[0][0] == http_client.BAD_REQUEST
        assert e.args[0][1] == "quack-quack"
    finally:
        del e  # explicitly break circular reference chain in Python 3 
Example #11
Source File: test_api_validation.py    From masakari with Apache License 2.0 6 votes vote down vote up
def check_validation_error(self, method, body, expected_detail, req=None):
        if not req:
            req = FakeRequest()
        try:
            method(body=body, req=req,)
        except exception.ValidationError as ex:
            self.assertEqual(http.BAD_REQUEST, ex.kwargs['code'])
            if isinstance(expected_detail, list):
                self.assertIn(ex.kwargs['detail'], expected_detail,
                              'Exception details did not match expected')
            elif not re.match(expected_detail, ex.kwargs['detail']):
                self.assertEqual(expected_detail, ex.kwargs['detail'],
                                 'Exception details did not match expected')
        except Exception as ex:
            self.fail('An unexpected exception happens: %s' % ex)
        else:
            self.fail('Any exception does not happen.') 
Example #12
Source File: test_reply_handling.py    From suds with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_reply_error_with_detail_without_fault():
    client = testutils.client_from_wsdl(_wsdl__simple_f, faults=False)

    for http_status in (http_client.OK, http_client.INTERNAL_SERVER_ERROR):
        status, fault = client.service.f(__inject=dict(
            reply=_fault_reply__with_detail, status=http_status))
        assert status == http_client.INTERNAL_SERVER_ERROR
        _test_fault(fault, True)

    status, fault = client.service.f(__inject=dict(
        reply=_fault_reply__with_detail, status=http_client.BAD_REQUEST))
    assert status == http_client.BAD_REQUEST
    assert fault == "injected reply"

    status, fault = client.service.f(__inject=dict(
        reply=_fault_reply__with_detail, status=http_client.BAD_REQUEST,
        description="haleluja"))
    assert status == http_client.BAD_REQUEST
    assert fault == "haleluja" 
Example #13
Source File: test_reply_handling.py    From suds with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_reply_error_with_detail_with_fault(monkeypatch):
    monkeypatch.delitem(locals(), "e", False)

    client = testutils.client_from_wsdl(_wsdl__simple_f, faults=True)

    for http_status in (http_client.OK, http_client.INTERNAL_SERVER_ERROR):
        inject = dict(reply=_fault_reply__with_detail, status=http_status)
        e = pytest.raises(suds.WebFault, client.service.f, __inject=inject)
        try:
            e = e.value
            _test_fault(e.fault, True)
            assert e.document.__class__ is suds.sax.document.Document
            assert str(e) == "Server raised fault: 'Dummy error.'"
        finally:
            del e  # explicitly break circular reference chain in Python 3

    inject = dict(reply=_fault_reply__with_detail,
        status=http_client.BAD_REQUEST, description="quack-quack")
    e = pytest.raises(Exception, client.service.f, __inject=inject).value
    try:
        assert e.__class__ is Exception
        assert e.args[0][0] == http_client.BAD_REQUEST
        assert e.args[0][1] == "quack-quack"
    finally:
        del e  # explicitly break circular reference chain in Python 3 
Example #14
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 #15
Source File: credentials_lib.py    From apitools with Apache License 2.0 6 votes vote down vote up
def GetUserinfo(credentials, http=None):  # pylint: disable=invalid-name
    """Get the userinfo associated with the given credentials.

    This is dependent on the token having either the userinfo.email or
    userinfo.profile scope for the given token.

    Args:
      credentials: (oauth2client.client.Credentials) incoming credentials
      http: (httplib2.Http, optional) http instance to use

    Returns:
      The email address for this token, or None if the required scopes
      aren't available.
    """
    http = http or httplib2.Http()
    url = _GetUserinfoUrl(credentials)
    # We ignore communication woes here (i.e. SSL errors, socket
    # timeout), as handling these should be done in a common location.
    response, content = http.request(url)
    if response.status == http_client.BAD_REQUEST:
        credentials.refresh(http)
        url = _GetUserinfoUrl(credentials)
        response, content = http.request(url)
    return json.loads(content or '{}')  # Save ourselves from an empty reply. 
Example #16
Source File: test_controller.py    From tacker with Apache License 2.0 6 votes vote down vote up
def test_instantiate_with_non_existing_deployment_flavour(
            self, mock_vnf_package_get_by_id, mock_vnf_package_vnfd_get_by_id,
            mock_vnf_instance_get_by_id):

        mock_vnf_instance_get_by_id.return_value =\
            fakes.return_vnf_instance_model()
        mock_vnf_package_vnfd_get_by_id.return_value = \
            fakes.return_vnf_package_vnfd()
        mock_vnf_package_get_by_id.return_value = \
            fakes.return_vnf_package_with_deployment_flavour()

        body = {"flavourId": "invalid"}
        req = fake_request.HTTPRequest.blank(
            '/vnf_instances/%s/instantiate' % uuidsentinel.vnf_instance_id)
        req.body = jsonutils.dump_as_bytes(body)
        req.headers['Content-Type'] = 'application/json'
        req.method = 'POST'

        # Call Instantiate API
        resp = req.get_response(self.app)
        self.assertEqual(http_client.BAD_REQUEST, resp.status_code)
        self.assertEqual("No flavour with id 'invalid'.",
            resp.json['badRequest']['message']) 
Example #17
Source File: test_controller.py    From tacker with Apache License 2.0 6 votes vote down vote up
def test_instantiate_with_non_existing_instantiation_level(
            self, mock_instantiate, mock_vnf_package_get_by_id,
            mock_vnf_package_vnfd_get_by_id,
            mock_vnf_instance_get_by_id):

        mock_vnf_instance_get_by_id.return_value =\
            fakes.return_vnf_instance_model()
        mock_vnf_package_vnfd_get_by_id.return_value = \
            fakes.return_vnf_package_vnfd()
        mock_vnf_package_get_by_id.return_value = \
            fakes.return_vnf_package_with_deployment_flavour()

        body = {"flavourId": "simple",
                "instantiationLevelId": "non-existing"}
        req = fake_request.HTTPRequest.blank(
            '/vnf_instances/%s/instantiate' % uuidsentinel.vnf_instance_id)
        req.body = jsonutils.dump_as_bytes(body)
        req.headers['Content-Type'] = 'application/json'
        req.method = 'POST'

        # Call Instantiate API
        resp = req.get_response(self.app)
        self.assertEqual(http_client.BAD_REQUEST, resp.status_code)
        self.assertEqual("No instantiation level with id 'non-existing'.",
            resp.json['badRequest']['message']) 
Example #18
Source File: base_api_test.py    From apitools with Apache License 2.0 6 votes vote down vote up
def testHttpError(self):
        def fakeMakeRequest(*unused_args, **unused_kwargs):
            return http_wrapper.Response(
                info={'status': http_client.BAD_REQUEST},
                content='{"field": "abc"}',
                request_url='http://www.google.com')
        method_config = base_api.ApiMethodInfo(
            request_type_name='SimpleMessage',
            response_type_name='SimpleMessage')
        client = self.__GetFakeClient()
        service = FakeService(client=client)
        request = SimpleMessage()
        with mock(base_api.http_wrapper, 'MakeRequest', fakeMakeRequest):
            with self.assertRaises(exceptions.HttpBadRequestError) as err:
                service._RunMethod(method_config, request)
        http_error = err.exception
        self.assertEquals('http://www.google.com', http_error.url)
        self.assertEquals('{"field": "abc"}', http_error.content)
        self.assertEquals(method_config, http_error.method_config)
        self.assertEquals(request, http_error.request) 
Example #19
Source File: test_controller.py    From tacker with Apache License 2.0 6 votes vote down vote up
def test_instantiate_with_default_vim_not_configured(
            self, mock_vnf_package_get_by_id, mock_vnf_package_vnfd_get_by_id,
            mock_vnf_instance_get_by_id, mock_get_vim):

        mock_vnf_instance_get_by_id.return_value =\
            fakes.return_vnf_instance_model()
        mock_vnf_package_vnfd_get_by_id.return_value = \
            fakes.return_vnf_package_vnfd()
        mock_vnf_package_get_by_id.return_value = \
            fakes.return_vnf_package_with_deployment_flavour()
        mock_get_vim.side_effect = nfvo.VimDefaultNotDefined

        body = {"flavourId": "simple"}
        req = fake_request.HTTPRequest.blank(
            '/vnf_instances/%s/instantiate' % uuidsentinel.vnf_instance_id)
        req.body = jsonutils.dump_as_bytes(body)
        req.headers['Content-Type'] = 'application/json'
        req.method = 'POST'

        # Call Instantiate API
        resp = req.get_response(self.app)
        self.assertEqual(http_client.BAD_REQUEST, resp.status_code)
        self.assertEqual("Default VIM is not defined.",
            resp.json['badRequest']['message']) 
Example #20
Source File: test_controller.py    From tacker with Apache License 2.0 6 votes vote down vote up
def test_heal_with_invalid_vnfc_id(self, mock_vnf_by_id):
        vnf_instance_obj = fakes.return_vnf_instance(
            fields.VnfInstanceState.INSTANTIATED)
        mock_vnf_by_id.return_value = vnf_instance_obj

        body = {'vnfcInstanceId': [uuidsentinel.vnfc_instance_id]}
        req = fake_request.HTTPRequest.blank(
            '/vnf_instances/%s/heal' % uuidsentinel.vnf_instance_id)
        req.body = jsonutils.dump_as_bytes(body)
        req.headers['Content-Type'] = 'application/json'
        req.method = 'POST'

        resp = req.get_response(self.app)
        self.assertEqual(http_client.BAD_REQUEST, resp.status_code)
        expected_msg = "Vnfc id %s not present in vnf instance %s"
        self.assertEqual(expected_msg % (uuidsentinel.vnfc_instance_id,
            uuidsentinel.vnf_instance_id), resp.json['badRequest']['message']) 
Example #21
Source File: test_inquiries.py    From st2 with Apache License 2.0 6 votes vote down vote up
def test_respond_duplicate_rejected(self):
        """Test that responding to an already-responded Inquiry fails
        """

        post_resp = self._do_create_inquiry(INQUIRY_2, RESULT_DEFAULT)
        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"))

        # The inquiry no longer exists, since the status should not be "pending"
        # Get the execution and confirm this.
        inquiry_execution = self._do_get_execution(inquiry_id)
        self.assertEqual(inquiry_execution.json.get('status'), 'succeeded')

        # A second, equivalent response attempt should not succeed, since the Inquiry
        # has already been successfully responded to
        put_resp = self._do_respond(inquiry_id, response, expect_errors=True)
        self.assertEqual(put_resp.status_int, http_client.BAD_REQUEST)
        self.assertIn('has already been responded to', put_resp.json['faultstring']) 
Example #22
Source File: handlers.py    From st2 with Apache License 2.0 6 votes vote down vote up
def handle_auth(self, request, headers=None, remote_addr=None,
                    remote_user=None, authorization=None, **kwargs):
        remote_addr = headers.get('x-forwarded-for',
                                  remote_addr)
        extra = {'remote_addr': remote_addr}

        if remote_user:
            ttl = getattr(request, 'ttl', None)
            username = self._get_username_for_request(remote_user, request)
            try:
                token = self._create_token_for_user(username=username,
                                                    ttl=ttl)
            except TTLTooLargeException as e:
                abort_request(status_code=http_client.BAD_REQUEST,
                              message=six.text_type(e))
            return token

        LOG.audit('Access denied to anonymous user.', extra=extra)
        abort_request() 
Example #23
Source File: test_inquiries.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_respond_timeout_rejected(self):
        """Test that responding to a timed-out Inquiry fails
        """

        post_resp = self._do_create_inquiry(INQUIRY_TIMEOUT, RESULT_DEFAULT, status='timeout')
        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.BAD_REQUEST)
        self.assertIn('timed out and cannot be responded to', put_resp.json['faultstring']) 
Example #24
Source File: annotator.py    From python-stanford-corenlp with MIT License 5 votes vote down vote up
def do_POST(self):
            """
            Handle an annotate request
            """
            if not self.path.endswith("/"): self.path += "/"
            if self.path == "/annotate/":
                # Read message
                length = int(self.headers.get('content-length'))
                msg = self.rfile.read(length)

                # Do the annotation
                doc = Document()
                parseFromDelimitedString(doc, msg)
                self.annotator.annotate(doc)

                with io.BytesIO() as stream:
                    writeToDelimitedString(doc, stream)
                    msg = stream.getvalue()

                # write message
                self.send_response(HTTPStatus.OK)
                self.send_header("Content-Type", "application/x-protobuf")
                self.send_header("Content-Length", len(msg))
                self.end_headers()
                self.wfile.write(msg)

            else:
                self.send_response(HTTPStatus.BAD_REQUEST)
                self.end_headers() 
Example #25
Source File: test_inquiries.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_respond_not_an_inquiry(self):
        """Test that attempts to respond to an execution ID that isn't an Inquiry fails
        """
        test_exec = json.loads(self.app.post_json('/v1/executions', LIVE_ACTION_1).body)
        response = {"continue": 123}
        put_resp = self._do_respond(test_exec.get('id'), response, expect_errors=True)
        self.assertEqual(put_resp.status_int, http_client.BAD_REQUEST)
        self.assertIn('is not an inquiry', put_resp.json['faultstring']) 
Example #26
Source File: test_inquiries.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_respond_fail(self):
        """Test that an incorrect response is unsuccessful
        """

        post_resp = self._do_create_inquiry(INQUIRY_2, RESULT_DEFAULT)
        inquiry_id = self._get_inquiry_id(post_resp)
        response = {"continue": 123}
        put_resp = self._do_respond(inquiry_id, response, expect_errors=True)
        self.assertEqual(put_resp.status_int, http_client.BAD_REQUEST)
        self.assertIn('did not pass schema validation', put_resp.json['faultstring']) 
Example #27
Source File: test_lock_resources.py    From rotest with MIT License 5 votes vote down vote up
def test_invalid_resource(self):
        """Assert invalid resource requested."""
        User.objects.create_user(username='localhost',
                                 email='email@email.com',
                                 password='localhost')
        response, content = self.requester(
            json_data={
                "descriptors": [
                    {
                        "type": "invalidmodule.invalidtype",
                        "properties": {}
                    }
                ],
                "timeout": 0,
                "token": self.token
            })
        self.assertEqual(response.status_code, http_client.BAD_REQUEST)
        self.assertIn("Failed to extract type", content.details)
        self.assertIn("invalidmodule.invalidtype", content.details)
        self.assertIn("Reason: No module named", content.details)
        self.assertIn("invalidmodule", content.details)

        # no available resources
        response, content = self.requester(
            json_data={
                "descriptors": [
                    {
                        "type": "rotest.management.models.ut_models."
                                "DemoResourceData",
                        "properties": {}
                    }
                ],
                "timeout": 0,
                "token": self.token
            })

        self.assertEqual(response.status_code, http_client.BAD_REQUEST)
        self.assertTrue(content.details.startswith(
            "No existing resource meets the requirements")) 
Example #28
Source File: test_lock_resources.py    From rotest with MIT License 5 votes vote down vote up
def test_lock_complex_sub_resource_unavailable(self):
        """Assert trying to lock resource with sub-resource unavailable."""
        resources = DemoComplexResourceData.objects.filter(
            name='complex_resource1')

        resource, = resources
        sub_resource = resource.demo1

        sub_resource.reserved = "unknown_person"
        sub_resource.save()

        response, _ = self.requester(
            json_data={
                "descriptors": [
                    {
                        "type": "rotest.management.models.ut_models."
                                "DemoComplexResourceData",
                        "properties": {}
                    }
                ],
                "timeout": 0,
                "token": self.token
            })

        resources = DemoComplexResourceData.objects.filter(
            name='complex_resource1')
        resource, = resources
        sub_resource = resource.demo1

        self.assertEqual(response.status_code, http_client.BAD_REQUEST)
        # no reserved nor owner for main resource
        self.assertFalse(resource.reserved)
        self.assertFalse(resource.owner)
        self.assertFalse(resource.is_available())

        # sub resource left untouched
        self.assertFalse(sub_resource.is_available())
        self.assertEqual(sub_resource.reserved, "unknown_person") 
Example #29
Source File: inquiries.py    From st2 with Apache License 2.0 5 votes vote down vote up
def get_one(self, inquiry_id, requester_user=None):
        """Retrieve a single Inquiry

            Handles requests:
                GET /inquiries/<inquiry id>
        """

        # Retrieve the inquiry by id.
        # (Passing permission_type here leverages inquiry service built-in RBAC assertions)
        try:
            inquiry = self._get_one_by_id(
                id=inquiry_id,
                requester_user=requester_user,
                permission_type=rbac_types.PermissionType.INQUIRY_VIEW
            )
        except db_exceptions.StackStormDBObjectNotFoundError as e:
            LOG.exception('Unable to identify inquiry with id "%s".' % inquiry_id)
            api_router.abort(http_client.NOT_FOUND, six.text_type(e))
        except rbac_exceptions.ResourceAccessDeniedError as e:
            LOG.exception('User is denied access to inquiry "%s".' % inquiry_id)
            api_router.abort(http_client.FORBIDDEN, six.text_type(e))
        except Exception as e:
            LOG.exception('Unable to get record for inquiry "%s".' % inquiry_id)
            api_router.abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e))

        try:
            inquiry_service.check_inquiry(inquiry)
        except Exception as e:
            api_router.abort(http_client.BAD_REQUEST, six.text_type(e))

        return inqy_api_models.InquiryResponseAPI.from_inquiry_api(inquiry) 
Example #30
Source File: policies.py    From st2 with Apache License 2.0 5 votes vote down vote up
def put(self, instance, ref_or_id, requester_user):
        op = 'PUT /policies/%s/' % ref_or_id

        db_model = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        LOG.debug('%s found object: %s', op, db_model)

        permission_type = PermissionType.POLICY_MODIFY
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=db_model,
                                                          permission_type=permission_type)

        db_model_id = db_model.id

        try:
            validate_not_part_of_system_pack(db_model)
        except ValueValidationException as e:
            LOG.exception('%s unable to update object from system pack.', op)
            abort(http_client.BAD_REQUEST, six.text_type(e))

        if not getattr(instance, 'pack', None):
            instance.pack = db_model.pack

        try:
            db_model = self.model.to_model(instance)
            db_model.id = db_model_id
            db_model = self.access.add_or_update(db_model)
        except (ValidationError, ValueError) as e:
            LOG.exception('%s unable to update object: %s', op, db_model)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        LOG.debug('%s updated object: %s', op, db_model)
        LOG.audit('Policy updated. Policy.id=%s' % (db_model.id), extra={'policy_db': db_model})

        exec_result = self.model.from_model(db_model)

        return Response(json=exec_result, status=http_client.OK)