3 # Copyright (c) 2016 Orange and others.
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
18 from six.moves import urllib
20 from functest.tests.unit import test_utils
21 from functest.utils import functest_utils
22 from functest.utils.constants import CONST
25 class FunctestUtilsTesting(unittest.TestCase):
28 self.url = 'http://www.opnfv.org/'
30 self.dest_path = 'test_path'
31 self.repo_path = 'test_repo_path'
32 self.installer = 'test_installer'
33 self.scenario = 'test_scenario'
34 self.build_tag = 'jenkins-functest-fuel-opnfv-jump-2-daily-master-190'
35 self.build_tag_week = 'jenkins-functest-fuel-baremetal-weekly-master-8'
36 self.version = 'master'
37 self.node_name = 'test_node_name'
38 self.project = 'test_project'
39 self.case_name = 'test_case_name'
40 self.status = 'test_status'
41 self.details = 'test_details'
42 self.db_url = 'test_db_url'
45 self.start_date = 1482624000
46 self.stop_date = 1482624000
47 self.start_time = time.time()
48 self.stop_time = time.time()
50 self.test_ip = ['10.1.23.4', '10.1.14.15', '10.1.16.15']
51 self.test_file = 'test_file'
52 self.error_msg = 'test_error_msg'
54 self.output_file = 'test_output_file'
55 self.testname = 'testname'
56 self.testcase_dict = {'case_name': 'testname',
57 'criteria': self.criteria}
58 self.parameter = 'general.openstack.image_name'
59 self.config_yaml = pkg_resources.resource_filename(
60 'functest', 'ci/config_functest.yaml')
61 self.db_url_env = 'http://foo/testdb'
62 self.testcases_yaml = "test_testcases_yaml"
63 self.file_yaml = {'general': {'openstack': {'image_name':
66 @mock.patch('six.moves.urllib.request.urlopen',
67 side_effect=urllib.error.URLError('no host given'))
68 def test_check_internet_connectivity_failed(self, mock_method):
69 self.assertFalse(functest_utils.check_internet_connectivity())
70 mock_method.assert_called_once_with(self.url, timeout=self.timeout)
72 @mock.patch('six.moves.urllib.request.urlopen')
73 def test_check_internet_connectivity_default(self, mock_method):
74 self.assertTrue(functest_utils.check_internet_connectivity())
75 mock_method.assert_called_once_with(self.url, timeout=self.timeout)
77 @mock.patch('six.moves.urllib.request.urlopen')
78 def test_check_internet_connectivity_debian(self, mock_method):
79 self.url = "https://www.debian.org/"
80 self.assertTrue(functest_utils.check_internet_connectivity(self.url))
81 mock_method.assert_called_once_with(self.url, timeout=self.timeout)
83 @mock.patch('six.moves.urllib.request.urlopen',
84 side_effect=urllib.error.URLError('no host given'))
85 def test_download_url_failed(self, mock_url):
86 self.assertFalse(functest_utils.download_url(self.url, self.dest_path))
88 @mock.patch('six.moves.urllib.request.urlopen')
89 def test_download_url_default(self, mock_url):
90 with mock.patch("six.moves.builtins.open", mock.mock_open()) as m, \
91 mock.patch('functest.utils.functest_utils.shutil.copyfileobj')\
93 name = self.url.rsplit('/')[-1]
94 dest = self.dest_path + "/" + name
95 self.assertTrue(functest_utils.download_url(self.url,
97 m.assert_called_once_with(dest, 'wb')
98 self.assertTrue(mock_sh.called)
100 @mock.patch('functest.utils.functest_utils.logger.error')
101 def test_get_installer_type_failed(self, mock_logger_error):
102 with mock.patch.dict(os.environ,
105 self.assertEqual(functest_utils.get_installer_type(),
107 mock_logger_error.assert_called_once_with("Impossible to retrieve"
108 " the installer type")
110 def test_get_installer_type_default(self):
111 with mock.patch.dict(os.environ,
112 {'INSTALLER_TYPE': 'test_installer'},
114 self.assertEqual(functest_utils.get_installer_type(),
117 @mock.patch('functest.utils.functest_utils.logger.info')
118 def test_get_scenario_failed(self, mock_logger_info):
119 with mock.patch.dict(os.environ,
122 self.assertEqual(functest_utils.get_scenario(),
123 "os-nosdn-nofeature-noha")
124 mock_logger_info.assert_called_once_with("Impossible to retrieve "
127 "os-nosdn-nofeature-noha")
129 def test_get_scenario_default(self):
130 with mock.patch.dict(os.environ,
131 {'DEPLOY_SCENARIO': 'test_scenario'},
133 self.assertEqual(functest_utils.get_scenario(),
136 def test_get_version_daily_job(self):
137 CONST.__setattr__('BUILD_TAG', self.build_tag)
138 self.assertEqual(functest_utils.get_version(), self.version)
140 def test_get_version_weekly_job(self):
141 CONST.__setattr__('BUILD_TAG', self.build_tag_week)
142 self.assertEqual(functest_utils.get_version(), self.version)
144 def test_get_version_with_dummy_build_tag(self):
145 CONST.__setattr__('BUILD_TAG', 'whatever')
146 self.assertEqual(functest_utils.get_version(), 'unknown')
148 def test_get_version_unknown(self):
149 CONST.__setattr__('BUILD_TAG', 'unknown_build_tag')
150 self.assertEqual(functest_utils.get_version(), "unknown")
152 @mock.patch('functest.utils.functest_utils.logger.info')
153 def test_get_pod_name_failed(self, mock_logger_info):
154 with mock.patch.dict(os.environ,
157 self.assertEqual(functest_utils.get_pod_name(),
159 mock_logger_info.assert_called_once_with("Unable to retrieve "
161 "environment. Using "
162 "pod name 'unknown-pod'")
164 def test_get_pod_name_default(self):
165 with mock.patch.dict(os.environ,
166 {'NODE_NAME': 'test_node_name'},
168 self.assertEqual(functest_utils.get_pod_name(),
171 @mock.patch('functest.utils.functest_utils.logger.info')
172 def test_logger_test_results(self, mock_logger_info):
173 CONST.__setattr__('results_test_db_url', self.db_url)
174 CONST.__setattr__('BUILD_TAG', self.build_tag)
175 with mock.patch('functest.utils.functest_utils.get_pod_name',
176 return_value=self.node_name), \
177 mock.patch('functest.utils.functest_utils.get_scenario',
178 return_value=self.scenario), \
179 mock.patch('functest.utils.functest_utils.get_version',
180 return_value=self.version):
181 functest_utils.logger_test_results(self.project, self.case_name,
182 self.status, self.details)
183 mock_logger_info.assert_called_once_with(
185 "****************************************\n"
186 "\t %(p)s/%(n)s results \n\n"
187 "****************************************\n"
193 "build tag:\t%(b)s\n"
195 % {'p': self.project,
197 'db': CONST.__getattribute__('results_test_db_url'),
198 'pod': self.node_name,
205 def _get_env_dict(self, var):
206 dic = {'INSTALLER_TYPE': self.installer,
207 'DEPLOY_SCENARIO': self.scenario,
208 'NODE_NAME': self.node_name,
209 'BUILD_TAG': self.build_tag}
213 def _test_push_results_to_db_missing_env(self, env_var):
214 dic = self._get_env_dict(env_var)
215 CONST.__setattr__('results_test_db_url', self.db_url)
216 with mock.patch.dict(os.environ,
219 mock.patch('functest.utils.functest_utils.logger.error') \
220 as mock_logger_error:
221 functest_utils.push_results_to_db(self.project, self.case_name,
222 self.start_date, self.stop_date,
223 self.result, self.details)
224 mock_logger_error.assert_called_once_with("Please set env var: " +
228 def test_push_results_to_db_missing_installer(self):
229 self._test_push_results_to_db_missing_env('INSTALLER_TYPE')
231 def test_push_results_to_db_missing_scenario(self):
232 self._test_push_results_to_db_missing_env('DEPLOY_SCENARIO')
234 def test_push_results_to_db_missing_nodename(self):
235 self._test_push_results_to_db_missing_env('NODE_NAME')
237 def test_push_results_to_db_missing_buildtag(self):
238 self._test_push_results_to_db_missing_env('BUILD_TAG')
240 def test_push_results_to_db_request_post_failed(self):
241 dic = self._get_env_dict(None)
242 CONST.__setattr__('results_test_db_url', self.db_url)
243 with mock.patch.dict(os.environ,
246 mock.patch('functest.utils.functest_utils.logger.error') \
247 as mock_logger_error, \
248 mock.patch('functest.utils.functest_utils.requests.post',
249 side_effect=requests.RequestException):
250 self.assertFalse(functest_utils.
251 push_results_to_db(self.project, self.case_name,
254 self.result, self.details))
255 mock_logger_error.assert_called_once_with(test_utils.
256 RegexMatch("Pushing "
262 def test_push_results_to_db_request_post_exception(self):
263 dic = self._get_env_dict(None)
264 CONST.__setattr__('results_test_db_url', self.db_url)
265 with mock.patch.dict(os.environ,
268 mock.patch('functest.utils.functest_utils.logger.error') \
269 as mock_logger_error, \
270 mock.patch('functest.utils.functest_utils.requests.post',
271 side_effect=Exception):
272 self.assertFalse(functest_utils.
273 push_results_to_db(self.project, self.case_name,
276 self.result, self.details))
277 self.assertTrue(mock_logger_error.called)
279 def test_push_results_to_db_default(self):
280 dic = self._get_env_dict(None)
281 CONST.__setattr__('results_test_db_url', self.db_url)
282 with mock.patch.dict(os.environ,
285 mock.patch('functest.utils.functest_utils.requests.post'):
286 self.assertTrue(functest_utils.
287 push_results_to_db(self.project, self.case_name,
290 self.result, self.details))
292 test_ip = ['10.1.23.4', '10.1.14.15', '10.1.16.15']
296 if FunctestUtilsTesting.readline == \
297 len(FunctestUtilsTesting.test_ip) - 1:
299 FunctestUtilsTesting.readline += 1
300 return FunctestUtilsTesting.test_ip[FunctestUtilsTesting.readline]
302 # TODO: get_resolvconf_ns
303 @mock.patch('functest.utils.functest_utils.dns.resolver.Resolver')
304 def test_get_resolvconf_ns_default(self, mock_dns_resolve):
305 attrs = {'query.return_value': ["test"]}
306 mock_dns_resolve.configure_mock(**attrs)
309 attrs = {'readline.side_effect': self.readline_side}
310 m.configure_mock(**attrs)
312 with mock.patch("six.moves.builtins.open") as mo:
314 self.assertEqual(functest_utils.get_resolvconf_ns(),
317 def _get_environ(self, var):
318 if var == 'INSTALLER_TYPE':
319 return self.installer
320 elif var == 'DEPLOY_SCENARIO':
324 def test_get_ci_envvars_default(self):
325 with mock.patch('os.environ.get',
326 side_effect=self._get_environ):
327 dic = {"installer": self.installer,
328 "scenario": self.scenario}
329 self.assertDictEqual(functest_utils.get_ci_envvars(), dic)
331 def cmd_readline(self):
332 return 'test_value\n'
334 @mock.patch('functest.utils.functest_utils.logger.error')
335 @mock.patch('functest.utils.functest_utils.logger.info')
336 def test_execute_command_args_present_with_error(self, mock_logger_info,
338 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
339 as mock_subproc_open, \
340 mock.patch('six.moves.builtins.open',
341 mock.mock_open()) as mopen:
343 FunctestUtilsTesting.readline = 0
345 mock_obj = mock.Mock()
346 attrs = {'readline.side_effect': self.cmd_readline()}
347 mock_obj.configure_mock(**attrs)
349 mock_obj2 = mock.Mock()
350 attrs = {'stdout': mock_obj, 'wait.return_value': 1}
351 mock_obj2.configure_mock(**attrs)
353 mock_subproc_open.return_value = mock_obj2
355 resp = functest_utils.execute_command(self.cmd, info=True,
356 error_msg=self.error_msg,
358 output_file=self.output_file)
359 self.assertEqual(resp, 1)
360 msg_exec = ("Executing command: '%s'" % self.cmd)
361 mock_logger_info.assert_called_once_with(msg_exec)
362 mopen.assert_called_once_with(self.output_file, "w")
363 mock_logger_error.assert_called_once_with(self.error_msg)
365 @mock.patch('functest.utils.functest_utils.logger.info')
366 def test_execute_command_args_present_with_success(self, mock_logger_info,
368 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
369 as mock_subproc_open, \
370 mock.patch('six.moves.builtins.open',
371 mock.mock_open()) as mopen:
373 FunctestUtilsTesting.readline = 0
375 mock_obj = mock.Mock()
376 attrs = {'readline.side_effect': self.cmd_readline()}
377 mock_obj.configure_mock(**attrs)
379 mock_obj2 = mock.Mock()
380 attrs = {'stdout': mock_obj, 'wait.return_value': 0}
381 mock_obj2.configure_mock(**attrs)
383 mock_subproc_open.return_value = mock_obj2
385 resp = functest_utils.execute_command(self.cmd, info=True,
386 error_msg=self.error_msg,
388 output_file=self.output_file)
389 self.assertEqual(resp, 0)
390 msg_exec = ("Executing command: '%s'" % self.cmd)
391 mock_logger_info.assert_called_once_with(msg_exec)
392 mopen.assert_called_once_with(self.output_file, "w")
394 @mock.patch('sys.stdout')
395 def test_execute_command_args_missing_with_success(self, stdout=None):
396 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
397 as mock_subproc_open:
399 FunctestUtilsTesting.readline = 2
401 mock_obj = mock.Mock()
402 attrs = {'readline.side_effect': self.cmd_readline()}
403 mock_obj.configure_mock(**attrs)
405 mock_obj2 = mock.Mock()
406 attrs = {'stdout': mock_obj, 'wait.return_value': 0}
407 mock_obj2.configure_mock(**attrs)
409 mock_subproc_open.return_value = mock_obj2
411 resp = functest_utils.execute_command(self.cmd, info=False,
415 self.assertEqual(resp, 0)
417 @mock.patch('sys.stdout')
418 def test_execute_command_args_missing_with_error(self, stdout=None):
419 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
420 as mock_subproc_open:
422 FunctestUtilsTesting.readline = 2
423 mock_obj = mock.Mock()
424 attrs = {'readline.side_effect': self.cmd_readline()}
425 mock_obj.configure_mock(**attrs)
427 mock_obj2 = mock.Mock()
428 attrs = {'stdout': mock_obj, 'wait.return_value': 1}
429 mock_obj2.configure_mock(**attrs)
431 mock_subproc_open.return_value = mock_obj2
433 resp = functest_utils.execute_command(self.cmd, info=False,
437 self.assertEqual(resp, 1)
439 def _get_functest_config(self, var):
442 @mock.patch('functest.utils.functest_utils.logger.error')
443 def test_get_dict_by_test(self, mock_logger_error):
444 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
445 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
447 mock_obj = mock.Mock()
448 attrs = {'get.return_value': [{'testcases': [self.testcase_dict]}]}
449 mock_obj.configure_mock(**attrs)
451 mock_yaml.return_value = mock_obj
453 self.assertDictEqual(functest_utils.
454 get_dict_by_test(self.testname),
457 @mock.patch('functest.utils.functest_utils.get_dict_by_test')
458 def test_get_criteria_by_test_default(self, mock_get_dict_by_test):
459 mock_get_dict_by_test.return_value = self.testcase_dict
460 self.assertEqual(functest_utils.get_criteria_by_test(self.testname),
463 @mock.patch('functest.utils.functest_utils.get_dict_by_test')
464 def test_get_criteria_by_test_failed(self, mock_get_dict_by_test):
465 mock_get_dict_by_test.return_value = None
466 self.assertIsNone(functest_utils.get_criteria_by_test(self.testname))
468 def test_get_parameter_from_yaml_failed(self):
469 self.file_yaml['general'] = None
470 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
471 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
473 self.assertRaises(ValueError) as excep:
474 mock_yaml.return_value = self.file_yaml
475 functest_utils.get_parameter_from_yaml(self.parameter,
477 self.assertTrue(("The parameter %s is not"
478 " defined in config_functest.yaml" %
479 self.parameter) in excep.exception)
481 def test_get_parameter_from_yaml_default(self):
482 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
483 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
485 mock_yaml.return_value = self.file_yaml
486 self.assertEqual(functest_utils.
487 get_parameter_from_yaml(self.parameter,
491 @mock.patch('functest.utils.functest_utils.get_parameter_from_yaml')
492 def test_get_functest_config_default(self, mock_get_parameter_from_yaml):
493 with mock.patch.dict(os.environ,
494 {'CONFIG_FUNCTEST_YAML': self.config_yaml}):
495 functest_utils.get_functest_config(self.parameter)
496 mock_get_parameter_from_yaml. \
497 assert_called_once_with(self.parameter,
500 def test_get_functest_yaml(self):
501 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
502 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
504 mock_yaml.return_value = self.file_yaml
505 resp = functest_utils.get_functest_yaml()
506 self.assertEqual(resp, self.file_yaml)
508 @mock.patch('functest.utils.functest_utils.logger.info')
509 def test_print_separator(self, mock_logger_info):
510 functest_utils.print_separator()
511 mock_logger_info.assert_called_once_with("======================="
512 "=======================")
515 if __name__ == "__main__":
516 logging.disable(logging.CRITICAL)
517 unittest.main(verbosity=2)