Update Functest to meet last snaps updates
[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
17 from functest.core import testcase
18 from functest.opnfv_tests.openstack.rally import rally
19
20 from snaps.openstack.os_credentials import OSCreds
21
22
23 class OSRallyTesting(unittest.TestCase):
24     # pylint: disable=too-many-public-methods
25     def setUp(self):
26         os_creds = OSCreds(
27             username='user', password='pass',
28             auth_url='http://foo.com:5000/v3', project_name='bar')
29         with mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
30                         'get_credentials',
31                         return_value=os_creds) as mock_get_creds:
32             self.rally_base = rally.RallyBase()
33         self.assertTrue(mock_get_creds.called)
34
35     def test_build_task_args_missing_floating_network(self):
36         os.environ['OS_AUTH_URL'] = ''
37         self.rally_base.ext_net_name = ''
38         task_args = self.rally_base._build_task_args('test_file_name')
39         self.assertEqual(task_args['floating_network'], '')
40
41     def test_build_task_args_missing_net_id(self):
42         os.environ['OS_AUTH_URL'] = ''
43         self.rally_base.priv_net_id = ''
44         task_args = self.rally_base._build_task_args('test_file_name')
45         self.assertEqual(task_args['netid'], '')
46
47     @staticmethod
48     def check_scenario_file(value):
49         yaml_file = 'opnfv-{}.yaml'.format('test_file_name')
50         if yaml_file in value:
51             return False
52         return True
53
54     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists')
55     def test_prepare_test_list_missing_scenario_file(self, mock_func):
56         mock_func.side_effect = self.check_scenario_file
57         with self.assertRaises(Exception):
58             self.rally_base._prepare_test_list('test_file_name')
59         mock_func.assert_called()
60
61     @staticmethod
62     def check_temp_dir(value):
63         yaml_file = 'opnfv-{}.yaml'.format('test_file_name')
64         if yaml_file in value:
65             return True
66         return False
67
68     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists')
69     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs')
70     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
71                 '_apply_blacklist')
72     def test_prepare_test_list_missing_temp_dir(
73             self, mock_method, mock_os_makedirs, mock_path_exists):
74         mock_path_exists.side_effect = self.check_temp_dir
75
76         yaml_file = 'opnfv-{}.yaml'.format('test_file_name')
77         ret_val = os.path.join(self.rally_base.TEMP_DIR, yaml_file)
78         self.assertEqual(self.rally_base._prepare_test_list('test_file_name'),
79                          ret_val)
80         mock_path_exists.assert_called()
81         mock_method.assert_called()
82         mock_os_makedirs.assert_called()
83
84     def test_get_task_id_default(self):
85         cmd_raw = 'Task 1: started'
86         self.assertEqual(self.rally_base.get_task_id(cmd_raw),
87                          '1')
88
89     def test_get_task_id_missing_id(self):
90         cmd_raw = ''
91         self.assertEqual(self.rally_base.get_task_id(cmd_raw),
92                          None)
93
94     def test_task_succeed_fail(self):
95         json_raw = json.dumps([None])
96         self.assertEqual(self.rally_base.task_succeed(json_raw),
97                          False)
98         json_raw = json.dumps([{'result': [{'error': ['test_error']}]}])
99         self.assertEqual(self.rally_base.task_succeed(json_raw),
100                          False)
101
102     def test_task_succeed_success(self):
103         json_raw = json.dumps('')
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('__builtin__.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('__builtin__.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('__builtin__.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('__builtin__.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('__builtin__.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                 '_append_summary')
225     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
226                 'get_task_id', return_value=None)
227     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
228                 'get_cmd_output', return_value='')
229     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
230                 return_value=True)
231     @mock.patch('functest.opnfv_tests.openstack.rally.rally.subprocess.Popen')
232     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.error')
233     def test_run_task_taskid_missing(self, mock_logger_error, *args):
234         # pylint: disable=unused-argument
235         self.rally_base._run_task('test_name')
236         text = 'Failed to retrieve task_id, validating task...'
237         mock_logger_error.assert_any_call(text)
238
239     @mock.patch('__builtin__.open', mock.mock_open())
240     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
241                 '_prepare_test_list', return_value='test_file_name')
242     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
243                 'file_is_empty', return_value=False)
244     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
245                 '_build_task_args', return_value={})
246     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
247                 '_append_summary')
248     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
249                 'get_task_id', return_value='1')
250     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
251                 'get_cmd_output', return_value='')
252     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
253                 'task_succeed', return_value=True)
254     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.path.exists',
255                 return_value=True)
256     @mock.patch('functest.opnfv_tests.openstack.rally.rally.subprocess.Popen')
257     @mock.patch('functest.opnfv_tests.openstack.rally.rally.os.makedirs')
258     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.info')
259     @mock.patch('functest.opnfv_tests.openstack.rally.rally.LOGGER.error')
260     def test_run_task_default(self, mock_logger_error, mock_logger_info,
261                               *args):
262         # pylint: disable=unused-argument
263         self.rally_base._run_task('test_name')
264         text = 'Test scenario: "test_name" OK.\n'
265         mock_logger_info.assert_any_call(text)
266         mock_logger_error.assert_not_called()
267
268     def test_prepare_env_testname_invalid(self):
269         self.rally_base.TESTS = ['test1', 'test2']
270         self.rally_base.test_name = 'test'
271         with self.assertRaises(Exception):
272             self.rally_base._prepare_env()
273
274     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
275                 'get_active_compute_cnt')
276     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
277                 'get_ext_net_name', return_value='test_net_name')
278     @mock.patch('snaps.openstack.utils.deploy_utils.create_image',
279                 return_value=None)
280     def test_prepare_env_image_missing(
281             self, mock_get_img, mock_get_net, mock_get_comp_cnt):
282         self.rally_base.TESTS = ['test1', 'test2']
283         self.rally_base.test_name = 'test1'
284         with self.assertRaises(Exception):
285             self.rally_base._prepare_env()
286         mock_get_img.assert_called()
287         mock_get_net.assert_called()
288         mock_get_comp_cnt.assert_called()
289
290     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
291                 'get_active_compute_cnt')
292     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
293                 'get_ext_net_name', return_value='test_net_name')
294     @mock.patch('snaps.openstack.utils.deploy_utils.create_image')
295     @mock.patch('snaps.openstack.utils.deploy_utils.create_network',
296                 return_value=None)
297     def test_prepare_env_network_creation_failed(
298             self, mock_create_net, mock_get_img, mock_get_net,
299             mock_get_comp_cnt):
300         self.rally_base.TESTS = ['test1', 'test2']
301         self.rally_base.test_name = 'test1'
302         with self.assertRaises(Exception):
303             self.rally_base._prepare_env()
304         mock_create_net.assert_called()
305         mock_get_img.assert_called()
306         mock_get_net.assert_called()
307         mock_get_comp_cnt.assert_called()
308
309     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
310                 'get_active_compute_cnt')
311     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
312                 'get_ext_net_name', return_value='test_net_name')
313     @mock.patch('snaps.openstack.utils.deploy_utils.create_image')
314     @mock.patch('snaps.openstack.utils.deploy_utils.create_network')
315     @mock.patch('snaps.openstack.utils.deploy_utils.create_router',
316                 return_value=None)
317     def test_prepare_env_router_creation_failed(self, *args):
318         self.rally_base.TESTS = ['test1', 'test2']
319         self.rally_base.test_name = 'test1'
320         with self.assertRaises(Exception):
321             self.rally_base._prepare_env()
322         for func in args:
323             func.assert_called()
324
325     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
326                 'get_active_compute_cnt')
327     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
328                 'get_ext_net_name', return_value='test_net_name')
329     @mock.patch('snaps.openstack.utils.deploy_utils.create_image')
330     @mock.patch('snaps.openstack.utils.deploy_utils.create_network')
331     @mock.patch('snaps.openstack.utils.deploy_utils.create_router')
332     @mock.patch('snaps.openstack.create_flavor.OpenStackFlavor.create',
333                 return_value=None)
334     def test_prepare_env_flavor_creation_failed(self, mock_create_flavor,
335                                                 *args):
336         self.rally_base.TESTS = ['test1', 'test2']
337         self.rally_base.test_name = 'test1'
338         with self.assertRaises(Exception):
339             self.rally_base._prepare_env()
340         for func in args:
341             func.assert_called()
342         mock_create_flavor.assert_called_once()
343
344     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
345                 'get_active_compute_cnt')
346     @mock.patch('functest.opnfv_tests.openstack.snaps.snaps_utils.'
347                 'get_ext_net_name', return_value='test_net_name')
348     @mock.patch('snaps.openstack.utils.deploy_utils.create_image')
349     @mock.patch('snaps.openstack.utils.deploy_utils.create_network')
350     @mock.patch('snaps.openstack.utils.deploy_utils.create_router')
351     @mock.patch('snaps.openstack.create_flavor.OpenStackFlavor.create',
352                 side_effect=[mock.Mock, None])
353     def test_prepare_env_flavor_alt_creation_failed(self, mock_create_flavor,
354                                                     *args):
355         self.rally_base.TESTS = ['test1', 'test2']
356         self.rally_base.test_name = 'test1'
357         with self.assertRaises(Exception):
358             self.rally_base._prepare_env()
359         for func in args:
360             func.assert_called()
361         self.assertEqual(mock_create_flavor.call_count, 2)
362
363     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
364                 '_run_task')
365     def test_run_tests_all(self, mock_run_task):
366         self.rally_base.TESTS = ['test1', 'test2']
367         self.rally_base.test_name = 'all'
368         self.rally_base._run_tests()
369         mock_run_task.assert_any_call('test1')
370         mock_run_task.assert_any_call('test2')
371
372     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
373                 '_run_task')
374     def test_run_tests_default(self, mock_run_task):
375         self.rally_base.TESTS = ['test1', 'test2']
376         self.rally_base.test_name = 'test1'
377         self.rally_base._run_tests()
378         mock_run_task.assert_any_call('test1')
379
380     def test_clean_up_default(self):
381         creator1 = mock.Mock()
382         creator2 = mock.Mock()
383         self.rally_base.creators = [creator1, creator2]
384         self.rally_base._clean_up()
385         self.assertTrue(creator1.clean.called)
386         self.assertTrue(creator2.clean.called)
387
388     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
389                 'create_rally_deployment')
390     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
391                 '_prepare_env')
392     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
393                 '_run_tests')
394     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
395                 '_generate_report')
396     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
397                 '_clean_up')
398     def test_run_default(self, *args):
399         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_OK)
400         for func in args:
401             func.assert_called()
402
403     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
404                 'create_rally_deployment', side_effect=Exception)
405     def test_run_exception_create_rally_dep(self, mock_create_rally_dep):
406         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_RUN_ERROR)
407         mock_create_rally_dep.assert_called()
408
409     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
410                 'create_rally_deployment', return_value=mock.Mock())
411     @mock.patch('functest.opnfv_tests.openstack.rally.rally.RallyBase.'
412                 '_prepare_env', side_effect=Exception)
413     def test_run_exception_prepare_env(self, mock_prep_env, *args):
414         # pylint: disable=unused-argument
415         self.assertEqual(self.rally_base.run(), testcase.TestCase.EX_RUN_ERROR)
416         mock_prep_env.assert_called()
417
418     def test_append_summary(self):
419         text = '[{"result":[{"error":[]},{"error":["err"]}],' \
420                '"full_duration": 17.312026}]'
421         self.rally_base._append_summary(text, "foo_test")
422         self.assertEqual(self.rally_base.summary[0]['test_name'], "foo_test")
423         self.assertEqual(self.rally_base.summary[0]['overall_duration'],
424                          17.312026)
425         self.assertEqual(self.rally_base.summary[0]['nb_tests'], 2)
426         self.assertEqual(self.rally_base.summary[0]['nb_success'], 1)
427
428
429 if __name__ == "__main__":
430     logging.disable(logging.CRITICAL)
431     unittest.main(verbosity=2)