da4418b800bfa616e3538dd95a7e4454e3e890b0
[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=invalid-name,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_tempest_resources_missing_network_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_tempest_resources_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.create_flavor.OpenStackFlavor.create',
71                 return_value=None)
72     def test_create_tempest_resources_missing_flavor(self, *mock_args):
73         # pylint: disable=unused-argument
74         tempest_resources = tempest.TempestResourcesManager(
75             os_creds=self.os_creds)
76
77         CONST.__setattr__('tempest_use_custom_flavors', 'True')
78         with self.assertRaises(Exception) as context:
79             tempest_resources.create()
80         msg = 'Failed to create flavor'
81         self.assertTrue(msg in context.exception, msg=str(context.exception))
82
83         CONST.__setattr__('tempest_use_custom_flavors', 'False')
84         with self.assertRaises(Exception) as context:
85             tempest_resources.create(use_custom_flavors=True)
86         msg = 'Failed to create flavor'
87         self.assertTrue(msg in context.exception, msg=str(context.exception))
88
89     @staticmethod
90     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils'
91                 '.LOGGER.info')
92     @mock.patch('functest.utils.functest_utils.execute_command_raise')
93     @mock.patch('functest.utils.functest_utils.execute_command')
94     def test_create_rally_deployment(mock_exec, mock_exec_raise,
95                                      mock_logger_info):
96
97         conf_utils.create_rally_deployment()
98
99         cmd = "rally deployment destroy opnfv-rally"
100         error_msg = "Deployment %s does not exist." % \
101                     CONST.__getattribute__('rally_deployment_name')
102         mock_logger_info.assert_any_call("Creating Rally environment...")
103         mock_exec.assert_any_call(cmd, error_msg=error_msg, verbose=False)
104
105         cmd = "rally deployment create --fromenv --name="
106         cmd += CONST.__getattribute__('rally_deployment_name')
107         error_msg = "Problem while creating Rally deployment"
108         mock_exec_raise.assert_any_call(cmd, error_msg=error_msg)
109
110         cmd = "rally deployment check"
111         error_msg = ("OpenStack not responding or "
112                      "faulty Rally deployment.")
113         mock_exec_raise.assert_any_call(cmd, error_msg=error_msg)
114
115     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils'
116                 '.LOGGER.debug')
117     def test_create_verifier(self, mock_logger_debug):
118         mock_popen = mock.Mock()
119         attrs = {'poll.return_value': None,
120                  'stdout.readline.return_value': '0'}
121         mock_popen.configure_mock(**attrs)
122
123         CONST.__setattr__('tempest_verifier_name', 'test_veifier_name')
124         with mock.patch('functest.utils.functest_utils.execute_command_raise',
125                         side_effect=Exception), \
126                 self.assertRaises(Exception):
127             conf_utils.create_verifier()
128             mock_logger_debug.assert_any_call("Tempest test_veifier_name"
129                                               " does not exist")
130
131     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
132                 'create_verifier', return_value=mock.Mock())
133     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
134                 'create_rally_deployment', return_value=mock.Mock())
135     def test_get_verifier_id_missing_verifier(self, mock_rally, mock_tempest):
136         # pylint: disable=unused-argument
137         CONST.__setattr__('tempest_verifier_name', 'test_verifier_name')
138         with mock.patch('functest.opnfv_tests.openstack.tempest.'
139                         'conf_utils.subprocess.Popen') as mock_popen, \
140                 self.assertRaises(Exception):
141             mock_stdout = mock.Mock()
142             attrs = {'stdout.readline.return_value': ''}
143             mock_stdout.configure_mock(**attrs)
144             mock_popen.return_value = mock_stdout
145             conf_utils.get_verifier_id()
146
147     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
148                 'create_verifier', return_value=mock.Mock())
149     @mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
150                 'create_rally_deployment', return_value=mock.Mock())
151     def test_get_verifier_id_default(self, mock_rally, mock_tempest):
152         # pylint: disable=unused-argument
153         CONST.__setattr__('tempest_verifier_name', 'test_verifier_name')
154         with mock.patch('functest.opnfv_tests.openstack.tempest.'
155                         'conf_utils.subprocess.Popen') as mock_popen:
156             mock_stdout = mock.Mock()
157             attrs = {'stdout.readline.return_value': 'test_deploy_id'}
158             mock_stdout.configure_mock(**attrs)
159             mock_popen.return_value = mock_stdout
160
161             self.assertEqual(conf_utils.get_verifier_id(),
162                              'test_deploy_id')
163
164     def test_get_verifier_deployment_id_missing_rally(self):
165         CONST.__setattr__('tempest_verifier_name', 'test_deploy_name')
166         with mock.patch('functest.opnfv_tests.openstack.tempest.'
167                         'conf_utils.subprocess.Popen') as mock_popen, \
168                 self.assertRaises(Exception):
169             mock_stdout = mock.Mock()
170             attrs = {'stdout.readline.return_value': ''}
171             mock_stdout.configure_mock(**attrs)
172             mock_popen.return_value = mock_stdout
173             conf_utils.get_verifier_deployment_id()
174
175     def test_get_verifier_deployment_id_default(self):
176         CONST.__setattr__('tempest_verifier_name', 'test_deploy_name')
177         with mock.patch('functest.opnfv_tests.openstack.tempest.'
178                         'conf_utils.subprocess.Popen') as mock_popen:
179             mock_stdout = mock.Mock()
180             attrs = {'stdout.readline.return_value': 'test_deploy_id'}
181             mock_stdout.configure_mock(**attrs)
182             mock_popen.return_value = mock_stdout
183
184             self.assertEqual(conf_utils.get_verifier_deployment_id(),
185                              'test_deploy_id')
186
187     def test_get_verifier_repo_dir_default(self):
188         with mock.patch('functest.opnfv_tests.openstack.tempest.'
189                         'conf_utils.os.path.join',
190                         return_value='test_verifier_repo_dir'), \
191             mock.patch('functest.opnfv_tests.openstack.tempest.'
192                        'conf_utils.get_verifier_id') as m:
193             self.assertEqual(conf_utils.get_verifier_repo_dir(''),
194                              'test_verifier_repo_dir')
195             self.assertTrue(m.called)
196
197     def test_get_verifier_deployment_dir_default(self):
198         with mock.patch('functest.opnfv_tests.openstack.tempest.'
199                         'conf_utils.os.path.join',
200                         return_value='test_verifier_repo_dir'), \
201             mock.patch('functest.opnfv_tests.openstack.tempest.'
202                        'conf_utils.get_verifier_id') as m1, \
203             mock.patch('functest.opnfv_tests.openstack.tempest.'
204                        'conf_utils.get_verifier_deployment_id') as m2:
205             self.assertEqual(conf_utils.get_verifier_deployment_dir('', ''),
206                              'test_verifier_repo_dir')
207             self.assertTrue(m1.called)
208             self.assertTrue(m2.called)
209
210     def test_backup_tempest_config_default(self):
211         with mock.patch('functest.opnfv_tests.openstack.tempest.'
212                         'conf_utils.os.path.exists',
213                         return_value=False), \
214             mock.patch('functest.opnfv_tests.openstack.tempest.'
215                        'conf_utils.os.makedirs') as m1, \
216             mock.patch('functest.opnfv_tests.openstack.tempest.'
217                        'conf_utils.shutil.copyfile') as m2:
218             conf_utils.backup_tempest_config('test_conf_file')
219             self.assertTrue(m1.called)
220             self.assertTrue(m2.called)
221
222         with mock.patch('functest.opnfv_tests.openstack.tempest.'
223                         'conf_utils.os.path.exists',
224                         return_value=True), \
225             mock.patch('functest.opnfv_tests.openstack.tempest.'
226                        'conf_utils.shutil.copyfile') as m2:
227             conf_utils.backup_tempest_config('test_conf_file')
228             self.assertTrue(m2.called)
229
230     def test_configure_tempest_default(self):
231         with mock.patch('functest.opnfv_tests.openstack.tempest.'
232                         'conf_utils.configure_verifier',
233                         return_value='test_conf_file'), \
234             mock.patch('functest.opnfv_tests.openstack.tempest.'
235                        'conf_utils.configure_tempest_update_params') as m1:
236             conf_utils.configure_tempest('test_dep_dir')
237             self.assertTrue(m1.called)
238
239     def test_configure_tempest_defcore_default(self):
240         with mock.patch('functest.opnfv_tests.openstack.tempest.'
241                         'conf_utils.configure_verifier',
242                         return_value='test_conf_file'), \
243             mock.patch('functest.opnfv_tests.openstack.tempest.'
244                        'conf_utils.configure_tempest_update_params'), \
245             mock.patch('functest.opnfv_tests.openstack.tempest.'
246                        'conf_utils.ConfigParser.RawConfigParser.'
247                        'set') as mset, \
248             mock.patch('functest.opnfv_tests.openstack.tempest.'
249                        'conf_utils.ConfigParser.RawConfigParser.'
250                        'read') as mread, \
251             mock.patch('functest.opnfv_tests.openstack.tempest.'
252                        'conf_utils.ConfigParser.RawConfigParser.'
253                        'write') as mwrite, \
254             mock.patch('__builtin__.open', mock.mock_open()), \
255             mock.patch('functest.opnfv_tests.openstack.tempest.'
256                        'conf_utils.generate_test_accounts_file'), \
257             mock.patch('functest.opnfv_tests.openstack.tempest.'
258                        'conf_utils.shutil.copyfile'):
259             conf_utils.configure_tempest_defcore(
260                 'test_dep_dir', 'test_network_name', 'test_image_id',
261                 'test_flavor_id', 'test_image_alt_id', 'test_flavor_alt_id',
262                 'test_tenant_id')
263             mset.assert_any_call('compute', 'image_ref', 'test_image_id')
264             mset.assert_any_call('compute', 'image_ref_alt',
265                                  'test_image_alt_id')
266             mset.assert_any_call('compute', 'flavor_ref', 'test_flavor_id')
267             mset.assert_any_call('compute', 'flavor_ref_alt',
268                                  'test_flavor_alt_id')
269             self.assertTrue(mread.called)
270             self.assertTrue(mwrite.called)
271
272     def test_generate_test_accounts_file_default(self):
273         with mock.patch("__builtin__.open", mock.mock_open()), \
274             mock.patch('functest.opnfv_tests.openstack.tempest.conf_utils.'
275                        'yaml.dump') as mock_dump:
276             conf_utils.generate_test_accounts_file('test_tenant_id')
277             self.assertTrue(mock_dump.called)
278
279     def _test_missing_param(self, params, image_id, flavor_id):
280         with mock.patch('functest.opnfv_tests.openstack.tempest.'
281                         'conf_utils.ConfigParser.RawConfigParser.'
282                         'set') as mset, \
283             mock.patch('functest.opnfv_tests.openstack.tempest.'
284                        'conf_utils.ConfigParser.RawConfigParser.'
285                        'read') as mread, \
286             mock.patch('functest.opnfv_tests.openstack.tempest.'
287                        'conf_utils.ConfigParser.RawConfigParser.'
288                        'write') as mwrite, \
289             mock.patch('__builtin__.open', mock.mock_open()), \
290             mock.patch('functest.opnfv_tests.openstack.tempest.'
291                        'conf_utils.backup_tempest_config'), \
292             mock.patch('functest.utils.functest_utils.yaml.safe_load',
293                        return_value={'validation': {'ssh_timeout': 300}}):
294             CONST.__setattr__('OS_ENDPOINT_TYPE', None)
295             conf_utils.configure_tempest_update_params(
296                 'test_conf_file', image_id=image_id, flavor_id=flavor_id)
297             mset.assert_any_call(params[0], params[1], params[2])
298             self.assertTrue(mread.called)
299             self.assertTrue(mwrite.called)
300
301     def test_configure_tempest_update_params_missing_image_id(self):
302         self._test_missing_param(('compute', 'image_ref', 'test_image_id'),
303                                  'test_image_id', None)
304
305     def test_configure_tempest_update_params_missing_image_id_alt(self):
306         conf_utils.IMAGE_ID_ALT = 'test_image_id_alt'
307         self._test_missing_param(('compute', 'image_ref_alt',
308                                   'test_image_id_alt'), None, None)
309
310     def test_configure_tempest_update_params_missing_flavor_id(self):
311         CONST.__setattr__('tempest_use_custom_flavors', 'True')
312         self._test_missing_param(('compute', 'flavor_ref', 'test_flavor_id'),
313                                  None, 'test_flavor_id')
314
315     def test_configure_tempest_update_params_missing_flavor_id_alt(self):
316         CONST.__setattr__('tempest_use_custom_flavors', 'True')
317         conf_utils.FLAVOR_ID_ALT = 'test_flavor_id_alt'
318         self._test_missing_param(('compute', 'flavor_ref_alt',
319                                   'test_flavor_id_alt'), None, None)
320
321     def test_configure_verifier_missing_temp_conf_file(self):
322         with mock.patch('functest.opnfv_tests.openstack.tempest.'
323                         'conf_utils.os.path.isfile',
324                         return_value=False), \
325             mock.patch('functest.opnfv_tests.openstack.tempest.'
326                        'conf_utils.ft_utils.execute_command') as mexe, \
327                 self.assertRaises(Exception) as context:
328             conf_utils.configure_verifier('test_dep_dir')
329             mexe.assert_any_call("rally verify configure-verifier")
330             msg = ("Tempest configuration file 'test_dep_dir/tempest.conf'"
331                    " NOT found.")
332             self.assertTrue(msg in context)
333
334     def test_configure_verifier_default(self):
335         with mock.patch('functest.opnfv_tests.openstack.tempest.'
336                         'conf_utils.os.path.isfile',
337                         return_value=True), \
338             mock.patch('functest.opnfv_tests.openstack.tempest.'
339                        'conf_utils.ft_utils.execute_command') as mexe:
340             self.assertEqual(conf_utils.configure_verifier('test_dep_dir'),
341                              'test_dep_dir/tempest.conf')
342             mexe.assert_any_call("rally verify configure-verifier "
343                                  "--reconfigure")
344
345
346 if __name__ == "__main__":
347     logging.disable(logging.CRITICAL)
348     unittest.main(verbosity=2)