989ade090a5dbe21d02f90013dc4347b49390c8d
[functest.git] / functest / tests / unit / openstack / rally / test_rally.py
1 #!/usr/bin/env python
2
3 # All rights reserved. This program and the accompanying materials
4 # are made available under the terms of the Apache License, Version 2.0
5 # which accompanies this distribution, and is available at
6 # http://www.apache.org/licenses/LICENSE-2.0
7
8 # pylint: disable=missing-docstring,protected-access,invalid-name
9
10 import json
11 import logging
12 import os
13 import unittest
14
15 import mock
16 from snaps.openstack.os_credentials import OSCreds
17 from xtesting.core import testcase
18
19 from functest.opnfv_tests.openstack.rally import rally
20
21
22 class OSRallyTesting(unittest.TestCase):
23     # pylint: disable=too-many-public-methods
24     def setUp(self):
25         os_creds = OSCreds(
26             username='user', password='pass',
27             auth_url='http://foo.com:5000/v3', project_name='bar')
28         with mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
29                         'get_credentials',
30                         return_value=os_creds) as mock_get_creds:
31             self.rally_base = rally.RallyBase()
32         self.assertTrue(mock_get_creds.called)
33
34     def test_build_task_args_missing_floating_network(self):
35         os.environ['OS_AUTH_URL'] = ''
36         self.rally_base.ext_net_name = ''
37         task_args = self.rally_base._build_task_args('test_file_name')
38         self.assertEqual(task_args['floating_network'], '')
39
40     def test_build_task_args_missing_net_id(self):
41         os.environ['OS_AUTH_URL'] = ''
42         self.rally_base.priv_net_id = ''
43         task_args = self.rally_base._build_task_args('test_file_name')
44         self.assertEqual(task_args['netid'], '')
45
46     @staticmethod
47     def check_scenario_file(value):
48         yaml_file = 'opnfv-{}.yaml'.format('test_file_name')
49         if yaml_file in value:
50             return False
51         return True
52
53     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists')
54     def test_prepare_test_list_missing_scenario_file(self, mock_func):
55         mock_func.side_effect = self.check_scenario_file
56         with self.assertRaises(Exception):
57             self.rally_base._prepare_test_list('test_file_name')
58         mock_func.assert_called()
59
60     @staticmethod
61     def check_temp_dir(value):
62         yaml_file = 'opnfv-{}.yaml'.format('test_file_name')
63         if yaml_file in value:
64             return True
65         return False
66
67     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists')
68     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs')
69     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
70                 '_apply_blacklist')
71     def test_prepare_test_list_missing_temp_dir(
72             self, mock_method, mock_os_makedirs, mock_path_exists):
73         mock_path_exists.side_effect = self.check_temp_dir
74
75         yaml_file = 'opnfv-{}.yaml'.format('test_file_name')
76         ret_val = os.path.join(self.rally_base.TEMP_DIR, yaml_file)
77         self.assertEqual(self.rally_base._prepare_test_list('test_file_name'),
78                          ret_val)
79         mock_path_exists.assert_called()
80         mock_method.assert_called()
81         mock_os_makedirs.assert_called()
82
83     def test_get_task_id_default(self):
84         cmd_raw = 'Task 1: started'
85         self.assertEqual(self.rally_base.get_task_id(cmd_raw),
86                          '1')
87
88     def test_get_task_id_missing_id(self):
89         cmd_raw = ''
90         self.assertEqual(self.rally_base.get_task_id(cmd_raw),
91                          None)
92
93     def test_task_succeed_fail(self):
94         json_raw = json.dumps([None])
95         self.assertEqual(self.rally_base.task_succeed(json_raw),
96                          False)
97         json_raw = json.dumps([{'result': [{'error': ['test_error']}]}])
98         self.assertEqual(self.rally_base.task_succeed(json_raw),
99                          False)
100
101     def test_task_succeed_success(self):
102         json_raw = json.dumps('')
103         self.assertEqual(self.rally_base.task_succeed(json_raw),
104                          True)
105
106     def test_get_cmd_output(self):
107         proc = mock.Mock()
108         proc.stdout.__iter__ = mock.Mock(return_value=iter(['line1', 'line2']))
109         self.assertEqual(self.rally_base.get_cmd_output(proc),
110                          'line1line2')
111
112     @mock.patch('__builtin__.open', mock.mock_open())
113     @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load',
114                 return_value={'scenario': [
115                     {'scenarios': ['test_scenario'],
116                      'installers': ['test_installer'],
117                      'tests': ['test']},
118                     {'scenarios': ['other_scenario'],
119                      'installers': ['test_installer'],
120                      'tests': ['other_test']}]})
121     def test_excl_scenario_default(self, mock_func):
122         os.environ['INSTALLER_TYPE'] = 'test_installer'
123         os.environ['DEPLOY_SCENARIO'] = 'test_scenario'
124         self.assertEqual(self.rally_base.excl_scenario(), ['test'])
125         mock_func.assert_called()
126
127     @mock.patch('__builtin__.open', mock.mock_open())
128     @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load',
129                 return_value={'scenario': [
130                     {'scenarios': ['^os-[^-]+-featT-modeT$'],
131                      'installers': ['test_installer'],
132                      'tests': ['test1']},
133                     {'scenarios': ['^os-ctrlT-[^-]+-modeT$'],
134                      'installers': ['test_installer'],
135                      'tests': ['test2']},
136                     {'scenarios': ['^os-ctrlT-featT-[^-]+$'],
137                      'installers': ['test_installer'],
138                      'tests': ['test3']},
139                     {'scenarios': ['^os-'],
140                      'installers': ['test_installer'],
141                      'tests': ['test4']},
142                     {'scenarios': ['other_scenario'],
143                      'installers': ['test_installer'],
144                      'tests': ['test0a']},
145                     {'scenarios': [''],  # empty scenario
146                      'installers': ['test_installer'],
147                      'tests': ['test0b']}]})
148     def test_excl_scenario_regex(self, mock_func):
149         os.environ['INSTALLER_TYPE'] = 'test_installer'
150         os.environ['DEPLOY_SCENARIO'] = 'os-ctrlT-featT-modeT'
151         self.assertEqual(self.rally_base.excl_scenario(),
152                          ['test1', 'test2', 'test3', 'test4'])
153         mock_func.assert_called()
154
155     @mock.patch('__builtin__.open', side_effect=Exception)
156     def test_excl_scenario_exception(self, mock_open):
157         self.assertEqual(self.rally_base.excl_scenario(), [])
158         mock_open.assert_called()
159
160     @mock.patch('__builtin__.open', mock.mock_open())
161     @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load',
162                 return_value={'functionality': [
163                     {'functions': ['no_migration'], 'tests': ['test']}]})
164     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
165                 '_migration_supported', return_value=False)
166     def test_excl_func_default(self, mock_func, mock_yaml_load):
167         os.environ['INSTALLER_TYPE'] = 'test_installer'
168         os.environ['DEPLOY_SCENARIO'] = 'test_scenario'
169         self.assertEqual(self.rally_base.excl_func(), ['test'])
170         mock_func.assert_called()
171         mock_yaml_load.assert_called()
172
173     @mock.patch('__builtin__.open', side_effect=Exception)
174     def test_excl_func_exception(self, mock_open):
175         self.assertEqual(self.rally_base.excl_func(), [])
176         mock_open.assert_called()
177
178     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.stat')
179     def test_file_is_empty_default(self, mock_os_stat):
180         attrs = {'st_size': 10}
181         mock_os_stat.return_value.configure_mock(**attrs)
182         self.assertEqual(self.rally_base.file_is_empty('test_file_name'),
183                          False)
184         mock_os_stat.assert_called()
185
186     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.stat',
187                 side_effect=Exception)
188     def test_file_is_empty_exception(self, mock_os_stat):
189         self.assertEqual(self.rally_base.file_is_empty('test_file_name'), True)
190         mock_os_stat.assert_called()
191
192     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
193                 return_value=False)
194     def test_run_task_missing_task_file(self, mock_path_exists):
195         with self.assertRaises(Exception):
196             self.rally_base._run_task('test_name')
197         mock_path_exists.assert_called()
198
199     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
200                 return_value=True)
201     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
202                 '_prepare_test_list', return_value='test_file_name')
203     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
204                 'file_is_empty', return_value=True)
205     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info')
206     def test_run_task_no_tests_for_scenario(self, mock_logger_info,
207                                             mock_file_empty, mock_prep_list,
208                                             mock_path_exists):
209         self.rally_base._run_task('test_name')
210         mock_logger_info.assert_any_call('No tests for scenario \"%s\"',
211                                          'test_name')
212         mock_file_empty.assert_called()
213         mock_prep_list.assert_called()
214         mock_path_exists.assert_called()
215
216     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
217                 '_prepare_test_list', return_value='test_file_name')
218     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
219                 'file_is_empty', return_value=False)
220     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
221                 '_build_task_args', return_value={})
222     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
223                 '_append_summary')
224     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
225                 'get_task_id', return_value=None)
226     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
227                 'get_cmd_output', return_value='')
228     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
229                 return_value=True)
230     @mock.patch('functest.opnfv_tests.openstack.rally.rally.subprocess.Popen')
231     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.error')
232     def test_run_task_taskid_missing(self, mock_logger_error, *args):
233         # pylint: disable=unused-argument
234         self.rally_base._run_task('test_name')
235         text = 'Failed to retrieve task_id, validating task...'
236         mock_logger_error.assert_any_call(text)
237
238     @mock.patch('__builtin__.open', mock.mock_open())
239     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
240                 '_prepare_test_list', return_value='test_file_name')
241     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
242                 'file_is_empty', return_value=False)
243     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
244                 '_build_task_args', return_value={})
245     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
246                 '_append_summary')
247     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
248                 'get_task_id', return_value='1')
249     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
250                 'get_cmd_output', return_value='')
251     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
252                 'task_succeed', return_value=True)
253     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
254                 return_value=True)
255     @mock.patch('functest.opnfv_tests.openstack.rally.rally.subprocess.Popen')
256     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs')
257     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info')
258     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.error')
259     def test_run_task_default(self, mock_logger_error, mock_logger_info,
260                               *args):
261         # pylint: disable=unused-argument
262         self.rally_base._run_task('test_name')
263         text = 'Test scenario: "test_name" OK.\n'
264         mock_logger_info.assert_any_call(text)
265         mock_logger_error.assert_not_called()
266
267     def test_prepare_env_testname_invalid(self):
268         self.rally_base.TESTS = ['test1', 'test2']
269         self.rally_base.test_name = 'test'
270         with self.assertRaises(Exception):
271             self.rally_base._prepare_env()
272
273     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
274                 'get_active_compute_cnt')
275     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
276                 'get_ext_net_name', return_value='test_net_name')
277     @mock.patch('snaps.openstack.utils.deploy_utils.create_image',
278                 return_value=None)
279     def test_prepare_env_image_missing(
280             self, mock_get_img, mock_get_net, mock_get_comp_cnt):
281         self.rally_base.TESTS = ['test1', 'test2']
282         self.rally_base.test_name = 'test1'
283         with self.assertRaises(Exception):
284             self.rally_base._prepare_env()
285         mock_get_img.assert_called()
286         mock_get_net.assert_called()
287         mock_get_comp_cnt.assert_called()
288
289     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
290                 'get_active_compute_cnt')
291     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
292                 'get_ext_net_name', return_value='test_net_name')
293     @mock.patch('snaps.openstack.utils.deploy_utils.create_image')
294     @mock.patch('snaps.openstack.utils.deploy_utils.create_network',
295                 return_value=None)
296     def test_prepare_env_network_creation_failed(
297             self, mock_create_net, mock_get_img, mock_get_net,
298             mock_get_comp_cnt):
299         self.rally_base.TESTS = ['test1', 'test2']
300         self.rally_base.test_name = 'test1'
301         with self.assertRaises(Exception):
302             self.rally_base._prepare_env()
303         mock_create_net.assert_called()
304         mock_get_img.assert_called()
305         mock_get_net.assert_called()
306         mock_get_comp_cnt.assert_called()
307
308     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
309                 'get_active_compute_cnt')
310     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
311                 'get_ext_net_name', return_value='test_net_name')
312     @mock.patch('snaps.openstack.utils.deploy_utils.create_image')
313     @mock.patch('snaps.openstack.utils.deploy_utils.create_network')
314     @mock.patch('snaps.openstack.utils.deploy_utils.create_router',
315                 return_value=None)
316     def test_prepare_env_router_creation_failed(self, *args):
317         self.rally_base.TESTS = ['test1', 'test2']
318         self.rally_base.test_name = 'test1'
319         with self.assertRaises(Exception):
320             self.rally_base._prepare_env()
321         for func in args:
322             func.assert_called()
323
324     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
325                 'get_active_compute_cnt')
326     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
327                 'get_ext_net_name', return_value='test_net_name')
328     @mock.patch('snaps.openstack.utils.deploy_utils.create_image')
329     @mock.patch('snaps.openstack.utils.deploy_utils.create_network')
330     @mock.patch('snaps.openstack.utils.deploy_utils.create_router')
331     @mock.patch('snaps.openstack.create_flavor.OpenStackFlavor.create',
332                 return_value=None)
333     def test_prepare_env_flavor_creation_failed(self, mock_create_flavor,
334                                                 *args):
335         self.rally_base.TESTS = ['test1', 'test2']
336         self.rally_base.test_name = 'test1'
337         with self.assertRaises(Exception):
338             self.rally_base._prepare_env()
339         for func in args:
340             func.assert_called()
341         mock_create_flavor.assert_called_once()
342
343     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
344                 'get_active_compute_cnt')
345     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
346                 'get_ext_net_name', return_value='test_net_name')
347     @mock.patch('snaps.openstack.utils.deploy_utils.create_image')
348     @mock.patch('snaps.openstack.utils.deploy_utils.create_network')
349     @mock.patch('snaps.openstack.utils.deploy_utils.create_router')
350     @mock.patch('snaps.openstack.create_flavor.OpenStackFlavor.create',
351                 side_effect=[mock.Mock, None])
352     def test_prepare_env_flavor_alt_creation_failed(self, mock_create_flavor,
353                                                     *args):
354         self.rally_base.TESTS = ['test1', 'test2']
355         self.rally_base.test_name = 'test1'
356         with self.assertRaises(Exception):
357             self.rally_base._prepare_env()
358         for func in args:
359             func.assert_called()
360         self.assertEqual(mock_create_flavor.call_count, 2)
361
362     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
363                 '_run_task')
364     def test_run_tests_all(self, mock_run_task):
365         self.rally_base.TESTS = ['test1', 'test2']
366         self.rally_base.test_name = 'all'
367         self.rally_base._run_tests()
368         mock_run_task.assert_any_call('test1')
369         mock_run_task.assert_any_call('test2')
370
371     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
372                 '_run_task')
373     def test_run_tests_default(self, mock_run_task):
374         self.rally_base.TESTS = ['test1', 'test2']
375         self.rally_base.test_name = 'test1'
376         self.rally_base._run_tests()
377         mock_run_task.assert_any_call('test1')
378
379     def test_clean_up_default(self):
380         creator1 = mock.Mock()
381         creator2 = mock.Mock()
382         self.rally_base.creators = [creator1, creator2]
383         self.rally_base._clean_up()
384         self.assertTrue(creator1.clean.called)
385         self.assertTrue(creator2.clean.called)
386
387     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
388                 'create_rally_deployment')
389     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
390                 '_prepare_env')
391     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
392                 '_run_tests')
393     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
394                 '_generate_report')
395     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
396                 '_clean_up')
397     def test_run_default(self, *args):
398         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_OK)
399         for func in args:
400             func.assert_called()
401
402     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
403                 'create_rally_deployment', side_effect=Exception)
404     def test_run_exception_create_rally_dep(self, mock_create_rally_dep):
405         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_RUN_ERROR)
406         mock_create_rally_dep.assert_called()
407
408     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
409                 'create_rally_deployment', return_value=mock.Mock())
410     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
411                 '_prepare_env', side_effect=Exception)
412     def test_run_exception_prepare_env(self, mock_prep_env, *args):
413         # pylint: disable=unused-argument
414         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_RUN_ERROR)
415         mock_prep_env.assert_called()
416
417     def test_append_summary(self):
418         text = '[{"result":[{"error":[]},{"error":["err"]}],' \
419                '"full_duration": 17.312026}]'
420         self.rally_base._append_summary(text, "foo_test")
421         self.assertEqual(self.rally_base.summary[0]['test_name'], "foo_test")
422         self.assertEqual(self.rally_base.summary[0]['overall_duration'],
423                          17.312026)
424         self.assertEqual(self.rally_base.summary[0]['nb_tests'], 2)
425         self.assertEqual(self.rally_base.summary[0]['nb_success'], 1)
426
427
428 if __name__ == "__main__":
429     logging.disable(logging.CRITICAL)
430     unittest.main(verbosity=2)