Python six.moves.http_client.CREATED Examples

The following are 30 code examples of six.moves.http_client.CREATED(). 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_run.py    From column with GNU General Public License v3.0 6 votes vote down vote up
def _test_get_run_by_id(self):
        response = self.app.get('/runs/1234')
        self.assertEqual(http_client.NOT_FOUND, response.status_code)

        pb = 'tests/fixtures/playbooks/hello_world.yml'
        response = self.app.post(
            '/runs',
            data=json.dumps(dict(playbook_path=pb,
                                 inventory_file='localhosti,',
                                 options={'connection': 'local'})),
            content_type='application/json')
        res_dict = json.loads(response.data)
        run_id = res_dict['id']
        self.assertEqual(http_client.CREATED, response.status_code)
        response = self.app.get('/runs/{}'.format(run_id))
        self.assertEqual(http_client.OK, response.status_code)
        self._wait_for_run_complete(run_id) 
Example #2
Source File: test_arqs.py    From cyborg with Apache License 2.0 6 votes vote down vote up
def test_create(self, mock_obj_extarq, mock_obj_dp):
        dp_list = fake_device_profile.get_obj_devprofs()
        mock_obj_dp.return_value = dp = dp_list[0]
        mock_obj_extarq.side_effect = self.fake_extarqs
        params = {'device_profile_name': dp['name']}
        response = self.post_json(self.ARQ_URL, params, headers=self.headers)
        data = jsonutils.loads(response.__dict__['controller_output'])
        out_arqs = data['arqs']

        self.assertEqual(http_client.CREATED, response.status_int)
        self.assertEqual(len(out_arqs), 3)
        for in_extarq, out_arq in zip(self.fake_extarqs, out_arqs):
            self._validate_arq(in_extarq.arq, out_arq)
        for idx, out_arq in enumerate(out_arqs):
            dp_group_id = idx
            self.assertEqual(dp_group_id, out_arq['device_profile_group_id']) 
Example #3
Source File: base_api.py    From apitools with Apache License 2.0 6 votes vote down vote up
def __ProcessHttpResponse(self, method_config, http_response, request):
        """Process the given http response."""
        if http_response.status_code not in (http_client.OK,
                                             http_client.CREATED,
                                             http_client.NO_CONTENT):
            raise exceptions.HttpError.FromResponse(
                http_response, method_config=method_config, request=request)
        if http_response.status_code == http_client.NO_CONTENT:
            # TODO(craigcitro): Find out why _replace doesn't seem to work
            # here.
            http_response = http_wrapper.Response(
                info=http_response.info, content='{}',
                request_url=http_response.request_url)

        content = http_response.content
        if self._client.response_encoding and isinstance(content, bytes):
            content = content.decode(self._client.response_encoding)

        if self.__client.response_type_model == 'json':
            return content
        response_type = _LoadClass(method_config.response_type_name,
                                   self.__client.MESSAGES_MODULE)
        return self.__client.DeserializeMessage(response_type, content) 
Example #4
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 #5
Source File: test_policies.py    From st2 with Apache License 2.0 6 votes vote down vote up
def test_crud(self):
        instance = self.__create_instance()

        post_resp = self.__do_post(instance)
        self.assertEqual(post_resp.status_int, http_client.CREATED)
        get_resp = self.__do_get_one(self.__get_obj_id(post_resp))
        self.assertEqual(get_resp.status_int, http_client.OK)

        updated_input = get_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.OK)
        self.assertEqual(put_resp.json['enabled'], updated_input['enabled'])

        del_resp = self.__do_delete(self.__get_obj_id(post_resp))
        self.assertEqual(del_resp.status_int, http_client.NO_CONTENT) 
Example #6
Source File: test_controller.py    From tacker with Apache License 2.0 6 votes vote down vote up
def test_patch_failed_with_same_user_data(self, mock_save,
                                              mock_vnf_by_id):
        vnf_package_updates = {"operational_state": "DISABLED",
            "onboarding_state": "CREATED",
            "user_data": {"testKey1": "val01",
                          "testKey2": "val02",
                          "testkey3": "val03"}}
        req_body = {"userDefinedData": {"testKey1": "val01",
                                        "testKey2": "val02",
                                        "testkey3": "val03"}}
        fake_obj = fakes.return_vnfpkg_obj(
            vnf_package_updates=vnf_package_updates)
        mock_vnf_by_id.return_value = fake_obj

        req = fake_request.HTTPRequest.blank('/vnf_packages/%s'
                                             % constants.UUID)
        self.assertRaises(exc.HTTPConflict,
                          self.controller.patch,
                          req, constants.UUID, body=req_body) 
Example #7
Source File: test_controller.py    From tacker with Apache License 2.0 6 votes vote down vote up
def test_patch_update_existing_user_data(self, mock_save, mock_vnf_by_id):
        fake_obj = fakes.return_vnfpkg_obj(vnf_package_updates={
            "operational_state": "DISABLED", "onboarding_state": "CREATED",
            "user_data": {"testKey1": "val01", "testKey2": "val02",
            "testKey3": "val03"}})
        mock_vnf_by_id.return_value = fake_obj
        req_body = {"userDefinedData": {"testKey1": "changed_val01",
                                        "testKey2": "changed_val02",
                                        "testKey3": "changed_val03"}}
        req = fake_request.HTTPRequest.blank(
            '/vnf_packages/%s'
            % constants.UUID)
        req.headers['Content-Type'] = 'application/json'
        req.method = 'PATCH'
        req.body = jsonutils.dump_as_bytes(req_body)
        resp = req.get_response(self.app)
        self.assertEqual(http_client.OK, resp.status_code)
        self.assertEqual(req_body, jsonutils.loads(resp.body)) 
Example #8
Source File: test_controller.py    From tacker with Apache License 2.0 6 votes vote down vote up
def test_upload_vnf_package_from_uri(self, mock_vnf_pack_save,
                                         mock_vnf_by_id,
                                         mock_upload_vnf_package_from_uri,
                                         mock_url_open):
        body = {"addressInformation": "http://localhost/test_data.zip"}
        updates = {'onboarding_state': 'CREATED',
                   'operational_state': 'DISABLED'}
        vnf_package_dict = fakes.fake_vnf_package(updates)
        vnf_package_obj = objects.VnfPackage(**vnf_package_dict)
        mock_vnf_by_id.return_value = vnf_package_obj
        mock_vnf_pack_save.return_value = vnf_package_obj
        req = fake_request.HTTPRequest.blank(
            '/vnf_packages/%s/package_content/upload_from_uri'
            % constants.UUID)
        req.headers['Content-Type'] = 'application/json'
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes(body)
        resp = req.get_response(self.app)
        self.assertEqual(http_client.ACCEPTED, resp.status_code) 
Example #9
Source File: controller.py    From tacker with Apache License 2.0 6 votes vote down vote up
def create(self, request, body):
        context = request.environ['tacker.context']
        context.can(vnf_package_policies.VNFPKGM % 'create')

        vnf_package = vnf_package_obj.VnfPackage(context=request.context)
        vnf_package.onboarding_state = (
            fields.PackageOnboardingStateType.CREATED)
        vnf_package.operational_state = (
            fields.PackageOperationalStateType.DISABLED)
        vnf_package.usage_state = fields.PackageUsageStateType.NOT_IN_USE
        vnf_package.user_data = body.get('userDefinedData', dict())
        vnf_package.tenant_id = request.context.project_id

        vnf_package.create()

        return self._view_builder.create(request, vnf_package) 
Example #10
Source File: test_segments.py    From masakari with Apache License 2.0 6 votes vote down vote up
def test_create_success_with_201_response_code(
        self, mock_client, mock_create):
        body = {
            "segment": {
                "name": "segment1",
                "service_type": "COMPUTE",
                "recovery_method": "auto",
                "description": "failover_segment for compute"
            }
        }
        fake_req = self.req
        fake_req.headers['Content-Type'] = 'application/json'
        fake_req.method = 'POST'
        fake_req.body = jsonutils.dump_as_bytes(body)
        resp = fake_req.get_response(self.app)
        self.assertEqual(http.CREATED, resp.status_code) 
Example #11
Source File: test_hosts.py    From masakari with Apache License 2.0 6 votes vote down vote up
def test_create_success_with_201_response_code(
        self, mock_client, mock_create):
        body = {
            "host": {
                "name": "host-1", "type": "fake",
                "reserved": False,
                "on_maintenance": False,
                "control_attributes": "fake-control_attributes"
            }
        }
        fake_req = self.req
        fake_req.headers['Content-Type'] = 'application/json'
        fake_req.method = 'POST'
        fake_req.body = jsonutils.dump_as_bytes(body)
        resp = fake_req.get_response(self.app)
        self.assertEqual(http.CREATED, resp.status_code) 
Example #12
Source File: restclient.py    From manila with Apache License 2.0 6 votes vote down vote up
def _authorize(self):
        """Performs authorization setting x-auth-session."""
        self.headers['authorization'] = 'Basic %s' % self.auth_str
        if 'x-auth-session' in self.headers:
            del self.headers['x-auth-session']

        try:
            result = self.post("/access/v1")
            del self.headers['authorization']
            if result.status == http_client.CREATED:
                self.headers['x-auth-session'] = (
                    result.get_header('x-auth-session'))
                self.do_logout = True
                log_debug_msg(self, ('ZFSSA version: %s')
                              % result.get_header('x-zfssa-version'))

            elif result.status == http_client.NOT_FOUND:
                raise RestClientError(result.status, name="ERR_RESTError",
                                      message=("REST Not Available:"
                                               "Please Upgrade"))

        except RestClientError:
            del self.headers['authorization']
            raise 
Example #13
Source File: test_run.py    From column with GNU General Public License v3.0 6 votes vote down vote up
def _test_get_run_list(self):
        pb = 'tests/fixtures/playbooks/hello_world.yml'
        response = self.app.post(
            '/runs',
            data=json.dumps(dict(playbook_path=pb,
                                 inventory_file='localhost,',
                                 options={'connection': 'local'})),
            content_type='application/json')
        res_dict = json.loads(response.data)
        run_id = res_dict['id']
        self.assertEqual(http_client.CREATED, response.status_code)
        response = self.app.get('/runs')
        res_list = json.loads(response.data)
        found = False
        for item in res_list:
            if item['id'] == run_id:
                found = True
                break
        self.assertEqual(True, found)
        self._wait_for_run_complete(run_id) 
Example #14
Source File: test_run.py    From column with GNU General Public License v3.0 6 votes vote down vote up
def _test_delete_running_job(self):
        pb = 'tests/fixtures/playbooks/hello_world_with_sleep.yml'
        response = self.app.post(
            '/runs',
            data=json.dumps(dict(playbook_path=pb,
                                 inventory_file='localhost,',
                                 options={'connection': 'local',
                                          'subset': None})),
            content_type='application/json')
        res_dict = json.loads(response.data)
        self.assertEqual(http_client.CREATED, response.status_code)
        response = self.app.delete('/runs/{}'.format(res_dict['id']))
        self.assertEqual(http_client.NO_CONTENT, response.status_code)
        response = self.app.get('/runs/{}'.format(res_dict['id']))
        res_dict = json.loads(response.data)
        self.assertEqual('ABORTED', res_dict['state'])
        self._wait_for_run_complete(res_dict['id']) 
Example #15
Source File: core.py    From osbs-client with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_response(response, log_level=logging.ERROR):
    if response.status_code not in (http_client.OK, http_client.CREATED):
        if hasattr(response, 'content'):
            content = response.content
        else:
            content = b''.join(response.iter_lines())

        logger.log(log_level, "[%d] %s", response.status_code, content)
        raise OsbsResponseException(message=content, status_code=response.status_code)


# TODO: error handling: create function which handles errors in response object 
Example #16
Source File: rest_conf_switch.py    From ryu with Apache License 2.0 5 votes vote down vote up
def set_key(self, req, dpid, key, **_kwargs):
        def _set_val(dpid, key):
            val = json.loads(req.body)
            self.conf_switch.set_key(dpid, key, val)
            return None

        def _ret(_ret):
            return Response(status=http_client.CREATED)

        return self._do_key(dpid, key, _set_val, _ret) 
Example #17
Source File: test_device_profiles.py    From cyborg with Apache License 2.0 5 votes vote down vote up
def test_create(self, mock_cond_dp):
        dp = [self.fake_dps[0]]
        mock_cond_dp.return_value = self.fake_dp_objs[0]
        dp[0]['created_at'] = str(dp[0]['created_at'])
        response = self.post_json(self.DP_URL, dp, headers=self.headers)
        out_dp = jsonutils.loads(response.controller_output)

        self.assertEqual(http_client.CREATED, response.status_int)
        self._validate_dp(dp[0], out_dp) 
Example #18
Source File: device_profiles.py    From cyborg with Apache License 2.0 5 votes vote down vote up
def post(self, req_devprof_list):
        """Create one or more device_profiles.

        NOTE: Only one device profile supported in Train.

        :param devprof: a list of device_profiles.
         [{ "name": <string>,
           "groups": [ {"key1: "value1", "key2": "value2"} ]
           "uuid": <uuid> # optional
         }]
         :returns: The list of created device profiles
        """
        # TODO(Sundar) Support more than one devprof per request, if needed

        LOG.info("[device_profiles] POST request = (%s)", req_devprof_list)
        if len(req_devprof_list) != 1:
            raise exception.InvalidParameterValue(
                err="Only one device profile allowed "
                    "per POST request for now.")
        req_devprof = req_devprof_list[0]
        self._validate_post_request(req_devprof)

        context = pecan.request.context
        obj_devprof = objects.DeviceProfile(context, **req_devprof)

        new_devprof = pecan.request.conductor_api.device_profile_create(
            context, obj_devprof)
        ret = self.get_device_profile(new_devprof)
        return wsme.api.Response(ret, status_code=http_client.CREATED,
                                 return_type=wsme.types.DictType) 
Example #19
Source File: transfer.py    From apitools with Apache License 2.0 5 votes vote down vote up
def RefreshResumableUploadState(self):
        """Talk to the server and refresh the state of this resumable upload.

        Returns:
          Response if the upload is complete.
        """
        if self.strategy != RESUMABLE_UPLOAD:
            return
        self.EnsureInitialized()
        refresh_request = http_wrapper.Request(
            url=self.url, http_method='PUT',
            headers={'Content-Range': 'bytes */*'})
        refresh_response = http_wrapper.MakeRequest(
            self.http, refresh_request, redirections=0,
            retries=self.num_retries)
        range_header = self._GetRangeHeaderFromResponse(refresh_response)
        if refresh_response.status_code in (http_client.OK,
                                            http_client.CREATED):
            self.__complete = True
            self.__progress = self.total_size
            self.stream.seek(self.progress)
            # If we're finished, the refresh response will contain the metadata
            # originally requested. Cache it so it can be returned in
            # StreamInChunks.
            self.__final_response = refresh_response
        elif refresh_response.status_code == http_wrapper.RESUME_INCOMPLETE:
            if range_header is None:
                self.__progress = 0
            else:
                self.__progress = self.__GetLastByte(range_header) + 1
            self.stream.seek(self.progress)
        else:
            raise exceptions.HttpError.FromResponse(refresh_response) 
Example #20
Source File: test_policies.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_delete_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)

        del_resp = self.__do_delete(self.__get_obj_id(post_resp))
        self.assertEqual(del_resp.status_int, http_client.BAD_REQUEST)
        self.assertEqual(del_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 #21
Source File: test_run.py    From column with GNU General Public License v3.0 5 votes vote down vote up
def _test_trigger_run(self):
        pb = 'tests/fixtures/playbooks/hello_world.yml'
        response = self.app.post(
            '/runs',
            data=json.dumps(dict(playbook_path=pb,
                                 inventory_file='localhost,',
                                 options={'connection': 'local'})),
            content_type='application/json')
        res_dict = json.loads(response.data)
        self.assertEqual(http_client.CREATED, response.status_code)
        self.assertEqual('RUNNING', res_dict['state'])
        self._wait_for_run_complete(res_dict['id'])
        response = self.app.get('/runs/{}'.format(res_dict['id']))
        res_dict = json.loads(response.data)
        self.assertEqual('COMPLETED', res_dict['state']) 
Example #22
Source File: test_policies.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_post_duplicate(self):
        instance = self.__create_instance()

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

        post_dup_resp = self.__do_post(instance)
        self.assertEqual(post_dup_resp.status_int, http_client.CONFLICT)

        del_resp = self.__do_delete(self.__get_obj_id(post_resp))
        self.assertEqual(del_resp.status_int, http_client.NO_CONTENT) 
Example #23
Source File: test_run.py    From column with GNU General Public License v3.0 5 votes vote down vote up
def _test_null_parameter_in_payload(self):
        pb = 'tests/fixtures/playbooks/hello_world.yml'
        response = self.app.post(
            '/runs',
            data=json.dumps(dict(playbook_path=pb,
                                 inventory_file='localhost,',
                                 options={'connection': 'local',
                                          'subset': None})),
            content_type='application/json')
        res_dict = json.loads(response.data)
        self.assertEqual(http_client.CREATED, response.status_code)
        self._wait_for_run_complete(res_dict['id']) 
Example #24
Source File: auth.py    From st2 with Apache License 2.0 5 votes vote down vote up
def process_successful_response(token):
    resp = Response(json=token, status=http_client.CREATED)
    # NOTE: gunicon fails and throws an error if header value is not a string (e.g. if it's None)
    resp.headers['X-API-URL'] = api_utils.get_base_public_api_url()
    return resp 
Example #25
Source File: test_controller.py    From tacker with Apache License 2.0 5 votes vote down vote up
def test_create_with_name_and_description(
            self, mock_get_by_id, mock_vnf_instance_create):
        mock_get_by_id.return_value = fakes.return_vnf_package_vnfd()
        updates = {'vnf_instance_description': 'SampleVnf Description',
                   'vnf_instance_name': 'SampleVnf'}
        mock_vnf_instance_create.return_value =\
            fakes.return_vnf_instance_model(**updates)

        body = {'vnfdId': uuidsentinel.vnfd_id,
                "vnfInstanceName": "SampleVnf",
                "vnfInstanceDescription": "SampleVnf Description"}
        req = fake_request.HTTPRequest.blank('/vnf_instances')
        req.body = jsonutils.dump_as_bytes(body)
        req.headers['Content-Type'] = 'application/json'
        req.method = 'POST'

        # Call Create API
        resp = req.get_response(self.app)

        self.assertEqual(http_client.CREATED, resp.status_code)
        updates = {"vnfInstanceName": "SampleVnf",
            "vnfInstanceDescription": "SampleVnf Description"}
        expected_vnf = fakes.fake_vnf_instance_response(**updates)
        location_header = ('http://localhost/vnflcm/v1/vnf_instances/%s'
            % resp.json['id'])

        self.assertEqual(expected_vnf, resp.json)
        self.assertEqual(location_header, resp.headers['location']) 
Example #26
Source File: test_controller.py    From tacker with Apache License 2.0 5 votes vote down vote up
def test_get_vnf_package_vnfd_failed_with_invalid_status(
            self, mock_vnf_by_id):
        vnf_package_updates = {
            'onboarding_state': 'CREATED',
            'operational_state': 'DISABLED'
        }
        mock_vnf_by_id.return_value = fakes.return_vnfpkg_obj(
            vnf_package_updates=vnf_package_updates)
        req = fake_request.HTTPRequest.blank(
            '/vnf_packages/%s/vnfd'
            % constants.UUID)
        req.headers['Accept'] = 'application/zip'
        req.method = 'GET'
        resp = req.get_response(self.app)
        self.assertEqual(http_client.CONFLICT, resp.status_code) 
Example #27
Source File: test_controller.py    From tacker with Apache License 2.0 5 votes vote down vote up
def test_patch_not_in_onboarded_state(self, mock_vnf_by_id):
        vnf_package_updates = {'onboarding_state': 'CREATED',
            'operational_state': 'DISABLED'}
        mock_vnf_by_id.return_value = fakes.return_vnfpkg_obj(
            vnf_package_updates=vnf_package_updates)
        body = {"operationalState": "DISABLED"}
        req = fake_request.HTTPRequest.blank('/vnf_packages/%s'
                                             % constants.UUID)
        self.assertRaises(exc.HTTPBadRequest,
                          self.controller.patch,
                          req, constants.UUID, body=body) 
Example #28
Source File: test_views.py    From django-cassandra-engine with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_post(self):
        response = self.client.post(
            reverse('thing_listcreate_api'),
            {'created_on': '2015-06-14T15:44:25Z'},
        )
        self.assertEqual(response.status_code, http_client.CREATED)
        assert CassandraThingMultiplePK.objects.all().count() == 1 
Example #29
Source File: test__helpers.py    From google-resumable-media-python with Apache License 2.0 5 votes vote down vote up
def test_success(self):
        status_codes = (http_client.OK, http_client.CREATED)
        acceptable = (
            http_client.OK,
            int(http_client.OK),
            http_client.CREATED,
            int(http_client.CREATED),
        )
        for value in acceptable:
            response = _make_response(value)
            status_code = _helpers.require_status_code(
                response, status_codes, self._get_status_code
            )
            assert value == status_code 
Example #30
Source File: test_controller.py    From tacker with Apache License 2.0 5 votes vote down vote up
def test_create_without_userdefine_data(self, mock_from_db,
                                            mock_vnf_pack):
        body = {'userDefinedData': {}}
        req = fake_request.HTTPRequest.blank('/vnf_packages')
        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.CREATED, resp.status_code)