Refactor tempest common
[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('functest.opnfv_tests.openstack.tempest.tempest.'
27                         'conf_utils.get_verifier_id',
28                         return_value='test_deploy_id'), \
29                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
30                            'conf_utils.get_verifier_deployment_id',
31                            return_value='test_deploy_id'), \
32                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
33                            'conf_utils.get_verifier_repo_dir',
34                            return_value='test_verifier_repo_dir'), \
35                 mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
36                            'conf_utils.get_verifier_deployment_dir',
37                            return_value='test_verifier_deploy_dir'), \
38                 mock.patch('os_client_config.make_shade'):
39             self.tempestcommon = tempest.TempestCommon()
40
41     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.error')
42     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.debug')
43     def test_gen_tl_cm_missing_file(self, mock_logger_debug,
44                                     mock_logger_error):
45         # pylint: disable=unused-argument
46         self.tempestcommon.mode = 'custom'
47         with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
48                         'os.path.isfile', return_value=False), \
49                 self.assertRaises(Exception) as context:
50             msg = "Tempest test list file %s NOT found."
51             self.tempestcommon.generate_test_list()
52             self.assertTrue(
53                 (msg % conf_utils.TEMPEST_CUSTOM) in context.exception)
54
55     @mock.patch('subprocess.check_output')
56     @mock.patch('os.remove')
57     def test_gen_tl_cm_default(self, *args):
58         self.tempestcommon.mode = 'custom'
59         with mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
60                         'shutil.copyfile') as mock_copyfile, \
61             mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
62                        'os.path.isfile', return_value=True):
63             self.tempestcommon.generate_test_list()
64             self.assertTrue(mock_copyfile.called)
65         args[0].assert_called_once_with('/etc/tempest.conf')
66
67     @mock.patch('os.remove')
68     @mock.patch('shutil.copyfile')
69     @mock.patch('subprocess.check_output')
70     def _test_gen_tl_mode_default(self, mode, *args):
71         if mode == 'smoke':
72             testr_mode = r'^tempest\.(api|scenario).*\[.*\bsmoke\b.*\]$'
73         elif mode == 'full':
74             testr_mode = r'^tempest\.'
75         else:
76             testr_mode = self.tempestcommon.mode
77         verifier_repo_dir = 'test_verifier_repo_dir'
78         cmd = "(cd {0}; stestr list '{1}' >{2} 2>/dev/null)".format(
79             verifier_repo_dir, testr_mode, self.tempestcommon.list)
80         self.tempestcommon.generate_test_list(mode=testr_mode)
81         args[0].assert_called_once_with(cmd, shell=True)
82         args[2].assert_called_once_with('/etc/tempest.conf')
83
84     def test_gen_tl_smoke_mode(self):
85         self._test_gen_tl_mode_default('smoke')
86
87     def test_gen_tl_full_mode(self):
88         self._test_gen_tl_mode_default('full')
89
90     def test_verif_res_missing_verif_id(self):
91         self.tempestcommon.verification_id = None
92         with self.assertRaises(Exception):
93             self.tempestcommon.parse_verifier_result()
94
95     def test_backup_config_default(self):
96         with mock.patch('os.path.exists', return_value=False), \
97                 mock.patch('os.makedirs') as mock_makedirs, \
98                 mock.patch('shutil.copyfile') as mock_copyfile:
99             self.tempestcommon.backup_tempest_config(
100                 'test_conf_file', res_dir='test_dir')
101             self.assertTrue(mock_makedirs.called)
102             self.assertTrue(mock_copyfile.called)
103
104         with mock.patch('os.path.exists', return_value=True), \
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_copyfile.called)
109
110     @mock.patch("os.rename")
111     @mock.patch("os.remove")
112     @mock.patch("os.path.exists", return_value=True)
113     def test_apply_missing_blacklist(self, *args):
114         with mock.patch('six.moves.builtins.open',
115                         mock.mock_open()) as mock_open, \
116             mock.patch.object(self.tempestcommon, 'read_file',
117                               return_value=['test1', 'test2']):
118             conf_utils.TEMPEST_BLACKLIST = Exception
119             os.environ['INSTALLER_TYPE'] = 'installer_type'
120             os.environ['DEPLOY_SCENARIO'] = 'deploy_scenario'
121             self.tempestcommon.apply_tempest_blacklist()
122             obj = mock_open()
123             obj.write.assert_any_call('test1\n')
124             obj.write.assert_any_call('test2\n')
125             args[0].assert_called_once_with(self.tempestcommon.raw_list)
126             args[1].assert_called_once_with(self.tempestcommon.raw_list)
127             args[2].assert_called_once_with(
128                 self.tempestcommon.list, self.tempestcommon.raw_list)
129
130     @mock.patch("os.rename")
131     @mock.patch("os.remove")
132     @mock.patch("os.path.exists", return_value=True)
133     def test_apply_blacklist_default(self, *args):
134         item_dict = {'scenarios': ['deploy_scenario'],
135                      'installers': ['installer_type'],
136                      'tests': ['test2']}
137         with mock.patch('six.moves.builtins.open',
138                         mock.mock_open()) as mock_open, \
139             mock.patch.object(self.tempestcommon, 'read_file',
140                               return_value=['test1', 'test2']), \
141             mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
142                        'yaml.safe_load', return_value=item_dict):
143             os.environ['INSTALLER_TYPE'] = 'installer_type'
144             os.environ['DEPLOY_SCENARIO'] = 'deploy_scenario'
145             self.tempestcommon.apply_tempest_blacklist()
146             obj = mock_open()
147             obj.write.assert_any_call('test1\n')
148             self.assertFalse(obj.write.assert_any_call('test2\n'))
149             args[0].assert_called_once_with(self.tempestcommon.raw_list)
150             args[1].assert_called_once_with(self.tempestcommon.raw_list)
151             args[2].assert_called_once_with(
152                 self.tempestcommon.list, self.tempestcommon.raw_list)
153
154     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.LOGGER.info')
155     def test_run_verifier_tests_default(self, mock_logger_info):
156         with mock.patch('six.moves.builtins.open', mock.mock_open()), \
157             mock.patch('six.moves.builtins.iter',
158                        return_value=[r'\} tempest\.']), \
159             mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
160                        'subprocess.Popen'):
161             conf_utils.TEMPEST_LIST = 'test_tempest_list'
162             cmd = ["rally", "verify", "start", "--load-list",
163                    conf_utils.TEMPEST_LIST]
164             with self.assertRaises(Exception):
165                 self.tempestcommon.run_verifier_tests()
166                 mock_logger_info. \
167                     assert_any_call("Starting Tempest test suite: '%s'.", cmd)
168
169     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
170                 'subprocess.Popen')
171     def test_generate_report(self, mock_popen):
172         self.tempestcommon.verification_id = "1234"
173         html_file = os.path.join(
174             os.path.join(
175                 getattr(config.CONF, 'dir_results'),
176                 self.tempestcommon.case_name),
177             "tempest-report.html")
178         cmd = ["rally", "verify", "report", "--type", "html", "--uuid",
179                "1234", "--to", html_file]
180         self.tempestcommon.generate_report()
181         mock_popen.assert_called_once_with(cmd, stdout=mock.ANY,
182                                            stderr=mock.ANY)
183
184     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
185                 'os.path.exists', return_value=False)
186     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs',
187                 side_effect=Exception)
188     def test_run_makedirs_ko(self, *args):
189         # pylint: disable=unused-argument
190         self.assertEqual(self.tempestcommon.run(),
191                          testcase.TestCase.EX_RUN_ERROR)
192
193     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
194                 'os.path.exists', return_value=False)
195     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs')
196     def test_run_create_resources_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', side_effect=Exception)
206     def test_run_configure_tempest_ko(self, *args):
207         # pylint: disable=unused-argument
208         self.assertEqual(self.tempestcommon.run(),
209                          testcase.TestCase.EX_RUN_ERROR)
210
211     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
212                 'os.path.exists', return_value=False)
213     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs')
214     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
215                 'TempestCommon.configure')
216     def _test_run(self, status, *args):
217         # pylint: disable=unused-argument
218         self.assertEqual(self.tempestcommon.run(), status)
219
220     def test_run_missing_gen_test_list(self):
221         with mock.patch.object(self.tempestcommon, 'generate_test_list',
222                                side_effect=Exception):
223             self._test_run(testcase.TestCase.EX_RUN_ERROR)
224
225     def test_run_apply_blacklist_ko(self):
226         with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
227                 mock.patch.object(
228                     self.tempestcommon, 'apply_tempest_blacklist',
229                     side_effect=Exception()):
230             self._test_run(testcase.TestCase.EX_RUN_ERROR)
231
232     def test_run_verifier_tests_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                                   side_effect=Exception()), \
238                 mock.patch.object(self.tempestcommon, 'parse_verifier_result',
239                                   side_effect=Exception):
240             self._test_run(testcase.TestCase.EX_RUN_ERROR)
241
242     def test_run_verif_result_ko(self):
243         with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
244                 mock.patch.object(self.tempestcommon,
245                                   'apply_tempest_blacklist'), \
246                 mock.patch.object(self.tempestcommon, 'run_verifier_tests'), \
247                 mock.patch.object(self.tempestcommon, 'parse_verifier_result',
248                                   side_effect=Exception):
249             self._test_run(testcase.TestCase.EX_RUN_ERROR)
250
251     def test_run(self):
252         with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
253                 mock.patch.object(self.tempestcommon,
254                                   'apply_tempest_blacklist'), \
255                 mock.patch.object(self.tempestcommon, 'run_verifier_tests'), \
256                 mock.patch.object(self.tempestcommon,
257                                   'parse_verifier_result'), \
258                 mock.patch.object(self.tempestcommon, 'generate_report'):
259             self._test_run(testcase.TestCase.EX_OK)
260
261
262 if __name__ == "__main__":
263     logging.disable(logging.CRITICAL)
264     unittest.main(verbosity=2)