Harden Rally generate report
[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.tempest import tempest
18 from functest.opnfv_tests.openstack.tempest import conf_utils
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.tempest.tempest.'
30                            'conf_utils.create_rally_deployment'), \
31                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
32                            'conf_utils.create_verifier'), \
33                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
34                            'conf_utils.get_verifier_id',
35                            return_value='test_deploy_id'), \
36                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
37                            'conf_utils.get_verifier_deployment_id',
38                            return_value='test_deploy_id'), \
39                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
40                            'conf_utils.get_verifier_repo_dir',
41                            return_value='test_verifier_repo_dir'), \
42                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
43                            'conf_utils.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 % conf_utils.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         cmd = "(cd {0}; stestr list '{1}' >{2} 2>/dev/null)".format(
86             verifier_repo_dir, testr_mode, self.tempestcommon.list)
87         self.tempestcommon.generate_test_list(mode=testr_mode)
88         args[0].assert_called_once_with(cmd, shell=True)
89         args[2].assert_called_once_with('/etc/tempest.conf')
90
91     def test_gen_tl_smoke_mode(self):
92         self._test_gen_tl_mode_default('smoke')
93
94     def test_gen_tl_full_mode(self):
95         self._test_gen_tl_mode_default('full')
96
97     def test_verif_res_missing_verif_id(self):
98         self.tempestcommon.verification_id = None
99         with self.assertRaises(Exception):
100             self.tempestcommon.parse_verifier_result()
101
102     def test_backup_config_default(self):
103         with mock.patch('os.path.exists', return_value=False), \
104                 mock.patch('os.makedirs') as mock_makedirs, \
105                 mock.patch('shutil.copyfile') as mock_copyfile:
106             self.tempestcommon.backup_tempest_config(
107                 'test_conf_file', res_dir='test_dir')
108             self.assertTrue(mock_makedirs.called)
109             self.assertTrue(mock_copyfile.called)
110
111         with mock.patch('os.path.exists', return_value=True), \
112                 mock.patch('shutil.copyfile') as mock_copyfile:
113             self.tempestcommon.backup_tempest_config(
114                 'test_conf_file', res_dir='test_dir')
115             self.assertTrue(mock_copyfile.called)
116
117     @mock.patch("os.rename")
118     @mock.patch("os.remove")
119     @mock.patch("os.path.exists", return_value=True)
120     def test_apply_missing_blacklist(self, *args):
121         with mock.patch('six.moves.builtins.open',
122                         mock.mock_open()) as mock_open, \
123             mock.patch.object(self.tempestcommon, 'read_file',
124                               return_value=['test1', 'test2']):
125             conf_utils.TEMPEST_BLACKLIST = Exception
126             os.environ['DEPLOY_SCENARIO'] = 'deploy_scenario'
127             self.tempestcommon.apply_tempest_blacklist()
128             obj = mock_open()
129             obj.write.assert_any_call('test1\n')
130             obj.write.assert_any_call('test2\n')
131             args[0].assert_called_once_with(self.tempestcommon.raw_list)
132             args[1].assert_called_once_with(self.tempestcommon.raw_list)
133             args[2].assert_called_once_with(
134                 self.tempestcommon.list, self.tempestcommon.raw_list)
135
136     @mock.patch("os.rename")
137     @mock.patch("os.remove")
138     @mock.patch("os.path.exists", return_value=True)
139     def test_apply_blacklist_default(self, *args):
140         item_dict = {'scenarios': ['deploy_scenario'],
141                      'tests': ['test2']}
142         with mock.patch('six.moves.builtins.open',
143                         mock.mock_open()) as mock_open, \
144             mock.patch.object(self.tempestcommon, 'read_file',
145                               return_value=['test1', 'test2']), \
146             mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
147                        'yaml.safe_load', return_value=item_dict):
148             os.environ['DEPLOY_SCENARIO'] = 'deploy_scenario'
149             self.tempestcommon.apply_tempest_blacklist()
150             obj = mock_open()
151             obj.write.assert_any_call('test1\n')
152             self.assertFalse(obj.write.assert_any_call('test2\n'))
153             args[0].assert_called_once_with(self.tempestcommon.raw_list)
154             args[1].assert_called_once_with(self.tempestcommon.raw_list)
155             args[2].assert_called_once_with(
156                 self.tempestcommon.list, self.tempestcommon.raw_list)
157
158     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.info')
159     def test_run_verifier_tests_default(self, mock_logger_info):
160         with mock.patch('six.moves.builtins.open', mock.mock_open()), \
161             mock.patch('six.moves.builtins.iter',
162                        return_value=[r'\} tempest\.']), \
163             mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
164                        'subprocess.Popen'):
165             conf_utils.TEMPEST_LIST = 'test_tempest_list'
166             cmd = ["rally", "verify", "start", "--load-list",
167                    conf_utils.TEMPEST_LIST]
168             with self.assertRaises(Exception):
169                 self.tempestcommon.run_verifier_tests()
170                 mock_logger_info. \
171                     assert_any_call("Starting Tempest test suite: '%s'.", cmd)
172
173     @mock.patch('subprocess.check_output')
174     def test_generate_report(self, mock_popen):
175         self.tempestcommon.verification_id = "1234"
176         html_file = os.path.join(
177             os.path.join(
178                 getattr(config.CONF, 'dir_results'),
179                 self.tempestcommon.case_name),
180             "tempest-report.html")
181         cmd = ["rally", "verify", "report", "--type", "html", "--uuid",
182                "1234", "--to", html_file]
183         self.tempestcommon.generate_report()
184         mock_popen.assert_called_once_with(cmd)
185
186     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
187                 'os.path.exists', return_value=False)
188     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs',
189                 side_effect=Exception)
190     def test_run_makedirs_ko(self, *args):
191         # pylint: disable=unused-argument
192         self.assertEqual(self.tempestcommon.run(),
193                          testcase.TestCase.EX_RUN_ERROR)
194
195     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
196                 'os.path.exists', return_value=False)
197     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs')
198     def test_run_create_resources_ko(self, *args):
199         # pylint: disable=unused-argument
200         self.assertEqual(self.tempestcommon.run(),
201                          testcase.TestCase.EX_RUN_ERROR)
202
203     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
204                 'os.path.exists', return_value=False)
205     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs')
206     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
207                 'TempestCommon.configure', side_effect=Exception)
208     def test_run_configure_tempest_ko(self, *args):
209         # pylint: disable=unused-argument
210         self.assertEqual(self.tempestcommon.run(),
211                          testcase.TestCase.EX_RUN_ERROR)
212
213     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
214                 'os.path.exists', return_value=False)
215     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs')
216     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
217                 'TempestCommon.configure')
218     def _test_run(self, status, *args):
219         # pylint: disable=unused-argument
220         self.assertEqual(self.tempestcommon.run(), status)
221
222     def test_run_missing_gen_test_list(self):
223         with mock.patch.object(self.tempestcommon, 'generate_test_list',
224                                side_effect=Exception):
225             self._test_run(testcase.TestCase.EX_RUN_ERROR)
226
227     def test_run_apply_blacklist_ko(self):
228         with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
229                 mock.patch.object(
230                     self.tempestcommon, 'apply_tempest_blacklist',
231                     side_effect=Exception()):
232             self._test_run(testcase.TestCase.EX_RUN_ERROR)
233
234     def test_run_verifier_tests_ko(self):
235         with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
236                 mock.patch.object(self.tempestcommon,
237                                   'apply_tempest_blacklist'), \
238                 mock.patch.object(self.tempestcommon, 'run_verifier_tests',
239                                   side_effect=Exception()), \
240                 mock.patch.object(self.tempestcommon, 'parse_verifier_result',
241                                   side_effect=Exception):
242             self._test_run(testcase.TestCase.EX_RUN_ERROR)
243
244     def test_run_verif_result_ko(self):
245         with 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, 'parse_verifier_result',
250                                   side_effect=Exception):
251             self._test_run(testcase.TestCase.EX_RUN_ERROR)
252
253     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.TempestCommon.'
254                 'run', return_value=testcase.TestCase.EX_OK)
255     def test_run(self, *args):
256         with mock.patch.object(self.tempestcommon, 'update_rally_regex'), \
257                 mock.patch.object(self.tempestcommon, 'generate_test_list'), \
258                 mock.patch.object(self.tempestcommon,
259                                   'apply_tempest_blacklist'), \
260                 mock.patch.object(self.tempestcommon, 'run_verifier_tests'), \
261                 mock.patch.object(self.tempestcommon,
262                                   'parse_verifier_result'), \
263                 mock.patch.object(self.tempestcommon, 'generate_report'):
264             self._test_run(testcase.TestCase.EX_OK)
265             args[0].assert_called_once_with()
266
267
268 if __name__ == "__main__":
269     logging.disable(logging.CRITICAL)
270     unittest.main(verbosity=2)