예제 #1
0
파일: test_volume.py 프로젝트: gerryw/heat
    def test_volume_deleting_delete(self):
        fv = vt_base.FakeVolume('creating', 'available')
        stack_name = 'test_volume_deleting_stack'

        self._mock_create_volume(fv, stack_name)

        self.cinder_fc.volumes.get('vol-123').AndReturn(fv)
        self.m.ReplayAll()

        stack = utils.parse_stack(self.t, stack_name=stack_name)

        rsrc = self.create_volume(self.t, stack, 'DataVolume')
        self.assertEqual('available', fv.status)

        # make sure that delete was not called
        self.m.StubOutWithMock(fv, 'delete')

        self.m.StubOutWithMock(fv, 'get')
        fv.get().AndReturn(None)
        fv.get().AndRaise(cinder_exp.NotFound('Not found'))
        self.m.ReplayAll()

        fv.status = 'deleting'
        scheduler.TaskRunner(rsrc.destroy)()

        self.m.VerifyAll()
예제 #2
0
파일: test_volume.py 프로젝트: zzjeric/heat
    def test_volume_detach_non_exist(self):
        fv = vt_base.FakeVolume('creating')
        fva = vt_base.FakeVolume('in-use')
        stack_name = 'test_volume_detach_nonexist_stack'

        mock_attachment = self._mock_create_server_volume_script(fva)
        self._mock_create_volume(fv,
                                 stack_name,
                                 mock_attachment=mock_attachment)
        self.stub_VolumeConstraint_validate()

        stack = utils.parse_stack(self.t, stack_name=stack_name)

        self.create_volume(self.t, stack, 'DataVolume')
        rsrc = self.create_attachment(self.t, stack, 'MountPoint')

        # delete script
        self.fc.volumes.delete_server_volume.return_value = None
        self.cinder_fc.volumes.get.side_effect = cinder_exp.NotFound(
            'Not found')

        exc = fakes_nova.fake_exception()
        self.fc.volumes.get_server_volume.side_effect = exc

        scheduler.TaskRunner(rsrc.delete)()

        self.fc.volumes.delete_server_volume.assert_called_once_with(
            u'WikiDatabase', 'vol-123')
        self.fc.volumes.get_server_volume.assert_called_with(
            u'WikiDatabase', 'vol-123')
        self.validate_mock_create_server_volume_script()
예제 #3
0
    def test_get_snapshot_failed(self):
        snapshot_id = 'snapshot_id'
        cinder.cinderclient(self.ctx).AndRaise(cinder_exception.NotFound(''))
        self.mox.ReplayAll()

        self.assertRaises(exception.SnapshotNotFound, self.api.get_snapshot,
                          self.ctx, snapshot_id)
예제 #4
0
파일: test_cinder.py 프로젝트: zsvic/nova
 def test_attachment_create_volume_not_found(self, mock_cinderclient):
     """Tests that the translate_volume_exception decorator is used."""
     # fake out the volume not found error
     mock_cinderclient.return_value.attachments.create.side_effect = (
         cinder_exception.NotFound(404))
     self.assertRaises(exception.VolumeNotFound, self.api.attachment_create,
                       self.ctx, uuids.volume_id, uuids.instance_id)
예제 #5
0
    def test_volume_default_az(self):
        fv = vt_base.FakeVolume('creating')
        stack_name = 'test_volume_defaultaz_stack'

        # create script
        nova.NovaClientPlugin._create().AndReturn(self.fc)
        self.m.StubOutWithMock(instance.Instance, 'handle_create')
        self.m.StubOutWithMock(instance.Instance, 'check_create_complete')
        self.m.StubOutWithMock(instance.Instance, '_resolve_attribute')
        self.m.StubOutWithMock(aws_vol.VolumeAttachment,
                               'handle_create')
        self.m.StubOutWithMock(aws_vol.VolumeAttachment,
                               'check_create_complete')

        instance.Instance.handle_create().AndReturn(None)
        instance.Instance.check_create_complete(None).AndReturn(True)
        instance.Instance._resolve_attribute(
            'AvailabilityZone').MultipleTimes().AndReturn(None)
        cinder.CinderClientPlugin._create().AndReturn(
            self.cinder_fc)
        self.stub_ImageConstraint_validate()
        self.stub_ServerConstraint_validate()
        self.stub_VolumeConstraint_validate()
        vol_name = utils.PhysName(stack_name, 'DataVolume')
        self.cinder_fc.volumes.create(
            size=1, availability_zone=None,
            description=vol_name,
            name=vol_name,
            metadata={u'Usage': u'Wiki Data Volume'}).AndReturn(fv)
        self.cinder_fc.volumes.get(fv.id).AndReturn(fv)
        fv_ready = vt_base.FakeVolume('available', id=fv.id)
        self.cinder_fc.volumes.get(fv.id).AndReturn(fv_ready)
        aws_vol.VolumeAttachment.handle_create().AndReturn(None)
        aws_vol.VolumeAttachment.check_create_complete(
            None).AndReturn(True)

        # delete script
        self.m.StubOutWithMock(instance.Instance, 'handle_delete')
        self.m.StubOutWithMock(aws_vol.VolumeAttachment, 'handle_delete')
        self.m.StubOutWithMock(aws_vol.VolumeAttachment,
                               'check_delete_complete')
        instance.Instance.handle_delete().AndReturn(None)
        self.cinder_fc.volumes.get('vol-123').AndRaise(
            cinder_exp.NotFound('Not found'))
        cookie = object()
        aws_vol.VolumeAttachment.handle_delete().AndReturn(cookie)
        aws_vol.VolumeAttachment.check_delete_complete(cookie).AndReturn(True)

        self.m.ReplayAll()

        stack = utils.parse_stack(self.t, stack_name=stack_name)

        rsrc = stack['DataVolume']
        self.assertIsNone(rsrc.validate())
        scheduler.TaskRunner(stack.create)()
        self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state)

        scheduler.TaskRunner(stack.delete)()

        self.m.VerifyAll()
예제 #6
0
    def test_volume_detach_non_exist(self):
        fv = vt_base.FakeVolume('creating')
        fva = vt_base.FakeVolume('in-use')
        stack_name = 'test_volume_detach_nonexist_stack'

        self._mock_create_volume(fv, stack_name)
        self._mock_create_server_volume_script(fva)
        self.stub_VolumeConstraint_validate()
        # delete script
        self.fc.volumes.delete_server_volume(u'WikiDatabase',
                                             'vol-123').AndReturn(None)
        self.cinder_fc.volumes.get(fva.id).AndRaise(
            cinder_exp.NotFound('Not found'))
        self.fc.volumes.get_server_volume(u'WikiDatabase', 'vol-123').AndRaise(
            fakes_nova.fake_exception())

        self.m.ReplayAll()

        stack = utils.parse_stack(self.t, stack_name=stack_name)

        self.create_volume(self.t, stack, 'DataVolume')
        rsrc = self.create_attachment(self.t, stack, 'MountPoint')

        scheduler.TaskRunner(rsrc.delete)()

        self.m.VerifyAll()
예제 #7
0
 def _mock_delete_volume(self, fv):
     self.m.StubOutWithMock(fv, 'delete')
     fv.delete().AndReturn(True)
     self.m.StubOutWithMock(fv, 'get')
     fv.get().AndReturn(None)
     fv.get().AndRaise(cinder_exp.NotFound('Not found'))
     self.m.ReplayAll()
예제 #8
0
    def test_snapshot_no_volume(self):
        """Test that backup does not start for failed resource."""
        stack_name = 'test_volume_snapshot_novol_stack'
        cfg.CONF.set_override('action_retry_limit', 0)
        fva = vt_base.FakeVolume('error')
        fv = self._mock_create_volume(vt_base.FakeVolume('creating'),
                                      stack_name,
                                      final_status='error',
                                      mock_attachment=fva)

        self._mock_delete_volume(fv)

        self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Snapshot'
        self.t['Resources']['DataVolume']['Properties'][
            'AvailabilityZone'] = 'nova'
        stack = utils.parse_stack(self.t, stack_name=stack_name)
        resource_defns = stack.t.resource_definitions(stack)
        rsrc = aws_vol.Volume('DataVolume',
                              resource_defns['DataVolume'],
                              stack)

        create = scheduler.TaskRunner(rsrc.create)
        ex = self.assertRaises(exception.ResourceFailure, create)
        self.assertIn('Went to status error due to "Unknown"',
                      six.text_type(ex))

        self.cinder_fc.volumes.get.side_effect = [
            fva,
            cinder_exp.NotFound('Not found')
        ]

        scheduler.TaskRunner(rsrc.destroy)()
예제 #9
0
    def test_snapshot(self):
        stack_name = 'test_volume_snapshot_stack'
        fv = vt_base.FakeVolume('creating')
        fv_ready = vt_base.FakeVolume('available', id=fv.id)
        fv = self._mock_create_volume(fv,
                                      stack_name, mock_attachment=fv_ready)

        # snapshot script
        fb = vt_base.FakeBackup('available')
        self.m_backups.create.return_value = fb
        self.m_backups.get.return_value = fb
        self._mock_delete_volume(fv)

        self.t['Resources']['DataVolume']['DeletionPolicy'] = 'Snapshot'
        stack = utils.parse_stack(self.t, stack_name=stack_name)

        rsrc = self.create_volume(self.t, stack, 'DataVolume')

        self.cinder_fc.volumes.get.side_effect = [
            fv,
            vt_base.FakeVolume('available'),
            cinder_exp.NotFound('Not found')
        ]
        scheduler.TaskRunner(rsrc.destroy)()

        self.m_backups.create.assert_called_once_with(fv.id)
        self.m_backups.get.assert_called_once_with(fb.id)
예제 #10
0
파일: test_volume.py 프로젝트: zzjeric/heat
    def test_volume_default_az(self):
        fv = vt_base.FakeVolume('creating')
        stack_name = 'test_volume_defaultaz_stack'

        # create script
        self.patchobject(instance.Instance, 'handle_create')
        self.patchobject(instance.Instance,
                         'check_create_complete',
                         return_value=True)
        self.patchobject(instance.Instance,
                         '_resolve_attribute',
                         return_value=None)
        self.patchobject(aws_vol.VolumeAttachment, 'handle_create')
        self.patchobject(aws_vol.VolumeAttachment,
                         'check_create_complete',
                         return_value=True)

        cinder.CinderClientPlugin._create.return_value = self.cinder_fc
        self.stub_ImageConstraint_validate()
        self.stub_ServerConstraint_validate()
        self.stub_VolumeConstraint_validate()
        vol_name = utils.PhysName(stack_name, 'DataVolume')
        self.cinder_fc.volumes.create.return_value = fv
        fv_ready = vt_base.FakeVolume('available', id=fv.id)
        self.cinder_fc.volumes.get.side_effect = [
            fv, fv_ready, cinder_exp.NotFound('Not found')
        ]

        # delete script
        cookie = object()
        self.patchobject(instance.Instance, 'handle_delete')
        self.patchobject(aws_vol.VolumeAttachment,
                         'handle_delete',
                         return_value=cookie)
        self.patchobject(aws_vol.VolumeAttachment,
                         'check_delete_complete',
                         return_value=True)

        stack = utils.parse_stack(self.t, stack_name=stack_name)
        stack._update_all_resource_data(True, False)

        rsrc = stack['DataVolume']
        self.assertIsNone(rsrc.validate())
        scheduler.TaskRunner(stack.create)()
        self.assertEqual((rsrc.CREATE, rsrc.COMPLETE), rsrc.state)

        scheduler.TaskRunner(stack.delete)()

        instance.Instance._resolve_attribute.assert_called_with(
            'AvailabilityZone')
        self.cinder_fc.volumes.create.assert_called_once_with(
            size=1,
            availability_zone=None,
            description=vol_name,
            name=vol_name,
            metadata={u'Usage': u'Wiki Data Volume'})
        self.cinder_fc.volumes.get.assert_called_with('vol-123')
        aws_vol.VolumeAttachment.check_delete_complete.assert_called_once_with(
            cookie)
예제 #11
0
 def test_attachment_update_attachment_not_found(self, mock_cinderclient):
     """Tests that the translate_attachment_exception decorator is used."""
     # fake out the volume not found error
     mock_cinderclient.return_value.attachments.update.side_effect = (
         cinder_exception.NotFound(404))
     self.assertRaises(exception.VolumeAttachmentNotFound,
                       self.api.attachment_update,
                       self.ctx, uuids.attachment_id,
                       connector={'host': 'fake-host'})
예제 #12
0
    def test_when_project_is_cleaned_all_resources_are_deleted(self):
        self.mocked_cinder().volumes.get.side_effect = cinder_exceptions.NotFound(
            code=404
        )
        self.mocked_nova().servers.get.side_effect = nova_exceptions.NotFound(code=404)

        ProjectCleanupExecutor.execute(self.project, is_async=False)
        self.assertFalse(Project.objects.filter(id=self.project.id).exists())
        self.assertFalse(models.Instance.objects.filter(id=self.instance.id).exists())
예제 #13
0
    def test_filter_non_existing_volume(self):
        opts = copy.deepcopy(self.opts)
        opts['search_opts_tenant'] = {'tenant_id': ['existing_tenant_id']}
        opts['search_opts_vol'] = {'volumes_list': ['non_existing_volume_id']}

        self.src_storage.cinder_client.volumes.get.side_effect = (
            cinder_exc.NotFound(404))

        self.assertRaises(exception.AbortMigrationError, self.fake_action.run,
                          **opts)
예제 #14
0
    def test_get_failed(self):
        volume_id = 'volume_id'
        cinder.cinderclient(self.ctx).AndRaise(cinder_exception.NotFound(''))
        cinder.cinderclient(self.ctx).AndRaise(cinder_exception.BadRequest(''))
        self.mox.ReplayAll()

        self.assertRaises(exception.VolumeNotFound, self.api.get, self.ctx,
                          volume_id)
        self.assertRaises(exception.InvalidInput, self.api.get, self.ctx,
                          volume_id)
예제 #15
0
    def test_get_volume_fail(self, mock_cinder):

        cinder_util = cinder_helper.CinderHelper()

        volume = self.fake_volume()
        side_effect = cinder_exception.NotFound(404)
        cinder_util.cinder.volumes.get.side_effect = side_effect
        cinder_util.cinder.volumes.find.return_value = False
        result = cinder_util.get_volume(volume)
        self.assertFalse(result)
 def __call__(self, *args, **kwargs):
     res = mock.Mock()
     res.id = self._id
     if self._time_to_work > 0:
         self._time_to_work -= 1
         res.status = self._working_status
     else:
         res.status = self._final_status
     if res.status == 'not-found':
         raise cinder_exc.NotFound(403)
     return res
예제 #17
0
파일: test_cinder.py 프로젝트: zsvic/nova
    def test_attachment_get_failed(self, mock_cinderclient):
        mock_cinderclient.return_value.attachments.show.side_effect = (
            cinder_exception.NotFound(404, '404'))

        attachment_id = uuids.attachment
        ex = self.assertRaises(exception.VolumeAttachmentNotFound,
                               self.api.attachment_get, self.ctx,
                               attachment_id)

        self.assertEqual(404, ex.code)
        self.assertIn(attachment_id, six.text_type(ex))
예제 #18
0
    def test_attachment_delete_failed(self, mock_cinderclient, mock_log):
        mock_cinderclient.return_value.attachments.delete.side_effect = (
            cinder_exception.NotFound(404, '404'))

        attachment_id = uuids.attachment
        ex = self.assertRaises(exception.VolumeAttachmentNotFound,
                               self.api.attachment_delete, self.ctx,
                               attachment_id)

        self.assertEqual(404, ex.code)
        self.assertIn(attachment_id, ex.message)
예제 #19
0
    def test_can_get_volume_fail(self, mock_cinder):

        cinder_util = cinder_helper.CinderHelper()

        volume = self.fake_volume()
        cinder_util.get_volume = mock.MagicMock()
        cinder_util.get_volume.side_effect = cinder_exception.NotFound(404)
        result = cinder_util._can_get_volume(volume.id)
        self.assertFalse(result)

        cinder_util.get_volume = mock.MagicMock(return_value=None)
        self.assertRaises(
            Exception,
            cinder_util._can_get_volume,
            volume.id)
예제 #20
0
    def test_detach_volumes_vol_not_found(self, mock_get, mock_set_meta,
                                          mock_session):
        """Raise an error if the volume lookup fails"""
        volumes = ['vol1']
        connector = {'foo': 'bar'}
        mock_get.side_effect = cinder_exceptions.NotFound(404, message='error')

        with task_manager.acquire(self.context, self.node.uuid) as task:
            self.assertRaises(exception.StorageError, cinder.detach_volumes,
                              task, volumes, connector)
            self.assertFalse(mock_set_meta.called)
            # We should not raise any exception when issuing a command
            # with errors being permitted.
            cinder.detach_volumes(task, volumes, connector, allow_errors=True)
            self.assertFalse(mock_set_meta.called)
예제 #21
0
    def find(self, **kwargs):
        """
        Find a single item with attributes matching ``**kwargs``.

        This isn't very efficient: it loads the entire list then filters on
        the Python side.
        """
        matches = self.findall(**kwargs)
        num_matches = len(matches)
        if num_matches == 0:
            msg = "No %s matching %s." % (self.resource_class.__name__, kwargs)
            raise exceptions.NotFound(404, msg)
        elif num_matches > 1:
            raise exceptions.NoUniqueMatch
        else:
            return matches[0]
예제 #22
0
    def find(self, **kwargs):
        """
        Find a single item with attributes matching ``**kwargs``.

        This isn't very efficient for search options which require the
        Python side filtering(e.g. 'human_id')
        """
        matches = self.findall(**kwargs)
        num_matches = len(matches)
        if num_matches == 0:
            msg = "No %s matching %s." % (self.resource_class.__name__, kwargs)
            raise exceptions.NotFound(404, msg)
        elif num_matches > 1:
            raise exceptions.NoUniqueMatch
        else:
            return matches[0]
예제 #23
0
파일: test_volume.py 프로젝트: zzjeric/heat
    def test_volume_deleting_delete(self):
        vt_base.FakeVolume('creating')
        stack_name = 'test_volume_deleting_stack'

        self._mock_create_volume(vt_base.FakeVolume('creating'), stack_name)

        stack = utils.parse_stack(self.t, stack_name=stack_name)
        rsrc = self.create_volume(self.t, stack, 'DataVolume')

        self.assertEqual(2, self.cinder_fc.volumes.get.call_count)
        # delete script
        self.cinder_fc.volumes.get.side_effect = [
            vt_base.FakeVolume('deleting'),
            vt_base.FakeVolume('deleting'),
            cinder_exp.NotFound('NotFound')
        ]

        scheduler.TaskRunner(rsrc.destroy)()
        self.assertEqual(5, self.cinder_fc.volumes.get.call_count)
예제 #24
0
    def test_volume_deleting_delete(self):
        fv = vt_base.FakeVolume('creating')
        stack_name = 'test_volume_deleting_stack'

        fv = self._mock_create_volume(vt_base.FakeVolume('creating'),
                                      stack_name)

        self.cinder_fc.volumes.get(fv.id).AndReturn(
            vt_base.FakeVolume('deleting'))
        self.cinder_fc.volumes.get(fv.id).AndReturn(
            vt_base.FakeVolume('deleting'))
        self.cinder_fc.volumes.get(fv.id).AndRaise(
            cinder_exp.NotFound('NotFound'))

        self.m.ReplayAll()

        stack = utils.parse_stack(self.t, stack_name=stack_name)
        rsrc = self.create_volume(self.t, stack, 'DataVolume')
        scheduler.TaskRunner(rsrc.destroy)()

        self.m.VerifyAll()
예제 #25
0
    def test_volume(self):
        stack_name = 'test_volume_create_stack'

        # create script
        fv = self._mock_create_volume(vt_base.FakeVolume('creating'),
                                      stack_name)
        # delete script
        self._mock_delete_volume(fv)

        stack = utils.parse_stack(self.t, stack_name=stack_name)

        rsrc = self.create_volume(self.t, stack, 'DataVolume')

        # delete script
        self._mock_delete_volume(fv)
        ex = self.assertRaises(exception.ResourceFailure,
                               scheduler.TaskRunner(rsrc.destroy))
        self.assertIn("Volume in use", six.text_type(ex))
        self.cinder_fc.volumes.get.side_effect = [
            vt_base.FakeVolume('available'), cinder_exp.NotFound('Not found')]

        scheduler.TaskRunner(rsrc.destroy)()
예제 #26
0
class TestIsNotFound(common.HeatTestCase):

    scenarios = [
        ('ceilometer_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='ceilometer',
            exception=lambda: ceil_exc.HTTPNotFound(details='gone'),
        )),
        ('ceilometer_not_found_apiclient', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='ceilometer',
            exception=lambda: c_a_exc.NotFound(details='gone'),
        )),
        ('ceilometer_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='ceilometer',
            exception=lambda: Exception()
        )),
        ('ceilometer_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='ceilometer',
            exception=lambda: ceil_exc.HTTPOverLimit(details='over'),
        )),
        ('ceilometer_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='ceilometer',
            exception=lambda: ceil_exc.HTTPConflict(),
        )),
        ('cinder_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='cinder',
            exception=lambda: cinder_exc.NotFound(code=404),
        )),
        ('cinder_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='cinder',
            exception=lambda: Exception()
        )),
        ('cinder_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='cinder',
            exception=lambda: cinder_exc.OverLimit(code=413),
        )),
        ('cinder_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='cinder',
            exception=lambda: cinder_exc.ClientException(code=409),
        )),
        ('glance_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='glance',
            exception=lambda: glance_exc.HTTPNotFound(details='gone'),
        )),
        ('glance_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='glance',
            exception=lambda: Exception()
        )),
        ('glance_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='glance',
            exception=lambda: glance_exc.HTTPOverLimit(details='over'),
        )),
        ('glance_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='glance',
            exception=lambda: glance_exc.HTTPConflict(),
        )),
        ('heat_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='heat',
            exception=lambda: heat_exc.HTTPNotFound(message='gone'),
        )),
        ('heat_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='heat',
            exception=lambda: Exception()
        )),
        ('heat_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='heat',
            exception=lambda: heat_exc.HTTPOverLimit(message='over'),
        )),
        ('heat_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='heat',
            exception=lambda: heat_exc.HTTPConflict(),
        )),
        ('keystone_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='keystone',
            exception=lambda: keystone_exc.NotFound(details='gone'),
        )),
        ('keystone_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='keystone',
            exception=lambda: Exception()
        )),
        ('keystone_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='keystone',
            exception=lambda: keystone_exc.RequestEntityTooLarge(
                details='over'),
        )),
        ('keystone_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='keystone',
            exception=lambda: keystone_exc.Conflict(
                message='Conflict'),
        )),
        ('neutron_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: neutron_exc.NotFound,
        )),
        ('neutron_network_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: neutron_exc.NetworkNotFoundClient(),
        )),
        ('neutron_port_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: neutron_exc.PortNotFoundClient(),
        )),
        ('neutron_status_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: neutron_exc.NeutronClientException(
                status_code=404),
        )),
        ('neutron_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: Exception()
        )),
        ('neutron_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: neutron_exc.NeutronClientException(
                status_code=413),
        )),
        ('neutron_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='neutron',
            exception=lambda: neutron_exc.Conflict(),
        )),
        ('nova_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            is_unprocessable_entity=False,
            plugin='nova',
            exception=lambda: fakes_nova.fake_exception(),
        )),
        ('nova_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            is_unprocessable_entity=False,
            plugin='nova',
            exception=lambda: Exception()
        )),
        ('nova_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            is_unprocessable_entity=False,
            plugin='nova',
            exception=lambda: fakes_nova.fake_exception(413),
        )),
        ('nova_unprocessable_entity', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            is_unprocessable_entity=True,
            plugin='nova',
            exception=lambda: fakes_nova.fake_exception(422),
        )),
        ('nova_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            is_unprocessable_entity=False,
            plugin='nova',
            exception=lambda: fakes_nova.fake_exception(409),
        )),
        ('swift_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='swift',
            exception=lambda: swift_exc.ClientException(
                msg='gone', http_status=404),
        )),
        ('swift_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='swift',
            exception=lambda: Exception()
        )),
        ('swift_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='swift',
            exception=lambda: swift_exc.ClientException(
                msg='ouch', http_status=413),
        )),
        ('swift_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='swift',
            exception=lambda: swift_exc.ClientException(
                msg='conflict', http_status=409),
        )),
        ('trove_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='trove',
            exception=lambda: troveclient.exceptions.NotFound(message='gone'),
        )),
        ('trove_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='trove',
            exception=lambda: Exception()
        )),
        ('trove_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='trove',
            exception=lambda: troveclient.exceptions.RequestEntityTooLarge(
                message='over'),
        )),
        ('trove_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='trove',
            exception=lambda: troveclient.exceptions.Conflict(
                message='Conflict'),
        )),
        ('sahara_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='sahara',
            exception=lambda: sahara_base.APIException(
                error_message='gone1', error_code=404),
        )),
        ('sahara_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='sahara',
            exception=lambda: Exception()
        )),
        ('sahara_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='sahara',
            exception=lambda: sahara_base.APIException(
                error_message='over1', error_code=413),
        )),
        ('sahara_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='sahara',
            exception=lambda: sahara_base.APIException(
                error_message='conflict1', error_code=409),
        )),
    ]

    def test_is_not_found(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            raise self.exception()
        except Exception as e:
            if self.is_not_found != client_plugin.is_not_found(e):
                raise

    def test_ignore_not_found(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            exp = self.exception()
            exp_class = exp.__class__
            raise exp
        except Exception as e:
            if self.is_not_found:
                client_plugin.ignore_not_found(e)
            else:
                self.assertRaises(exp_class,
                                  client_plugin.ignore_not_found,
                                  e)

    def test_ignore_conflict_and_not_found(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            exp = self.exception()
            exp_class = exp.__class__
            raise exp
        except Exception as e:
            if self.is_conflict or self.is_not_found:
                client_plugin.ignore_conflict_and_not_found(e)
            else:
                self.assertRaises(exp_class,
                                  client_plugin.ignore_conflict_and_not_found,
                                  e)

    def test_is_over_limit(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            raise self.exception()
        except Exception as e:
            if self.is_over_limit != client_plugin.is_over_limit(e):
                raise

    def test_is_client_exception(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            raise self.exception()
        except Exception as e:
            ice = self.is_client_exception
            actual = client_plugin.is_client_exception(e)
            if ice != actual:
                raise

    def test_is_conflict(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            raise self.exception()
        except Exception as e:
            if self.is_conflict != client_plugin.is_conflict(e):
                raise

    def test_is_unprocessable_entity(self):
        con = mock.Mock()
        c = clients.Clients(con)
        # only 'nova' client plugin need to check this exception
        if self.plugin == 'nova':
            client_plugin = c.client_plugin(self.plugin)
            try:
                raise self.exception()
            except Exception as e:
                iue = self.is_unprocessable_entity
                if iue != client_plugin.is_unprocessable_entity(e):
                    raise
예제 #27
0
 def get(self, resource_id, **kwargs):
     for resource in self.resources:
         if resource.id == str(resource_id):
             return resource
     raise exceptions.NotFound(resource_id)
예제 #28
0
 def test_create_not_found_error(self):
     cinder.cinderclient.side_effect = cinder_exception.NotFound(404)
     self.assertRaises(exception.NotFound, self.api.create, self.ctx, 1, '',
                       '')
예제 #29
0
class CinderApiTestCase(test.TestCase):
    def setUp(self):
        super(CinderApiTestCase, self).setUp()

        self.api = cinder.API()
        self.cinderclient = FakeCinderClient()
        self.ctx = context.get_admin_context()
        self.mock_object(cinder, 'cinderclient',
                         mock.Mock(return_value=self.cinderclient))
        self.mock_object(cinder, '_untranslate_volume_summary_view',
                         lambda ctx, vol: vol)
        self.mock_object(cinder, '_untranslate_snapshot_summary_view',
                         lambda ctx, snap: snap)

    def test_get(self):
        volume_id = 'volume_id1'
        result = self.api.get(self.ctx, volume_id)
        self.assertEqual(volume_id, result['id'])

    @ddt.data(
        {
            'cinder_e': cinder_exception.NotFound(404),
            'manila_e': exception.VolumeNotFound
        },
        {
            'cinder_e': cinder_exception.BadRequest(400),
            'manila_e': exception.InvalidInput
        },
    )
    @ddt.unpack
    def test_get_failed(self, cinder_e, manila_e):
        cinder.cinderclient.side_effect = cinder_e
        volume_id = 'volume_id'
        self.assertRaises(manila_e, self.api.get, self.ctx, volume_id)

    def test_create(self):
        result = self.api.create(self.ctx, 1, '', '')
        self.assertEqual('created_id', result['id'])

    def test_create_failed(self):
        cinder.cinderclient.side_effect = cinder_exception.BadRequest(400)
        self.assertRaises(exception.InvalidInput, self.api.create, self.ctx, 1,
                          '', '')

    def test_create_not_found_error(self):
        cinder.cinderclient.side_effect = cinder_exception.NotFound(404)
        self.assertRaises(exception.NotFound, self.api.create, self.ctx, 1, '',
                          '')

    def test_create_failed_exception(self):
        cinder.cinderclient.side_effect = Exception("error msg")
        self.assertRaises(exception.ManilaException, self.api.create, self.ctx,
                          1, '', '')

    def test_get_all(self):
        cinder._untranslate_volume_summary_view.return_value = ['id1', 'id2']
        self.assertEqual([{
            'id': 'id1'
        }, {
            'id': 'id2'
        }], self.api.get_all(self.ctx))

    def test_check_attach_volume_status_error(self):
        volume = {'status': 'error'}
        self.assertRaises(exception.InvalidVolume, self.api.check_attach,
                          self.ctx, volume)

    def test_check_attach_volume_already_attached(self):
        volume = {'status': 'available'}
        volume['attach_status'] = "attached"
        self.assertRaises(exception.InvalidVolume, self.api.check_attach,
                          self.ctx, volume)

    def test_check_attach_availability_zone_differs(self):
        volume = {'status': 'available'}
        volume['attach_status'] = "detached"
        instance = {'availability_zone': 'zone1'}
        volume['availability_zone'] = 'zone2'
        cinder.CONF.set_override('cinder_cross_az_attach', False)
        self.assertRaises(exception.InvalidVolume, self.api.check_attach,
                          self.ctx, volume, instance)
        volume['availability_zone'] = 'zone1'
        self.assertIsNone(self.api.check_attach(self.ctx, volume, instance))
        cinder.CONF.reset()

    def test_check_attach(self):
        volume = {'status': 'available'}
        volume['attach_status'] = "detached"
        volume['availability_zone'] = 'zone1'
        instance = {'availability_zone': 'zone1'}
        cinder.CONF.set_override('cinder_cross_az_attach', False)
        self.assertIsNone(self.api.check_attach(self.ctx, volume, instance))
        cinder.CONF.reset()

    def test_check_detach(self):
        volume = {'status': 'available'}
        self.assertRaises(exception.InvalidVolume, self.api.check_detach,
                          self.ctx, volume)
        volume['status'] = 'non-available'
        self.assertIsNone(self.api.check_detach(self.ctx, volume))

    def test_update(self):
        fake_volume = {'fake': 'fake'}
        self.mock_object(self.cinderclient.volumes, 'get',
                         mock.Mock(return_value=fake_volume))
        self.mock_object(self.cinderclient.volumes, 'update')
        fake_volume_id = 'fake_volume'
        fake_data = {'test': 'test'}

        self.api.update(self.ctx, fake_volume_id, fake_data)

        self.cinderclient.volumes.get.assert_called_once_with(fake_volume_id)
        self.cinderclient.volumes.update.assert_called_once_with(
            fake_volume, **fake_data)

    def test_reserve_volume(self):
        self.mock_object(self.cinderclient.volumes, 'reserve')
        self.api.reserve_volume(self.ctx, 'id1')
        self.cinderclient.volumes.reserve.assert_called_once_with('id1')

    def test_unreserve_volume(self):
        self.mock_object(self.cinderclient.volumes, 'unreserve')
        self.api.unreserve_volume(self.ctx, 'id1')
        self.cinderclient.volumes.unreserve.assert_called_once_with('id1')

    def test_begin_detaching(self):
        self.mock_object(self.cinderclient.volumes, 'begin_detaching')
        self.api.begin_detaching(self.ctx, 'id1')
        self.cinderclient.volumes.begin_detaching.assert_called_once_with(
            'id1')

    def test_roll_detaching(self):
        self.mock_object(self.cinderclient.volumes, 'roll_detaching')
        self.api.roll_detaching(self.ctx, 'id1')
        self.cinderclient.volumes.roll_detaching.assert_called_once_with('id1')

    def test_attach(self):
        self.mock_object(self.cinderclient.volumes, 'attach')
        self.api.attach(self.ctx, 'id1', 'uuid', 'point')
        self.cinderclient.volumes.attach.assert_called_once_with(
            'id1', 'uuid', 'point')

    def test_detach(self):
        self.mock_object(self.cinderclient.volumes, 'detach')
        self.api.detach(self.ctx, 'id1')
        self.cinderclient.volumes.detach.assert_called_once_with('id1')

    def test_initialize_connection(self):
        self.mock_object(self.cinderclient.volumes, 'initialize_connection')
        self.api.initialize_connection(self.ctx, 'id1', 'connector')
        self.cinderclient.volumes.initialize_connection.\
            assert_called_once_with('id1', 'connector')

    def test_terminate_connection(self):
        self.mock_object(self.cinderclient.volumes, 'terminate_connection')
        self.api.terminate_connection(self.ctx, 'id1', 'connector')
        self.cinderclient.volumes.terminate_connection.\
            assert_called_once_with('id1', 'connector')

    def test_delete(self):
        self.mock_object(self.cinderclient.volumes, 'delete')
        self.api.delete(self.ctx, 'id1')
        self.cinderclient.volumes.delete.assert_called_once_with('id1')

    def test_get_snapshot(self):
        snapshot_id = 'snapshot_id1'
        result = self.api.get_snapshot(self.ctx, snapshot_id)
        self.assertEqual(snapshot_id, result['id'])

    def test_get_snapshot_failed(self):
        cinder.cinderclient.side_effect = cinder_exception.NotFound(404)
        snapshot_id = 'snapshot_id'
        self.assertRaises(exception.VolumeSnapshotNotFound,
                          self.api.get_snapshot, self.ctx, snapshot_id)

    def test_get_all_snapshots(self):
        cinder._untranslate_snapshot_summary_view.return_value = ['id1', 'id2']
        self.assertEqual([{
            'id': 'id1'
        }, {
            'id': 'id2'
        }], self.api.get_all_snapshots(self.ctx))

    def test_create_snapshot(self):
        result = self.api.create_snapshot(self.ctx, {'id': 'id1'}, '', '')
        self.assertEqual('created_id', result['id'])

    def test_create_force(self):
        result = self.api.create_snapshot_force(self.ctx, {'id': 'id1'}, '',
                                                '')
        self.assertEqual('created_id', result['id'])

    def test_delete_snapshot(self):
        self.mock_object(self.cinderclient.volume_snapshots, 'delete')
        self.api.delete_snapshot(self.ctx, 'id1')
        self.cinderclient.volume_snapshots.delete.assert_called_once_with(
            'id1')
예제 #30
0
 def test_get_snapshot_failed(self):
     cinder.cinderclient.side_effect = cinder_exception.NotFound(404)
     snapshot_id = 'snapshot_id'
     self.assertRaises(exception.VolumeSnapshotNotFound,
                       self.api.get_snapshot, self.ctx, snapshot_id)