Move logics out of TempestCommon.__init__()
[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         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             conf_utils.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             conf_utils.TEMPEST_LIST = 'test_tempest_list'
167             cmd = ["rally", "verify", "start", "--load-list",
168                    conf_utils.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('subprocess.check_output')
175     def test_generate_report(self, mock_popen):
176         self.tempestcommon.verification_id = "1234"
177         html_file = os.path.join(
178             os.path.join(
179                 getattr(config.CONF, 'dir_results'),
180                 self.tempestcommon.case_name),
181             "tempest-report.html")
182         cmd = ["rally", "verify", "report", "--type", "html", "--uuid",
183                "1234", "--to", html_file]
184         self.tempestcommon.generate_report()
185         mock_popen.assert_called_once_with(cmd)
186
187     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
188                 'os.path.exists', return_value=False)
189     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs',
190                 side_effect=Exception)
191     def test_run_makedirs_ko(self, *args):
192         # pylint: disable=unused-argument
193         self.assertEqual(self.tempestcommon.run(),
194                          testcase.TestCase.EX_RUN_ERROR)
195
196     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
197                 'os.path.exists', return_value=False)
198     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs')
199     def test_run_create_resources_ko(self, *args):
200         # pylint: disable=unused-argument
201         self.assertEqual(self.tempestcommon.run(),
202                          testcase.TestCase.EX_RUN_ERROR)
203
204     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
205                 'os.path.exists', return_value=False)
206     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs')
207     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
208                 'TempestCommon.configure', side_effect=Exception)
209     def test_run_configure_tempest_ko(self, *args):
210         # pylint: disable=unused-argument
211         self.assertEqual(self.tempestcommon.run(),
212                          testcase.TestCase.EX_RUN_ERROR)
213
214     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
215                 'os.path.exists', return_value=False)
216     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.os.makedirs')
217     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.'
218                 'TempestCommon.configure')
219     def _test_run(self, status, *args):
220         # pylint: disable=unused-argument
221         self.assertEqual(self.tempestcommon.run(), status)
222
223     def test_run_missing_gen_test_list(self):
224         with mock.patch.object(self.tempestcommon, 'generate_test_list',
225                                side_effect=Exception):
226             self._test_run(testcase.TestCase.EX_RUN_ERROR)
227
228     def test_run_apply_blacklist_ko(self):
229         with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
230                 mock.patch.object(
231                     self.tempestcommon, 'apply_tempest_blacklist',
232                     side_effect=Exception()):
233             self._test_run(testcase.TestCase.EX_RUN_ERROR)
234
235     def test_run_verifier_tests_ko(self):
236         with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
237                 mock.patch.object(self.tempestcommon,
238                                   'apply_tempest_blacklist'), \
239                 mock.patch.object(self.tempestcommon, 'run_verifier_tests',
240                                   side_effect=Exception()), \
241                 mock.patch.object(self.tempestcommon, 'parse_verifier_result',
242                                   side_effect=Exception):
243             self._test_run(testcase.TestCase.EX_RUN_ERROR)
244
245     def test_run_verif_result_ko(self):
246         with mock.patch.object(self.tempestcommon, 'generate_test_list'), \
247                 mock.patch.object(self.tempestcommon,
248                                   'apply_tempest_blacklist'), \
249                 mock.patch.object(self.tempestcommon, 'run_verifier_tests'), \
250                 mock.patch.object(self.tempestcommon, 'parse_verifier_result',
251                                   side_effect=Exception):
252             self._test_run(testcase.TestCase.EX_RUN_ERROR)
253
254     @mock.patch('functest.opnfv_tests.openstack.tempest.tempest.TempestCommon.'
255                 'run', return_value=testcase.TestCase.EX_OK)
256     def test_run(self, *args):
257         with mock.patch.object(self.tempestcommon, 'update_rally_regex'), \
258                 mock.patch.object(self.tempestcommon, 'generate_test_list'), \
259                 mock.patch.object(self.tempestcommon,
260                                   'apply_tempest_blacklist'), \
261                 mock.patch.object(self.tempestcommon, 'run_verifier_tests'), \
262                 mock.patch.object(self.tempestcommon,
263                                   'parse_verifier_result'), \
264                 mock.patch.object(self.tempestcommon, 'generate_report'):
265             self._test_run(testcase.TestCase.EX_OK)
266             args[0].assert_called_once_with()
267
268
269 if __name__ == "__main__":
270     logging.disable(logging.CRITICAL)
271     unittest.main(verbosity=2)