예제 #1
0
 def test_evacuate_raise_badrequest_with_vdpa_interface(
     self, mock_evacuate):
     mock_evacuate.side_effect = \
         exception.OperationNotSupportedForVDPAInterface(
             instance_uuid=uuids.instance, operation='foo')
     self._check_evacuate_failure(
         webob.exc.HTTPBadRequest,
         {'host': 'foo', 'onSharedStorage': 'False', 'adminPass': '******'})
예제 #2
0
class SuspendServerTestsV21(admin_only_action_common.CommonTests):
    suspend_server = suspend_server_v21
    controller_name = 'SuspendServerController'
    _api_version = '2.1'

    def setUp(self):
        super(SuspendServerTestsV21, self).setUp()
        self.controller = getattr(self.suspend_server, self.controller_name)()
        self.compute_api = self.controller.compute_api
        self.stub_out(
            'nova.api.openstack.compute.suspend_server.'
            'SuspendServerController', lambda *a, **kw: self.controller)

    def test_suspend_resume(self):
        self._test_actions(['_suspend', '_resume'])

    @ddt.data(
        exception.OperationNotSupportedForVDPAInterface(
            instance_uuid=uuids.instance, operation='foo'),
        exception.OperationNotSupportedForSEV(instance_uuid=uuids.instance,
                                              operation='foo'),
    )
    @mock.patch('nova.compute.api.API.suspend')
    def test_suspend__http_conflict_error(self, exc, mock_suspend):
        mock_suspend.side_effect = exc
        self.assertRaises(webob.exc.HTTPConflict,
                          self.controller._suspend,
                          self.req,
                          uuids.instance,
                          body={})
        self.assertTrue(mock_suspend.called)

    def test_suspend_resume_with_non_existed_instance(self):
        self._test_actions_with_non_existed_instance(['_suspend', '_resume'])

    def test_suspend_resume_raise_conflict_on_invalid_state(self):
        self._test_actions_raise_conflict_on_invalid_state(
            ['_suspend', '_resume'])

    def test_actions_with_locked_instance(self):
        self._test_actions_with_locked_instance(['_suspend', '_resume'])

    @mock.patch('nova.compute.api.API.suspend',
                side_effect=exception.ForbiddenWithAccelerators)
    def test_suspend_raises_http_forbidden(self, mock_suspend):
        self.assertRaises(webob.exc.HTTPForbidden,
                          self.controller._suspend,
                          self.req,
                          fakes.FAKE_UUID,
                          body={})
예제 #3
0
파일: test_shelve.py 프로젝트: sapcc/nova
class ShelveControllerTest(test.NoDBTestCase):
    plugin = shelve_v21

    def setUp(self):
        super().setUp()
        self.controller = self.plugin.ShelveController()
        self.req = fakes.HTTPRequest.blank('')

    @ddt.data(
        exception.InstanceIsLocked(instance_uuid=uuids.instance),
        exception.OperationNotSupportedForVTPM(
            instance_uuid=uuids.instance, operation='foo'),
        exception.OperationNotSupportedForVDPAInterface(
            instance_uuid=uuids.instance, operation='foo'),
        exception.UnexpectedTaskStateError(
            instance_uuid=uuids.instance, expected=None,
            actual=task_states.SHELVING),
    )
    @mock.patch('nova.compute.api.API.shelve')
    @mock.patch('nova.api.openstack.common.get_instance')
    def test_shelve__http_conflict_error(
        self, exc, mock_get_instance, mock_shelve,
    ):
        mock_get_instance.return_value = (
            fake_instance.fake_instance_obj(self.req.environ['nova.context']))
        mock_shelve.side_effect = exc

        self.assertRaises(
            webob.exc.HTTPConflict, self.controller._shelve,
            self.req, uuids.fake, {})

    @mock.patch('nova.compute.api.API.shelve')
    @mock.patch('nova.api.openstack.common.get_instance')
    def test_shelve_raise_http_forbidden(
        self, mock_get_instance, mock_shelve,
    ):
        mock_get_instance.return_value = (
            fake_instance.fake_instance_obj(self.req.environ['nova.context']))
        mock_shelve.side_effect = exception.ForbiddenWithAccelerators

        self.assertRaises(
            webob.exc.HTTPForbidden, self.controller._shelve,
            self.req, uuids.fake, {})

    @mock.patch('nova.api.openstack.common.get_instance')
    def test_unshelve_locked_server(self, get_instance_mock):
        get_instance_mock.return_value = (
            fake_instance.fake_instance_obj(self.req.environ['nova.context']))
        self.stub_out('nova.compute.api.API.unshelve',
                      fakes.fake_actions_to_locked_server)
        self.assertRaises(webob.exc.HTTPConflict, self.controller._unshelve,
                          self.req, uuids.fake, body={'unshelve': {}})

    @mock.patch('nova.api.openstack.common.get_instance')
    def test_shelve_offload_locked_server(self, get_instance_mock):
        get_instance_mock.return_value = (
            fake_instance.fake_instance_obj(self.req.environ['nova.context']))
        self.stub_out('nova.compute.api.API.shelve_offload',
                      fakes.fake_actions_to_locked_server)
        self.assertRaises(webob.exc.HTTPConflict,
                          self.controller._shelve_offload,
                          self.req, uuids.fake, {})
예제 #4
0
 def test_migrate_live_vdpa_interfaces_not_supported(self):
     self._test_migrate_live_failed_with_exception(
         exception.OperationNotSupportedForVDPAInterface(
             instance_uuid=uuids.instance, operation='foo'),
         expected_exc=webob.exc.HTTPConflict,
         check_response=False)
예제 #5
0
class RescueTestV21(test.NoDBTestCase):

    image_uuid = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6'

    def setUp(self):
        super(RescueTestV21, self).setUp()

        self.stub_out("nova.compute.api.API.get", fake_compute_get)
        self.stub_out("nova.compute.api.API.rescue", rescue)
        self.stub_out("nova.compute.api.API.unrescue", unrescue)
        self.controller = self._set_up_controller()
        self.fake_req = fakes.HTTPRequest.blank('')

    def _set_up_controller(self):
        return rescue_v21.RescueController()

    def _allow_bfv_rescue(self):
        return api_version_request.is_supported(self.fake_req, '2.87')

    @ddt.data(
        exception.InstanceIsLocked(instance_uuid=uuids.instance),
        exception.InvalidVolume(reason='foo'),
    )
    @mock.patch.object(compute.api.API, 'rescue')
    def test_rescue__http_conflict_error(self, exc, mock_rescue):
        """Test that exceptions are translated into HTTP Conflict errors."""
        mock_rescue.side_effect = exc
        body = {"rescue": {"adminPass": "******"}}
        self.assertRaises(webob.exc.HTTPConflict,
                          self.controller._rescue,
                          self.fake_req,
                          UUID,
                          body=body)
        self.assertTrue(mock_rescue.called)

    @ddt.data(
        exception.OperationNotSupportedForVTPM(instance_uuid=uuids.instance,
                                               operation='foo'),
        exception.OperationNotSupportedForVDPAInterface(
            instance_uuid=uuids.instance, operation='foo'),
    )
    @mock.patch.object(compute.api.API, 'rescue')
    def test_rescue_raise_badrequest_for_not_supported_features(
            self, exc, mock_rescue):
        """Test that exceptions are translated into HTTP BadRequest errors."""
        mock_rescue.side_effect = exc
        body = {"rescue": {"adminPass": "******"}}
        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller._rescue,
                          self.fake_req,
                          UUID,
                          body=body)
        self.assertTrue(mock_rescue.called)

    def test_rescue_with_preset_password(self):
        body = {"rescue": {"adminPass": "******"}}
        resp = self.controller._rescue(self.fake_req, UUID, body=body)
        self.assertEqual("AABBCC112233", resp['adminPass'])

    def test_rescue_generates_password(self):
        body = dict(rescue=None)
        resp = self.controller._rescue(self.fake_req, UUID, body=body)
        self.assertEqual(CONF.password_length, len(resp['adminPass']))

    @mock.patch.object(compute.api.API, "rescue")
    def test_rescue_of_rescued_instance(self, mock_rescue):
        mock_rescue.side_effect = exception.InstanceInvalidState(
            'fake message')
        body = dict(rescue=None)

        self.assertRaises(webob.exc.HTTPConflict,
                          self.controller._rescue,
                          self.fake_req,
                          UUID,
                          body=body)
        self.assertTrue(mock_rescue.called)

    def test_unrescue(self):
        body = dict(unrescue=None)
        resp = self.controller._unrescue(self.fake_req, UUID, body=body)
        # NOTE: on v2.1, http status code is set as wsgi_code of API
        # method instead of status_int in a response object.
        if isinstance(self.controller, rescue_v21.RescueController):
            status_int = self.controller._unrescue.wsgi_code
        else:
            status_int = resp.status_int
        self.assertEqual(202, status_int)

    @mock.patch.object(compute.api.API, "unrescue")
    def test_unrescue_from_locked_server(self, mock_unrescue):
        mock_unrescue.side_effect = exception.InstanceIsLocked(
            instance_uuid=UUID)

        body = dict(unrescue=None)
        self.assertRaises(webob.exc.HTTPConflict,
                          self.controller._unrescue,
                          self.fake_req,
                          UUID,
                          body=body)
        self.assertTrue(mock_unrescue.called)

    @mock.patch.object(compute.api.API, "unrescue")
    def test_unrescue_of_active_instance(self, mock_unrescue):
        mock_unrescue.side_effect = exception.InstanceInvalidState(
            'fake message')
        body = dict(unrescue=None)

        self.assertRaises(webob.exc.HTTPConflict,
                          self.controller._unrescue,
                          self.fake_req,
                          UUID,
                          body=body)
        self.assertTrue(mock_unrescue.called)

    @mock.patch.object(compute.api.API, "rescue")
    def test_rescue_raises_unrescuable(self, mock_rescue):
        mock_rescue.side_effect = exception.InstanceNotRescuable(
            'fake message')
        body = dict(rescue=None)

        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller._rescue,
                          self.fake_req,
                          UUID,
                          body=body)
        self.assertTrue(mock_rescue.called)

    @mock.patch.object(
        compute.api.API,
        "rescue",
        side_effect=exception.UnsupportedRescueImage(image='fake'))
    def test_rescue_raises_unsupported_image(self, mock_rescue):
        body = dict(rescue=None)

        self.assertRaises(webob.exc.HTTPBadRequest,
                          self.controller._rescue,
                          self.fake_req,
                          UUID,
                          body=body)
        self.assertTrue(mock_rescue.called)

    def test_rescue_with_bad_image_specified(self):
        body = {
            "rescue": {
                "adminPass": "******",
                "rescue_image_ref": "img-id"
            }
        }
        self.assertRaises(exception.ValidationError,
                          self.controller._rescue,
                          self.fake_req,
                          UUID,
                          body=body)

    def test_rescue_with_imageRef_as_full_url(self):
        image_href = ('http://localhost/v2/fake/images/'
                      '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6')
        body = {
            "rescue": {
                "adminPass": "******",
                "rescue_image_ref": image_href
            }
        }
        self.assertRaises(exception.ValidationError,
                          self.controller._rescue,
                          self.fake_req,
                          UUID,
                          body=body)

    def test_rescue_with_imageRef_as_empty_string(self):
        body = {"rescue": {"adminPass": "******", "rescue_image_ref": ''}}
        self.assertRaises(exception.ValidationError,
                          self.controller._rescue,
                          self.fake_req,
                          UUID,
                          body=body)

    @mock.patch('nova.compute.api.API.rescue')
    @mock.patch('nova.api.openstack.common.get_instance')
    def test_rescue_with_image_specified(self, get_instance_mock,
                                         mock_compute_api_rescue):
        instance = fake_instance.fake_instance_obj(
            self.fake_req.environ['nova.context'])
        get_instance_mock.return_value = instance
        body = {
            "rescue": {
                "adminPass": "******",
                "rescue_image_ref": self.image_uuid
            }
        }
        resp_json = self.controller._rescue(self.fake_req, UUID, body=body)
        self.assertEqual("ABC123", resp_json['adminPass'])

        mock_compute_api_rescue.assert_called_with(
            mock.ANY,
            instance,
            rescue_password=u'ABC123',
            rescue_image_ref=self.image_uuid,
            allow_bfv_rescue=self._allow_bfv_rescue())

    @mock.patch('nova.compute.api.API.rescue')
    @mock.patch('nova.api.openstack.common.get_instance')
    def test_rescue_without_image_specified(self, get_instance_mock,
                                            mock_compute_api_rescue):
        instance = fake_instance.fake_instance_obj(
            self.fake_req.environ['nova.context'])
        get_instance_mock.return_value = instance
        body = {"rescue": {"adminPass": "******"}}

        resp_json = self.controller._rescue(self.fake_req, UUID, body=body)
        self.assertEqual("ABC123", resp_json['adminPass'])

        mock_compute_api_rescue.assert_called_with(
            mock.ANY,
            instance,
            rescue_password=u'ABC123',
            rescue_image_ref=None,
            allow_bfv_rescue=self._allow_bfv_rescue())

    def test_rescue_with_none(self):
        body = dict(rescue=None)
        resp = self.controller._rescue(self.fake_req, UUID, body=body)
        self.assertEqual(CONF.password_length, len(resp['adminPass']))

    def test_rescue_with_empty_dict(self):
        body = dict(rescue=dict())
        resp = self.controller._rescue(self.fake_req, UUID, body=body)
        self.assertEqual(CONF.password_length, len(resp['adminPass']))

    def test_rescue_disable_password(self):
        self.flags(enable_instance_password=False, group='api')
        body = dict(rescue=None)
        resp_json = self.controller._rescue(self.fake_req, UUID, body=body)
        self.assertNotIn('adminPass', resp_json)

    def test_rescue_with_invalid_property(self):
        body = {"rescue": {"test": "test"}}
        self.assertRaises(exception.ValidationError,
                          self.controller._rescue,
                          self.fake_req,
                          UUID,
                          body=body)
예제 #6
0
 def test_migrate_raise_badrequest_for_vdpainterface(self):
     exc_info = exception.OperationNotSupportedForVDPAInterface(
         instance_uuid=uuids.instance, operation='foo')
     self._test_migrate_exception(exc_info, webob.exc.HTTPBadRequest)
예제 #7
0
class InterfaceAttachTestsV21(test.NoDBTestCase):
    controller_cls = attach_interfaces_v21.InterfaceAttachmentController
    validate_exc = exception.ValidationError
    in_use_exc = exc.HTTPConflict
    not_found_exc = exc.HTTPNotFound
    not_usable_exc = exc.HTTPBadRequest

    def setUp(self):
        super(InterfaceAttachTestsV21, self).setUp()
        self.flags(timeout=30, group='neutron')
        self.stub_out('nova.compute.api.API.get', fake_get_instance)
        self.expected_show = {
            'interfaceAttachment': {
                'net_id': FAKE_NET_ID1,
                'port_id': FAKE_PORT_ID1,
                'mac_addr': port_data1['mac_address'],
                'port_state': port_data1['status'],
                'fixed_ips': port_data1['fixed_ips'],
            }
        }
        self.attachments = self.controller_cls()
        show_port_patch = mock.patch.object(self.attachments.network_api,
                                            'show_port', fake_show_port)
        show_port_patch.start()
        self.addCleanup(show_port_patch.stop)
        self.req = fakes.HTTPRequest.blank('')

    @mock.patch.object(compute_api.API,
                       'get',
                       side_effect=exception.InstanceNotFound(instance_id=''))
    def _test_instance_not_found(self, func, args, mock_get, kwargs=None):
        if not kwargs:
            kwargs = {}
        self.assertRaises(exc.HTTPNotFound, func, self.req, *args, **kwargs)

    def test_show_instance_not_found(self):
        self._test_instance_not_found(self.attachments.show, ('fake', 'fake'))

    def test_index_instance_not_found(self):
        self._test_instance_not_found(self.attachments.index, ('fake', ))

    def test_detach_interface_instance_not_found(self):
        self._test_instance_not_found(self.attachments.delete,
                                      ('fake', 'fake'))

    def test_attach_interface_instance_not_found(self):
        self._test_instance_not_found(
            self.attachments.create, ('fake', ),
            kwargs={'body': {
                'interfaceAttachment': {}
            }})

    def test_show(self):
        result = self.attachments.show(self.req, FAKE_UUID1, FAKE_PORT_ID1)
        self.assertEqual(self.expected_show, result)

    def test_show_with_port_not_found(self):
        self.assertRaises(exc.HTTPNotFound, self.attachments.show, self.req,
                          FAKE_UUID2, FAKE_PORT_ID1)

    def test_show_forbidden(self):
        with mock.patch.object(self.attachments.network_api,
                               'show_port',
                               side_effect=exception.Forbidden):
            self.assertRaises(exc.HTTPForbidden, self.attachments.show,
                              self.req, FAKE_UUID1, FAKE_PORT_ID1)

    def test_delete(self):
        self.stub_out('nova.compute.api.API.detach_interface',
                      fake_detach_interface)
        req_context = self.req.environ['nova.context']
        inst = objects.Instance(uuid=FAKE_UUID1,
                                project_id=req_context.project_id)
        with mock.patch.object(common, 'get_instance',
                               return_value=inst) as mock_get_instance:
            result = self.attachments.delete(self.req, FAKE_UUID1,
                                             FAKE_PORT_ID1)
            # NOTE: on v2.1, http status code is set as wsgi_code of API
            # method instead of status_int in a response object.
            if isinstance(self.attachments,
                          attach_interfaces_v21.InterfaceAttachmentController):
                status_int = self.attachments.delete.wsgi_code
            else:
                status_int = result.status_int
            self.assertEqual(202, status_int)
            ctxt = self.req.environ['nova.context']
            mock_get_instance.assert_called_with(
                self.attachments.compute_api,
                ctxt,
                FAKE_UUID1,
                expected_attrs=['device_metadata'])

    def test_detach_interface_instance_locked(self):
        def fake_detach_interface_from_locked_server(self, context, instance,
                                                     port_id):
            raise exception.InstanceIsLocked(instance_uuid=FAKE_UUID1)

        self.stub_out('nova.compute.api.API.detach_interface',
                      fake_detach_interface_from_locked_server)

        self.assertRaises(exc.HTTPConflict, self.attachments.delete, self.req,
                          FAKE_UUID1, FAKE_PORT_ID1)

    def test_delete_interface_not_found(self):
        self.stub_out('nova.compute.api.API.detach_interface',
                      fake_detach_interface)

        self.assertRaises(exc.HTTPNotFound, self.attachments.delete, self.req,
                          FAKE_UUID1, 'invalid-port-id')

    def test_attach_interface_instance_locked(self):
        def fake_attach_interface_to_locked_server(self,
                                                   context,
                                                   instance,
                                                   network_id,
                                                   port_id,
                                                   requested_ip,
                                                   tag=None):
            raise exception.InstanceIsLocked(instance_uuid=FAKE_UUID1)

        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface_to_locked_server)
        body = {}
        self.assertRaises(exc.HTTPConflict,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    def test_attach_interface_without_network_id(self):
        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface)
        body = {}
        result = self.attachments.create(self.req, FAKE_UUID1, body=body)
        self.assertEqual(result['interfaceAttachment']['net_id'], FAKE_NET_ID1)

    @mock.patch.object(
        compute_api.API,
        'attach_interface',
        side_effect=exception.NetworkInterfaceTaggedAttachNotSupported())
    def test_interface_tagged_attach_not_supported(self, mock_attach):
        body = {'interfaceAttachment': {'net_id': FAKE_NET_ID2}}
        self.assertRaises(exc.HTTPBadRequest,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    @mock.patch.object(
        compute_api.API,
        'attach_interface',
        side_effect=exception.OperationNotSupportedForVDPAInterface(
            instance_uuid=FAKE_UUID1, operation='foo'))
    def test_interface_vdpa_interface_not_supported(self, mock_attach):
        body = {'interfaceAttachment': {'net_id': FAKE_NET_ID2}}
        self.assertRaises(exc.HTTPBadRequest,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    @mock.patch.object(
        compute_api.API,
        'detach_interface',
        side_effect=exception.OperationNotSupportedForVDPAInterface(
            instance_uuid=FAKE_UUID1, operation='foo'))
    def test_detach_interface_vdpa_interface_not_supported(self, mock_detach):
        self.assertRaises(exc.HTTPBadRequest, self.attachments.delete,
                          self.req, FAKE_UUID1, FAKE_NET_ID1)

    def test_attach_interface_with_network_id(self):
        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface)
        body = {'interfaceAttachment': {'net_id': FAKE_NET_ID2}}
        result = self.attachments.create(self.req, FAKE_UUID1, body=body)
        self.assertEqual(result['interfaceAttachment']['net_id'], FAKE_NET_ID2)

    def _attach_interface_bad_request_case(self, body):
        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface)
        self.assertRaises(exc.HTTPBadRequest,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    def _attach_interface_not_found_case(self, body):
        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface)
        self.assertRaises(self.not_found_exc,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    def test_attach_interface_with_port_and_network_id(self):
        body = {
            'interfaceAttachment': {
                'port_id': FAKE_PORT_ID1,
                'net_id': FAKE_NET_ID2
            }
        }
        self._attach_interface_bad_request_case(body)

    def test_attach_interface_with_not_found_network_id(self):
        body = {'interfaceAttachment': {'net_id': FAKE_BAD_NET_ID}}
        self._attach_interface_not_found_case(body)

    def test_attach_interface_with_not_found_port_id(self):
        body = {'interfaceAttachment': {'port_id': FAKE_NOT_FOUND_PORT_ID}}
        self._attach_interface_not_found_case(body)

    def test_attach_interface_with_invalid_state(self):
        def fake_attach_interface_invalid_state(*args, **kwargs):
            raise exception.InstanceInvalidState(instance_uuid='',
                                                 attr='',
                                                 state='',
                                                 method='attach_interface')

        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface_invalid_state)
        body = {'interfaceAttachment': {'net_id': FAKE_NET_ID1}}
        self.assertRaises(exc.HTTPConflict,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    def test_attach_interface_port_limit_exceeded(self):
        """Tests the scenario where nova-compute attempts to create a port to
        attach but the tenant port quota is exceeded and PortLimitExceeded
        is raised from the neutron API code which results in a 403 response.
        """
        with mock.patch.object(self.attachments.compute_api,
                               'attach_interface',
                               side_effect=exception.PortLimitExceeded):
            body = {'interfaceAttachment': {}}
            ex = self.assertRaises(exc.HTTPForbidden,
                                   self.attachments.create,
                                   self.req,
                                   FAKE_UUID1,
                                   body=body)
        self.assertIn('Maximum number of ports exceeded', str(ex))

    def test_detach_interface_with_invalid_state(self):
        def fake_detach_interface_invalid_state(*args, **kwargs):
            raise exception.InstanceInvalidState(instance_uuid='',
                                                 attr='',
                                                 state='',
                                                 method='detach_interface')

        self.stub_out('nova.compute.api.API.detach_interface',
                      fake_detach_interface_invalid_state)
        self.assertRaises(exc.HTTPConflict, self.attachments.delete, self.req,
                          FAKE_UUID1, FAKE_NET_ID1)

    @mock.patch.object(compute_api.API,
                       'detach_interface',
                       side_effect=NotImplementedError())
    def test_detach_interface_with_not_implemented(self, _mock):
        self.assertRaises(exc.HTTPNotImplemented, self.attachments.delete,
                          self.req, FAKE_UUID1, FAKE_NET_ID1)

    def test_attach_interface_invalid_fixed_ip(self):
        body = {
            'interfaceAttachment': {
                'net_id': FAKE_NET_ID1,
                'fixed_ips': [{
                    'ip_address': 'invalid_ip'
                }]
            }
        }
        self.assertRaises(self.validate_exc,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_fixed_ip_already_in_use(self, attach_mock,
                                                      get_mock):
        req_context = self.req.environ['nova.context']
        fake_instance = objects.Instance(uuid=FAKE_UUID1,
                                         project_id=req_context.project_id)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = exception.FixedIpAlreadyInUse(
            address='10.0.2.2', instance_uuid=FAKE_UUID1)
        body = {}
        self.assertRaises(self.in_use_exc,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_port_in_use(self, attach_mock, get_mock):
        req_context = self.req.environ['nova.context']
        fake_instance = objects.Instance(uuid=FAKE_UUID1,
                                         project_id=req_context.project_id)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = exception.PortInUse(port_id=FAKE_PORT_ID1)
        body = {}
        self.assertRaises(self.in_use_exc,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_port_not_usable(self, attach_mock, get_mock):
        req_context = self.req.environ['nova.context']
        fake_instance = objects.Instance(uuid=FAKE_UUID1,
                                         project_id=req_context.project_id)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = exception.PortNotUsable(
            port_id=FAKE_PORT_ID1, instance=fake_instance.uuid)
        body = {}
        self.assertRaises(self.not_usable_exc,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_failed_no_network(self, attach_mock, get_mock):
        req_context = self.req.environ['nova.context']
        fake_instance = objects.Instance(uuid=FAKE_UUID1,
                                         project_id=req_context.project_id)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = (exception.InterfaceAttachFailedNoNetwork(
            project_id=FAKE_UUID2))
        self.assertRaises(exc.HTTPBadRequest,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body={})
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_no_more_fixed_ips(self, attach_mock, get_mock):
        req_context = self.req.environ['nova.context']
        fake_instance = objects.Instance(uuid=FAKE_UUID1,
                                         project_id=req_context.project_id)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = exception.NoMoreFixedIps(net=FAKE_NET_ID1)
        body = {}
        self.assertRaises(exc.HTTPBadRequest,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_failed_securitygroup_cannot_be_applied(
            self, attach_mock, get_mock):
        req_context = self.req.environ['nova.context']
        fake_instance = objects.Instance(uuid=FAKE_UUID1,
                                         project_id=req_context.project_id)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = (exception.SecurityGroupCannotBeApplied())
        self.assertRaises(exc.HTTPBadRequest,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body={})
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    def _test_attach_interface_with_invalid_parameter(self, param):
        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface)
        body = {'interface_attachment': param}
        self.assertRaises(exception.ValidationError,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    def test_attach_interface_instance_with_non_uuid_net_id(self):
        param = {'net_id': 'non_uuid'}
        self._test_attach_interface_with_invalid_parameter(param)

    def test_attach_interface_instance_with_non_uuid_port_id(self):
        param = {'port_id': 'non_uuid'}
        self._test_attach_interface_with_invalid_parameter(param)

    def test_attach_interface_instance_with_non_array_fixed_ips(self):
        param = {'fixed_ips': 'non_array'}
        self._test_attach_interface_with_invalid_parameter(param)