1097d481d1a46abd6448b2588db122bbfd760081
[functest.git] / functest / tests / unit / openstack / tempest / test_conf_utils.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 unittest
12
13 import mock
14
15 from functest.opnfv_tests.openstack.tempest import tempest, conf_utils
16 from functest.utils.constants import CONST
17 from snaps.openstack.os_credentials import OSCreds
18
19
20 class OSTempestConfUtilsTesting(unittest.TestCase):
21     # pylint: disable=too-many-public-methods
22     def setUp(self):
23         self.os_creds = OSCreds(
24             username='user', password='pass',
25             auth_url='http://foo.com:5000/v3', project_name='bar')
26
27     @mock.patch('snaps.openstack.utils.deploy_utils.create_project',
28                 return_value=mock.Mock())
29     @mock.patch('snaps.openstack.utils.deploy_utils.create_user',
30                 return_value=mock.Mock())
31     @mock.patch('snaps.openstack.utils.deploy_utils.create_network',
32                 return_value=None)
33     @mock.patch('snaps.openstack.utils.deploy_utils.create_image',
34                 return_value=mock.Mock())
35     def test_create_res_missing_net_dic(self, *mock_args):
36         # pylint: disable=unused-argument
37         tempest_resources = tempest.TempestResourcesManager(
38             os_creds=self.os_creds)
39         with self.assertRaises(Exception) as context:
40             tempest_resources.create()
41         msg = 'Failed to create private network'
42         self.assertTrue(msg in context.exception)
43
44     @mock.patch('snaps.openstack.utils.deploy_utils.create_project',
45                 return_value=mock.Mock())
46     @mock.patch('snaps.openstack.utils.deploy_utils.create_user',
47                 return_value=mock.Mock())
48     @mock.patch('snaps.openstack.utils.deploy_utils.create_network',
49                 return_value=mock.Mock())
50     @mock.patch('snaps.openstack.utils.deploy_utils.create_image',
51                 return_value=None)
52     def test_create_res_missing_image(self, *mock_args):
53         # pylint: disable=unused-argument
54         tempest_resources = tempest.TempestResourcesManager(
55             os_creds=self.os_creds)
56
57         with self.assertRaises(Exception) as context:
58             tempest_resources.create()
59         msg = 'Failed to create image'
60         self.assertTrue(msg in context.exception, msg=str(context.exception))
61
62     @mock.patch('snaps.openstack.utils.deploy_utils.create_project',
63                 return_value=mock.Mock())
64     @mock.patch('snaps.openstack.utils.deploy_utils.create_user',
65                 return_value=mock.Mock())
66     @mock.patch('snaps.openstack.utils.deploy_utils.create_network',
67                 return_value=mock.Mock())
68     @mock.patch('snaps.openstack.utils.deploy_utils.create_image',
69                 return_value=mock.Mock())
70     @mock.patch('snaps.openstack.utils.keystone_utils.keystone_client')
71     @mock.patch('snaps.openstack.utils.keystone_utils.get_project')
72     @mock.patch('snaps.openstack.create_flavor.OpenStackFlavor.create',
73                 return_value=None)
74     def test_create_res_missing_flavor(self, *mock_args):
75         # pylint: disable=unused-argument
76         tempest_resources = tempest.TempestResourcesManager(
77             os_creds=self.os_creds)
78
79         CONST.__setattr__('tempest_use_custom_flavors', 'True')
80         with self.assertRaises(Exception) as context:
81             tempest_resources.create()
82         msg = 'Failed to create flavor'
83         self.assertTrue(msg in context.exception, msg=str(context.exception))
84
85         CONST.__setattr__('tempest_use_custom_flavors', 'False')
86         with self.assertRaises(Exception) as context:
87             tempest_resources.create(use_custom_flavors=True)
88         msg = 'Failed to create flavor'
89         self.assertTrue(msg in context.exception, msg=str(context.exception))
90
91     @staticmethod
92     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils'
93                 '.LOGGER.info')
94     @mock.patch('functest.utils.functest_utils.execute_command_raise')
95     @mock.patch('functest.utils.functest_utils.execute_command')
96     def test_create_rally_deployment(mock_exec, mock_exec_raise,
97                                      mock_logger_info):
98
99         conf_utils.create_rally_deployment()
100
101         cmd = "rally deployment destroy opnfv-rally"
102         error_msg = "Deployment %s does not exist." % \
103                     CONST.__getattribute__('rally_deployment_name')
104         mock_logger_info.assert_any_call("Creating Rally environment...")
105         mock_exec.assert_any_call(cmd, error_msg=error_msg, verbose=False)
106
107         cmd = "rally deployment create --fromenv --name="
108         cmd += CONST.__getattribute__('rally_deployment_name')
109         error_msg = "Problem while creating Rally deployment"
110         mock_exec_raise.assert_any_call(cmd, error_msg=error_msg)
111
112         cmd = "rally deployment check"
113         error_msg = ("OpenStack not responding or "
114                      "faulty Rally deployment.")
115         mock_exec_raise.assert_any_call(cmd, error_msg=error_msg)
116
117     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils'
118                 '.LOGGER.debug')
119     def test_create_verifier(self, mock_logger_debug):
120         mock_popen = mock.Mock()
121         attrs = {'poll.return_value': None,
122                  'stdout.readline.return_value': '0'}
123         mock_popen.configure_mock(**attrs)
124
125         CONST.__setattr__('tempest_verifier_name', 'test_veifier_name')
126         with mock.patch('functest.utils.functest_utils.execute_command_raise',
127                         side_effect=Exception), \
128                 self.assertRaises(Exception):
129             conf_utils.create_verifier()
130             mock_logger_debug.assert_any_call("Tempest test_veifier_name"
131                                               " does not exist")
132
133     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
134                 'create_verifier', return_value=mock.Mock())
135     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
136                 'create_rally_deployment', return_value=mock.Mock())
137     def test_get_verif_id_missing_verif(self, mock_rally, mock_tempest):
138         # pylint: disable=unused-argument
139         CONST.__setattr__('tempest_verifier_name', 'test_verifier_name')
140         with mock.patch('functest.opnfv_tests.openstack.tempest.'
141                         'conf_utils.subprocess.Popen') as mock_popen, \
142                 self.assertRaises(Exception):
143             mock_stdout = mock.Mock()
144             attrs = {'stdout.readline.return_value': ''}
145             mock_stdout.configure_mock(**attrs)
146             mock_popen.return_value = mock_stdout
147             conf_utils.get_verifier_id()
148
149     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
150                 'create_verifier', return_value=mock.Mock())
151     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
152                 'create_rally_deployment', return_value=mock.Mock())
153     def test_get_verifier_id_default(self, mock_rally, mock_tempest):
154         # pylint: disable=unused-argument
155         CONST.__setattr__('tempest_verifier_name', 'test_verifier_name')
156         with mock.patch('functest.opnfv_tests.openstack.tempest.'
157                         'conf_utils.subprocess.Popen') as mock_popen:
158             mock_stdout = mock.Mock()
159             attrs = {'stdout.readline.return_value': 'test_deploy_id'}
160             mock_stdout.configure_mock(**attrs)
161             mock_popen.return_value = mock_stdout
162
163             self.assertEqual(conf_utils.get_verifier_id(),
164                              'test_deploy_id')
165
166     def test_get_depl_id_missing_rally(self):
167         CONST.__setattr__('tempest_verifier_name', 'test_deploy_name')
168         with mock.patch('functest.opnfv_tests.openstack.tempest.'
169                         'conf_utils.subprocess.Popen') as mock_popen, \
170                 self.assertRaises(Exception):
171             mock_stdout = mock.Mock()
172             attrs = {'stdout.readline.return_value': ''}
173             mock_stdout.configure_mock(**attrs)
174             mock_popen.return_value = mock_stdout
175             conf_utils.get_verifier_deployment_id()
176
177     def test_get_depl_id_default(self):
178         CONST.__setattr__('tempest_verifier_name', 'test_deploy_name')
179         with mock.patch('functest.opnfv_tests.openstack.tempest.'
180                         'conf_utils.subprocess.Popen') as mock_popen:
181             mock_stdout = mock.Mock()
182             attrs = {'stdout.readline.return_value': 'test_deploy_id'}
183             mock_stdout.configure_mock(**attrs)
184             mock_popen.return_value = mock_stdout
185
186             self.assertEqual(conf_utils.get_verifier_deployment_id(),
187                              'test_deploy_id')
188
189     def test_get_verif_repo_dir_default(self):
190         with mock.patch('functest.opnfv_tests.openstack.tempest.'
191                         'conf_utils.os.path.join',
192                         return_value='test_verifier_repo_dir'), \
193             mock.patch('functest.opnfv_tests.openstack.tempest.'
194                        'conf_utils.get_verifier_id') as mock_get_id:
195             self.assertEqual(conf_utils.get_verifier_repo_dir(''),
196                              'test_verifier_repo_dir')
197             self.assertTrue(mock_get_id.called)
198
199     def test_get_depl_dir_default(self):
200         with mock.patch('functest.opnfv_tests.openstack.tempest.'
201                         'conf_utils.os.path.join',
202                         return_value='test_verifier_repo_dir'), \
203             mock.patch('functest.opnfv_tests.openstack.tempest.'
204                        'conf_utils.get_verifier_id') as mock_get_vid, \
205             mock.patch('functest.opnfv_tests.openstack.tempest.'
206                        'conf_utils.get_verifier_deployment_id') \
207                 as mock_get_did:
208             self.assertEqual(conf_utils.get_verifier_deployment_dir('', ''),
209                              'test_verifier_repo_dir')
210             self.assertTrue(mock_get_vid.called)
211             self.assertTrue(mock_get_did.called)
212
213     def test_backup_config_default(self):
214         with mock.patch('functest.opnfv_tests.openstack.tempest.'
215                         'conf_utils.os.path.exists',
216                         return_value=False), \
217             mock.patch('functest.opnfv_tests.openstack.tempest.'
218                        'conf_utils.os.makedirs') as mock_makedirs, \
219             mock.patch('functest.opnfv_tests.openstack.tempest.'
220                        'conf_utils.shutil.copyfile') as mock_copyfile:
221             conf_utils.backup_tempest_config('test_conf_file')
222             self.assertTrue(mock_makedirs.called)
223             self.assertTrue(mock_copyfile.called)
224
225         with mock.patch('functest.opnfv_tests.openstack.tempest.'
226                         'conf_utils.os.path.exists',
227                         return_value=True), \
228             mock.patch('functest.opnfv_tests.openstack.tempest.'
229                        'conf_utils.shutil.copyfile') as mock_copyfile:
230             conf_utils.backup_tempest_config('test_conf_file')
231             self.assertTrue(mock_copyfile.called)
232
233     def test_conf_tempest_def(self):
234         with mock.patch('functest.opnfv_tests.openstack.tempest.'
235                         'conf_utils.configure_verifier',
236                         return_value='test_conf_file'), \
237             mock.patch('functest.opnfv_tests.openstack.tempest.'
238                        'conf_utils.configure_tempest_update_params')\
239                 as mock_upd:
240             conf_utils.configure_tempest('test_dep_dir')
241             self.assertTrue(mock_upd.called)
242
243     def test_conf_tempest_defcore_def(self):
244         with mock.patch('functest.opnfv_tests.openstack.tempest.'
245                         'conf_utils.configure_verifier',
246                         return_value='test_conf_file'), \
247             mock.patch('functest.opnfv_tests.openstack.tempest.'
248                        'conf_utils.configure_tempest_update_params'), \
249             mock.patch('functest.opnfv_tests.openstack.tempest.'
250                        'conf_utils.ConfigParser.RawConfigParser.'
251                        'set') as mset, \
252             mock.patch('functest.opnfv_tests.openstack.tempest.'
253                        'conf_utils.ConfigParser.RawConfigParser.'
254                        'read') as mread, \
255             mock.patch('functest.opnfv_tests.openstack.tempest.'
256                        'conf_utils.ConfigParser.RawConfigParser.'
257                        'write') as mwrite, \
258             mock.patch('__builtin__.open', mock.mock_open()), \
259             mock.patch('functest.opnfv_tests.openstack.tempest.'
260                        'conf_utils.generate_test_accounts_file'), \
261             mock.patch('functest.opnfv_tests.openstack.tempest.'
262                        'conf_utils.shutil.copyfile'):
263             conf_utils.configure_tempest_defcore(
264                 'test_dep_dir', 'test_network_name', 'test_image_id',
265                 'test_flavor_id', 'test_image_alt_id', 'test_flavor_alt_id',
266                 'test_tenant_id')
267             mset.assert_any_call('compute', 'image_ref', 'test_image_id')
268             mset.assert_any_call('compute', 'image_ref_alt',
269                                  'test_image_alt_id')
270             mset.assert_any_call('compute', 'flavor_ref', 'test_flavor_id')
271             mset.assert_any_call('compute', 'flavor_ref_alt',
272                                  'test_flavor_alt_id')
273             self.assertTrue(mread.called)
274             self.assertTrue(mwrite.called)
275
276     def test_gen_test_accounts_file_def(self):
277         with mock.patch("__builtin__.open", mock.mock_open()), \
278             mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
279                        'yaml.dump') as mock_dump:
280             conf_utils.generate_test_accounts_file('test_tenant_id')
281             self.assertTrue(mock_dump.called)
282
283     def _test_missing_param(self, params, image_id, flavor_id):
284         with mock.patch('functest.opnfv_tests.openstack.tempest.'
285                         'conf_utils.ConfigParser.RawConfigParser.'
286                         'set') as mset, \
287             mock.patch('functest.opnfv_tests.openstack.tempest.'
288                        'conf_utils.ConfigParser.RawConfigParser.'
289                        'read') as mread, \
290             mock.patch('functest.opnfv_tests.openstack.tempest.'
291                        'conf_utils.ConfigParser.RawConfigParser.'
292                        'write') as mwrite, \
293             mock.patch('__builtin__.open', mock.mock_open()), \
294             mock.patch('functest.opnfv_tests.openstack.tempest.'
295                        'conf_utils.backup_tempest_config'), \
296             mock.patch('functest.utils.functest_utils.yaml.safe_load',
297                        return_value={'validation': {'ssh_timeout': 300}}):
298             CONST.__setattr__('OS_ENDPOINT_TYPE', None)
299             conf_utils.configure_tempest_update_params(
300                 'test_conf_file', image_id=image_id, flavor_id=flavor_id)
301             mset.assert_any_call(params[0], params[1], params[2])
302             self.assertTrue(mread.called)
303             self.assertTrue(mwrite.called)
304
305     def test_upd_missing_image_id(self):
306         self._test_missing_param(('compute', 'image_ref', 'test_image_id'),
307                                  'test_image_id', None)
308
309     def test_upd_missing_image_id_alt(self):
310         conf_utils.IMAGE_ID_ALT = 'test_image_id_alt'
311         self._test_missing_param(('compute', 'image_ref_alt',
312                                   'test_image_id_alt'), None, None)
313
314     def test_upd_missing_flavor_id(self):
315         CONST.__setattr__('tempest_use_custom_flavors', 'True')
316         self._test_missing_param(('compute', 'flavor_ref', 'test_flavor_id'),
317                                  None, 'test_flavor_id')
318
319     def test_upd_missing_flavor_id_alt(self):
320         CONST.__setattr__('tempest_use_custom_flavors', 'True')
321         conf_utils.FLAVOR_ID_ALT = 'test_flavor_id_alt'
322         self._test_missing_param(('compute', 'flavor_ref_alt',
323                                   'test_flavor_id_alt'), None, None)
324
325     def test_verif_missing_conf_file(self):
326         with mock.patch('functest.opnfv_tests.openstack.tempest.'
327                         'conf_utils.os.path.isfile',
328                         return_value=False), \
329             mock.patch('functest.opnfv_tests.openstack.tempest.'
330                        'conf_utils.ft_utils.execute_command') as mexe, \
331                 self.assertRaises(Exception) as context:
332             conf_utils.configure_verifier('test_dep_dir')
333             mexe.assert_any_call("rally verify configure-verifier")
334             msg = ("Tempest configuration file 'test_dep_dir/tempest.conf'"
335                    " NOT found.")
336             self.assertTrue(msg in context)
337
338     def test_configure_verifier_default(self):
339         with mock.patch('functest.opnfv_tests.openstack.tempest.'
340                         'conf_utils.os.path.isfile',
341                         return_value=True), \
342             mock.patch('functest.opnfv_tests.openstack.tempest.'
343                        'conf_utils.ft_utils.execute_command') as mexe:
344             self.assertEqual(conf_utils.configure_verifier('test_dep_dir'),
345                              'test_dep_dir/tempest.conf')
346             mexe.assert_any_call("rally verify configure-verifier "
347                                  "--reconfigure")
348
349
350 if __name__ == "__main__":
351     logging.disable(logging.CRITICAL)
352     unittest.main(verbosity=2)