Update to Python3
[functest.git] / functest / tests / unit / openstack / tempest / test_tempest.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
9
10 import logging
11 import os
12 import unittest
13
14 import mock
15 from xtesting.core import testcase
16
17 from functest.opnfv_tests.openstack.rally import rally
18 from functest.opnfv_tests.openstack.tempest import tempest
19 from functest.utils import config
20
21
22 class OSTempestTesting(unittest.TestCase):
23     # pylint: disable=too-many-public-methods
24
25     def setUp(self):
26         with mock.patch('os_client_config.get_config'), \
27                 mock.patch('shade.OpenStackCloud'), \
28                 mock.patch('functest.core.tenantnetwork.NewProject'), \
29                 mock.patch('functest.opnfv_tests.openstack.rally.rally.'
30                            'RallyBase.create_rally_deployment'), \
31                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
32                            'TempestCommon.create_verifier'), \
33                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
34                            'TempestCommon.get_verifier_id',
35                            return_value='test_deploy_id'), \
36                 mock.patch('functest.opnfv_tests.openstack.rally.rally.'
37                            'RallyBase.get_verifier_deployment_id',
38                            return_value='test_deploy_id'), \
39                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
40                            'TempestCommon.get_verifier_repo_dir',
41                            return_value='test_verifier_repo_dir'), \
42                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
43                            'TempestCommon.get_verifier_deployment_dir',
44                            return_value='test_verifier_deploy_dir'), \
45                 mock.patch('os_client_config.make_shade'):
46             self.tempestcommon = tempest.TempestCommon()
47
48     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.error')
49     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.debug')
50     def test_gen_tl_cm_missing_file(self, mock_logger_debug,
51                                     mock_logger_error):
52         # pylint: disable=unused-argument
53         self.tempestcommon.mode = 'custom'
54         with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
55                         'os.path.isfile', return_value=False), \
56                 self.assertRaises(Exception) as context:
57             msg = "Tempest test list file %s NOT found."
58             self.tempestcommon.generate_test_list()
59             self.assertTrue(
60                 (msg % self.tempestcommon.TEMPEST_CUSTOM) in context.exception)
61
62     @mock.patch('subprocess.check_output')
63     @mock.patch('os.remove')
64     def test_gen_tl_cm_default(self, *args):
65         self.tempestcommon.mode = 'custom'
66         with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
67                         'shutil.copyfile') as mock_copyfile, \
68             mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
69                        'os.path.isfile', return_value=True):
70             self.tempestcommon.generate_test_list()
71             self.assertTrue(mock_copyfile.called)
72         args[0].assert_called_once_with('/etc/tempest.conf')
73
74     @mock.patch('os.remove')
75     @mock.patch('shutil.copyfile')
76     @mock.patch('subprocess.check_output')
77     def _test_gen_tl_mode_default(self, mode, *args):
78         if mode == 'smoke':
79             testr_mode = r'^tempest\.(api|scenario).*\[.*\bsmoke\b.*\]$'
80         elif mode == 'full':
81             testr_mode = r'^tempest\.'
82         else:
83             testr_mode = self.tempestcommon.mode
84         verifier_repo_dir = 'test_verifier_repo_dir'
85         self.tempestcommon.verifier_repo_dir = verifier_repo_dir
86         cmd = "(cd {0}; stestr list '{1}' >{2} 2>/dev/null)".format(
87             verifier_repo_dir, testr_mode, self.tempestcommon.list)
88         self.tempestcommon.generate_test_list(mode=testr_mode)
89         args[0].assert_called_once_with(cmd, shell=True)
90         args[2].assert_called_once_with('/etc/tempest.conf')
91
92     def test_gen_tl_smoke_mode(self):
93         self._test_gen_tl_mode_default('smoke')
94
95     def test_gen_tl_full_mode(self):
96         self._test_gen_tl_mode_default('full')
97
98     def test_verif_res_missing_verif_id(self):
99         self.tempestcommon.verification_id = None
100         with self.assertRaises(Exception):
101             self.tempestcommon.parse_verifier_result()
102
103     def test_backup_config_default(self):
104         with mock.patch('os.path.exists', return_value=False), \
105                 mock.patch('os.makedirs') as mock_makedirs, \
106                 mock.patch('shutil.copyfile') as mock_copyfile:
107             self.tempestcommon.backup_tempest_config(
108                 'test_conf_file', res_dir='test_dir')
109             self.assertTrue(mock_makedirs.called)
110             self.assertTrue(mock_copyfile.called)
111
112         with mock.patch('os.path.exists', return_value=True), \
113                 mock.patch('shutil.copyfile') as mock_copyfile:
114             self.tempestcommon.backup_tempest_config(
115                 'test_conf_file', res_dir='test_dir')
116             self.assertTrue(mock_copyfile.called)
117
118     @mock.patch("os.rename")
119     @mock.patch("os.remove")
120     @mock.patch("os.path.exists", return_value=True)
121     def test_apply_missing_blacklist(self, *args):
122         with mock.patch('six.moves.builtins.open',
123                         mock.mock_open()) as mock_open, \
124             mock.patch.object(self.tempestcommon, 'read_file',
125                               return_value=['test1', 'test2']):
126             self.tempestcommon.TEMPEST_BLACKLIST = Exception
127             os.environ['DEPLOY_SCENARIO'] = 'deploy_scenario'
128             self.tempestcommon.apply_tempest_blacklist()
129             obj = mock_open()
130             obj.write.assert_any_call('test1\n')
131             obj.write.assert_any_call('test2\n')
132             args[0].assert_called_once_with(self.tempestcommon.raw_list)
133             args[1].assert_called_once_with(self.tempestcommon.raw_list)
134             args[2].assert_called_once_with(
135                 self.tempestcommon.list, self.tempestcommon.raw_list)
136
137     @mock.patch("os.rename")
138     @mock.patch("os.remove")
139     @mock.patch("os.path.exists", return_value=True)
140     def test_apply_blacklist_default(self, *args):
141         item_dict = {'scenarios': ['deploy_scenario'],
142                      'tests': ['test2']}
143         with mock.patch('six.moves.builtins.open',
144                         mock.mock_open()) as mock_open, \
145             mock.patch.object(self.tempestcommon, 'read_file',
146                               return_value=['test1', 'test2']), \
147             mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
148                        'yaml.safe_load', return_value=item_dict):
149             os.environ['DEPLOY_SCENARIO'] = 'deploy_scenario'
150             self.tempestcommon.apply_tempest_blacklist()
151             obj = mock_open()
152             obj.write.assert_any_call('test1\n')
153             self.assertFalse(obj.write.assert_any_call('test2\n'))
154             args[0].assert_called_once_with(self.tempestcommon.raw_list)
155             args[1].assert_called_once_with(self.tempestcommon.raw_list)
156             args[2].assert_called_once_with(
157                 self.tempestcommon.list, self.tempestcommon.raw_list)
158
159     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.info')
160     def test_run_verifier_tests_default(self, mock_logger_info):
161         with mock.patch('six.moves.builtins.open', mock.mock_open()), \
162             mock.patch('six.moves.builtins.iter',
163                        return_value=[r'\} tempest\.']), \
164             mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
165                        'subprocess.Popen'):
166             self.tempestcommon.TEMPEST_LIST = 'test_tempest_list'
167             cmd = ["rally", "verify", "start", "--load-list",
168                    self.tempestcommon.TEMPEST_LIST]
169             with self.assertRaises(Exception):
170                 self.tempestcommon.run_verifier_tests()
171                 mock_logger_info. \
172                     assert_any_call("Starting Tempest test suite: '%s'.", cmd)
173
174     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
175                 'os.path.exists', return_value=False)
176     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs',
177                 side_effect=Exception)
178     def test_run_makedirs_ko(self, *args):
179         # pylint: disable=unused-argument
180         self.assertEqual(self.tempestcommon.run(),
181                          testcase.TestCase.EX_RUN_ERROR)
182
183     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
184                 'os.path.exists', return_value=False)
185     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs')
186     def test_run_create_resources_ko(self, *args):
187         # pylint: disable=unused-argument
188         self.assertEqual(self.tempestcommon.run(),
189                          testcase.TestCase.EX_RUN_ERROR)
190
191     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
192                 'os.path.exists', return_value=False)
193     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs')
194     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
195                 'TempestCommon.configure', side_effect=Exception)
196     def test_run_configure_tempest_ko(self, *args):
197         # pylint: disable=unused-argument
198         self.assertEqual(self.tempestcommon.run(),
199                          testcase.TestCase.EX_RUN_ERROR)
200
201     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
202                 'os.path.exists', return_value=False)
203     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs')
204     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
205                 'TempestCommon.configure')
206     def _test_run(self, status, *args):
207         # pylint: disable=unused-argument
208         self.assertEqual(self.tempestcommon.run(), status)
209
210     def test_run_missing_gen_test_list(self):
211         with mock.patch.object(self.tempestcommon, 'generate_test_list',
212                                side_effect=Exception):
213             self._test_run(testcase.TestCase.EX_RUN_ERROR)
214
215     def test_run_apply_blacklist_ko(self):
216         with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
217                 mock.patch.object(self.tempestcommon,
218                                   'apply_tempest_blacklist',
219                                   side_effect=Exception()):
220             self._test_run(testcase.TestCase.EX_RUN_ERROR)
221
222     def test_run_verifier_tests_ko(self):
223         with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
224                 mock.patch.object(self.tempestcommon,
225                                   'apply_tempest_blacklist'), \
226                 mock.patch.object(self.tempestcommon, 'run_verifier_tests',
227                                   side_effect=Exception()), \
228                 mock.patch.object(self.tempestcommon, 'parse_verifier_result',
229                                   side_effect=Exception):
230             self._test_run(testcase.TestCase.EX_RUN_ERROR)
231
232     def test_run_verif_result_ko(self):
233         with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
234                 mock.patch.object(self.tempestcommon,
235                                   'apply_tempest_blacklist'), \
236                 mock.patch.object(self.tempestcommon, 'run_verifier_tests'), \
237                 mock.patch.object(self.tempestcommon, 'parse_verifier_result',
238                                   side_effect=Exception):
239             self._test_run(testcase.TestCase.EX_RUN_ERROR)
240
241     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.TempestCommon.'
242                 'run', return_value=testcase.TestCase.EX_OK)
243     def test_run(self, *args):
244         with mock.patch.object(self.tempestcommon, 'update_rally_regex'), \
245                 mock.patch.object(self.tempestcommon, 'generate_test_list'), \
246                 mock.patch.object(self.tempestcommon,
247                                   'apply_tempest_blacklist'), \
248                 mock.patch.object(self.tempestcommon, 'run_verifier_tests'), \
249                 mock.patch.object(self.tempestcommon,
250                                   'parse_verifier_result'):
251             self._test_run(testcase.TestCase.EX_OK)
252             args[0].assert_called_once_with()
253
254     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.debug')
255     def test_create_verifier(self, mock_logger_debug):
256         mock_popen = mock.Mock()
257         attrs = {'poll.return_value': None,
258                  'stdout.readline.return_value': '0'}
259         mock_popen.configure_mock(**attrs)
260
261         setattr(config.CONF, 'tempest_verifier_name', 'test_verifier_name')
262         with mock.patch('subprocess.Popen', side_effect=Exception), \
263                 self.assertRaises(Exception):
264             self.tempestcommon.create_verifier()
265             mock_logger_debug.assert_any_call("Tempest test_verifier_name"
266                                               " does not exist")
267
268     def test_get_verifier_id_default(self):
269         setattr(config.CONF, 'tempest_verifier_name', 'test_verifier_name')
270
271         with mock.patch('functest.opnfv_tests.openstack.tempest.'
272                         'tempest.subprocess.Popen') as mock_popen:
273             mock_stdout = mock.Mock()
274             attrs = {'stdout.readline.return_value': b'test_deploy_id'}
275             mock_stdout.configure_mock(**attrs)
276             mock_popen.return_value = mock_stdout
277
278             self.assertEqual(self.tempestcommon.get_verifier_id(),
279                              'test_deploy_id')
280
281     def test_get_depl_id_default(self):
282         setattr(config.CONF, 'tempest_verifier_name', 'test_deploy_name')
283         with mock.patch('functest.opnfv_tests.openstack.tempest.'
284                         'tempest.subprocess.Popen') as mock_popen:
285             mock_stdout = mock.Mock()
286             attrs = {'stdout.readline.return_value': b'test_deploy_id'}
287             mock_stdout.configure_mock(**attrs)
288             mock_popen.return_value = mock_stdout
289
290             self.assertEqual(rally.RallyBase.get_verifier_deployment_id(),
291                              'test_deploy_id')
292
293     def test_get_verif_repo_dir_default(self):
294         with mock.patch('functest.opnfv_tests.openstack.tempest.'
295                         'tempest.os.path.join',
296                         return_value='test_verifier_repo_dir'):
297             self.assertEqual(self.tempestcommon.get_verifier_repo_dir(''),
298                              'test_verifier_repo_dir')
299
300     def test_get_depl_dir_default(self):
301         with mock.patch('functest.opnfv_tests.openstack.tempest.'
302                         'tempest.os.path.join',
303                         return_value='test_verifier_repo_dir'):
304             self.assertEqual(
305                 self.tempestcommon.get_verifier_deployment_dir('', ''),
306                 'test_verifier_repo_dir')
307
308     def _test_missing_param(self, params, image_id, flavor_id, alt=False):
309         with mock.patch('six.moves.configparser.RawConfigParser.'
310                         'set') as mset, \
311             mock.patch('six.moves.configparser.RawConfigParser.'
312                        'read') as mread, \
313             mock.patch('six.moves.configparser.RawConfigParser.'
314                        'write') as mwrite, \
315             mock.patch('six.moves.builtins.open', mock.mock_open()), \
316             mock.patch('functest.utils.functest_utils.yaml.safe_load',
317                        return_value={'validation': {'ssh_timeout': 300}}):
318             os.environ['OS_INTERFACE'] = ''
319             if not alt:
320                 self.tempestcommon.configure_tempest_update_params(
321                     'test_conf_file', image_id=image_id,
322                     flavor_id=flavor_id)
323                 mset.assert_any_call(params[0], params[1], params[2])
324             else:
325                 self.tempestcommon.configure_tempest_update_params(
326                     'test_conf_file', image_alt_id=image_id,
327                     flavor_alt_id=flavor_id)
328                 mset.assert_any_call(params[0], params[1], params[2])
329             self.assertTrue(mread.called)
330             self.assertTrue(mwrite.called)
331
332     def test_upd_missing_image_id(self):
333         self._test_missing_param(('compute', 'image_ref', 'test_image_id'),
334                                  'test_image_id', None)
335
336     def test_upd_missing_image_id_alt(self):
337         self._test_missing_param(
338             ('compute', 'image_ref_alt', 'test_image_id_alt'),
339             'test_image_id_alt', None, alt=True)
340
341     def test_upd_missing_flavor_id(self):
342         self._test_missing_param(('compute', 'flavor_ref', 'test_flavor_id'),
343                                  None, 'test_flavor_id')
344
345     def test_upd_missing_flavor_id_alt(self):
346         self._test_missing_param(
347             ('compute', 'flavor_ref_alt', 'test_flavor_id_alt'),
348             None, 'test_flavor_id_alt', alt=True)
349
350     def test_verif_missing_conf_file(self):
351         with mock.patch('functest.opnfv_tests.openstack.tempest.'
352                         'tempest.os.path.isfile',
353                         return_value=False), \
354                 mock.patch('subprocess.check_output') as mexe, \
355                 self.assertRaises(Exception) as context:
356             self.tempestcommon.configure_verifier('test_dep_dir')
357             mexe.assert_called_once_with("rally verify configure-verifier")
358             msg = ("Tempest configuration file 'test_dep_dir/tempest.conf'"
359                    " NOT found.")
360             self.assertTrue(msg in context.exception)
361
362     def test_configure_verifier_default(self):
363         with mock.patch('functest.opnfv_tests.openstack.tempest.'
364                         'tempest.os.path.isfile',
365                         return_value=True), \
366                 mock.patch('subprocess.check_output') as mexe:
367             self.assertEqual(
368                 self.tempestcommon.configure_verifier('test_dep_dir'),
369                 'test_dep_dir/tempest.conf')
370             mexe.assert_called_once_with(
371                 ['rally', 'verify', 'configure-verifier', '--reconfigure',
372                  '--id', str(getattr(config.CONF, 'tempest_verifier_name'))])
373
374     def test_is_successful_false(self):
375         with mock.patch('six.moves.builtins.super') as mock_super:
376             self.tempestcommon.deny_skipping = True
377             self.tempestcommon.details = {"skipped_number": 2}
378             self.assertEqual(self.tempestcommon.is_successful(),
379                              testcase.TestCase.EX_TESTCASE_FAILED)
380             mock_super(tempest.TempestCommon,
381                        self).is_successful.assert_not_called()
382
383     def test_is_successful_true(self):
384         with mock.patch('six.moves.builtins.super') as mock_super:
385             self.tempestcommon.deny_skipping = False
386             self.tempestcommon.details = {"skipped_number": 2}
387             mock_super(tempest.TempestCommon,
388                        self).is_successful.return_value = 567
389             self.assertEqual(self.tempestcommon.is_successful(), 567)
390             mock_super(tempest.TempestCommon,
391                        self).is_successful.assert_called()
392
393
394 if __name__ == "__main__":
395     logging.disable(logging.CRITICAL)
396     unittest.main(verbosity=2)