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_logger_test_results(self, mock_logger_info):
154 CONST.__setattr__('results_test_db_url', self.db_url)
155 CONST.__setattr__('BUILD_TAG', self.build_tag)
156 CONST.__setattr__('NODE_NAME', self.node_name)
157 with mock.patch('functest.utils.functest_utils.get_scenario',
158 return_value=self.scenario), \
159 mock.patch('functest.utils.functest_utils.get_version',
160 return_value=self.version):
161 functest_utils.logger_test_results(self.project, self.case_name,
162 self.status, self.details)
163 mock_logger_info.assert_called_once_with(
165 "****************************************\n"
166 "\t %(p)s/%(n)s results \n\n"
167 "****************************************\n"
173 "build tag:\t%(b)s\n"
175 % {'p': self.project,
177 'db': CONST.__getattribute__('results_test_db_url'),
178 'pod': self.node_name,
185 def _get_env_dict(self, var):
186 dic = {'INSTALLER_TYPE': self.installer,
187 'DEPLOY_SCENARIO': self.scenario,
188 'NODE_NAME': self.node_name,
189 'BUILD_TAG': self.build_tag}
193 def _test_push_results_to_db_missing_env(self, env_var):
194 dic = self._get_env_dict(env_var)
195 CONST.__setattr__('results_test_db_url', self.db_url)
196 with mock.patch.dict(os.environ,
199 mock.patch('functest.utils.functest_utils.logger.error') \
200 as mock_logger_error:
201 functest_utils.push_results_to_db(self.project, self.case_name,
202 self.start_date, self.stop_date,
203 self.result, self.details)
204 mock_logger_error.assert_called_once_with("Please set env var: " +
208 def test_push_results_to_db_missing_installer(self):
209 self._test_push_results_to_db_missing_env('INSTALLER_TYPE')
211 def test_push_results_to_db_missing_scenario(self):
212 self._test_push_results_to_db_missing_env('DEPLOY_SCENARIO')
214 def test_push_results_to_db_missing_nodename(self):
215 self._test_push_results_to_db_missing_env('NODE_NAME')
217 def test_push_results_to_db_missing_buildtag(self):
218 self._test_push_results_to_db_missing_env('BUILD_TAG')
220 def test_push_results_to_db_request_post_failed(self):
221 dic = self._get_env_dict(None)
222 CONST.__setattr__('results_test_db_url', self.db_url)
223 with mock.patch.dict(os.environ,
226 mock.patch('functest.utils.functest_utils.logger.error') \
227 as mock_logger_error, \
228 mock.patch('functest.utils.functest_utils.requests.post',
229 side_effect=requests.RequestException):
230 self.assertFalse(functest_utils.
231 push_results_to_db(self.project, self.case_name,
234 self.result, self.details))
235 mock_logger_error.assert_called_once_with(test_utils.
236 RegexMatch("Pushing "
242 def test_push_results_to_db_request_post_exception(self):
243 dic = self._get_env_dict(None)
244 CONST.__setattr__('results_test_db_url', self.db_url)
245 with mock.patch.dict(os.environ,
248 mock.patch('functest.utils.functest_utils.logger.error') \
249 as mock_logger_error, \
250 mock.patch('functest.utils.functest_utils.requests.post',
251 side_effect=Exception):
252 self.assertFalse(functest_utils.
253 push_results_to_db(self.project, self.case_name,
256 self.result, self.details))
257 self.assertTrue(mock_logger_error.called)
259 def test_push_results_to_db_default(self):
260 dic = self._get_env_dict(None)
261 CONST.__setattr__('results_test_db_url', self.db_url)
262 with mock.patch.dict(os.environ,
265 mock.patch('functest.utils.functest_utils.requests.post'):
266 self.assertTrue(functest_utils.
267 push_results_to_db(self.project, self.case_name,
270 self.result, self.details))
272 test_ip = ['10.1.23.4', '10.1.14.15', '10.1.16.15']
276 if FunctestUtilsTesting.readline == \
277 len(FunctestUtilsTesting.test_ip) - 1:
279 FunctestUtilsTesting.readline += 1
280 return FunctestUtilsTesting.test_ip[FunctestUtilsTesting.readline]
282 # TODO: get_resolvconf_ns
283 @mock.patch('functest.utils.functest_utils.dns.resolver.Resolver')
284 def test_get_resolvconf_ns_default(self, mock_dns_resolve):
285 attrs = {'query.return_value': ["test"]}
286 mock_dns_resolve.configure_mock(**attrs)
289 attrs = {'readline.side_effect': self.readline_side}
290 m.configure_mock(**attrs)
292 with mock.patch("six.moves.builtins.open") as mo:
294 self.assertEqual(functest_utils.get_resolvconf_ns(),
297 def _get_environ(self, var):
298 if var == 'INSTALLER_TYPE':
299 return self.installer
300 elif var == 'DEPLOY_SCENARIO':
304 def test_get_ci_envvars_default(self):
305 with mock.patch('os.environ.get',
306 side_effect=self._get_environ):
307 dic = {"installer": self.installer,
308 "scenario": self.scenario}
309 self.assertDictEqual(functest_utils.get_ci_envvars(), dic)
311 def cmd_readline(self):
312 return 'test_value\n'
314 @mock.patch('functest.utils.functest_utils.logger.error')
315 @mock.patch('functest.utils.functest_utils.logger.info')
316 def test_execute_command_args_present_with_error(self, mock_logger_info,
318 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
319 as mock_subproc_open, \
320 mock.patch('six.moves.builtins.open',
321 mock.mock_open()) as mopen:
323 FunctestUtilsTesting.readline = 0
325 mock_obj = mock.Mock()
326 attrs = {'readline.side_effect': self.cmd_readline()}
327 mock_obj.configure_mock(**attrs)
329 mock_obj2 = mock.Mock()
330 attrs = {'stdout': mock_obj, 'wait.return_value': 1}
331 mock_obj2.configure_mock(**attrs)
333 mock_subproc_open.return_value = mock_obj2
335 resp = functest_utils.execute_command(self.cmd, info=True,
336 error_msg=self.error_msg,
338 output_file=self.output_file)
339 self.assertEqual(resp, 1)
340 msg_exec = ("Executing command: '%s'" % self.cmd)
341 mock_logger_info.assert_called_once_with(msg_exec)
342 mopen.assert_called_once_with(self.output_file, "w")
343 mock_logger_error.assert_called_once_with(self.error_msg)
345 @mock.patch('functest.utils.functest_utils.logger.info')
346 def test_execute_command_args_present_with_success(self, mock_logger_info,
348 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
349 as mock_subproc_open, \
350 mock.patch('six.moves.builtins.open',
351 mock.mock_open()) as mopen:
353 FunctestUtilsTesting.readline = 0
355 mock_obj = mock.Mock()
356 attrs = {'readline.side_effect': self.cmd_readline()}
357 mock_obj.configure_mock(**attrs)
359 mock_obj2 = mock.Mock()
360 attrs = {'stdout': mock_obj, 'wait.return_value': 0}
361 mock_obj2.configure_mock(**attrs)
363 mock_subproc_open.return_value = mock_obj2
365 resp = functest_utils.execute_command(self.cmd, info=True,
366 error_msg=self.error_msg,
368 output_file=self.output_file)
369 self.assertEqual(resp, 0)
370 msg_exec = ("Executing command: '%s'" % self.cmd)
371 mock_logger_info.assert_called_once_with(msg_exec)
372 mopen.assert_called_once_with(self.output_file, "w")
374 @mock.patch('sys.stdout')
375 def test_execute_command_args_missing_with_success(self, stdout=None):
376 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
377 as mock_subproc_open:
379 FunctestUtilsTesting.readline = 2
381 mock_obj = mock.Mock()
382 attrs = {'readline.side_effect': self.cmd_readline()}
383 mock_obj.configure_mock(**attrs)
385 mock_obj2 = mock.Mock()
386 attrs = {'stdout': mock_obj, 'wait.return_value': 0}
387 mock_obj2.configure_mock(**attrs)
389 mock_subproc_open.return_value = mock_obj2
391 resp = functest_utils.execute_command(self.cmd, info=False,
395 self.assertEqual(resp, 0)
397 @mock.patch('sys.stdout')
398 def test_execute_command_args_missing_with_error(self, stdout=None):
399 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
400 as mock_subproc_open:
402 FunctestUtilsTesting.readline = 2
403 mock_obj = mock.Mock()
404 attrs = {'readline.side_effect': self.cmd_readline()}
405 mock_obj.configure_mock(**attrs)
407 mock_obj2 = mock.Mock()
408 attrs = {'stdout': mock_obj, 'wait.return_value': 1}
409 mock_obj2.configure_mock(**attrs)
411 mock_subproc_open.return_value = mock_obj2
413 resp = functest_utils.execute_command(self.cmd, info=False,
417 self.assertEqual(resp, 1)
419 def _get_functest_config(self, var):
422 @mock.patch('functest.utils.functest_utils.logger.error')
423 def test_get_dict_by_test(self, mock_logger_error):
424 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
425 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
427 mock_obj = mock.Mock()
428 attrs = {'get.return_value': [{'testcases': [self.testcase_dict]}]}
429 mock_obj.configure_mock(**attrs)
431 mock_yaml.return_value = mock_obj
433 self.assertDictEqual(functest_utils.
434 get_dict_by_test(self.testname),
437 @mock.patch('functest.utils.functest_utils.get_dict_by_test')
438 def test_get_criteria_by_test_default(self, mock_get_dict_by_test):
439 mock_get_dict_by_test.return_value = self.testcase_dict
440 self.assertEqual(functest_utils.get_criteria_by_test(self.testname),
443 @mock.patch('functest.utils.functest_utils.get_dict_by_test')
444 def test_get_criteria_by_test_failed(self, mock_get_dict_by_test):
445 mock_get_dict_by_test.return_value = None
446 self.assertIsNone(functest_utils.get_criteria_by_test(self.testname))
448 def test_get_parameter_from_yaml_failed(self):
449 self.file_yaml['general'] = None
450 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
451 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
453 self.assertRaises(ValueError) as excep:
454 mock_yaml.return_value = self.file_yaml
455 functest_utils.get_parameter_from_yaml(self.parameter,
457 self.assertTrue(("The parameter %s is not"
458 " defined in config_functest.yaml" %
459 self.parameter) in excep.exception)
461 def test_get_parameter_from_yaml_default(self):
462 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
463 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
465 mock_yaml.return_value = self.file_yaml
466 self.assertEqual(functest_utils.
467 get_parameter_from_yaml(self.parameter,
471 @mock.patch('functest.utils.functest_utils.get_parameter_from_yaml')
472 def test_get_functest_config_default(self, mock_get_parameter_from_yaml):
473 with mock.patch.dict(os.environ,
474 {'CONFIG_FUNCTEST_YAML': self.config_yaml}):
475 functest_utils.get_functest_config(self.parameter)
476 mock_get_parameter_from_yaml. \
477 assert_called_once_with(self.parameter,
480 def test_get_functest_yaml(self):
481 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
482 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
484 mock_yaml.return_value = self.file_yaml
485 resp = functest_utils.get_functest_yaml()
486 self.assertEqual(resp, self.file_yaml)
488 @mock.patch('functest.utils.functest_utils.logger.info')
489 def test_print_separator(self, mock_logger_info):
490 functest_utils.print_separator()
491 mock_logger_info.assert_called_once_with("======================="
492 "=======================")
495 if __name__ == "__main__":
496 logging.disable(logging.CRITICAL)
497 unittest.main(verbosity=2)