File: test_existing.py

package info (click to toggle)
rally-openstack 3.0.0-9
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,968 kB
  • sloc: python: 53,131; sh: 262; makefile: 38
file content (416 lines) | stat: -rw-r--r-- 16,278 bytes parent folder | download | duplicates (4)
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
416
# 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 json
from unittest import mock

import jsonschema

from rally.env import env_mgr
from rally.env import platform
from rally import exceptions

from rally_openstack.environment.platforms import existing
from tests.unit import test


class PlatformBaseTestCase(test.TestCase):

    def _check_schema(self, schema, obj):
        jsonschema.validate(obj, schema)

    def _check_health_schema(self, obj):
        self._check_schema(env_mgr.EnvManager._HEALTH_FORMAT, obj)

    def _check_cleanup_schema(self, obj):
        self._check_schema(env_mgr.EnvManager._CLEANUP_FORMAT, obj)

    def _check_info_schema(self, obj):
        self._check_schema(env_mgr.EnvManager._INFO_FORMAT, obj)


class ExistingPlatformTestCase(PlatformBaseTestCase):

    def test_validate_spec_schema(self):
        spec = {
            "existing@openstack": {
                "auth_url": "url",
                "admin": {
                    "username": "admin",
                    "password": "password123",
                    "tenant_name": "admin"
                },
                "users": [{
                    "username": "admin",
                    "password": "password123",
                    "tenant_name": "admin"
                }]
            }
        }
        result = platform.Platform.validate("existing@openstack", {},
                                            spec, spec["existing@openstack"])
        self.assertEqual([], result)

    def test_validate_invalid_spec(self):
        spec = {
            "existing@openstack": {
                "something_wrong": {
                    "username": "not_an_admin",
                    "password": "password123",
                    "project_name": "not_an_admin"
                }
            }
        }
        result = platform.Platform.validate("existing@openstack", {},
                                            spec, spec["existing@openstack"])
        self.assertNotEqual([], result)

    def test_validate_spec_schema_with_api_info(self):
        spec = {
            "existing@openstack": {
                "auth_url": "url",
                "admin": {
                    "username": "admin",
                    "password": "password123",
                    "tenant_name": "admin"
                },
                "api_info": {
                    "nova": {"version": 1},
                    "cinder": {"version": 2, "service_type": "volumev2"}
                }
            }
        }
        result = platform.Platform.validate("existing@openstack", {},
                                            spec, spec["existing@openstack"])
        self.assertEqual([], result)

    def test_create_users_only(self):

        spec = {
            "auth_url": "https://best",
            "endpoint": "check_that_its_poped",
            "users": [
                {"project_name": "a", "username": "a", "password": "a"},
                {"project_name": "b", "username": "b", "password": "b"}
            ]
        }

        self.assertEqual(
            ({
                "admin": None,
                "users": [
                    {
                        "auth_url": "https://best", "endpoint_type": None,
                        "region_name": None,
                        "domain_name": None,
                        "user_domain_name": "default",
                        "project_domain_name": "default",
                        "https_insecure": False, "https_cacert": None,
                        "tenant_name": "a", "username": "a", "password": "a"
                    },
                    {
                        "auth_url": "https://best", "endpoint_type": None,
                        "region_name": None,
                        "domain_name": None,
                        "user_domain_name": "default",
                        "project_domain_name": "default",
                        "https_insecure": False, "https_cacert": None,
                        "tenant_name": "b", "username": "b", "password": "b"
                    }
                ]
            }, {}),
            existing.OpenStack(spec).create())

    def test_create_admin_only(self):
        spec = {
            "auth_url": "https://best",
            "endpoint_type": "public",
            "https_insecure": True,
            "https_cacert": "/my.ca",
            "profiler_hmac_key": "key",
            "profiler_conn_str": "http://prof",
            "admin": {
                "domain_name": "d", "user_domain_name": "d",
                "project_domain_name": "d", "project_name": "d",
                "username": "d", "password": "d"
            }
        }
        self.assertEqual(
            (
                {
                    "admin": {
                        "auth_url": "https://best",
                        "endpoint_type": "public",
                        "https_insecure": True, "https_cacert": "/my.ca",
                        "profiler_hmac_key": "key",
                        "profiler_conn_str": "http://prof",
                        "region_name": None, "domain_name": "d",
                        "user_domain_name": "d", "project_domain_name": "d",
                        "tenant_name": "d", "username": "d", "password": "d"
                    },
                    "users": []
                },
                {}
            ),
            existing.OpenStack(spec).create())

    def test_create_spec_from_sys_environ(self):
        # keystone v2
        sys_env = {
            "OS_AUTH_URL": "https://example.com",
            "OS_USERNAME": "user",
            "OS_PASSWORD": "pass",
            "OS_TENANT_NAME": "projectX",
            "OS_INTERFACE": "publicURL",
            "OS_REGION_NAME": "Region1",
            "OS_CACERT": "Cacert",
            "OS_CERT": "cert",
            "OS_KEY": "key",
            "OS_INSECURE": True,
            "OSPROFILER_HMAC_KEY": "hmackey",
            "OSPROFILER_CONN_STR": "https://example2.com",
        }

        result = existing.OpenStack.create_spec_from_sys_environ(sys_env)
        self.assertTrue(result["available"])
        self.assertEqual(
            {
                "admin": {
                    "username": "user",
                    "tenant_name": "projectX",
                    "password": "pass"
                },
                "auth_url": "https://example.com",
                "endpoint_type": "public",
                "region_name": "Region1",
                "https_cacert": "Cacert",
                "https_cert": "cert",
                "https_key": "key",
                "https_insecure": True,
                "profiler_hmac_key": "hmackey",
                "profiler_conn_str": "https://example2.com",
                "api_info": {
                    "keystone": {
                        "version": 2,
                        "service_type": "identity"
                    }
                }
            }, result["spec"])

        # keystone v3
        sys_env["OS_IDENTITY_API_VERSION"] = "3"

        result = existing.OpenStack.create_spec_from_sys_environ(sys_env)

        self.assertEqual(
            {
                "admin": {
                    "username": "user",
                    "project_name": "projectX",
                    "user_domain_name": "Default",
                    "password": "pass",
                    "project_domain_name": "Default"
                },
                "endpoint_type": "public",
                "auth_url": "https://example.com",
                "region_name": "Region1",
                "https_cacert": "Cacert",
                "https_cert": "cert",
                "https_key": "key",
                "https_insecure": True,
                "profiler_hmac_key": "hmackey",
                "profiler_conn_str": "https://example2.com",
                "api_info": {
                    "keystone": {
                        "version": 3,
                        "service_type": "identityv3"
                    }
                }
            }, result["spec"])

    def test_create_spec_from_sys_environ_fails_with_missing_vars(self):
        sys_env = {"OS_AUTH_URL": "https://example.com"}
        result = existing.OpenStack.create_spec_from_sys_environ(sys_env)
        self.assertFalse(result["available"])
        self.assertIn("OS_USERNAME", result["message"])
        self.assertIn("OS_PASSWORD", result["message"])
        self.assertNotIn("OS_AUTH_URL", result["message"])

        sys_env = {"OS_AUTH_URL": "https://example.com",
                   "OS_USERNAME": "user",
                   "OS_PASSWORD": "pass"}
        result = existing.OpenStack.create_spec_from_sys_environ(sys_env)
        self.assertFalse(result["available"])
        self.assertIn("OS_PROJECT_NAME or OS_TENANT_NAME", result["message"])

    def test_destroy(self):
        self.assertIsNone(existing.OpenStack({}).destroy())

    def test_cleanup(self):
        result1 = existing.OpenStack({}).cleanup()
        result2 = existing.OpenStack({}).cleanup(task_uuid="any")
        self.assertEqual(result1, result2)
        self.assertEqual(
            {
                "message": "Coming soon!",
                "discovered": 0,
                "deleted": 0,
                "failed": 0,
                "resources": {},
                "errors": []
            },
            result1
        )
        self._check_cleanup_schema(result1)

    @mock.patch("rally_openstack.common.osclients.Clients")
    def test_check_health(self, mock_clients):
        pdata = {
            "admin": mock.MagicMock(),
            "users": [mock.MagicMock(), mock.MagicMock()]
        }
        result = existing.OpenStack({}, platform_data=pdata).check_health()
        self._check_health_schema(result)
        self.assertEqual({"available": True}, result)
        mock_clients.assert_has_calls(
            [mock.call(pdata["users"][0]), mock.call().keystone(),
             mock.call(pdata["users"][1]), mock.call().keystone(),
             mock.call(pdata["admin"]), mock.call().verified_keystone()])

    @mock.patch("rally_openstack.common.osclients.Clients")
    def test_check_failed_with_native_rally_exc(self, mock_clients):
        e = exceptions.RallyException("foo")
        mock_clients.return_value.keystone.side_effect = e
        pdata = {"admin": None,
                 "users": [{"username": "balbab", "password": "12345"}]}
        result = existing.OpenStack({}, platform_data=pdata).check_health()
        self._check_health_schema(result)
        self.assertEqual(
            {
                "available": False,
                "message": e.format_message(),
                "traceback": mock.ANY
            },
            result)

    @mock.patch("rally_openstack.common.osclients.Clients")
    def test_check_failed_admin(self, mock_clients):
        mock_clients.return_value.verified_keystone.side_effect = Exception
        pdata = {"admin": {"username": "balbab", "password": "12345"},
                 "users": []}
        result = existing.OpenStack({}, platform_data=pdata).check_health()
        self._check_health_schema(result)
        self.assertEqual(
            {"available": False,
             "message":
                "Bad admin creds: \n%s"
                % json.dumps({"username": "balbab", "password": "***",
                              "api_info": {}},
                             indent=2, sort_keys=True),
             "traceback": mock.ANY},
            result)
        self.assertIn("Traceback (most recent call last)", result["traceback"])

    @mock.patch("rally_openstack.common.osclients.Clients")
    def test_check_failed_users(self, mock_clients):
        mock_clients.return_value.keystone.side_effect = Exception
        pdata = {"admin": None,
                 "users": [{"username": "balbab", "password": "12345"}]}
        result = existing.OpenStack({}, platform_data=pdata).check_health()
        self._check_health_schema(result)
        self.assertEqual(
            {"available": False,
             "message":
                "Bad user creds: \n%s"
                % json.dumps({"username": "balbab", "password": "***",
                              "api_info": {}},
                             indent=2, sort_keys=True),
             "traceback": mock.ANY},
            result)
        self.assertIn("Traceback (most recent call last)", result["traceback"])

    @mock.patch("rally_openstack.common.osclients.Clients")
    def test_check_health_with_api_info(self, mock_clients):
        pdata = {"admin": mock.MagicMock(),
                 "users": [],
                 "api_info": {"fakeclient": "version"}}
        result = existing.OpenStack({}, platform_data=pdata).check_health()
        self._check_health_schema(result)
        self.assertEqual({"available": True}, result)
        mock_clients.assert_has_calls(
            [mock.call(pdata["admin"]), mock.call().verified_keystone(),
             mock.call().fakeclient.choose_version(),
             mock.call().fakeclient.validate_version(
                 mock_clients.return_value.fakeclient.choose_version
                 .return_value),
             mock.call().fakeclient.create_client()])

    @mock.patch("rally_openstack.common.osclients.Clients")
    def test_check_version_failed_with_api_info(self, mock_clients):
        pdata = {"admin": mock.MagicMock(),
                 "users": [],
                 "api_info": {"fakeclient": "version"}}

        def validate_version(version):
            raise exceptions.RallyException("Version is not supported.")
        (mock_clients.return_value.fakeclient
         .validate_version) = validate_version
        result = existing.OpenStack({}, platform_data=pdata).check_health()
        self._check_health_schema(result)
        self.assertEqual({"available": False,
                          "message": ("Invalid setting for 'fakeclient':"
                                      " Version is not supported.")},
                         result)

    @mock.patch("rally_openstack.common.osclients.Clients")
    def test_check_unexpected_failed_with_api_info(self, mock_clients):
        pdata = {"admin": mock.MagicMock(),
                 "users": [],
                 "api_info": {"fakeclient": "version"}}

        def create_client():
            raise Exception("Invalid client.")

        (mock_clients.return_value.fakeclient
         .choose_version.return_value) = "1.0"
        mock_clients.return_value.fakeclient.create_client = create_client
        result = existing.OpenStack({}, platform_data=pdata).check_health()
        self._check_health_schema(result)
        self.assertEqual({"available": False,
                          "message": ("Can not create 'fakeclient' with"
                                      " 1.0 version."),
                          "traceback": mock.ANY},
                         result)

    @mock.patch("rally_openstack.common.osclients.Clients")
    def test_info(self, mock_clients):
        mock_clients.return_value.services.return_value = {
            "foo": "bar",
            "volumev4": "__unknown__"}
        platform_data = {
            "admin": None,
            "users": [{"username": "u1", "password": "123"}]
        }
        p = existing.OpenStack({}, platform_data=platform_data)

        result = p.info()
        mock_clients.assert_called_once_with(platform_data["users"][0])
        mock_clients.return_value.services.assert_called_once_with()
        self.assertEqual(
            {
                "info": {
                    "services": [{"type": "foo", "name": "bar"},
                                 {"type": "volumev4"}]}},
            result)
        self._check_info_schema(result)