Make synchronous Shade calls
[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 import munch
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         with mock.patch('os_client_config.get_config') as mock_get_config, \
26                 mock.patch('shade.OpenStackCloud') as mock_shade:
27             self.rally_base = rally.RallyBase()
28             self.rally_base.image = munch.Munch(name='foo')
29             self.rally_base.flavor = munch.Munch(name='foo')
30             self.rally_base.flavor_alt = munch.Munch(name='bar')
31         self.assertTrue(mock_get_config.called)
32         self.assertTrue(mock_shade.called)
33
34     def test_build_task_args_missing_floating_network(self):
35         os.environ['OS_AUTH_URL'] = ''
36         self.rally_base.ext_net = None
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.network = None
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({})
95         self.assertEqual(self.rally_base.task_succeed(json_raw),
96                          False)
97         json_raw = json.dumps({'tasks': [{'status': 'crashed'}]})
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({'tasks': [{'status': 'finished',
103                                           'pass_sla': True}]})
104         self.assertEqual(self.rally_base.task_succeed(json_raw),
105                          True)
106
107     def test_get_cmd_output(self):
108         proc = mock.Mock()
109         proc.stdout.__iter__ = mock.Mock(return_value=iter(['line1', 'line2']))
110         self.assertEqual(self.rally_base.get_cmd_output(proc),
111                          'line1line2')
112
113     @mock.patch('six.moves.builtins.open', mock.mock_open())
114     @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load',
115                 return_value={'scenario': [
116                     {'scenarios': ['test_scenario'],
117                      'installers': ['test_installer'],
118                      'tests': ['test']},
119                     {'scenarios': ['other_scenario'],
120                      'installers': ['test_installer'],
121                      'tests': ['other_test']}]})
122     def test_excl_scenario_default(self, mock_func):
123         os.environ['INSTALLER_TYPE'] = 'test_installer'
124         os.environ['DEPLOY_SCENARIO'] = 'test_scenario'
125         self.assertEqual(self.rally_base.excl_scenario(), ['test'])
126         mock_func.assert_called()
127
128     @mock.patch('six.moves.builtins.open', mock.mock_open())
129     @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load',
130                 return_value={'scenario': [
131                     {'scenarios': ['^os-[^-]+-featT-modeT$'],
132                      'installers': ['test_installer'],
133                      'tests': ['test1']},
134                     {'scenarios': ['^os-ctrlT-[^-]+-modeT$'],
135                      'installers': ['test_installer'],
136                      'tests': ['test2']},
137                     {'scenarios': ['^os-ctrlT-featT-[^-]+$'],
138                      'installers': ['test_installer'],
139                      'tests': ['test3']},
140                     {'scenarios': ['^os-'],
141                      'installers': ['test_installer'],
142                      'tests': ['test4']},
143                     {'scenarios': ['other_scenario'],
144                      'installers': ['test_installer'],
145                      'tests': ['test0a']},
146                     {'scenarios': [''],  # empty scenario
147                      'installers': ['test_installer'],
148                      'tests': ['test0b']}]})
149     def test_excl_scenario_regex(self, mock_func):
150         os.environ['INSTALLER_TYPE'] = 'test_installer'
151         os.environ['DEPLOY_SCENARIO'] = 'os-ctrlT-featT-modeT'
152         self.assertEqual(self.rally_base.excl_scenario(),
153                          ['test1', 'test2', 'test3', 'test4'])
154         mock_func.assert_called()
155
156     @mock.patch('six.moves.builtins.open', side_effect=Exception)
157     def test_excl_scenario_exception(self, mock_open):
158         self.assertEqual(self.rally_base.excl_scenario(), [])
159         mock_open.assert_called()
160
161     @mock.patch('six.moves.builtins.open', mock.mock_open())
162     @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load',
163                 return_value={'functionality': [
164                     {'functions': ['no_migration'], 'tests': ['test']}]})
165     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
166                 '_migration_supported', return_value=False)
167     def test_excl_func_default(self, mock_func, mock_yaml_load):
168         os.environ['INSTALLER_TYPE'] = 'test_installer'
169         os.environ['DEPLOY_SCENARIO'] = 'test_scenario'
170         self.assertEqual(self.rally_base.excl_func(), ['test'])
171         mock_func.assert_called()
172         mock_yaml_load.assert_called()
173
174     @mock.patch('six.moves.builtins.open', side_effect=Exception)
175     def test_excl_func_exception(self, mock_open):
176         self.assertEqual(self.rally_base.excl_func(), [])
177         mock_open.assert_called()
178
179     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.stat')
180     def test_file_is_empty_default(self, mock_os_stat):
181         attrs = {'st_size': 10}
182         mock_os_stat.return_value.configure_mock(**attrs)
183         self.assertEqual(self.rally_base.file_is_empty('test_file_name'),
184                          False)
185         mock_os_stat.assert_called()
186
187     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.stat',
188                 side_effect=Exception)
189     def test_file_is_empty_exception(self, mock_os_stat):
190         self.assertEqual(self.rally_base.file_is_empty('test_file_name'), True)
191         mock_os_stat.assert_called()
192
193     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
194                 return_value=False)
195     def test_run_task_missing_task_file(self, mock_path_exists):
196         with self.assertRaises(Exception):
197             self.rally_base._run_task('test_name')
198         mock_path_exists.assert_called()
199
200     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
201                 return_value=True)
202     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
203                 '_prepare_test_list', return_value='test_file_name')
204     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
205                 'file_is_empty', return_value=True)
206     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info')
207     def test_run_task_no_tests_for_scenario(self, mock_logger_info,
208                                             mock_file_empty, mock_prep_list,
209                                             mock_path_exists):
210         self.rally_base._run_task('test_name')
211         mock_logger_info.assert_any_call('No tests for scenario \"%s\"',
212                                          'test_name')
213         mock_file_empty.assert_called()
214         mock_prep_list.assert_called()
215         mock_path_exists.assert_called()
216
217     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
218                 '_prepare_test_list', return_value='test_file_name')
219     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
220                 'file_is_empty', return_value=False)
221     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
222                 '_build_task_args', return_value={})
223     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
224                 'get_task_id', return_value=None)
225     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
226                 'get_cmd_output', return_value='')
227     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
228                 return_value=True)
229     @mock.patch('functest.opnfv_tests.openstack.rally.rally.subprocess.Popen')
230     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.error')
231     def test_run_task_taskid_missing(self, mock_logger_error, *args):
232         # pylint: disable=unused-argument
233         with self.assertRaises(Exception):
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('six.moves.builtins.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                 'get_task_id', return_value='1')
247     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
248                 'get_cmd_output', return_value='')
249     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
250                 'task_succeed', return_value=True)
251     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
252                 return_value=True)
253     @mock.patch('functest.opnfv_tests.openstack.rally.rally.subprocess.Popen')
254     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs')
255     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info')
256     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.error')
257     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
258                 '_save_results')
259     def test_run_task_default(self, mock_save_res, *args):
260         # pylint: disable=unused-argument
261         self.rally_base._run_task('test_name')
262         mock_save_res.assert_called()
263
264     @mock.patch('six.moves.builtins.open', mock.mock_open())
265     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
266                 'task_succeed', return_value=True)
267     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
268                 'get_cmd_output', return_value='')
269     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
270                 return_value=True)
271     @mock.patch('subprocess.check_output')
272     @mock.patch('functest.opnfv_tests.openstack.rally.rally.subprocess.Popen')
273     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs')
274     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info')
275     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.debug')
276     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
277                 '_append_summary')
278     def test_save_results(self, mock_summary, *args):
279         # pylint: disable=unused-argument
280         self.rally_base._save_results('test_name', '1234')
281         mock_summary.assert_called()
282
283     def test_prepare_env_testname_invalid(self):
284         self.rally_base.TESTS = ['test1', 'test2']
285         self.rally_base.test_name = 'test'
286         with self.assertRaises(Exception):
287             self.rally_base._prepare_env()
288
289     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
290                 'get_external_network')
291     def test_prepare_env_flavor_alt_creation_failed(self, *args):
292         # pylint: disable=unused-argument
293         self.rally_base.TESTS = ['test1', 'test2']
294         self.rally_base.test_name = 'test1'
295         with mock.patch.object(self.rally_base.cloud,
296                                'list_hypervisors') as mock_list_hyperv, \
297             mock.patch.object(self.rally_base.cloud,
298                               'set_flavor_specs') as mock_set_flavor_specs, \
299             mock.patch.object(self.rally_base.cloud, 'create_flavor',
300                               side_effect=Exception) \
301                 as mock_create_flavor:
302             with self.assertRaises(Exception):
303                 self.rally_base._prepare_env()
304             mock_list_hyperv.assert_called_once()
305             mock_create_flavor.assert_called_once()
306             mock_set_flavor_specs.assert_not_called()
307
308     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
309                 '_run_task')
310     def test_run_tests_all(self, mock_run_task):
311         self.rally_base.TESTS = ['test1', 'test2']
312         self.rally_base.test_name = 'all'
313         self.rally_base._run_tests()
314         mock_run_task.assert_any_call('test1')
315         mock_run_task.assert_any_call('test2')
316
317     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
318                 '_run_task')
319     def test_run_tests_default(self, mock_run_task):
320         self.rally_base.TESTS = ['test1', 'test2']
321         self.rally_base.test_name = 'test1'
322         self.rally_base._run_tests()
323         mock_run_task.assert_any_call('test1')
324
325     def test_clean_up_default(self):
326         with mock.patch.object(self.rally_base.cloud,
327                                'delete_flavor') as mock_delete_flavor:
328             self.rally_base.flavor_alt = mock.Mock()
329             self.rally_base.clean()
330             self.assertEqual(mock_delete_flavor.call_count, 1)
331
332     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
333                 'create_rally_deployment')
334     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
335                 '_prepare_env')
336     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
337                 '_run_tests')
338     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
339                 '_generate_report')
340     def test_run_default(self, *args):
341         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_OK)
342         for func in args:
343             func.assert_called()
344
345     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
346                 'create_rally_deployment', side_effect=Exception)
347     def test_run_exception_create_rally_dep(self, mock_create_rally_dep):
348         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_RUN_ERROR)
349         mock_create_rally_dep.assert_called()
350
351     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
352                 'create_rally_deployment', return_value=mock.Mock())
353     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
354                 '_prepare_env', side_effect=Exception)
355     def test_run_exception_prepare_env(self, mock_prep_env, *args):
356         # pylint: disable=unused-argument
357         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_RUN_ERROR)
358         mock_prep_env.assert_called()
359
360     def test_append_summary(self):
361         text = '{"tasks": [{"subtasks": [{"workloads": [{"full_duration": ' \
362                '1.23,"data": [{"error": []}]}]},{"workloads": ' \
363                '[{"full_duration": 2.78, "data": [{"error": ["err"]}]}]}]}]}'
364         self.rally_base._append_summary(text, "foo_test")
365         self.assertEqual(self.rally_base.summary[0]['test_name'], "foo_test")
366         self.assertEqual(self.rally_base.summary[0]['overall_duration'], 4.01)
367         self.assertEqual(self.rally_base.summary[0]['nb_tests'], 2)
368         self.assertEqual(self.rally_base.summary[0]['nb_success'], 1)
369
370     def test_is_successful_false(self):
371         with mock.patch('six.moves.builtins.super') as mock_super:
372             self.rally_base.summary = [{"task_status": True},
373                                        {"task_status": False}]
374             self.assertEqual(self.rally_base.is_successful(),
375                              testcase.TestCase.EX_TESTCASE_FAILED)
376             mock_super(rally.RallyBase, self).is_successful.assert_not_called()
377
378     def test_is_successful_true(self):
379         with mock.patch('six.moves.builtins.super') as mock_super:
380             mock_super(rally.RallyBase, self).is_successful.return_value = 424
381             self.rally_base.summary = [{"task_status": True},
382                                        {"task_status": True}]
383             self.assertEqual(self.rally_base.is_successful(), 424)
384             mock_super(rally.RallyBase, self).is_successful.assert_called()
385
386
387 if __name__ == "__main__":
388     logging.disable(logging.CRITICAL)
389     unittest.main(verbosity=2)