コード例 #1
0
    def test_update_not_found(self):
        share_nw = 'fake network id'
        db_api.share_network_get.side_effect = exception.ShareNetworkNotFound(
            share_network_id=share_nw)

        self.assertRaises(webob_exc.HTTPNotFound, self.controller.update,
                          self.req, share_nw, self.body)
コード例 #2
0
    def test_share_server_migration_check_exception(self, exception_to_raise,
                                                    raise_server_get_exception,
                                                    raise_network_get_action,
                                                    body):
        req = self._get_server_migration_request('fake_id')
        context = req.environ['manila.context']
        if body:
            body['migration_check']['writable'] = False
            body['migration_check']['nondisruptive'] = False
            body['migration_check']['preserve_snapshots'] = False
            body['migration_check']['host'] = 'fakehost@fakebackend'
        else:
            body = {}

        server_get = mock.Mock()
        network_get = mock.Mock()
        if raise_server_get_exception:
            server_get = mock.Mock(side_effect=exception.ShareServerNotFound(
                share_server_id='fake'))
        if raise_network_get_action:
            network_get = mock.Mock(side_effect=exception.ShareNetworkNotFound(
                share_network_id='fake'))

        mock_server_get = self.mock_object(db_api, 'share_server_get',
                                           server_get)

        mock_network_get = self.mock_object(db_api, 'share_network_get',
                                            network_get)

        self.assertRaises(exception_to_raise,
                          self.controller.share_server_migration_check, req,
                          'fake_id', body)
        mock_server_get.assert_called_once_with(context, 'fake_id')
        if raise_network_get_action:
            mock_network_get.assert_called_once_with(context, 'fake_id')
コード例 #3
0
 def test_show_not_found(self):
     share_nw = 'fake network id'
     test_exception = exception.ShareNetworkNotFound(
         share_network_id=share_nw)
     with mock.patch.object(db_api, 'share_network_get',
                            mock.Mock(side_effect=test_exception)):
         self.assertRaises(webob_exc.HTTPNotFound, self.controller.show,
                           self.req, share_nw)
コード例 #4
0
    def test_delete_not_found(self):
        share_nw = 'fake network id'
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=exception.ShareNetworkNotFound(
                share_network_id=share_nw)))

        self.assertRaises(webob_exc.HTTPNotFound, self.controller.delete,
                          self.req, share_nw)
コード例 #5
0
    def test_list_subnet_share_network_not_found(self):
        req = fakes.HTTPRequest.blank('/subnets/', version="2.51")
        context = req.environ['manila.context']

        mock_sn_get = self.mock_object(
            db_api, 'share_network_get', mock.Mock(
                side_effect=exception.ShareNetworkNotFound(
                    share_network_id=self.share_network['id'])))

        self.assertRaises(exc.HTTPNotFound,
                          self.controller.index,
                          req,
                          self.share_network['id'])
        mock_sn_get.assert_called_once_with(context, self.share_network['id'])
コード例 #6
0
    def test__validate_manage_share_server_share_network_not_found(self):
        req = fakes.HTTPRequest.blank('/manage', version="2.49")
        context = req.environ['manila.context']
        self.mock_object(utils, 'validate_service_host')
        error = mock.Mock(side_effect=exception.ShareNetworkNotFound(
            share_network_id="foo"))
        self.mock_object(db_api, 'share_network_get', error)
        body = self._setup_manage_test_request_body()

        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.manage,
                          req, {'share_server': body})

        policy.check_policy.assert_called_once_with(context,
                                                    self.resource_name,
                                                    'manage_share_server')
コード例 #7
0
ファイル: test_share_servers.py プロジェクト: viroel/manila
    def test_index_share_network_not_found_filter_project(self):
        request, ctxt = self._prepare_request(
            url='/index?project_id=%s' %
            fake_share_server_get_all()[0].project_id,
            use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=exception.ShareNetworkNotFound(
                share_network_id='fake')))

        result = self.controller.index(request)
        db_api.share_server_get_all.assert_called_once_with(ctxt)
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'index')
        self.assertEqual(0, len(result['share_servers']))
コード例 #8
0
ファイル: test_share_servers.py プロジェクト: viroel/manila
    def test_index_share_network_not_found(self):
        request, ctxt = self._prepare_request(
            url='/index?identifier=%s' %
            fake_share_server_get_all()[0].identifier,
            use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=exception.ShareNetworkNotFound(
                share_network_id='fake')))

        result = self.controller.index(request)
        db_api.share_server_get_all.assert_called_once_with(ctxt)
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'index')
        exp_share_server = fake_share_server_list['share_servers'][0].copy()
        exp_share_server['project_id'] = ''
        exp_share_server['share_network_name'] = ''
        self.assertEqual([exp_share_server], result['share_servers'])
コード例 #9
0
    def test_subnet_create_share_network_not_found(self):
        fake_sn_id = 'fake_id'
        req = fakes.HTTPRequest.blank('/subnets', version="2.51")
        context = req.environ['manila.context']
        body = {
            'share-network-subnet': self._setup_create_test_request_body()
        }
        mock_sn_get = self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=exception.ShareNetworkNotFound(
                share_network_id=fake_sn_id)))

        self.assertRaises(exc.HTTPNotFound,
                          self.controller.create,
                          req,
                          fake_sn_id,
                          body)
        mock_sn_get.assert_called_once_with(context, fake_sn_id)
コード例 #10
0
    def test_share_network_subnet_delete_network_not_found(self):
        req = fakes.HTTPRequest.blank('/subnets/%s' % self.subnet['id'],
                                      version="2.51")
        context = req.environ['manila.context']

        mock_sn_get = self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=exception.ShareNetworkNotFound(
                share_network_id=self.share_network['id']
            )))

        self.assertRaises(exc.HTTPNotFound,
                          self.controller.delete,
                          req,
                          self.share_network['id'],
                          self.subnet['id'])
        mock_sn_get.assert_called_once_with(
            context, self.share_network['id'])
        self.mock_policy_check.assert_called_once_with(
            context, self.resource_name, 'delete')
コード例 #11
0
 def test_share_network_not_found(self):
     # Verify response code for exception.ShareNetworkNotFound
     share_network_id = "fake_share_network_id"
     e = exception.ShareNetworkNotFound(share_network_id=share_network_id)
     self.assertEqual(404, e.code)
     self.assertIn(share_network_id, e.msg)
コード例 #12
0
ファイル: test_share_servers.py プロジェクト: viroel/manila
class ShareServerAPITest(test.TestCase):
    def setUp(self):
        super(ShareServerAPITest, self).setUp()
        self.controller = share_servers.ShareServerController()
        self.resource_name = self.controller.resource_name
        self.mock_object(policy, 'check_policy', mock.Mock(return_value=True))
        self.mock_object(db_api, 'share_server_get_all',
                         mock.Mock(return_value=fake_share_server_get_all()))

    def _prepare_request(self,
                         url,
                         use_admin_context,
                         version=api_version._MAX_API_VERSION):
        request = fakes.HTTPRequest.blank(url,
                                          use_admin_context=use_admin_context,
                                          version=version)
        ctxt = request.environ['manila.context']
        return request, ctxt

    def test_index_no_filters(self):
        request, ctxt = self._prepare_request(url='/v2/share-servers/',
                                              use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=[
                fake_share_network_get_list['share_networks'][0],
                fake_share_network_get_list['share_networks'][1]
            ]))
        result = self.controller.index(request)
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'index')
        db_api.share_server_get_all.assert_called_once_with(ctxt)
        self.assertEqual(fake_share_server_list, result)

    def test_index_host_filter(self):
        request, ctxt = self._prepare_request(
            url='/index?host=%s' %
            fake_share_server_list['share_servers'][0]['host'],
            use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=[
                fake_share_network_get_list['share_networks'][0],
                fake_share_network_get_list['share_networks'][1]
            ]))
        result = self.controller.index(request)
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'index')
        db_api.share_server_get_all.assert_called_once_with(ctxt)
        self.assertEqual([fake_share_server_list['share_servers'][0]],
                         result['share_servers'])

    def test_index_status_filter(self):
        request, ctxt = self._prepare_request(url='/index?status=%s' %
                                              constants.STATUS_ERROR,
                                              use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=[
                fake_share_network_get_list['share_networks'][0],
                fake_share_network_get_list['share_networks'][1]
            ]))
        result = self.controller.index(request)
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'index')
        db_api.share_server_get_all.assert_called_once_with(ctxt)
        self.assertEqual([fake_share_server_list['share_servers'][1]],
                         result['share_servers'])

    def test_index_project_id_filter(self):
        request, ctxt = self._prepare_request(
            url='/index?project_id=%s' %
            fake_share_server_get_all()[0].project_id,
            use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=[
                fake_share_network_get_list['share_networks'][0],
                fake_share_network_get_list['share_networks'][1]
            ]))
        result = self.controller.index(request)
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'index')
        db_api.share_server_get_all.assert_called_once_with(ctxt)

        self.assertEqual([fake_share_server_list['share_servers'][0]],
                         result['share_servers'])

    def test_index_share_network_filter_by_name(self):
        request, ctxt = self._prepare_request(
            url='/index?host=%s' %
            fake_share_server_list['share_servers'][0]['host'],
            use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=[
                fake_share_network_get_list['share_networks'][0],
                fake_share_network_get_list['share_networks'][1]
            ]))
        result = self.controller.index(request)
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'index')
        db_api.share_server_get_all.assert_called_once_with(ctxt)
        self.assertEqual([fake_share_server_list['share_servers'][0]],
                         result['share_servers'])

    def test_index_share_network_filter_by_id(self):
        request, ctxt = self._prepare_request(
            url='/index?share_network=%s' %
            fake_share_network_get_list['share_networks'][0]['id'],
            use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=[
                fake_share_network_get_list['share_networks'][0],
                fake_share_network_get_list['share_networks'][1]
            ]))
        result = self.controller.index(request)
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'index')
        db_api.share_server_get_all.assert_called_once_with(ctxt)
        self.assertEqual([fake_share_server_list['share_servers'][0]],
                         result['share_servers'])

    def test_index_fake_filter(self):
        request, ctxt = self._prepare_request(url='/index?fake_key=fake_value',
                                              use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=[
                fake_share_network_get_list['share_networks'][0],
                fake_share_network_get_list['share_networks'][1]
            ]))
        result = self.controller.index(request)
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'index')
        db_api.share_server_get_all.assert_called_once_with(ctxt)
        self.assertEqual(0, len(result['share_servers']))

    def test_index_share_network_not_found(self):
        request, ctxt = self._prepare_request(
            url='/index?identifier=%s' %
            fake_share_server_get_all()[0].identifier,
            use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=exception.ShareNetworkNotFound(
                share_network_id='fake')))

        result = self.controller.index(request)
        db_api.share_server_get_all.assert_called_once_with(ctxt)
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'index')
        exp_share_server = fake_share_server_list['share_servers'][0].copy()
        exp_share_server['project_id'] = ''
        exp_share_server['share_network_name'] = ''
        self.assertEqual([exp_share_server], result['share_servers'])

    def test_index_share_network_not_found_filter_project(self):
        request, ctxt = self._prepare_request(
            url='/index?project_id=%s' %
            fake_share_server_get_all()[0].project_id,
            use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=exception.ShareNetworkNotFound(
                share_network_id='fake')))

        result = self.controller.index(request)
        db_api.share_server_get_all.assert_called_once_with(ctxt)
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'index')
        self.assertEqual(0, len(result['share_servers']))

    def test_show(self):
        self.mock_object(db_api, 'share_server_get',
                         mock.Mock(return_value=fake_share_server_get()))
        request, ctxt = self._prepare_request('/show', use_admin_context=True)
        self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(
                return_value=fake_share_network_get_list['share_networks'][0]))
        result = self.controller.show(
            request, fake_share_server_get_result['share_server']['id'])
        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'show')
        db_api.share_server_get.assert_called_once_with(
            ctxt, fake_share_server_get_result['share_server']['id'])
        self.assertEqual(fake_share_server_get_result['share_server'],
                         result['share_server'])

    @ddt.data(
        {
            'share_server_side_effect':
            exception.ShareServerNotFound(share_server_id="foo"),
            'share_net_side_effect':
            mock.Mock()
        }, {
            'share_server_side_effect':
            mock.Mock(return_value=fake_share_server_get()),
            'share_net_side_effect':
            exception.ShareNetworkNotFound(share_network_id="foo")
        })
    @ddt.unpack
    def test_show_server_not_found(self, share_server_side_effect,
                                   share_net_side_effect):
        self.mock_object(db_api, 'share_server_get',
                         mock.Mock(side_effect=share_server_side_effect))
        request, ctxt = self._prepare_request('/show', use_admin_context=True)
        self.mock_object(db_api, 'share_network_get',
                         mock.Mock(side_effect=share_net_side_effect))
        self.assertRaises(exc.HTTPNotFound, self.controller.show, request,
                          fake_share_server_get_result['share_server']['id'])

        policy.check_policy.assert_called_once_with(ctxt, self.resource_name,
                                                    'show')
        db_api.share_server_get.assert_called_once_with(
            ctxt, fake_share_server_get_result['share_server']['id'])
        if isinstance(share_net_side_effect, exception.ShareNetworkNotFound):
            exp_share_net_id = (fake_share_server_get().
                                share_network_subnet['share_network_id'])
            db_api.share_network_get.assert_called_once_with(
                ctxt, exp_share_net_id)

    def test_details(self):
        self.mock_object(db_api, 'share_server_get',
                         mock.Mock(return_value=fake_share_server_get()))
        result = self.controller.details(
            FakeRequestAdmin,
            fake_share_server_get_result['share_server']['id'])
        policy.check_policy.assert_called_once_with(CONTEXT,
                                                    self.resource_name,
                                                    'details')
        db_api.share_server_get.assert_called_once_with(
            CONTEXT, fake_share_server_get_result['share_server']['id'])
        self.assertEqual(fake_share_server_backend_details_get_result, result)

    def test_details_share_server_not_found(self):
        share_server_id = 'fake'
        self.mock_object(
            db_api, 'share_server_get',
            mock.Mock(side_effect=exception.ShareServerNotFound(
                share_server_id=share_server_id)))
        self.assertRaises(exc.HTTPNotFound, self.controller.details,
                          FakeRequestAdmin, share_server_id)
        policy.check_policy.assert_called_once_with(CONTEXT,
                                                    self.resource_name,
                                                    'details')
        db_api.share_server_get.assert_called_once_with(
            CONTEXT, share_server_id)

    def test_delete_active_server(self):
        share_server = FakeShareServer(status=constants.STATUS_ACTIVE)
        self.mock_object(db_api, 'share_server_get',
                         mock.Mock(return_value=share_server))
        self.mock_object(self.controller.share_api, 'delete_share_server')
        self.controller.delete(
            FakeRequestAdmin,
            fake_share_server_get_result['share_server']['id'])
        policy.check_policy.assert_called_once_with(CONTEXT,
                                                    self.resource_name,
                                                    'delete')
        db_api.share_server_get.assert_called_once_with(
            CONTEXT, fake_share_server_get_result['share_server']['id'])
        self.controller.share_api.delete_share_server.assert_called_once_with(
            CONTEXT, share_server)

    def test_delete_error_server(self):
        share_server = FakeShareServer(status=constants.STATUS_ERROR)
        self.mock_object(db_api, 'share_server_get',
                         mock.Mock(return_value=share_server))
        self.mock_object(self.controller.share_api, 'delete_share_server')
        self.controller.delete(
            FakeRequestAdmin,
            fake_share_server_get_result['share_server']['id'])
        policy.check_policy.assert_called_once_with(CONTEXT,
                                                    self.resource_name,
                                                    'delete')
        db_api.share_server_get.assert_called_once_with(
            CONTEXT, fake_share_server_get_result['share_server']['id'])
        self.controller.share_api.delete_share_server.assert_called_once_with(
            CONTEXT, share_server)

    def test_delete_used_server(self):
        share_server_id = fake_share_server_get_result['share_server']['id']

        def raise_not_share_server_in_use(*args, **kwargs):
            raise exception.ShareServerInUse(share_server_id=share_server_id)

        share_server = fake_share_server_get()
        self.mock_object(db_api, 'share_server_get',
                         mock.Mock(return_value=share_server))
        self.mock_object(self.controller.share_api, 'delete_share_server',
                         mock.Mock(side_effect=raise_not_share_server_in_use))
        self.assertRaises(exc.HTTPConflict, self.controller.delete,
                          FakeRequestAdmin, share_server_id)
        db_api.share_server_get.assert_called_once_with(
            CONTEXT, share_server_id)
        self.controller.share_api.delete_share_server.assert_called_once_with(
            CONTEXT, share_server)

    def test_delete_not_found(self):
        share_server_id = fake_share_server_get_result['share_server']['id']

        def raise_not_found(*args, **kwargs):
            raise exception.ShareServerNotFound(
                share_server_id=share_server_id)

        self.mock_object(db_api, 'share_server_get',
                         mock.Mock(side_effect=raise_not_found))
        self.assertRaises(exc.HTTPNotFound, self.controller.delete,
                          FakeRequestAdmin, share_server_id)
        db_api.share_server_get.assert_called_once_with(
            CONTEXT, share_server_id)
        policy.check_policy.assert_called_once_with(CONTEXT,
                                                    self.resource_name,
                                                    'delete')

    def test_delete_creating_server(self):
        share_server = FakeShareServer(status=constants.STATUS_CREATING)
        self.mock_object(db_api, 'share_server_get',
                         mock.Mock(return_value=share_server))
        self.assertRaises(exc.HTTPForbidden, self.controller.delete,
                          FakeRequestAdmin, share_server['id'])
        policy.check_policy.assert_called_once_with(CONTEXT,
                                                    self.resource_name,
                                                    'delete')

    def test_delete_deleting_server(self):
        share_server = FakeShareServer(status=constants.STATUS_DELETING)
        self.mock_object(db_api, 'share_server_get',
                         mock.Mock(return_value=share_server))
        self.assertRaises(exc.HTTPForbidden, self.controller.delete,
                          FakeRequestAdmin, share_server['id'])
        policy.check_policy.assert_called_once_with(CONTEXT,
                                                    self.resource_name,
                                                    'delete')
コード例 #13
0
ファイル: test_shares.py プロジェクト: yongwc09/manila
class ShareAPITest(test.TestCase):
    """Share API Test."""
    def setUp(self):
        super(ShareAPITest, self).setUp()
        self.controller = shares.ShareController()
        self.mock_object(db, 'availability_zone_get')
        self.mock_object(share_api.API, 'get_all', stubs.stub_get_all_shares)
        self.mock_object(share_api.API, 'get', stubs.stub_share_get)
        self.mock_object(share_api.API, 'update', stubs.stub_share_update)
        self.mock_object(share_api.API, 'delete', stubs.stub_share_delete)
        self.mock_object(share_api.API, 'get_snapshot',
                         stubs.stub_snapshot_get)
        self.mock_object(share_types, 'get_share_type',
                         stubs.stub_share_type_get)
        self.mock_object(
            common, 'validate_public_share_policy',
            mock.Mock(side_effect=lambda *args, **kwargs: args[1]))
        self.resource_name = self.controller.resource_name
        self.mock_policy_check = self.mock_object(policy, 'check_policy')
        self.maxDiff = None
        self.share = {
            "size": 100,
            "display_name": "Share Test Name",
            "display_description": "Share Test Desc",
            "share_proto": "fakeproto",
            "availability_zone": "zone1:host1",
            "is_public": False,
        }
        self.create_mock = mock.Mock(return_value=stubs.stub_share(
            '1',
            display_name=self.share['display_name'],
            display_description=self.share['display_description'],
            size=100,
            share_proto=self.share['share_proto'].upper(),
            availability_zone=self.share['availability_zone']))
        self.vt = {
            'id': 'fake_volume_type_id',
            'name': 'fake_volume_type_name',
            'required_extra_specs': {
                'driver_handles_share_servers': 'False'
            },
            'extra_specs': {
                'driver_handles_share_servers': 'False'
            }
        }

        CONF.set_default("default_share_type", None)

    def _get_expected_share_detailed_response(self, values=None, admin=False):
        share = {
            'id':
            '1',
            'name':
            'displayname',
            'availability_zone':
            'fakeaz',
            'description':
            'displaydesc',
            'export_location':
            'fake_location',
            'export_locations': ['fake_location', 'fake_location2'],
            'project_id':
            'fakeproject',
            'created_at':
            datetime.datetime(1, 1, 1, 1, 1, 1),
            'share_proto':
            'FAKEPROTO',
            'metadata': {},
            'size':
            1,
            'snapshot_id':
            '2',
            'share_network_id':
            None,
            'status':
            'fakestatus',
            'share_type':
            '1',
            'volume_type':
            '1',
            'snapshot_support':
            True,
            'is_public':
            False,
            'links': [{
                'href': 'http://localhost/v1/fake/shares/1',
                'rel': 'self'
            }, {
                'href': 'http://localhost/fake/shares/1',
                'rel': 'bookmark'
            }],
        }
        if values:
            if 'display_name' in values:
                values['name'] = values.pop('display_name')
            if 'display_description' in values:
                values['description'] = values.pop('display_description')
            share.update(values)
        if share.get('share_proto'):
            share['share_proto'] = share['share_proto'].upper()
        if admin:
            share['share_server_id'] = 'fake_share_server_id'
            share['host'] = 'fakehost'
        return {'share': share}

    @ddt.data("1.0", "2.0", "2.1")
    def test_share_create_original(self, microversion):
        self.mock_object(share_api.API, 'create', self.create_mock)
        body = {"share": copy.deepcopy(self.share)}
        req = fakes.HTTPRequest.blank('/shares', version=microversion)

        res_dict = self.controller.create(req, body)

        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')
        expected = self._get_expected_share_detailed_response(self.share)
        expected['share'].pop('snapshot_support')
        self.assertEqual(expected, res_dict)

    @ddt.data("2.2", "2.3")
    def test_share_create_with_snapshot_support_without_cg(self, microversion):
        self.mock_object(share_api.API, 'create', self.create_mock)
        body = {"share": copy.deepcopy(self.share)}
        req = fakes.HTTPRequest.blank('/shares', version=microversion)

        res_dict = self.controller.create(req, body)

        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')
        expected = self._get_expected_share_detailed_response(self.share)
        self.assertEqual(expected, res_dict)

    def test_share_create_with_valid_default_share_type(self):
        self.mock_object(share_types, 'get_share_type_by_name',
                         mock.Mock(return_value=self.vt))
        CONF.set_default("default_share_type", self.vt['name'])
        self.mock_object(share_api.API, 'create', self.create_mock)

        body = {"share": copy.deepcopy(self.share)}
        req = fakes.HTTPRequest.blank('/shares')
        res_dict = self.controller.create(req, body)

        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')
        expected = self._get_expected_share_detailed_response(self.share)
        expected['share'].pop('snapshot_support')
        share_types.get_share_type_by_name.assert_called_once_with(
            utils.IsAMatcher(context.RequestContext), self.vt['name'])
        self.assertEqual(expected, res_dict)

    def test_share_create_with_invalid_default_share_type(self):
        self.mock_object(
            share_types,
            'get_default_share_type',
            mock.Mock(side_effect=exception.ShareTypeNotFoundByName(
                self.vt['name'])),
        )
        CONF.set_default("default_share_type", self.vt['name'])
        req = fakes.HTTPRequest.blank('/shares')

        self.assertRaises(exception.ShareTypeNotFoundByName,
                          self.controller.create, req, {'share': self.share})
        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')
        share_types.get_default_share_type.assert_called_once_with()

    def test_share_create_with_dhss_true_and_network_notexist(self):
        fake_share_type = {
            'id': 'fake_volume_type_id',
            'name': 'fake_volume_type_name',
            'extra_specs': {
                'driver_handles_share_servers': True,
            }
        }
        self.mock_object(
            share_types,
            'get_default_share_type',
            mock.Mock(return_value=fake_share_type),
        )
        CONF.set_default("default_share_type", fake_share_type['name'])
        req = fakes.HTTPRequest.blank('/shares')

        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create,
                          req, {'share': self.share})
        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')
        share_types.get_default_share_type.assert_called_once_with()

    def test_share_create_with_share_net(self):
        shr = {
            "size": 100,
            "name": "Share Test Name",
            "description": "Share Test Desc",
            "share_proto": "fakeproto",
            "availability_zone": "zone1:host1",
            "share_network_id": "fakenetid"
        }
        create_mock = mock.Mock(return_value=stubs.stub_share(
            '1',
            display_name=shr['name'],
            display_description=shr['description'],
            size=shr['size'],
            share_proto=shr['share_proto'].upper(),
            availability_zone=shr['availability_zone'],
            share_network_id=shr['share_network_id']))
        self.mock_object(share_api.API, 'create', create_mock)
        self.mock_object(share_api.API, 'get_share_network',
                         mock.Mock(return_value={'id': 'fakenetid'}))
        self.mock_object(db,
                         'share_network_subnet_get_by_availability_zone_id',
                         mock.Mock(return_value={'id': 'fakesubnetid'}))

        body = {"share": copy.deepcopy(shr)}
        req = fakes.HTTPRequest.blank('/shares')
        res_dict = self.controller.create(req, body)

        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')
        expected = self._get_expected_share_detailed_response(shr)
        expected['share'].pop('snapshot_support')
        self.assertEqual(expected, res_dict)
        # pylint: disable=unsubscriptable-object
        self.assertEqual("fakenetid",
                         create_mock.call_args[1]['share_network_id'])

    def test_share_create_from_snapshot_without_share_net_no_parent(self):
        shr = {
            "size": 100,
            "name": "Share Test Name",
            "description": "Share Test Desc",
            "share_proto": "fakeproto",
            "availability_zone": "zone1:host1",
            "snapshot_id": 333,
            "share_network_id": None,
        }
        create_mock = mock.Mock(return_value=stubs.stub_share(
            '1',
            display_name=shr['name'],
            display_description=shr['description'],
            size=shr['size'],
            share_proto=shr['share_proto'].upper(),
            availability_zone=shr['availability_zone'],
            snapshot_id=shr['snapshot_id'],
            share_network_id=shr['share_network_id']))
        self.mock_object(share_api.API, 'create', create_mock)
        body = {"share": copy.deepcopy(shr)}
        req = fakes.HTTPRequest.blank('/shares')

        res_dict = self.controller.create(req, body)

        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')
        expected = self._get_expected_share_detailed_response(shr)
        expected['share'].pop('snapshot_support')
        self.assertEqual(expected, res_dict)

    def test_share_create_from_snapshot_without_share_net_parent_exists(self):
        shr = {
            "size": 100,
            "name": "Share Test Name",
            "description": "Share Test Desc",
            "share_proto": "fakeproto",
            "availability_zone": "zone1:host1",
            "snapshot_id": 333,
            "share_network_id": None,
        }
        parent_share_net = 444
        create_mock = mock.Mock(return_value=stubs.stub_share(
            '1',
            display_name=shr['name'],
            display_description=shr['description'],
            size=shr['size'],
            share_proto=shr['share_proto'].upper(),
            snapshot_id=shr['snapshot_id'],
            instance=dict(availability_zone=shr['availability_zone'],
                          share_network_id=shr['share_network_id'])))
        self.mock_object(share_api.API, 'create', create_mock)
        self.mock_object(share_api.API, 'get_snapshot',
                         stubs.stub_snapshot_get)
        parent_share = stubs.stub_share(
            '1',
            instance={'share_network_id': parent_share_net},
            create_share_from_snapshot_support=True)
        self.mock_object(share_api.API, 'get',
                         mock.Mock(return_value=parent_share))
        self.mock_object(share_api.API, 'get_share_network',
                         mock.Mock(return_value={'id': parent_share_net}))
        self.mock_object(db,
                         'share_network_subnet_get_by_availability_zone_id')

        body = {"share": copy.deepcopy(shr)}
        req = fakes.HTTPRequest.blank('/shares')

        res_dict = self.controller.create(req, body)

        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')
        expected = self._get_expected_share_detailed_response(shr)
        expected['share'].pop('snapshot_support')
        self.assertEqual(expected, res_dict)
        # pylint: disable=unsubscriptable-object
        self.assertEqual(parent_share_net,
                         create_mock.call_args[1]['share_network_id'])

    def test_share_create_from_snapshot_with_share_net_equals_parent(self):
        parent_share_net = 444
        shr = {
            "size": 100,
            "name": "Share Test Name",
            "description": "Share Test Desc",
            "share_proto": "fakeproto",
            "availability_zone": "zone1:host1",
            "snapshot_id": 333,
            "share_network_id": parent_share_net
        }
        create_mock = mock.Mock(return_value=stubs.stub_share(
            '1',
            display_name=shr['name'],
            display_description=shr['description'],
            size=shr['size'],
            share_proto=shr['share_proto'].upper(),
            snapshot_id=shr['snapshot_id'],
            instance=dict(availability_zone=shr['availability_zone'],
                          share_network_id=shr['share_network_id'])))
        self.mock_object(share_api.API, 'create', create_mock)
        self.mock_object(share_api.API, 'get_snapshot',
                         stubs.stub_snapshot_get)
        parent_share = stubs.stub_share(
            '1',
            instance={'share_network_id': parent_share_net},
            create_share_from_snapshot_support=True)
        self.mock_object(share_api.API, 'get',
                         mock.Mock(return_value=parent_share))
        self.mock_object(share_api.API, 'get_share_network',
                         mock.Mock(return_value={'id': parent_share_net}))
        self.mock_object(db,
                         'share_network_subnet_get_by_availability_zone_id')

        body = {"share": copy.deepcopy(shr)}
        req = fakes.HTTPRequest.blank('/shares')

        res_dict = self.controller.create(req, body)

        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')
        expected = self._get_expected_share_detailed_response(shr)
        expected['share'].pop('snapshot_support')
        self.assertEqual(expected, res_dict)
        # pylint: disable=unsubscriptable-object
        self.assertEqual(parent_share_net,
                         create_mock.call_args[1]['share_network_id'])

    def test_share_create_from_snapshot_invalid_share_net(self):
        self.mock_object(share_api.API, 'create')
        shr = {
            "size": 100,
            "name": "Share Test Name",
            "description": "Share Test Desc",
            "share_proto": "fakeproto",
            "availability_zone": "zone1:host1",
            "snapshot_id": 333,
            "share_network_id": 1234
        }
        body = {"share": shr}
        req = fakes.HTTPRequest.blank('/shares')

        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create,
                          req, body)
        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')

    @ddt.data("1.0", "2.0")
    def test_share_create_from_snapshot_not_supported(self, microversion):
        # This create operation should work, because the 1.0 API doesn't check
        # create_share_from_snapshot_support.

        parent_share_net = 444
        shr = {
            "size": 100,
            "name": "Share Test Name",
            "description": "Share Test Desc",
            "share_proto": "fakeproto",
            "availability_zone": "zone1:host1",
            "snapshot_id": 333,
            "share_network_id": parent_share_net
        }
        create_mock = mock.Mock(return_value=stubs.stub_share(
            '1',
            display_name=shr['name'],
            display_description=shr['description'],
            size=shr['size'],
            share_proto=shr['share_proto'].upper(),
            snapshot_id=shr['snapshot_id'],
            instance=dict(availability_zone=shr['availability_zone'],
                          share_network_id=shr['share_network_id'])))
        self.mock_object(share_api.API, 'create', create_mock)
        self.mock_object(share_api.API, 'get_snapshot',
                         stubs.stub_snapshot_get)
        parent_share = stubs.stub_share(
            '1',
            instance={'share_network_id': parent_share_net},
            create_share_from_snapshot_support=False)
        self.mock_object(share_api.API, 'get',
                         mock.Mock(return_value=parent_share))
        self.mock_object(share_api.API, 'get_share_network',
                         mock.Mock(return_value={'id': parent_share_net}))
        self.mock_object(db,
                         'share_network_subnet_get_by_availability_zone_id')

        body = {"share": copy.deepcopy(shr)}
        req = fakes.HTTPRequest.blank('/shares', version=microversion)

        res_dict = self.controller.create(req, body)

        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')
        expected = self._get_expected_share_detailed_response(shr)
        expected['share'].pop('snapshot_support')
        self.assertDictEqual(expected, res_dict)
        # pylint: disable=unsubscriptable-object
        self.assertEqual(parent_share_net,
                         create_mock.call_args[1]['share_network_id'])

    def test_share_creation_fails_with_bad_size(self):
        shr = {
            "size": '',
            "name": "Share Test Name",
            "description": "Share Test Desc",
            "share_proto": "fakeproto",
            "availability_zone": "zone1:host1"
        }
        body = {"share": shr}
        req = fakes.HTTPRequest.blank('/shares')
        self.assertRaises(exception.InvalidInput, self.controller.create, req,
                          body)
        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')

    def test_share_create_no_body(self):
        body = {}
        req = fakes.HTTPRequest.blank('/shares')
        self.assertRaises(webob.exc.HTTPUnprocessableEntity,
                          self.controller.create, req, body)
        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'create')

    def test_share_create_invalid_availability_zone(self):
        self.mock_object(
            db, 'availability_zone_get',
            mock.Mock(side_effect=exception.AvailabilityZoneNotFound(id='id')))
        body = {"share": copy.deepcopy(self.share)}

        req = fakes.HTTPRequest.blank('/shares')
        self.assertRaises(webob.exc.HTTPNotFound, self.controller.create, req,
                          body)

    @ddt.data((exception.ShareNetworkNotFound(share_network_id='fake'),
               webob.exc.HTTPNotFound),
              (mock.Mock(), webob.exc.HTTPBadRequest))
    @ddt.unpack
    def test_share_create_invalid_subnet(self, share_network_side_effect,
                                         exception_to_raise):
        fake_share_with_sn = copy.deepcopy(self.share)
        fake_share_with_sn['share_network_id'] = 'fakenetid'
        self.mock_object(db, 'share_network_get',
                         mock.Mock(side_effect=share_network_side_effect))
        self.mock_object(db,
                         'share_network_subnet_get_by_availability_zone_id',
                         mock.Mock(return_value=None))

        body = {"share": fake_share_with_sn}

        req = fakes.HTTPRequest.blank('/shares')
        self.assertRaises(exception_to_raise, self.controller.create, req,
                          body)

    def test_share_show(self):
        req = fakes.HTTPRequest.blank('/shares/1')
        expected = self._get_expected_share_detailed_response()
        expected['share'].pop('snapshot_support')

        res_dict = self.controller.show(req, '1')

        self.assertEqual(expected, res_dict)

    def test_share_show_with_share_type_name(self):
        req = fakes.HTTPRequest.blank('/shares/1', version='2.6')
        res_dict = self.controller.show(req, '1')
        expected = self._get_expected_share_detailed_response()
        expected['share']['share_type_name'] = None
        expected['share']['task_state'] = None
        self.assertEqual(expected, res_dict)

    def test_share_show_admin(self):
        req = fakes.HTTPRequest.blank('/shares/1', use_admin_context=True)
        expected = self._get_expected_share_detailed_response(admin=True)
        expected['share'].pop('snapshot_support')

        res_dict = self.controller.show(req, '1')

        self.assertEqual(expected, res_dict)

    def test_share_show_no_share(self):
        self.mock_object(share_api.API, 'get', stubs.stub_share_get_notfound)
        req = fakes.HTTPRequest.blank('/shares/1')
        self.assertRaises(webob.exc.HTTPNotFound, self.controller.show, req,
                          '1')

    def test_share_delete(self):
        req = fakes.HTTPRequest.blank('/shares/1')
        resp = self.controller.delete(req, 1)
        self.assertEqual(202, resp.status_int)

    def test_share_update(self):
        shr = self.share
        body = {"share": shr}

        req = fakes.HTTPRequest.blank('/share/1')

        res_dict = self.controller.update(req, 1, body)

        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'update')
        self.assertEqual(shr["display_name"], res_dict['share']["name"])
        self.assertEqual(shr["display_description"],
                         res_dict['share']["description"])
        self.assertEqual(shr['is_public'], res_dict['share']['is_public'])

    def test_share_not_updates_size(self):
        req = fakes.HTTPRequest.blank('/share/1')

        res_dict = self.controller.update(req, 1, {"share": self.share})

        self.mock_policy_check.assert_called_once_with(
            req.environ['manila.context'], self.resource_name, 'update')
        self.assertNotEqual(res_dict['share']["size"], self.share["size"])

    def test_share_delete_no_share(self):
        self.mock_object(share_api.API, 'get', stubs.stub_share_get_notfound)
        req = fakes.HTTPRequest.blank('/shares/1')
        self.assertRaises(webob.exc.HTTPNotFound, self.controller.delete, req,
                          1)

    def _share_list_summary_with_search_opts(self, use_admin_context):
        search_opts = {
            'name': 'fake_name',
            'status': constants.STATUS_AVAILABLE,
            'share_server_id': 'fake_share_server_id',
            'share_type_id': 'fake_share_type_id',
            'snapshot_id': 'fake_snapshot_id',
            'share_network_id': 'fake_share_network_id',
            'metadata': '%7B%27k1%27%3A+%27v1%27%7D',  # serialized k1=v1
            'extra_specs': '%7B%27k2%27%3A+%27v2%27%7D',  # serialized k2=v2
            'sort_key': 'fake_sort_key',
            'sort_dir': 'fake_sort_dir',
            'limit': '1',
            'offset': '1',
            'is_public': 'False',
        }
        if use_admin_context:
            search_opts['host'] = 'fake_host'
        # fake_key should be filtered for non-admin
        url = '/shares?fake_key=fake_value'
        for k, v in search_opts.items():
            url = url + '&' + k + '=' + v
        req = fakes.HTTPRequest.blank(url, use_admin_context=use_admin_context)

        shares = [
            {
                'id': 'id1',
                'display_name': 'n1'
            },
            {
                'id': 'id2',
                'display_name': 'n2'
            },
            {
                'id': 'id3',
                'display_name': 'n3'
            },
        ]
        self.mock_object(share_api.API, 'get_all',
                         mock.Mock(return_value=[shares[1]]))

        result = self.controller.index(req)

        search_opts_expected = {
            'display_name': search_opts['name'],
            'status': search_opts['status'],
            'share_server_id': search_opts['share_server_id'],
            'share_type_id': search_opts['share_type_id'],
            'snapshot_id': search_opts['snapshot_id'],
            'share_network_id': search_opts['share_network_id'],
            'metadata': {
                'k1': 'v1'
            },
            'extra_specs': {
                'k2': 'v2'
            },
            'is_public': 'False',
            'limit': '1',
            'offset': '1'
        }

        if use_admin_context:
            search_opts_expected.update({'fake_key': 'fake_value'})
            search_opts_expected['host'] = search_opts['host']
        share_api.API.get_all.assert_called_once_with(
            req.environ['manila.context'],
            sort_key=search_opts['sort_key'],
            sort_dir=search_opts['sort_dir'],
            search_opts=search_opts_expected,
        )
        self.assertEqual(1, len(result['shares']))
        self.assertEqual(shares[1]['id'], result['shares'][0]['id'])
        self.assertEqual(shares[1]['display_name'],
                         result['shares'][0]['name'])

    def test_share_list_summary_with_search_opts_by_non_admin(self):
        self._share_list_summary_with_search_opts(use_admin_context=False)

    def test_share_list_summary_with_search_opts_by_admin(self):
        self._share_list_summary_with_search_opts(use_admin_context=True)

    def test_share_list_summary(self):
        self.mock_object(share_api.API, 'get_all',
                         stubs.stub_share_get_all_by_project)
        req = fakes.HTTPRequest.blank('/shares')
        res_dict = self.controller.index(req)
        expected = {
            'shares': [{
                'name':
                'displayname',
                'id':
                '1',
                'links': [{
                    'href': 'http://localhost/v1/fake/shares/1',
                    'rel': 'self'
                }, {
                    'href': 'http://localhost/fake/shares/1',
                    'rel': 'bookmark'
                }],
            }]
        }
        self.assertEqual(expected, res_dict)

    def _share_list_detail_with_search_opts(self, use_admin_context):
        search_opts = {
            'name': 'fake_name',
            'status': constants.STATUS_AVAILABLE,
            'share_server_id': 'fake_share_server_id',
            'share_type_id': 'fake_share_type_id',
            'snapshot_id': 'fake_snapshot_id',
            'share_network_id': 'fake_share_network_id',
            'metadata': '%7B%27k1%27%3A+%27v1%27%7D',  # serialized k1=v1
            'extra_specs': '%7B%27k2%27%3A+%27v2%27%7D',  # serialized k2=v2
            'sort_key': 'fake_sort_key',
            'sort_dir': 'fake_sort_dir',
            'limit': '1',
            'offset': '1',
            'is_public': 'False',
        }
        if use_admin_context:
            search_opts['host'] = 'fake_host'
        # fake_key should be filtered for non-admin
        url = '/shares/detail?fake_key=fake_value'
        for k, v in search_opts.items():
            url = url + '&' + k + '=' + v
        req = fakes.HTTPRequest.blank(url, use_admin_context=use_admin_context)

        shares = [
            {
                'id': 'id1',
                'display_name': 'n1'
            },
            {
                'id': 'id2',
                'display_name': 'n2',
                'status': constants.STATUS_AVAILABLE,
                'snapshot_id': 'fake_snapshot_id',
                'instance': {
                    'host': 'fake_host',
                    'share_network_id': 'fake_share_network_id',
                    'share_type_id': 'fake_share_type_id'
                },
            },
            {
                'id': 'id3',
                'display_name': 'n3'
            },
        ]
        self.mock_object(share_api.API, 'get_all',
                         mock.Mock(return_value=[shares[1]]))

        result = self.controller.detail(req)

        search_opts_expected = {
            'display_name': search_opts['name'],
            'status': search_opts['status'],
            'share_server_id': search_opts['share_server_id'],
            'share_type_id': search_opts['share_type_id'],
            'snapshot_id': search_opts['snapshot_id'],
            'share_network_id': search_opts['share_network_id'],
            'metadata': {
                'k1': 'v1'
            },
            'extra_specs': {
                'k2': 'v2'
            },
            'is_public': 'False',
            'limit': '1',
            'offset': '1'
        }
        if use_admin_context:
            search_opts_expected.update({'fake_key': 'fake_value'})
            search_opts_expected['host'] = search_opts['host']
        share_api.API.get_all.assert_called_once_with(
            req.environ['manila.context'],
            sort_key=search_opts['sort_key'],
            sort_dir=search_opts['sort_dir'],
            search_opts=search_opts_expected,
        )
        self.assertEqual(1, len(result['shares']))
        self.assertEqual(shares[1]['id'], result['shares'][0]['id'])
        self.assertEqual(shares[1]['display_name'],
                         result['shares'][0]['name'])
        self.assertEqual(shares[1]['snapshot_id'],
                         result['shares'][0]['snapshot_id'])
        self.assertEqual(shares[1]['status'], result['shares'][0]['status'])
        self.assertEqual(shares[1]['instance']['share_type_id'],
                         result['shares'][0]['share_type'])
        self.assertEqual(shares[1]['snapshot_id'],
                         result['shares'][0]['snapshot_id'])
        if use_admin_context:
            self.assertEqual(shares[1]['instance']['host'],
                             result['shares'][0]['host'])
        self.assertEqual(shares[1]['instance']['share_network_id'],
                         result['shares'][0]['share_network_id'])

    def test_share_list_detail_with_search_opts_by_non_admin(self):
        self._share_list_detail_with_search_opts(use_admin_context=False)

    def test_share_list_detail_with_search_opts_by_admin(self):
        self._share_list_detail_with_search_opts(use_admin_context=True)

    def _list_detail_common_expected(self, admin=False):
        share_dict = {
            'status':
            'fakestatus',
            'description':
            'displaydesc',
            'export_location':
            'fake_location',
            'export_locations': ['fake_location', 'fake_location2'],
            'availability_zone':
            'fakeaz',
            'name':
            'displayname',
            'share_proto':
            'FAKEPROTO',
            'metadata': {},
            'project_id':
            'fakeproject',
            'id':
            '1',
            'snapshot_id':
            '2',
            'snapshot_support':
            True,
            'share_network_id':
            None,
            'created_at':
            datetime.datetime(1, 1, 1, 1, 1, 1),
            'size':
            1,
            'share_type':
            '1',
            'volume_type':
            '1',
            'is_public':
            False,
            'links': [{
                'href': 'http://localhost/v1/fake/shares/1',
                'rel': 'self'
            }, {
                'href': 'http://localhost/fake/shares/1',
                'rel': 'bookmark'
            }],
        }
        if admin:
            share_dict['host'] = 'fakehost'
        return {'shares': [share_dict]}

    def _list_detail_test_common(self, req, expected):
        self.mock_object(share_api.API, 'get_all',
                         stubs.stub_share_get_all_by_project)
        res_dict = self.controller.detail(req)
        self.assertEqual(expected, res_dict)
        self.assertEqual(res_dict['shares'][0]['volume_type'],
                         res_dict['shares'][0]['share_type'])

    def test_share_list_detail(self):
        env = {'QUERY_STRING': 'name=Share+Test+Name'}
        req = fakes.HTTPRequest.blank('/shares/detail', environ=env)
        expected = self._list_detail_common_expected()
        expected['shares'][0].pop('snapshot_support')
        self._list_detail_test_common(req, expected)

    def test_share_list_detail_with_task_state(self):
        env = {'QUERY_STRING': 'name=Share+Test+Name'}
        req = fakes.HTTPRequest.blank('/shares/detail',
                                      environ=env,
                                      version="2.5")
        expected = self._list_detail_common_expected()
        expected['shares'][0]['task_state'] = None
        self._list_detail_test_common(req, expected)

    def test_remove_invalid_options(self):
        ctx = context.RequestContext('fakeuser', 'fakeproject', is_admin=False)
        search_opts = {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}
        expected_opts = {'a': 'a', 'c': 'c'}
        allowed_opts = ['a', 'c']
        common.remove_invalid_options(ctx, search_opts, allowed_opts)
        self.assertEqual(expected_opts, search_opts)

    def test_remove_invalid_options_admin(self):
        ctx = context.RequestContext('fakeuser', 'fakeproject', is_admin=True)
        search_opts = {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}
        expected_opts = {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd'}
        allowed_opts = ['a', 'c']
        common.remove_invalid_options(ctx, search_opts, allowed_opts)
        self.assertEqual(expected_opts, search_opts)
コード例 #14
0
class ShareNetworkSubnetControllerTest(test.TestCase):
    """Share network subnet api test"""

    def setUp(self):
        super(ShareNetworkSubnetControllerTest, self).setUp()
        self.controller = share_network_subnets.ShareNetworkSubnetController()
        self.mock_policy_check = self.mock_object(
            policy, 'check_policy', mock.Mock(return_value=True))
        self.resource_name = self.controller.resource_name
        self.mock_az_get = self.mock_object(db_api, 'availability_zone_get',
                                            mock.Mock(return_value=fake_az))
        self.share_network = db_utils.create_share_network(
            name='fake_network', id='fake_sn_id')
        self.share_server = db_utils.create_share_server(
            share_network_subnet_id='fake_sns_id')
        self.subnet = db_utils.create_share_network_subnet(
            share_network_id=self.share_network['id'])
        self.share = db_utils.create_share()

    def test_share_network_subnet_delete(self):
        req = fakes.HTTPRequest.blank('/subnets/%s' % self.subnet['id'],
                                      version="2.51")
        context = req.environ['manila.context']

        mock_sns_get = self.mock_object(
            db_api, 'share_network_subnet_get',
            mock.Mock(return_value=self.subnet))
        mock_all_get_all_shares_by_ss = self.mock_object(
            db_api, 'share_instances_get_all_by_share_server',
            mock.Mock(return_value=[]))
        mock_all_ss_are_auto_deletable = self.mock_object(
            self.controller, '_all_share_servers_are_auto_deletable',
            mock.Mock(return_value=True))
        mock_delete_share_server = self.mock_object(
            self.controller.share_rpcapi, 'delete_share_server')
        mock_subnet_delete = self.mock_object(db_api,
                                              'share_network_subnet_delete')

        result = self.controller.delete(req, self.share_network['id'],
                                        self.subnet['id'])

        self.assertEqual(202, result.status_int)
        mock_sns_get.assert_called_once_with(
            context, self.subnet['id'])
        mock_all_get_all_shares_by_ss.assert_called_once_with(
            context, self.subnet['share_servers'][0].id
        )
        mock_all_ss_are_auto_deletable.assert_called_once_with(
            self.subnet)
        mock_delete_share_server.assert_called_once_with(
            context, self.subnet['share_servers'][0])
        mock_subnet_delete.assert_called_once_with(
            context, self.subnet['id'])
        policy.check_policy.assert_called_once_with(
            context, self.resource_name, 'delete')

    def test_share_network_subnet_delete_network_not_found(self):
        req = fakes.HTTPRequest.blank('/subnets/%s' % self.subnet['id'],
                                      version="2.51")
        context = req.environ['manila.context']

        mock_sn_get = self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=exception.ShareNetworkNotFound(
                share_network_id=self.share_network['id']
            )))

        self.assertRaises(exc.HTTPNotFound,
                          self.controller.delete,
                          req,
                          self.share_network['id'],
                          self.subnet['id'])
        mock_sn_get.assert_called_once_with(
            context, self.share_network['id'])
        self.mock_policy_check.assert_called_once_with(
            context, self.resource_name, 'delete')

    def test_share_network_subnet_delete_subnet_not_found(self):
        req = fakes.HTTPRequest.blank('/subnets/%s' % self.subnet['id'],
                                      version="2.51")
        context = req.environ['manila.context']

        mock_sns_get = self.mock_object(
            db_api, 'share_network_subnet_get',
            mock.Mock(side_effect=exception.ShareNetworkSubnetNotFound(
                share_network_subnet_id=self.subnet['id']
            )))

        self.assertRaises(exc.HTTPNotFound,
                          self.controller.delete,
                          req,
                          self.share_network['id'],
                          self.subnet['id'])
        mock_sns_get.assert_called_once_with(
            context, self.subnet['id'])
        self.mock_policy_check.assert_called_once_with(
            context, self.resource_name, 'delete')

    def test_delete_subnet_with_share_servers_fail(self):
        req = fakes.HTTPRequest.blank('/subnets/%s' % self.subnet['id'],
                                      version="2.51")
        context = req.environ['manila.context']

        mock_sns_get = self.mock_object(
            db_api, 'share_network_subnet_get',
            mock.Mock(return_value=self.subnet))
        mock_all_get_all_shares_by_ss = self.mock_object(
            db_api, 'share_instances_get_all_by_share_server',
            mock.Mock(return_value=[]))
        mock_all_ss_are_auto_deletable = self.mock_object(
            self.controller, '_all_share_servers_are_auto_deletable',
            mock.Mock(return_value=False))

        self.assertRaises(exc.HTTPConflict,
                          self.controller.delete,
                          req,
                          self.share_network['id'],
                          self.subnet['id'])

        mock_sns_get.assert_called_once_with(
            context, self.subnet['id'])
        mock_all_get_all_shares_by_ss.assert_called_once_with(
            context, self.subnet['share_servers'][0].id
        )
        mock_all_ss_are_auto_deletable.assert_called_once_with(
            self.subnet
        )
        self.mock_policy_check.assert_called_once_with(
            context, self.resource_name, 'delete')

    def test_delete_subnet_with_shares_fail(self):
        req = fakes.HTTPRequest.blank('/subnets/%s' % self.subnet['id'],
                                      version="2.51")
        context = req.environ['manila.context']

        mock_sns_get = self.mock_object(
            db_api, 'share_network_subnet_get',
            mock.Mock(return_value=self.subnet))
        mock_all_get_all_shares_by_ss = self.mock_object(
            db_api, 'share_instances_get_all_by_share_server',
            mock.Mock(return_value=[self.share]))

        self.assertRaises(exc.HTTPConflict,
                          self.controller.delete,
                          req,
                          self.share_network['id'],
                          self.subnet['id'])

        mock_sns_get.assert_called_once_with(
            context, self.subnet['id'])
        mock_all_get_all_shares_by_ss.assert_called_once_with(
            context, self.subnet['share_servers'][0].id
        )
        self.mock_policy_check.assert_called_once_with(
            context, self.resource_name, 'delete')

    @ddt.data((None, fake_default_subnet, None),
              (fake_az, None, fake_subnet_with_az))
    @ddt.unpack
    def test__validate_subnet(self, az, default_subnet, subnet_az):
        req = fakes.HTTPRequest.blank('/subnets', version='2.51')
        context = req.environ['manila.context']

        mock_get_default_sns = self.mock_object(
            db_api, 'share_network_subnet_get_default_subnet',
            mock.Mock(return_value=default_subnet))
        mock_get_subnet_by_az = self.mock_object(
            db_api, 'share_network_subnet_get_by_availability_zone_id',
            mock.Mock(return_value=subnet_az))

        self.assertRaises(exc.HTTPConflict,
                          self.controller._validate_subnet,
                          context,
                          self.share_network['id'],
                          az)
        if az:
            mock_get_subnet_by_az.assert_called_once_with(
                context, self.share_network['id'], az['id'])
            mock_get_default_sns.assert_not_called()
        else:
            mock_get_default_sns.assert_called_once_with(
                context, self.share_network['id'])
            mock_get_subnet_by_az.assert_not_called()

    def _setup_create_test_request_body(self):
        body = {
            'share_network_id': self.share_network['id'],
            'availability_zone': fake_az['name'],
            'neutron_net_id': 'fake_nn_id',
            'neutron_subnet_id': 'fake_nsn_id'
        }
        return body

    def test_subnet_create(self):
        req = fakes.HTTPRequest.blank('/subnets', version="2.51")
        context = req.environ['manila.context']
        body = {
            'share-network-subnet': self._setup_create_test_request_body()
        }
        sn_id = body['share-network-subnet']['share_network_id']

        expected_result = copy.deepcopy(body)
        expected_result['share-network-subnet']['id'] = self.subnet['id']
        mock_check_net_and_subnet_id = self.mock_object(
            common, 'check_net_id_and_subnet_id')
        mock_validate_subnet = self.mock_object(
            self.controller, '_validate_subnet')
        mock_subnet_create = self.mock_object(
            db_api, 'share_network_subnet_create',
            mock.Mock(return_value=self.subnet))

        self.controller.create(
            req, body['share-network-subnet']['share_network_id'], body)

        mock_check_net_and_subnet_id.assert_called_once_with(
            body['share-network-subnet'])
        mock_validate_subnet.assert_called_once_with(
            context, sn_id, az=fake_az)
        mock_subnet_create.assert_called_once_with(
            context, body['share-network-subnet'])

    def test_subnet_create_share_network_not_found(self):
        fake_sn_id = 'fake_id'
        req = fakes.HTTPRequest.blank('/subnets', version="2.51")
        context = req.environ['manila.context']
        body = {
            'share-network-subnet': self._setup_create_test_request_body()
        }
        mock_sn_get = self.mock_object(
            db_api, 'share_network_get',
            mock.Mock(side_effect=exception.ShareNetworkNotFound(
                share_network_id=fake_sn_id)))

        self.assertRaises(exc.HTTPNotFound,
                          self.controller.create,
                          req,
                          fake_sn_id,
                          body)
        mock_sn_get.assert_called_once_with(context, fake_sn_id)

    def test_subnet_create_az_not_found(self):
        fake_sn_id = 'fake_id'
        req = fakes.HTTPRequest.blank('/subnets', version="2.51")
        context = req.environ['manila.context']
        body = {
            'share-network-subnet': self._setup_create_test_request_body()
        }
        mock_sn_get = self.mock_object(db_api, 'share_network_get')
        mock_az_get = self.mock_object(
            db_api, 'availability_zone_get',
            mock.Mock(side_effect=exception.AvailabilityZoneNotFound(id='')))

        expected_az = body['share-network-subnet']['availability_zone']

        self.assertRaises(exc.HTTPBadRequest,
                          self.controller.create,
                          req,
                          fake_sn_id,
                          body)
        mock_sn_get.assert_called_once_with(context, fake_sn_id)
        mock_az_get.assert_called_once_with(
            context, expected_az)

    def test_subnet_create_subnet_default_or_same_az_exists(self):
        fake_sn_id = 'fake_id'
        req = fakes.HTTPRequest.blank('/subnets', version="2.51")
        context = req.environ['manila.context']
        body = {
            'share-network-subnet': self._setup_create_test_request_body()
        }
        mock_sn_get = self.mock_object(db_api, 'share_network_get')
        mock__validate_subnet = self.mock_object(
            self.controller, '_validate_subnet',
            mock.Mock(side_effect=exc.HTTPConflict(''))
        )
        expected_az = body['share-network-subnet']['availability_zone']

        self.assertRaises(exc.HTTPConflict,
                          self.controller.create,
                          req,
                          fake_sn_id,
                          body)
        mock_sn_get.assert_called_once_with(context, fake_sn_id)
        self.mock_az_get.assert_called_once_with(context, expected_az)
        mock__validate_subnet.assert_called_once_with(
            context, fake_sn_id, az=fake_az)

    def test_subnet_create_subnet_db_error(self):
        fake_sn_id = 'fake_sn_id'
        req = fakes.HTTPRequest.blank('/subnets', version="2.51")
        context = req.environ['manila.context']
        body = {
            'share-network-subnet': self._setup_create_test_request_body()
        }
        mock_sn_get = self.mock_object(db_api, 'share_network_get')
        mock__validate_subnet = self.mock_object(
            self.controller, '_validate_subnet')
        mock_db_subnet_create = self.mock_object(
            db_api, 'share_network_subnet_create',
            mock.Mock(side_effect=db_exception.DBError()))
        expected_data = copy.deepcopy(body['share-network-subnet'])
        expected_data['availability_zone_id'] = fake_az['id']
        expected_data.pop('availability_zone')

        self.assertRaises(exc.HTTPInternalServerError,
                          self.controller.create,
                          req,
                          fake_sn_id,
                          body)

        mock_sn_get.assert_called_once_with(context, fake_sn_id)
        self.mock_az_get.assert_called_once_with(context, fake_az['name'])
        mock__validate_subnet.assert_called_once_with(
            context, fake_sn_id, az=fake_az)
        mock_db_subnet_create.assert_called_once_with(
            context, expected_data
        )

    def test_show_subnet(self):
        subnet = db_utils.create_share_network_subnet(
            id='fake_sns_2', share_network_id=self.share_network['id'])
        expected_result = {
            'share_network_subnet': {
                "created_at": subnet['created_at'],
                "id": subnet['id'],
                "share_network_id": subnet['share_network_id'],
                "share_network_name": self.share_network['name'],
                "availability_zone": subnet['availability_zone'],
                "segmentation_id": subnet['segmentation_id'],
                "neutron_subnet_id": subnet['neutron_subnet_id'],
                "updated_at": subnet['updated_at'],
                "neutron_net_id": subnet['neutron_net_id'],
                "ip_version": subnet['ip_version'],
                "cidr": subnet['cidr'],
                "network_type": subnet['network_type'],
                "gateway": subnet['gateway'],
                "mtu": subnet['mtu'],
            }
        }
        req = fakes.HTTPRequest.blank('/subnets/%s' % subnet['id'],
                                      version="2.51")
        context = req.environ['manila.context']
        mock_sn_get = self.mock_object(
            db_api, 'share_network_get', mock.Mock(
                return_value=self.share_network))
        mock_sns_get = self.mock_object(
            db_api, 'share_network_subnet_get', mock.Mock(
                return_value=subnet))

        result = self.controller.show(req, self.share_network['id'],
                                      subnet['id'])

        self.assertEqual(expected_result, result)
        mock_sn_get.assert_called_once_with(context, self.share_network['id'])
        mock_sns_get.assert_called_once_with(context, subnet['id'])

    @ddt.data(
        (mock.Mock(side_effect=exception.ShareNetworkNotFound(
            share_network_id='fake_net_id')), None),
        (mock.Mock(), mock.Mock(
            side_effect=exception.ShareNetworkSubnetNotFound(
                share_network_subnet_id='fake_subnet_id'))))
    @ddt.unpack
    def test_show_subnet_not_found(self, sn_get_side_effect,
                                   sns_get_side_effect):
        req = fakes.HTTPRequest.blank('/subnets/%s' % self.subnet['id'],
                                      version="2.51")
        context = req.environ['manila.context']

        mock_sn_get = self.mock_object(
            db_api, 'share_network_get', sn_get_side_effect)
        mock_sns_get = self.mock_object(
            db_api, 'share_network_subnet_get', sns_get_side_effect)

        self.assertRaises(exc.HTTPNotFound,
                          self.controller.show,
                          req,
                          self.share_network['id'],
                          self.subnet['id'])
        mock_sn_get.assert_called_once_with(context, self.share_network['id'])
        if sns_get_side_effect:
            mock_sns_get.assert_called_once_with(context, self.subnet['id'])

    def test_list_subnet(self):
        share_network_id = 'fake_id'
        subnet = db_utils.create_share_network_subnet(
            share_network_id=share_network_id, id='fake_id')
        fake_sn = db_utils.create_share_network(id=share_network_id)
        expected_result = {
            'share_network_subnets': [{
                "created_at": subnet['created_at'],
                "id": subnet['id'],
                "share_network_id": subnet['id'],
                "share_network_name": fake_sn["name"],
                "availability_zone": subnet['availability_zone'],
                "segmentation_id": subnet['segmentation_id'],
                "neutron_subnet_id": subnet['neutron_subnet_id'],
                "updated_at": subnet['updated_at'],
                "neutron_net_id": subnet['neutron_net_id'],
                "ip_version": subnet['ip_version'],
                "cidr": subnet['cidr'],
                "network_type": subnet['network_type'],
                "gateway": subnet['gateway'],
                "mtu": subnet['mtu'],
            }]
        }

        req = fakes.HTTPRequest.blank('/subnets/', version="2.51")
        context = req.environ['manila.context']
        mock_sn_get = self.mock_object(
            db_api, 'share_network_get', mock.Mock(
                return_value=fake_sn))

        result = self.controller.index(req, self.share_network['id'])

        self.assertEqual(expected_result, result)
        mock_sn_get.assert_called_once_with(context, self.share_network['id'])

    def test_list_subnet_share_network_not_found(self):
        req = fakes.HTTPRequest.blank('/subnets/', version="2.51")
        context = req.environ['manila.context']

        mock_sn_get = self.mock_object(
            db_api, 'share_network_get', mock.Mock(
                side_effect=exception.ShareNetworkNotFound(
                    share_network_id=self.share_network['id'])))

        self.assertRaises(exc.HTTPNotFound,
                          self.controller.index,
                          req,
                          self.share_network['id'])
        mock_sn_get.assert_called_once_with(context, self.share_network['id'])