summaryrefslogtreecommitdiff
path: root/nova/tests/unit/api/openstack/compute/admin_only_action_common.py
blob: fdda030cfd5efddfa686941eae936f2bf282014d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# Copyright 2013 IBM Corp.
#
#   Licensed under the Apache License, Version 2.0 (the "License"); you may
#   not use this file except in compliance with the License. You may obtain
#   a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#   License for the specific language governing permissions and limitations
#   under the License.

import fixtures
import mock
from oslo_utils import timeutils
from oslo_utils import uuidutils
import webob

from nova.compute import vm_states
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_instance


class CommonMixin(object):
    def setUp(self):
        super(CommonMixin, self).setUp()
        self.compute_api = None
        self.req = fakes.HTTPRequest.blank('')
        self.context = self.req.environ['nova.context']

        self.mock_get = self.useFixture(
            fixtures.MockPatch('nova.compute.api.API.get')).mock

    def _stub_instance_get(self, uuid=None):
        if uuid is None:
            uuid = uuidutils.generate_uuid()
        instance = fake_instance.fake_instance_obj(self.context,
                id=1, uuid=uuid, vm_state=vm_states.ACTIVE,
                task_state=None, launched_at=timeutils.utcnow())
        self.mock_get.return_value = instance
        return instance

    def _test_non_existing_instance(self, action, body_map=None):
        # Reset the mock.
        self.mock_get.reset_mock()

        expected_attrs = None
        if action == '_migrate_live':
            expected_attrs = ['numa_topology']

        uuid = uuidutils.generate_uuid()
        self.mock_get.side_effect = exception.InstanceNotFound(
            instance_id=uuid)

        controller_function = getattr(self.controller, action)
        self.assertRaises(webob.exc.HTTPNotFound,
                          controller_function,
                          self.req, uuid, body=body_map)
        self.mock_get.assert_called_once_with(self.context, uuid,
                                              expected_attrs=expected_attrs,
                                              cell_down_support=False)

    def _test_action(self, action, body=None, method=None,
                     compute_api_args_map=None):
        # Reset the mock.
        self.mock_get.reset_mock()

        expected_attrs = None
        if action == '_migrate_live':
            expected_attrs = ['numa_topology']

        if method is None:
            method = action.replace('_', '')
        compute_api_args_map = compute_api_args_map or {}

        instance = self._stub_instance_get()
        args, kwargs = compute_api_args_map.get(action, ((), {}))

        with mock.patch.object(self.compute_api, method) as mock_method:
            controller_function = getattr(self.controller, action)
            res = controller_function(self.req, instance.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 self._api_version == '2.1':
                status_int = controller_function.wsgi_code
            else:
                status_int = res.status_int
            self.assertEqual(202, status_int)
            mock_method.assert_called_once_with(self.context, instance, *args,
                                                **kwargs)
        self.mock_get.assert_called_once_with(self.context, instance.uuid,
                                              expected_attrs=expected_attrs,
                                              cell_down_support=False)

    def _test_not_implemented_state(self, action, method=None):
        # Reset the mock.
        self.mock_get.reset_mock()

        expected_attrs = None
        if action == '_migrate_live':
            expected_attrs = ['numa_topology']

        if method is None:
            method = action.replace('_', '')

        instance = self._stub_instance_get()
        body = {}
        compute_api_args_map = {}
        args, kwargs = compute_api_args_map.get(action, ((), {}))

        with mock.patch.object(
                self.compute_api, method,
                side_effect=NotImplementedError()) as mock_method:
            controller_function = getattr(self.controller, action)
            self.assertRaises(webob.exc.HTTPNotImplemented,
                              controller_function,
                              self.req, instance.uuid, body=body)
            mock_method.assert_called_once_with(self.context, instance,
                                                *args, **kwargs)
        self.mock_get.assert_called_once_with(self.context, instance.uuid,
                                              expected_attrs=expected_attrs,
                                              cell_down_support=False)

    def _test_invalid_state(self, action, method=None, body_map=None,
                            compute_api_args_map=None,
                            exception_arg=None):
        # Reset the mock.
        self.mock_get.reset_mock()

        expected_attrs = None
        if action == '_migrate_live':
            expected_attrs = ['numa_topology']

        if method is None:
            method = action.replace('_', '')
        if body_map is None:
            body_map = {}
        if compute_api_args_map is None:
            compute_api_args_map = {}

        instance = self._stub_instance_get()

        args, kwargs = compute_api_args_map.get(action, ((), {}))

        with mock.patch.object(
                self.compute_api, method,
                side_effect=exception.InstanceInvalidState(
                    attr='vm_state', instance_uuid=instance.uuid,
                    state='foo', method=method)) as mock_method:
            controller_function = getattr(self.controller, action)
            ex = self.assertRaises(webob.exc.HTTPConflict,
                                   controller_function,
                                   self.req, instance.uuid,
                                   body=body_map)
            self.assertIn("Cannot \'%(action)s\' instance %(id)s"
                          % {'action': exception_arg or method,
                             'id': instance.uuid}, ex.explanation)
            mock_method.assert_called_once_with(self.context, instance,
                                                *args, **kwargs)
        self.mock_get.assert_called_once_with(self.context, instance.uuid,
                                              expected_attrs=expected_attrs,
                                              cell_down_support=False)

    def _test_locked_instance(self, action, method=None, body=None,
                              compute_api_args_map=None):
        # Reset the mock.
        self.mock_get.reset_mock()

        expected_attrs = None
        if action == '_migrate_live':
            expected_attrs = ['numa_topology']

        if method is None:
            method = action.replace('_', '')

        compute_api_args_map = compute_api_args_map or {}
        instance = self._stub_instance_get()

        args, kwargs = compute_api_args_map.get(action, ((), {}))

        with mock.patch.object(
                self.compute_api, method,
                side_effect=exception.InstanceIsLocked(
                    instance_uuid=instance.uuid)) as mock_method:
            controller_function = getattr(self.controller, action)
            self.assertRaises(webob.exc.HTTPConflict,
                              controller_function,
                              self.req, instance.uuid, body=body)
            mock_method.assert_called_once_with(self.context, instance,
                                                *args, **kwargs)
        self.mock_get.assert_called_once_with(self.context, instance.uuid,
                                              expected_attrs=expected_attrs,
                                              cell_down_support=False)

    def _test_instance_not_found_in_compute_api(self, action,
                         method=None, body=None, compute_api_args_map=None):
        # Reset the mock.
        self.mock_get.reset_mock()

        expected_attrs = None
        if action == '_migrate_live':
            expected_attrs = ['numa_topology']

        if method is None:
            method = action.replace('_', '')
        compute_api_args_map = compute_api_args_map or {}

        instance = self._stub_instance_get()

        args, kwargs = compute_api_args_map.get(action, ((), {}))

        with mock.patch.object(
                self.compute_api, method,
                side_effect=exception.InstanceNotFound(
                    instance_id=instance.uuid)) as mock_method:
            controller_function = getattr(self.controller, action)
            self.assertRaises(webob.exc.HTTPNotFound,
                              controller_function,
                              self.req, instance.uuid, body=body)
            mock_method.assert_called_once_with(self.context, instance,
                                                *args, **kwargs)
        self.mock_get.assert_called_once_with(self.context, instance.uuid,
                                              expected_attrs=expected_attrs,
                                              cell_down_support=False)


class CommonTests(CommonMixin, test.NoDBTestCase):
    def _test_actions(self, actions, method_translations=None, body_map=None,
                      args_map=None):
        method_translations = method_translations or {}
        body_map = body_map or {}
        args_map = args_map or {}
        for action in actions:
            method = method_translations.get(action)
            body = body_map.get(action)
            self._test_action(action, method=method, body=body,
                              compute_api_args_map=args_map)

    def _test_actions_instance_not_found_in_compute_api(self,
                  actions, method_translations=None, body_map=None,
                  args_map=None):
        method_translations = method_translations or {}
        body_map = body_map or {}
        args_map = args_map or {}
        for action in actions:
            method = method_translations.get(action)
            body = body_map.get(action)
            self._test_instance_not_found_in_compute_api(
                action, method=method, body=body,
                compute_api_args_map=args_map)

    def _test_actions_with_non_existed_instance(self, actions, body_map=None):
        body_map = body_map or {}
        for action in actions:
            self._test_non_existing_instance(action,
                                             body_map=body_map.get(action))

    def _test_actions_raise_conflict_on_invalid_state(
            self, actions, method_translations=None, body_map=None,
            args_map=None, exception_args=None):
        method_translations = method_translations or {}
        body_map = body_map or {}
        args_map = args_map or {}
        exception_args = exception_args or {}
        for action in actions:
            method = method_translations.get(action)
            exception_arg = exception_args.get(action)
            self._test_invalid_state(action, method=method,
                                     body_map=body_map.get(action),
                                     compute_api_args_map=args_map,
                                     exception_arg=exception_arg)

    def _test_actions_with_locked_instance(self, actions,
                                           method_translations=None,
                                           body_map=None, args_map=None):
        method_translations = method_translations or {}
        body_map = body_map or {}
        args_map = args_map or {}
        for action in actions:
            method = method_translations.get(action)
            body = body_map.get(action)
            self._test_locked_instance(action, method=method, body=body,
                                       compute_api_args_map=args_map)