File: test_instance_controller.py

package info (click to toggle)
openstack-trove 1%3A23.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,976 kB
  • sloc: python: 50,709; sh: 2,858; makefile: 71
file content (415 lines) | stat: -rw-r--r-- 17,015 bytes parent folder | download | duplicates (2)
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
#    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 copy
from unittest import mock
from unittest.mock import MagicMock
from unittest.mock import Mock
import uuid

import jsonschema
from testtools.matchers import Equals
from testtools.matchers import Is
from testtools.testcase import skip

from trove.common import apischema
from trove.common import exception
from trove.instance.service import InstanceController
from trove.tests.unittests import trove_testtools


class TestInstanceController(trove_testtools.TestCase):
    def setUp(self):
        super(TestInstanceController, self).setUp()
        self.controller = InstanceController()
        self.locality = 'affinity'
        self.instance = {
            "instance": {
                "volume": {"size": "1"},
                "users": [
                    {"name": "user1",
                     "password": "litepass",
                     "databases": [{"name": "firstdb"}]}
                ],
                "flavorRef": "https://localhost:8779/v1.0/2500/1",
                "name": "TEST-XYS2d2fe2kl;zx;jkl2l;sjdcma239(E)@(D",
                "databases": [
                    {
                        "name": "firstdb",
                        "collate": "latin2_general_ci",
                        "character_set": "latin2"
                    },
                    {
                        "name": "db2"
                    }
                ],
                "locality": self.locality
            }
        }
        self.context = trove_testtools.TroveTestContext(self)
        self.req = Mock(remote_addr='ip:port', host='myhost')

    def verify_errors(self, errors, msg=None, properties=None, path=None):
        msg = msg or []
        properties = properties or []
        self.assertThat(len(errors), Is(len(msg)))
        i = 0
        while i < len(msg):
            self.assertIn(errors[i].message, msg)
            if path:
                self.assertThat(path, Equals(properties[i]))
            else:
                self.assertThat(errors[i].path.pop(), Equals(properties[i]))
            i += 1

    def test_get_schema_create(self):
        schema = self.controller.get_schema('create', {'instance': {}})
        self.assertIsNotNone(schema)
        self.assertIn('instance', schema['properties'])

    def test_get_schema_action_restart(self):
        schema = self.controller.get_schema('action', {'restart': {}})
        self.assertIsNotNone(schema)
        self.assertIn('restart', schema['properties'])

    def test_get_schema_action_resize_volume(self):
        schema = self.controller.get_schema(
            'action', {'resize': {'volume': {}}})
        self.assertIsNotNone(schema)
        self.assertIn('resize', schema['properties'])
        self.assertIn(
            'volume', schema['properties']['resize']['properties'])

    def test_get_schema_action_resize_flavorRef(self):
        schema = self.controller.get_schema(
            'action', {'resize': {'flavorRef': {}}})
        self.assertIsNotNone(schema)
        self.assertIn('resize', schema['properties'])
        self.assertIn(
            'flavorRef', schema['properties']['resize']['properties'])

    def test_get_schema_action_other(self):
        schema = self.controller.get_schema(
            'action', {'supersized': {'flavorRef': {}}})
        self.assertIsNotNone(schema)
        self.assertThat(len(schema.keys()), Is(0))

    def test_validate_create_complete(self):
        body = self.instance
        schema = self.controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_create_complete_with_restore(self):
        body = self.instance
        body['instance']['restorePoint'] = {
            "backupRef": "d761edd8-0771-46ff-9743-688b9e297a3b"
        }
        schema = self.controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_create_complete_with_restore_error(self):
        body = self.instance
        backup_id_ref = "invalid-backup-id-ref"
        body['instance']['restorePoint'] = {
            "backupRef": backup_id_ref
        }
        schema = self.controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        self.assertThat(len(errors), Is(1))
        self.assertThat(errors[0].message,
                        Equals("'%s' does not match '%s'" %
                               (backup_id_ref, apischema.uuid['pattern'])))

    def test_validate_create_blankname(self):
        body = self.instance
        body['instance']['name'] = "     "
        schema = self.controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        self.assertThat(len(errors), Is(1))
        self.assertThat(errors[0].message,
                        Equals("'     ' does not match '^.*[0-9a-zA-Z]+.*$'"))

    def test_validate_create_invalid_name(self):
        body = self.instance
        body['instance']['name'] = "$#$%^^"
        schema = self.controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        self.assertEqual(1, len(errors))
        self.assertIn("'$#$%^^' does not match '^.*[0-9a-zA-Z]+.*$'",
                      errors[0].message)

    def test_validate_create_invalid_locality(self):
        body = self.instance
        body['instance']['locality'] = "$%^"
        schema = self.controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        error_messages = [error.message for error in errors]
        error_paths = [error.path.pop() for error in errors]
        self.assertEqual(1, len(errors))
        self.assertIn("'$%^' does not match '^.*[0-9a-zA-Z]+.*$'",
                      error_messages)
        self.assertIn("locality", error_paths)

    def test_validate_create_valid_nics(self):
        body = copy.copy(self.instance)
        body['instance']['nics'] = [
            {
                'network_id': str(uuid.uuid4()),
                'subnet_id': str(uuid.uuid4()),
                'ip_address': '192.168.1.11'
            }
        ]

        schema = self.controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_restart(self):
        body = {"restart": {}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_invalid_action(self):
        # TODO(juice) perhaps we should validate the schema not recognized
        body = {"restarted": {}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_resize_volume(self):
        body = {"resize": {"volume": {"size": 4}}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_resize_volume_string(self):
        body = {"resize": {"volume": {"size": "4"}}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_resize_volume_string_start_with_zero(self):
        body = {"resize": {"volume": {"size": "0040"}}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_resize_volume_string_invalid_number(self):
        body = {"resize": {"volume": {"size": '-44.0'}}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        self.assertThat(errors[0].context[1].message,
                        Equals("'-44.0' does not match '^0*[1-9]+[0-9]*$'"))
        self.assertThat(errors[0].path.pop(), Equals('size'))

    def test_validate_resize_volume_invalid_characters(self):
        body = {"resize": {"volume": {"size": 'x'}}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        self.assertThat(errors[0].context[0].message,
                        Equals("'x' is not of type 'integer'"))
        self.assertThat(errors[0].context[1].message,
                        Equals("'x' does not match '^0*[1-9]+[0-9]*$'"))
        self.assertThat(errors[0].path.pop(), Equals('size'))

    def test_validate_resize_volume_zero_number(self):
        body = {"resize": {"volume": {"size": 0}}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        self.assertThat(errors[0].context[0].message,
                        Equals("0 is less than the minimum of 1"))
        self.assertThat(errors[0].path.pop(), Equals('size'))

    def test_validate_resize_volume_string_zero_number(self):
        body = {"resize": {"volume": {"size": '0'}}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        self.assertThat(errors[0].context[1].message,
                        Equals("'0' does not match '^0*[1-9]+[0-9]*$'"))
        self.assertThat(errors[0].path.pop(), Equals('size'))

    def test_validate_resize_instance(self):
        body = {"resize": {"flavorRef": "https://endpoint/v1.0/123/flavors/2"}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_resize_instance_int(self):
        body = {"resize": {"flavorRef": 2}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_resize_instance_string(self):
        body = {"resize": {"flavorRef": 'foo'}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_resize_instance_empty_url(self):
        body = {"resize": {"flavorRef": ""}}
        schema = self.controller.get_schema('action', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)

    @skip("This URI validator allows just about anything you give it")
    def test_validate_resize_instance_invalid_url(self):
        body = {"resize": {"flavorRef": "xyz-re1f2-daze329d-f23901"}}
        schema = self.controller.get_schema('action', body)
        self.assertIsNotNone(schema)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        self.verify_errors(errors, ["'' should be non-empty"], ["flavorRef"])

    def _setup_modify_instance_mocks(self):
        instance = Mock()
        instance.detach_replica = Mock()
        instance.attach_configuration = Mock()
        instance.detach_configuration = Mock()
        instance.update_db = Mock()
        instance.update_access = Mock()
        return instance

    def test_modify_instance_with_empty_args(self):
        instance = self._setup_modify_instance_mocks()
        args = {}

        self.controller._modify_instance(self.context, self.req,
                                         instance, **args)

        self.assertEqual(0, instance.detach_replica.call_count)
        self.assertEqual(0, instance.detach_configuration.call_count)
        self.assertEqual(0, instance.attach_configuration.call_count)
        self.assertEqual(0, instance.update_db.call_count)

    def test_modify_instance_with_False_detach_replica_arg(self):
        instance = self._setup_modify_instance_mocks()
        args = {}
        args['detach_replica'] = False

        self.controller._modify_instance(self.context, self.req,
                                         instance, **args)

        self.assertEqual(0, instance.detach_replica.call_count)

    def test_modify_instance_with_True_detach_replica_arg(self):
        instance = self._setup_modify_instance_mocks()
        args = {}
        args['detach_replica'] = True

        self.controller._modify_instance(self.context, self.req,
                                         instance, **args)

        self.assertEqual(1, instance.detach_replica.call_count)

    def test_modify_instance_with_configuration_id_arg(self):
        instance = self._setup_modify_instance_mocks()
        args = {}
        args['configuration_id'] = 'some_id'

        self.controller._modify_instance(self.context, self.req,
                                         instance, **args)

        self.assertEqual(1, instance.attach_configuration.call_count)

    def test_modify_instance_with_None_configuration_id_arg(self):
        instance = self._setup_modify_instance_mocks()
        args = {}
        args['configuration_id'] = None

        self.controller._modify_instance(self.context, self.req,
                                         instance, **args)

        self.assertEqual(1, instance.detach_configuration.call_count)

    def test_update_api_invalid_field(self):
        body = {
            'instance': {
                'invalid': 'invalid'
            }
        }
        schema = self.controller.get_schema('update', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))

    @mock.patch('trove.instance.models.Instance.load')
    def test_update_name(self, load_mock):
        body = {
            'instance': {
                'name': 'new_name'
            }
        }
        ins_mock = MagicMock()
        load_mock.return_value = ins_mock

        self.controller.update(MagicMock(), 'fake_id', body, 'fake_tenant_id')

        ins_mock.update_db.assert_called_once_with(name='new_name')

    def test_update_multiple_operations(self):
        body = {
            'instance': {
                'name': 'new_name',
                'replica_of': None,
                'configuration': 'fake_config_id'
            }
        }

        self.assertRaises(
            exception.BadRequest,
            self.controller.update,
            MagicMock(), 'fake_id', body, 'fake_tenant_id'
        )

    @mock.patch('trove.instance.models.Instance.load')
    def test_update_name_and_access(self, load_mock):
        body = {
            'instance': {
                'name': 'new_name',
                'access': {
                    'is_public': True,
                    'allowed_cidrs': []
                }
            }
        }
        ins_mock = MagicMock()
        load_mock.return_value = ins_mock

        self.controller.update(MagicMock(), 'fake_id', body, 'fake_tenant_id')

        ins_mock.update_db.assert_called_once_with(name='new_name')
        ins_mock.update_access.assert_called_once_with(
            body['instance']['access'])