Ejemplo n.º 1
0
    def test_invalid_metadata_items_on_update_item(self):
        self.stub_out('nova.db.instance_metadata_update',
                      return_create_instance_metadata)
        self.stub_out('nova.db.instance_metadata_update',
                      return_create_instance_metadata)
        data = {"metadata": {}}
        for num in range(CONF.quota_metadata_items + 1):
            data['metadata']['key%i' % num] = "blah"
        req = self._get_request()
        req.method = 'PUT'
        req.body = jsonutils.dump_as_bytes(data)
        req.headers["content-type"] = "application/json"

        # test for long key
        data = {"metadata": {"a" * 260: "value1"}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(self.validation_ex_large,
                          self.controller.update_all, req, self.uuid,
                          body=data)

        # test for long value
        data = {"metadata": {"key": "v" * 260}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(self.validation_ex_large,
                          self.controller.update_all, req, self.uuid,
                          body=data)

        # test for empty key.
        data = {"metadata": {"": "value1"}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(self.validation_ex,
                          self.controller.update_all, req, self.uuid,
                          body=data)
Ejemplo n.º 2
0
    def test_attach_to_instance(self):
        body = {'os-attach': {'instance_uuid': fake.INSTANCE_ID,
                              'mountpoint': '/dev/vdc',
                              'mode': 'rw'}}
        req = webob.Request.blank('/v2/%s/volumes/%s/action' %
                                  (fake.PROJECT_ID, fake.VOLUME_ID))
        req.method = "POST"
        req.body = jsonutils.dump_as_bytes(body)
        req.headers["content-type"] = "application/json"

        res = req.get_response(fakes.wsgi_app(
            fake_auth_context=self.context))
        self.assertEqual(202, res.status_int)

        body = {'os-attach': {'instance_uuid': fake.INSTANCE_ID,
                              'host_name': 'fake_host',
                              'mountpoint': '/dev/vdc'}}
        req = webob.Request.blank('/v2/%s/volumes/%s/action' %
                                  (fake.PROJECT_ID, fake.VOLUME_ID))
        req.method = "POST"
        req.headers["content-type"] = "application/json"
        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(fakes.wsgi_app(
            fake_auth_context=self.context))
        self.assertEqual(202, res.status_int)
Ejemplo n.º 3
0
    def test_invalid_metadata_items_on_create(self, metadata_update):
        fake_volume = {"id": self.req_id, "status": "available"}
        fake_context = mock.Mock()
        metadata_update.side_effect = return_create_volume_metadata
        req = fakes.HTTPRequest.blank(self.url)
        req.method = "POST"
        req.headers["content-type"] = "application/json"

        # test for long key
        data = {"metadata": {"a" * 260: "value1"}}
        req.body = jsonutils.dump_as_bytes(data)
        req.environ["cinder.context"] = fake_context

        with mock.patch.object(self.controller.volume_api, "get") as get_volume:
            get_volume.return_value = fake_volume
            self.assertRaises(webob.exc.HTTPRequestEntityTooLarge, self.controller.create, req, self.req_id, data)

        # test for long value
        data = {"metadata": {"key": "v" * 260}}
        req.body = jsonutils.dump_as_bytes(data)
        req.environ["cinder.context"] = fake_context

        with mock.patch.object(self.controller.volume_api, "get") as get_volume:
            get_volume.return_value = fake_volume
            self.assertRaises(webob.exc.HTTPRequestEntityTooLarge, self.controller.create, req, self.req_id, data)

        # test for empty key.
        data = {"metadata": {"": "value1"}}
        req.body = jsonutils.dump_as_bytes(data)
        req.environ["cinder.context"] = fake_context

        with mock.patch.object(self.controller.volume_api, "get") as get_volume:
            get_volume.return_value = fake_volume
            self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, req, self.req_id, data)
Ejemplo n.º 4
0
    def test_invalid_metadata_items_on_create(self):
        self.stubs.Set(db, 'volume_metadata_update',
                       fake_create_volume_metadata)
        req = fakes.HTTPRequest.blank('/v2/%s/volumes/%s/action' % (
            fake.PROJECT_ID, fake.VOLUME_ID))
        req.method = 'POST'
        req.headers["content-type"] = "application/json"

        data = {"os-set_image_metadata": {
            "metadata": {"a" * 260: "value1"}}
        }

        # Test for long key
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(webob.exc.HTTPRequestEntityTooLarge,
                          self.controller.create, req, fake.VOLUME_ID, data)

        # Test for long value
        data = {"os-set_image_metadata": {
            "metadata": {"key": "v" * 260}}
        }
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(webob.exc.HTTPRequestEntityTooLarge,
                          self.controller.create, req, fake.VOLUME_ID, data)

        # Test for empty key.
        data = {"os-set_image_metadata": {
            "metadata": {"": "value1"}}
        }
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller.create, req, fake.VOLUME_ID, data)
Ejemplo n.º 5
0
    def test_list_env_templates_with_different_tenant(self):
        """Test listing public template from another tenant

        Create two template in two different tenants;
        test list public template from another tenant.
        """
        self._set_policy_rules(
            {'create_env_template': '@',
             'list_env_templates': '@'}
        )

        self.expect_policy_check('create_env_template')
        body = {'name': 'mytemp', 'is_public': False}
        req = self._post('/templates', jsonutils.dump_as_bytes(body),
                         tenant='first_tenant')
        result = req.get_response(self.api)
        self.assertFalse(jsonutils.loads(result.body)['is_public'])

        self.expect_policy_check('create_env_template')
        body = {'name': 'mytemp1', 'is_public': True}
        req = self._post('/templates', jsonutils.dump_as_bytes(body),
                         tenant='second_tenant')
        result = req.get_response(self.api)
        self.assertTrue(jsonutils.loads(result.body)['is_public'])

        self.expect_policy_check('list_env_templates')
        req = self._get('/templates', tenant='first_tenant')
        result = req.get_response(self.api)

        self.assertEqual(2, len(jsonutils.loads(result.body)['templates']))
Ejemplo n.º 6
0
    def test_attach_with_invalid_arguments(self):
        # Invalid request to attach volume an invalid target
        body = {'os-attach': {'mountpoint': '/dev/vdc'}}
        req = webob.Request.blank('/v2/fake/volumes/1/action')
        req.method = "POST"
        req.headers["content-type"] = "application/json"
        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(fakes.wsgi_app())
        self.assertEqual(400, res.status_int)

        # Invalid request to attach volume with an invalid mode
        body = {'os-attach': {'instance_uuid': 'fake',
                              'mountpoint': '/dev/vdc',
                              'mode': 'rr'}}
        req = webob.Request.blank('/v2/fake/volumes/1/action')
        req.method = "POST"
        req.headers["content-type"] = "application/json"
        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(fakes.wsgi_app())
        self.assertEqual(400, res.status_int)
        body = {'os-attach': {'host_name': 'fake_host',
                              'mountpoint': '/dev/vdc',
                              'mode': 'ww'}}
        req = webob.Request.blank('/v2/fake/volumes/1/action')
        req.method = "POST"
        req.headers["content-type"] = "application/json"
        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(fakes.wsgi_app())
        self.assertEqual(400, res.status_int)
Ejemplo n.º 7
0
    def test_list_env_templates(self):
        """Test listing public templates when there aren't any

        Create a template; test list public with no
        public templates.
        """
        self._set_policy_rules(
            {'create_env_template': '@',
             'list_env_templates': '@'}
        )

        self.expect_policy_check('create_env_template')
        body = {'name': 'mytemp', 'is_public': False}
        req = self._post('/templates', jsonutils.dump_as_bytes(body))
        result = req.get_response(self.api)
        self.assertFalse(jsonutils.loads(result.body)['is_public'])

        self.expect_policy_check('create_env_template')
        body = {'name': 'mytemp1', 'is_public': True}
        req = self._post('/templates', jsonutils.dump_as_bytes(body))
        result = req.get_response(self.api)
        self.assertTrue(jsonutils.loads(result.body)['is_public'])

        self.expect_policy_check('list_env_templates')
        req = self._get('/templates')
        result = req.get_response(self.api)

        self.assertEqual(2, len(jsonutils.loads(result.body)['templates']))
Ejemplo n.º 8
0
    def test_rpc_errors(self):
        api = create_api()
        req = webob.Request.blank('/rpc')
        req.method = 'POST'
        req.content_type = 'application/json'

        # Body is not a list, it should fail
        req.body = jsonutils.dump_as_bytes({})
        res = req.get_response(api)
        self.assertEqual(http.BAD_REQUEST, res.status_int)

        # cmd is not dict, it should fail.
        req.body = jsonutils.dump_as_bytes([None])
        res = req.get_response(api)
        self.assertEqual(http.BAD_REQUEST, res.status_int)

        # No command key, it should fail.
        req.body = jsonutils.dump_as_bytes([{}])
        res = req.get_response(api)
        self.assertEqual(http.BAD_REQUEST, res.status_int)

        # kwargs not dict, it should fail.
        req.body = jsonutils.dump_as_bytes([{"command": "test", "kwargs": 2}])
        res = req.get_response(api)
        self.assertEqual(http.BAD_REQUEST, res.status_int)

        # Command does not exist, it should fail.
        req.body = jsonutils.dump_as_bytes([{"command": "test"}])
        res = req.get_response(api)
        self.assertEqual(http.NOT_FOUND, res.status_int)
Ejemplo n.º 9
0
    def test_volume_force_detach_raises_remote_error(self):
        # current status is available
        volume = self._create_volume(self.ctx, {"provider_location": "", "size": 1})
        connector = {"initiator": "iqn.2012-07.org.fake:01"}

        self.volume_api.reserve_volume(self.ctx, volume)
        mountpoint = "/dev/vbd"
        attachment = self.volume_api.attach(self.ctx, volume, fake.INSTANCE_ID, None, mountpoint, "rw")
        # volume is attached
        volume.refresh()
        self.assertEqual("in-use", volume.status)
        self.assertEqual(fake.INSTANCE_ID, attachment["instance_uuid"])
        self.assertEqual(mountpoint, attachment["mountpoint"])
        self.assertEqual("attached", attachment["attach_status"])
        admin_metadata = volume.admin_metadata
        self.assertEqual(2, len(admin_metadata))
        self.assertEqual("False", admin_metadata["readonly"])
        self.assertEqual("rw", admin_metadata["attached_mode"])
        conn_info = self.volume_api.initialize_connection(self.ctx, volume, connector)
        self.assertEqual("rw", conn_info["data"]["access_mode"])
        # build request to force detach
        volume_remote_error = messaging.RemoteError(exc_type="VolumeAttachmentNotFound")
        with mock.patch.object(volume_api.API, "detach", side_effect=volume_remote_error):
            req = webob.Request.blank("/v2/%s/volumes/%s/action" % (fake.PROJECT_ID, volume.id))
            req.method = "POST"
            req.headers["content-type"] = "application/json"
            body = {"os-force_detach": {"attachment_id": fake.ATTACHMENT_ID}}
            req.body = jsonutils.dump_as_bytes(body)
            # attach admin context to request
            req.environ["cinder.context"] = self.ctx
            # make request
            resp = req.get_response(app())
            self.assertEqual(400, resp.status_int)

        # test for KeyError when missing connector
        volume_remote_error = messaging.RemoteError(exc_type="KeyError")
        with mock.patch.object(volume_api.API, "detach", side_effect=volume_remote_error):
            req = webob.Request.blank("/v2/%s/volumes/%s/action" % (fake.PROJECT_ID, volume.id))
            req.method = "POST"
            req.headers["content-type"] = "application/json"
            body = {"os-force_detach": {"attachment_id": fake.ATTACHMENT_ID}}
            req.body = jsonutils.dump_as_bytes(body)
            # attach admin context to request
            req.environ["cinder.context"] = self.ctx
            # make request
            self.assertRaises(messaging.RemoteError, req.get_response, app())

        # test for VolumeBackendAPIException
        volume_remote_error = messaging.RemoteError(exc_type="VolumeBackendAPIException")
        with mock.patch.object(volume_api.API, "detach", side_effect=volume_remote_error):
            req = webob.Request.blank("/v2/%s/volumes/%s/action" % (fake.PROJECT_ID, volume.id))
            req.method = "POST"
            req.headers["content-type"] = "application/json"
            body = {"os-force_detach": {"attachment_id": fake.ATTACHMENT_ID, "connector": connector}}
            req.body = jsonutils.dump_as_bytes(body)

            # attach admin context to request
            req.environ["cinder.context"] = self.ctx
            # make request
            self.assertRaises(messaging.RemoteError, req.get_response, app())
Ejemplo n.º 10
0
    def test_create_server_detect_from_image(self):
        """If user doesn't pass in diskConfig for server, use image metadata
        to specify AUTO or MANUAL.
        """
        req = fakes.HTTPRequest.blank('/fake/servers')
        req.method = 'POST'
        req.content_type = 'application/json'
        body = {'server': {
                  'name': 'server_test',
                  'imageRef': 'a440c04b-79fa-479c-bed1-0b816eaec379',
                  'flavorRef': '1',
               }}

        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(self.app)
        server_dict = jsonutils.loads(res.body)['server']
        self.assertDiskConfig(server_dict, 'MANUAL')

        req = fakes.HTTPRequest.blank('/fake/servers')
        req.method = 'POST'
        req.content_type = 'application/json'
        body = {'server': {
                  'name': 'server_test',
                  'imageRef': '70a599e0-31e7-49b7-b260-868f441e862b',
                  'flavorRef': '1',
               }}

        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(self.app)
        server_dict = jsonutils.loads(res.body)['server']
        self.assertDiskConfig(server_dict, 'AUTO')
Ejemplo n.º 11
0
    def test_invalid_metadata_items_on_create(self, snapshot_get_by_id):
        snapshot = {
            'id': self.req_id,
            'expected_attrs': ['metadata']
        }
        ctx = context.RequestContext('admin', 'fake', True)
        snapshot_obj = fake_snapshot.fake_snapshot_obj(ctx, **snapshot)
        snapshot_get_by_id.return_value = snapshot_obj

        self.stubs.Set(cinder.db, 'snapshot_metadata_update',
                       return_create_snapshot_metadata)
        req = fakes.HTTPRequest.blank(self.url)
        req.method = 'POST'
        req.headers["content-type"] = "application/json"

        # test for long key
        data = {"metadata": {"a" * 260: "value1"}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(webob.exc.HTTPRequestEntityTooLarge,
                          self.controller.create, req, self.req_id, data)

        # test for long value
        data = {"metadata": {"key": "v" * 260}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(webob.exc.HTTPRequestEntityTooLarge,
                          self.controller.create, req, self.req_id, data)

        # test for empty key.
        data = {"metadata": {"": "value1"}}
        req.body = jsonutils.dump_as_bytes(data)
        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller.create, req, self.req_id, data)
Ejemplo n.º 12
0
 def default(self, data, result=None):
     def sanitizer(obj):
         if isinstance(obj, datetime.datetime):
             _dtime = obj - datetime.timedelta(microseconds=obj.microsecond)
             return _dtime.isoformat()
         return six.text_type(obj)
     if result:
         data.body = jsonutils.dump_as_bytes(result)
     return jsonutils.dump_as_bytes(data, default=sanitizer)
Ejemplo n.º 13
0
    def test_create_consistencygroup_from_src_no_host(self):
        consistencygroup = utils.create_consistencygroup(self.ctxt, host=None)
        volume_id = utils.create_volume(self.ctxt, consistencygroup_id=consistencygroup.id)["id"]
        cgsnapshot = utils.create_cgsnapshot(self.ctxt, consistencygroup_id=consistencygroup.id)
        snapshot = utils.create_snapshot(self.ctxt, volume_id, cgsnapshot_id=cgsnapshot.id, status="available")

        test_cg_name = "test cg"
        body = {
            "consistencygroup-from-src": {
                "name": test_cg_name,
                "description": "Consistency Group 1",
                "cgsnapshot_id": cgsnapshot.id,
            }
        }
        req = webob.Request.blank("/v2/fake/consistencygroups/create_from_src")
        req.method = "POST"
        req.headers["Content-Type"] = "application/json"
        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(fakes.wsgi_app())
        res_dict = jsonutils.loads(res.body)

        self.assertEqual(400, res.status_int)
        self.assertEqual(400, res_dict["badRequest"]["code"])
        msg = _("Invalid ConsistencyGroup: No host to create consistency " "group")
        self.assertIn(msg, res_dict["badRequest"]["message"])

        snapshot.destroy()
        db.volume_destroy(self.ctxt.elevated(), volume_id)
        consistencygroup.destroy()
        cgsnapshot.destroy()
Ejemplo n.º 14
0
    def test_create_with_keys_in_uppercase_and_lowercase(
            self, snapshot_get_by_id, snapshot_update):
        snapshot = {
            'id': self.req_id,
            'expected_attrs': ['metadata']
        }
        ctx = context.RequestContext('admin', 'fake', True)
        snapshot_obj = fake_snapshot.fake_snapshot_obj(ctx, **snapshot)
        snapshot_get_by_id.return_value = snapshot_obj

        # if the keys in uppercase_and_lowercase, should return the one
        # which server added
        self.stubs.Set(cinder.db, 'snapshot_metadata_update',
                       return_create_snapshot_metadata_insensitive)

        req = fakes.HTTPRequest.blank('/v1/snapshot_metadata')
        req.method = 'POST'
        req.content_type = "application/json"
        body = {"metadata": {"key1": "value1",
                             "KEY1": "value1",
                             "key2": "value2",
                             "KEY2": "value2",
                             "key3": "value3",
                             "KEY4": "value4"}}
        expected = {"metadata": {"key1": "value1",
                                 "key2": "value2",
                                 "key3": "value3",
                                 "KEY4": "value4"}}
        req.body = jsonutils.dump_as_bytes(body)
        res_dict = self.controller.create(req, self.req_id, body)
        self.assertEqual(expected, res_dict)
Ejemplo n.º 15
0
    def test_update_all_with_keys_in_uppercase_and_lowercase(
            self, snapshot_get_by_id, snapshot_update):
        snapshot = {
            'id': self.req_id,
            'expected_attrs': ['metadata']
        }
        ctx = context.RequestContext('admin', 'fake', True)
        snapshot_obj = fake_snapshot.fake_snapshot_obj(ctx, **snapshot)
        snapshot_get_by_id.return_value = snapshot_obj

        self.stubs.Set(cinder.db, 'snapshot_metadata_update',
                       return_new_snapshot_metadata)
        req = fakes.HTTPRequest.blank(self.url)
        req.method = 'PUT'
        req.content_type = "application/json"
        body = {
            'metadata': {
                'key10': 'value10',
                'KEY10': 'value10',
                'key99': 'value99',
                'KEY20': 'value20',
            },
        }
        expected = {
            'metadata': {
                'key10': 'value10',
                'key99': 'value99',
                'KEY20': 'value20',
            },
        }
        req.body = jsonutils.dump_as_bytes(expected)
        res_dict = self.controller.update_all(req, self.req_id, body)

        self.assertEqual(expected, res_dict)
Ejemplo n.º 16
0
    def test_update_all_volume_maintenance(self, metadata_update):
        fake_volume = {'id': self.req_id, 'status': 'maintenance'}
        fake_context = mock.Mock()
        metadata_update.side_effect = return_new_volume_metadata
        req = fakes.HTTPRequest.blank(self.url)
        req.method = 'PUT'
        req.content_type = "application/json"
        expected = {
            'metadata': {
                'key10': 'value10',
                'key99': 'value99',
                'KEY20': 'value20',
            },
        }
        req.body = jsonutils.dump_as_bytes(expected)
        req.environ['cinder.context'] = fake_context

        with mock.patch.object(self.controller.volume_api,
                               'get') as get_volume:
            get_volume.return_value = fake_volume
            self.assertRaises(exception.InvalidVolume,
                              self.controller.update_all, req,
                              self.req_id, expected)
            self.assertFalse(metadata_update.called)
            get_volume.assert_called_once_with(fake_context, self.req_id)
Ejemplo n.º 17
0
    def test_create_consistencygroup_from_src_cg(self):
        self.mock_object(volume_api.API, "create", stubs.stub_volume_create)

        source_cg = utils.create_consistencygroup(self.ctxt)
        volume_id = utils.create_volume(self.ctxt, consistencygroup_id=source_cg.id)["id"]

        test_cg_name = "test cg"
        body = {
            "consistencygroup-from-src": {
                "name": test_cg_name,
                "description": "Consistency Group 1",
                "source_cgid": source_cg.id,
            }
        }
        req = webob.Request.blank("/v2/fake/consistencygroups/create_from_src")
        req.method = "POST"
        req.headers["Content-Type"] = "application/json"
        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(fakes.wsgi_app())
        res_dict = jsonutils.loads(res.body)

        self.assertEqual(202, res.status_int)
        self.assertIn("id", res_dict["consistencygroup"])
        self.assertEqual(test_cg_name, res_dict["consistencygroup"]["name"])

        cg = objects.ConsistencyGroup.get_by_id(self.ctxt, res_dict["consistencygroup"]["id"])
        cg.destroy
        db.volume_destroy(self.ctxt.elevated(), volume_id)
        source_cg.destroy()
Ejemplo n.º 18
0
    def test_accept_transfer_with_VolumeLimitExceeded(self):

        def fake_transfer_api_accept_throwing_VolumeLimitExceeded(cls,
                                                                  context,
                                                                  transfer,
                                                                  volume_id):
            raise exception.VolumeLimitExceeded(allowed=1)

        self.stubs.Set(cinder.transfer.API, 'accept',
                       fake_transfer_api_accept_throwing_VolumeLimitExceeded)

        volume_id = self._create_volume()
        transfer = self._create_transfer(volume_id)

        body = {"accept": {"id": transfer['id'],
                           "auth_key": transfer['auth_key']}}
        req = webob.Request.blank('/v2/%s/os-volume-transfer/%s/accept' % (
                                  fake.PROJECT_ID, transfer['id']))

        req.method = 'POST'
        req.headers['Content-Type'] = 'application/json'
        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(fakes.wsgi_app(
            fake_auth_context=self.user_ctxt))
        res_dict = jsonutils.loads(res.body)

        self.assertEqual(413, res.status_int)
        self.assertEqual(413, res_dict['overLimit']['code'])
        self.assertEqual("VolumeLimitExceeded: Maximum number of volumes "
                         "allowed (1) exceeded for quota 'volumes'.",
                         res_dict['overLimit']['message'])
Ejemplo n.º 19
0
    def test_create_consistencygroup_from_src_both_snap_cg(self):
        self.stubs.Set(volume_api.API, "create", stubs.stub_volume_create)

        consistencygroup = utils.create_consistencygroup(self.ctxt)
        volume_id = utils.create_volume(self.ctxt, consistencygroup_id=consistencygroup.id)["id"]
        cgsnapshot_id = utils.create_cgsnapshot(self.ctxt, consistencygroup_id=consistencygroup.id)["id"]
        snapshot = utils.create_snapshot(self.ctxt, volume_id, cgsnapshot_id=cgsnapshot_id, status="available")

        test_cg_name = "test cg"
        body = {
            "consistencygroup-from-src": {
                "name": test_cg_name,
                "description": "Consistency Group 1",
                "cgsnapshot_id": cgsnapshot_id,
                "source_cgid": consistencygroup.id,
            }
        }
        req = webob.Request.blank("/v2/fake/consistencygroups/create_from_src")
        req.method = "POST"
        req.headers["Content-Type"] = "application/json"
        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(fakes.wsgi_app())
        res_dict = jsonutils.loads(res.body)

        self.assertEqual(400, res.status_int)
        self.assertEqual(400, res_dict["badRequest"]["code"])
        self.assertIsNotNone(res_dict["badRequest"]["message"])

        snapshot.destroy()
        db.cgsnapshot_destroy(self.ctxt.elevated(), cgsnapshot_id)
        db.volume_destroy(self.ctxt.elevated(), volume_id)
        consistencygroup.destroy()
Ejemplo n.º 20
0
 def _migrate_volume_comp_exec(self,
                               ctx,
                               volume,
                               new_volume,
                               error,
                               expected_status,
                               expected_id,
                               no_body=False):
     req = webob.Request.blank(
         '/v2/%s/volumes/%s/action' % (fake.PROJECT_ID, volume['id']))
     req.method = 'POST'
     req.headers['content-type'] = 'application/json'
     body = {'new_volume': new_volume['id'], 'error': error}
     if no_body:
         body = {'': body}
     else:
         body = {'os-migrate_volume_completion': body}
     req.body = jsonutils.dump_as_bytes(body)
     req.environ['cinder.context'] = ctx
     resp = req.get_response(app())
     resp_dict = resp.json
     # verify status
     self.assertEqual(expected_status, resp.status_int)
     if expected_id:
         self.assertEqual(expected_id, resp_dict['save_volume_id'])
     else:
         self.assertNotIn('save_volume_id', resp_dict)
Ejemplo n.º 21
0
    def test_create_with_keys_in_uppercase_and_lowercase(self, metadata_get,
                                                         metadata_update):
        # if the keys in uppercase_and_lowercase, should return the one
        # which server added
        fake_volume = {'id': fake.VOLUME_ID, 'status': 'available'}
        fake_context = mock.Mock()
        metadata_get.side_effect = return_empty_volume_metadata
        metadata_update.side_effect = return_create_volume_metadata_insensitive

        req = fakes.HTTPRequest.blank('/v1/volume_metadata')
        req.method = 'POST'
        req.content_type = "application/json"
        body = {"metadata": {"key1": "value1",
                             "KEY1": "value1",
                             "key2": "value2",
                             "KEY2": "value2",
                             "key3": "value3",
                             "KEY4": "value4"}}
        expected = {"metadata": {"key1": "value1",
                                 "key2": "value2",
                                 "key3": "value3",
                                 "KEY4": "value4"}}
        req.body = jsonutils.dump_as_bytes(body)
        req.environ['cinder.context'] = fake_context

        with mock.patch.object(self.controller.volume_api,
                               'get') as get_volume:
            get_volume.return_value = fake_volume
            res_dict = self.controller.create(req, fake.VOLUME_ID, body)
            self.assertEqual(expected, res_dict)
Ejemplo n.º 22
0
 def test_create_root_volume_bdm_v2(self):
     body = dict(server=dict(
             name='test_server', imageRef=IMAGE_UUID,
             flavorRef=2, min_count=1, max_count=1,
             block_device_mapping_v2=[dict(
                     source_type='volume',
                     uuid='1',
                     device_name='/dev/vda',
                     boot_index=0,
                     delete_on_termination=False,
                     )]
             ))
     req = fakes.HTTPRequest.blank('/v2/fake/os-volumes_boot')
     req.method = 'POST'
     req.body = jsonutils.dump_as_bytes(body)
     req.headers['content-type'] = 'application/json'
     res = req.get_response(fakes.wsgi_app(
         init_only=('os-volumes_boot', 'servers')))
     self.assertEqual(202, res.status_int)
     server = jsonutils.loads(res.body)['server']
     self.assertEqual(FAKE_UUID, server['id'])
     self.assertEqual(CONF.password_length, len(server['adminPass']))
     self.assertEqual(1, len(self._block_device_mapping_seen))
     self.assertFalse(self._legacy_bdm_seen)
     self.assertEqual('1', self._block_device_mapping_seen[0]['volume_id'])
     self.assertEqual(0, self._block_device_mapping_seen[0]['boot_index'])
     self.assertEqual('/dev/vda',
                      self._block_device_mapping_seen[0]['device_name'])
Ejemplo n.º 23
0
 def _get_response(self):
     req = self._get_http_request(self.base_url)
     req.headers['Content-Type'] = 'application/json'
     req.method = 'POST'
     req.body = jsonutils.dump_as_bytes(self.expected)
     res = req.get_response(self.app)
     return jsonutils.loads(res.body)
Ejemplo n.º 24
0
    def test_create_consistencygroup_from_src_cgsnapshot_notfound(self):
        consistencygroup = utils.create_consistencygroup(self.ctxt)
        volume_id = utils.create_volume(self.ctxt, consistencygroup_id=consistencygroup.id)["id"]

        test_cg_name = "test cg"
        body = {
            "consistencygroup-from-src": {
                "name": test_cg_name,
                "description": "Consistency Group 1",
                "cgsnapshot_id": "fake_cgsnap",
            }
        }
        req = webob.Request.blank("/v2/fake/consistencygroups/create_from_src")
        req.method = "POST"
        req.headers["Content-Type"] = "application/json"
        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(fakes.wsgi_app())
        res_dict = jsonutils.loads(res.body)

        self.assertEqual(404, res.status_int)
        self.assertEqual(404, res_dict["itemNotFound"]["code"])
        self.assertIsNotNone(res_dict["itemNotFound"]["message"])

        db.volume_destroy(self.ctxt.elevated(), volume_id)
        consistencygroup.destroy()
Ejemplo n.º 25
0
    def test_volume_create(self):
        self.stubs.Set(cinder.API, "create", fakes.stub_volume_create)

        vol = {"size": 100,
               "display_name": "Volume Test Name",
               "display_description": "Volume Test Desc",
               "availability_zone": "zone1:host1"}
        body = {"volume": vol}
        req = fakes.HTTPRequest.blank(self.url_prefix + '/os-volumes')
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes(body)
        req.headers['content-type'] = 'application/json'
        resp = req.get_response(self.app)

        self.assertEqual(200, resp.status_int)

        resp_dict = jsonutils.loads(resp.body)
        self.assertIn('volume', resp_dict)
        self.assertEqual(vol['size'], resp_dict['volume']['size'])
        self.assertEqual(vol['display_name'],
                         resp_dict['volume']['displayName'])
        self.assertEqual(vol['display_description'],
                         resp_dict['volume']['displayDescription'])
        self.assertEqual(vol['availability_zone'],
                         resp_dict['volume']['availabilityZone'])
Ejemplo n.º 26
0
 def _goose_handler(req, res):
     #NOTE: This only handles JSON responses.
     # You can use content type header to test for XML.
     data = jsonutils.loads(res.body)
     data['FOXNSOX:googoose'] = req.GET.get('chewing')
     res.body = jsonutils.dump_as_bytes(data)
     return res
Ejemplo n.º 27
0
    def test_update_all_with_keys_in_uppercase_and_lowercase(self,
                                                             metadata_get,
                                                             metadata_update):
        fake_volume = {'id': fake.VOLUME_ID, 'status': 'available'}
        fake_context = mock.Mock()
        metadata_get.side_effect = return_create_volume_metadata
        metadata_update.side_effect = return_new_volume_metadata
        req = fakes.HTTPRequest.blank(self.url)
        req.method = 'PUT'
        req.content_type = "application/json"
        body = {
            'metadata': {
                'key10': 'value10',
                'KEY10': 'value10',
                'key99': 'value99',
                'KEY20': 'value20',
            },
        }
        expected = {
            'metadata': {
                'key10': 'value10',
                'key99': 'value99',
                'KEY20': 'value20',
            },
        }
        req.body = jsonutils.dump_as_bytes(expected)
        req.environ['cinder.context'] = fake_context

        with mock.patch.object(self.controller.volume_api,
                               'get') as get_volume:
            get_volume.return_value = fake_volume
            res_dict = self.controller.update_all(req, fake.VOLUME_ID, body)
            self.assertEqual(expected, res_dict)
            get_volume.assert_called_once_with(fake_context, fake.VOLUME_ID)
Ejemplo n.º 28
0
 def _bands_handler(req, res):
     #NOTE: This only handles JSON responses.
     # You can use content type header to test for XML.
     data = jsonutils.loads(res.body)
     data['FOXNSOX:big_bands'] = 'Pig Bands!'
     res.body = jsonutils.dump_as_bytes(data)
     return res
Ejemplo n.º 29
0
    def _force_delete_backup_util(self, test_status, mock_check_support,
                                  mock_service_get_all):
        mock_service_get_all.return_value = [{
            'availability_zone': "az1",
            'host': 'testhost',
            'disabled': 0,
            'updated_at': timeutils.utcnow()
        }]
        # admin context
        mock_check_support.return_value = True
        # current status is dependent on argument: test_status.
        id = test_backups.BackupsAPITestCase._create_backup(status=test_status)
        req = webob.Request.blank(
            '/v2/%s/backups/%s/action' % (fake.PROJECT_ID, id))
        req.method = 'POST'
        req.headers['Content-Type'] = 'application/json'
        req.body = jsonutils.dump_as_bytes({'os-force_delete': {}})
        req.environ['cinder.context'] = self.ctx
        res = req.get_response(app())

        self.assertEqual(202, res.status_int)
        self.assertEqual(
            'deleting',
            test_backups.BackupsAPITestCase._get_backup_attrib(id, 'status'))
        db.backup_destroy(self.ctx, id)
Ejemplo n.º 30
0
    def test_accept_transfer_with_VolumeSizeExceedsAvailableQuota(self):

        def fake_transfer_api_accept_throwing_VolumeSizeExceedsAvailableQuota(
                cls, context, transfer, volume_id):
            raise exception.VolumeSizeExceedsAvailableQuota(requested='2',
                                                            consumed='2',
                                                            quota='3')

        self.stubs.Set(
            cinder.transfer.API,
            'accept',
            fake_transfer_api_accept_throwing_VolumeSizeExceedsAvailableQuota)

        volume_id = self._create_volume()
        transfer = self._create_transfer(volume_id)

        body = {"accept": {"id": transfer['id'],
                           "auth_key": transfer['auth_key']}}
        req = webob.Request.blank('/v2/%s/os-volume-transfer/%s/accept' % (
                                  fake.PROJECT_ID, transfer['id']))

        req.method = 'POST'
        req.headers['Content-Type'] = 'application/json'
        req.body = jsonutils.dump_as_bytes(body)
        res = req.get_response(fakes.wsgi_app(
            fake_auth_context=self.user_ctxt))
        res_dict = jsonutils.loads(res.body)

        self.assertEqual(413, res.status_int)
        self.assertEqual(413, res_dict['overLimit']['code'])
        self.assertEqual('Requested volume or snapshot exceeds allowed '
                         'gigabytes quota. Requested 2G, quota is 3G and '
                         '2G has been consumed.',
                         res_dict['overLimit']['message'])