Add support for Rally OpenStack CI test cases
[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                 mock.patch('functest.core.tenantnetwork.NewProject') \
28                 as mock_new_project:
29             self.rally_base = rally.RallyBase()
30             self.rally_base.image = munch.Munch(name='foo')
31             self.rally_base.flavor = munch.Munch(name='foo')
32             self.rally_base.flavor_alt = munch.Munch(name='bar')
33             self.rally_base.test_name = 'all'
34         self.assertTrue(mock_get_config.called)
35         self.assertTrue(mock_shade.called)
36         self.assertTrue(mock_new_project.called)
37
38     def test_build_task_args_missing_floating_network(self):
39         os.environ['OS_AUTH_URL'] = ''
40         self.rally_base.ext_net = None
41         task_args = self.rally_base._build_task_args('test_file_name')
42         self.assertEqual(task_args['floating_network'], '')
43
44     def test_build_task_args_missing_net_id(self):
45         os.environ['OS_AUTH_URL'] = ''
46         self.rally_base.network = None
47         task_args = self.rally_base._build_task_args('test_file_name')
48         self.assertEqual(task_args['netid'], '')
49
50     @staticmethod
51     def check_scenario_file(value):
52         yaml_file = 'opnfv-{}.yaml'.format('test_file_name')
53         if yaml_file in value:
54             return False
55         return True
56
57     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists')
58     def test_prepare_test_list_missing_scenario_file(self, mock_func):
59         mock_func.side_effect = self.check_scenario_file
60         with self.assertRaises(Exception):
61             self.rally_base._prepare_test_list('test_file_name')
62         mock_func.assert_called()
63
64     @staticmethod
65     def check_temp_dir(value):
66         yaml_file = 'opnfv-{}.yaml'.format('test_file_name')
67         if yaml_file in value:
68             return True
69         return False
70
71     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists')
72     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs')
73     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
74                 'apply_blacklist')
75     def test_prepare_test_list_missing_temp_dir(
76             self, mock_method, mock_os_makedirs, mock_path_exists):
77         mock_path_exists.side_effect = self.check_temp_dir
78
79         yaml_file = 'opnfv-{}.yaml'.format('test_file_name')
80         ret_val = os.path.join(self.rally_base.TEMP_DIR, yaml_file)
81         self.assertEqual(self.rally_base._prepare_test_list('test_file_name'),
82                          ret_val)
83         mock_path_exists.assert_called()
84         mock_method.assert_called()
85         mock_os_makedirs.assert_called()
86
87     def test_get_task_id_default(self):
88         cmd_raw = 'Task 1: started'
89         self.assertEqual(self.rally_base.get_task_id(cmd_raw),
90                          '1')
91
92     def test_get_task_id_missing_id(self):
93         cmd_raw = ''
94         self.assertEqual(self.rally_base.get_task_id(cmd_raw),
95                          None)
96
97     def test_task_succeed_fail(self):
98         json_raw = json.dumps({})
99         self.assertEqual(self.rally_base.task_succeed(json_raw),
100                          False)
101         json_raw = json.dumps({'tasks': [{'status': 'crashed'}]})
102         self.assertEqual(self.rally_base.task_succeed(json_raw),
103                          False)
104
105     def test_task_succeed_success(self):
106         json_raw = json.dumps({'tasks': [{'status': 'finished',
107                                           'pass_sla': True}]})
108         self.assertEqual(self.rally_base.task_succeed(json_raw),
109                          True)
110
111     @mock.patch('six.moves.builtins.open', mock.mock_open())
112     @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load',
113                 return_value={'scenario': [
114                     {'scenarios': ['test_scenario'],
115                      'tests': ['test']},
116                     {'scenarios': ['other_scenario'],
117                      'tests': ['other_test']}]})
118     def test_excl_scenario_default(self, mock_func):
119         os.environ['INSTALLER_TYPE'] = 'test_installer'
120         os.environ['DEPLOY_SCENARIO'] = 'test_scenario'
121         self.assertEqual(self.rally_base.excl_scenario(), ['test'])
122         mock_func.assert_called()
123
124     @mock.patch('six.moves.builtins.open', mock.mock_open())
125     @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load',
126                 return_value={'scenario': [
127                     {'scenarios': ['^os-[^-]+-featT-modeT$'],
128                      'tests': ['test1']},
129                     {'scenarios': ['^os-ctrlT-[^-]+-modeT$'],
130                      'tests': ['test2']},
131                     {'scenarios': ['^os-ctrlT-featT-[^-]+$'],
132                      'tests': ['test3']},
133                     {'scenarios': ['^os-'],
134                      'tests': ['test4']},
135                     {'scenarios': ['other_scenario'],
136                      'tests': ['test0a']},
137                     {'scenarios': [''],  # empty scenario
138                      'tests': ['test0b']}]})
139     def test_excl_scenario_regex(self, mock_func):
140         os.environ['DEPLOY_SCENARIO'] = 'os-ctrlT-featT-modeT'
141         self.assertEqual(self.rally_base.excl_scenario(),
142                          ['test1', 'test2', 'test3', 'test4'])
143         mock_func.assert_called()
144
145     @mock.patch('six.moves.builtins.open', side_effect=Exception)
146     def test_excl_scenario_exception(self, mock_open):
147         self.assertEqual(self.rally_base.excl_scenario(), [])
148         mock_open.assert_called()
149
150     @mock.patch('six.moves.builtins.open', mock.mock_open())
151     @mock.patch('functest.opnfv_tests.openstack.rally.rally.yaml.safe_load',
152                 return_value={'functionality': [
153                     {'functions': ['no_migration'], 'tests': ['test']}]})
154     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
155                 '_migration_supported', return_value=False)
156     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
157                 '_network_trunk_supported', return_value=False)
158     def test_excl_func_default(self, mock_trunk, mock_func, mock_yaml_load):
159         os.environ['DEPLOY_SCENARIO'] = 'test_scenario'
160         self.assertEqual(self.rally_base.excl_func(), ['test'])
161         mock_func.assert_called()
162         mock_trunk.assert_called()
163         mock_yaml_load.assert_called()
164
165     @mock.patch('six.moves.builtins.open', side_effect=Exception)
166     def test_excl_func_exception(self, mock_open):
167         self.assertEqual(self.rally_base.excl_func(), [])
168         mock_open.assert_called()
169
170     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.stat')
171     def test_file_is_empty_default(self, mock_os_stat):
172         attrs = {'st_size': 10}
173         mock_os_stat.return_value.configure_mock(**attrs)
174         self.assertEqual(self.rally_base.file_is_empty('test_file_name'),
175                          False)
176         mock_os_stat.assert_called()
177
178     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.stat',
179                 side_effect=Exception)
180     def test_file_is_empty_exception(self, mock_os_stat):
181         self.assertEqual(self.rally_base.file_is_empty('test_file_name'), True)
182         mock_os_stat.assert_called()
183
184     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
185                 return_value=False)
186     def test_run_task_missing_task_file(self, mock_path_exists):
187         with self.assertRaises(Exception):
188             self.rally_base.prepare_run()
189         mock_path_exists.assert_called()
190
191     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
192                 '_prepare_test_list', return_value='test_file_name')
193     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
194                 'file_is_empty', return_value=True)
195     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info')
196     def test_prepare_task_no_tests_for_scenario(
197             self, mock_logger_info, mock_file_empty, mock_prep_list):
198         self.rally_base.prepare_task('test_name')
199         mock_logger_info.assert_any_call('No tests for scenario \"%s\"',
200                                          'test_name')
201         mock_file_empty.assert_called()
202         mock_prep_list.assert_called()
203
204     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
205                 '_prepare_test_list', return_value='test_file_name')
206     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
207                 'file_is_empty', return_value=False)
208     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
209                 '_build_task_args', return_value={})
210     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
211                 'get_task_id', return_value=None)
212     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
213                 return_value=True)
214     @mock.patch('functest.opnfv_tests.openstack.rally.rally.subprocess.Popen')
215     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.error')
216     def test_run_task_taskid_missing(self, mock_logger_error, *args):
217         # pylint: disable=unused-argument
218         with self.assertRaises(Exception):
219             self.rally_base.run_task('test_name')
220         text = 'Failed to retrieve task_id'
221         mock_logger_error.assert_any_call(text)
222
223     @mock.patch('six.moves.builtins.open', mock.mock_open())
224     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
225                 '_prepare_test_list', return_value='test_file_name')
226     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
227                 'file_is_empty', return_value=False)
228     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
229                 '_build_task_args', return_value={})
230     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
231                 'get_task_id', return_value='1')
232     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
233                 'task_succeed', return_value=True)
234     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
235                 return_value=True)
236     @mock.patch('functest.opnfv_tests.openstack.rally.rally.subprocess.Popen')
237     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs')
238     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info')
239     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.error')
240     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
241                 '_save_results')
242     def test_run_task_default(self, mock_save_res, *args):
243         # pylint: disable=unused-argument
244         self.rally_base.run_task('test_name')
245         mock_save_res.assert_called()
246
247     @mock.patch('six.moves.builtins.open', mock.mock_open())
248     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
249                 'task_succeed', return_value=True)
250     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
251                 return_value=True)
252     @mock.patch('subprocess.check_output')
253     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs')
254     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info')
255     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.debug')
256     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
257                 '_append_summary')
258     def test_save_results(self, mock_summary, *args):
259         # pylint: disable=unused-argument
260         self.rally_base._save_results('test_name', '1234')
261         mock_summary.assert_called()
262
263     def test_prepare_run_testname_invalid(self):
264         self.rally_base.TESTS = ['test1', 'test2']
265         self.rally_base.test_name = 'test'
266         with self.assertRaises(Exception):
267             self.rally_base.prepare_run()
268
269     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists')
270     def test_prepare_run_flavor_alt_creation_failed(self, *args):
271         # pylint: disable=unused-argument
272         self.rally_base.TESTS = ['test1', 'test2']
273         self.rally_base.test_name = 'test1'
274         with mock.patch.object(self.rally_base.cloud,
275                                'list_hypervisors') as mock_list_hyperv, \
276             mock.patch.object(self.rally_base, 'create_flavor_alt',
277                               side_effect=Exception) \
278                 as mock_create_flavor:
279             with self.assertRaises(Exception):
280                 self.rally_base.prepare_run()
281             mock_list_hyperv.assert_called_once()
282             mock_create_flavor.assert_called_once()
283
284     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
285                 'prepare_task', return_value=True)
286     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
287                 'run_task')
288     def test_run_tests_all(self, mock_run_task, mock_prepare_task):
289         self.rally_base.tests = ['test1', 'test2']
290         self.rally_base.test_name = 'all'
291         self.rally_base.run_tests()
292         mock_prepare_task.assert_any_call('test1')
293         mock_prepare_task.assert_any_call('test2')
294         mock_run_task.assert_any_call('test1')
295         mock_run_task.assert_any_call('test2')
296
297     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
298                 'prepare_task', return_value=True)
299     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
300                 'run_task')
301     def test_run_tests_default(self, mock_run_task, mock_prepare_task):
302         self.rally_base.tests = ['test1', 'test2']
303         self.rally_base.run_tests()
304         mock_prepare_task.assert_any_call('test1')
305         mock_prepare_task.assert_any_call('test2')
306         mock_run_task.assert_any_call('test1')
307         mock_run_task.assert_any_call('test2')
308
309     def test_clean_up_default(self):
310         with mock.patch.object(self.rally_base.orig_cloud,
311                                'delete_flavor') as mock_delete_flavor:
312             self.rally_base.flavor_alt = mock.Mock()
313             self.rally_base.clean()
314             self.assertEqual(mock_delete_flavor.call_count, 1)
315
316     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
317                 'create_rally_deployment')
318     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
319                 'prepare_run')
320     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
321                 'run_tests')
322     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
323                 '_generate_report')
324     def test_run_default(self, *args):
325         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_OK)
326         for func in args:
327             func.assert_called()
328
329     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
330                 'create_rally_deployment', side_effect=Exception)
331     def test_run_exception_create_rally_dep(self, mock_create_rally_dep):
332         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_RUN_ERROR)
333         mock_create_rally_dep.assert_called()
334
335     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
336                 'create_rally_deployment', return_value=mock.Mock())
337     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
338                 'prepare_run', side_effect=Exception)
339     def test_run_exception_prepare_run(self, mock_prep_env, *args):
340         # pylint: disable=unused-argument
341         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_RUN_ERROR)
342         mock_prep_env.assert_called()
343
344     def test_append_summary(self):
345         text = '{"tasks": [{"subtasks": [{"workloads": [{"full_duration": ' \
346                '1.23,"data": [{"error": []}]}]},{"workloads": ' \
347                '[{"full_duration": 2.78, "data": [{"error": ["err"]}]}]}]}]}'
348         self.rally_base._append_summary(text, "foo_test")
349         self.assertEqual(self.rally_base.summary[0]['test_name'], "foo_test")
350         self.assertEqual(self.rally_base.summary[0]['overall_duration'], 4.01)
351         self.assertEqual(self.rally_base.summary[0]['nb_tests'], 2)
352         self.assertEqual(self.rally_base.summary[0]['nb_success'], 1)
353
354     def test_is_successful_false(self):
355         with mock.patch('six.moves.builtins.super') as mock_super:
356             self.rally_base.summary = [{"task_status": True},
357                                        {"task_status": False}]
358             self.assertEqual(self.rally_base.is_successful(),
359                              testcase.TestCase.EX_TESTCASE_FAILED)
360             mock_super(rally.RallyBase, self).is_successful.assert_not_called()
361
362     def test_is_successful_true(self):
363         with mock.patch('six.moves.builtins.super') as mock_super:
364             mock_super(rally.RallyBase, self).is_successful.return_value = 424
365             self.rally_base.summary = [{"task_status": True},
366                                        {"task_status": True}]
367             self.assertEqual(self.rally_base.is_successful(), 424)
368             mock_super(rally.RallyBase, self).is_successful.assert_called()
369
370
371 if __name__ == "__main__":
372     logging.disable(logging.CRITICAL)
373     unittest.main(verbosity=2)