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 def test_get_version_daily_job(self):
118 CONST.__setattr__('BUILD_TAG', self.build_tag)
119 self.assertEqual(functest_utils.get_version(), self.version)
121 def test_get_version_weekly_job(self):
122 CONST.__setattr__('BUILD_TAG', self.build_tag_week)
123 self.assertEqual(functest_utils.get_version(), self.version)
125 def test_get_version_with_dummy_build_tag(self):
126 CONST.__setattr__('BUILD_TAG', 'whatever')
127 self.assertEqual(functest_utils.get_version(), 'unknown')
129 def test_get_version_unknown(self):
130 CONST.__setattr__('BUILD_TAG', 'unknown_build_tag')
131 self.assertEqual(functest_utils.get_version(), "unknown")
133 @mock.patch('functest.utils.functest_utils.logger.info')
134 def test_logger_test_results(self, mock_logger_info):
135 CONST.__setattr__('results_test_db_url', self.db_url)
136 CONST.__setattr__('BUILD_TAG', self.build_tag)
137 CONST.__setattr__('NODE_NAME', self.node_name)
138 CONST.__setattr__('DEPLOY_SCENARIO', self.scenario)
139 with mock.patch('functest.utils.functest_utils.get_version',
140 return_value=self.version):
141 functest_utils.logger_test_results(self.project, self.case_name,
142 self.status, self.details)
143 mock_logger_info.assert_called_once_with(
145 "****************************************\n"
146 "\t %(p)s/%(n)s results \n\n"
147 "****************************************\n"
153 "build tag:\t%(b)s\n"
155 % {'p': self.project,
157 'db': CONST.__getattribute__('results_test_db_url'),
158 'pod': self.node_name,
165 def _get_env_dict(self, var):
166 dic = {'INSTALLER_TYPE': self.installer,
167 'DEPLOY_SCENARIO': self.scenario,
168 'NODE_NAME': self.node_name,
169 'BUILD_TAG': self.build_tag}
173 def _test_push_results_to_db_missing_env(self, env_var):
174 dic = self._get_env_dict(env_var)
175 CONST.__setattr__('results_test_db_url', self.db_url)
176 with mock.patch.dict(os.environ,
179 mock.patch('functest.utils.functest_utils.logger.error') \
180 as mock_logger_error:
181 functest_utils.push_results_to_db(self.project, self.case_name,
182 self.start_date, self.stop_date,
183 self.result, self.details)
184 mock_logger_error.assert_called_once_with("Please set env var: " +
188 def test_push_results_to_db_missing_installer(self):
189 self._test_push_results_to_db_missing_env('INSTALLER_TYPE')
191 def test_push_results_to_db_missing_scenario(self):
192 self._test_push_results_to_db_missing_env('DEPLOY_SCENARIO')
194 def test_push_results_to_db_missing_nodename(self):
195 self._test_push_results_to_db_missing_env('NODE_NAME')
197 def test_push_results_to_db_missing_buildtag(self):
198 self._test_push_results_to_db_missing_env('BUILD_TAG')
200 def test_push_results_to_db_request_post_failed(self):
201 dic = self._get_env_dict(None)
202 CONST.__setattr__('results_test_db_url', self.db_url)
203 with mock.patch.dict(os.environ,
206 mock.patch('functest.utils.functest_utils.logger.error') \
207 as mock_logger_error, \
208 mock.patch('functest.utils.functest_utils.requests.post',
209 side_effect=requests.RequestException):
210 self.assertFalse(functest_utils.
211 push_results_to_db(self.project, self.case_name,
214 self.result, self.details))
215 mock_logger_error.assert_called_once_with(test_utils.
216 RegexMatch("Pushing "
222 def test_push_results_to_db_request_post_exception(self):
223 dic = self._get_env_dict(None)
224 CONST.__setattr__('results_test_db_url', self.db_url)
225 with mock.patch.dict(os.environ,
228 mock.patch('functest.utils.functest_utils.logger.error') \
229 as mock_logger_error, \
230 mock.patch('functest.utils.functest_utils.requests.post',
231 side_effect=Exception):
232 self.assertFalse(functest_utils.
233 push_results_to_db(self.project, self.case_name,
236 self.result, self.details))
237 self.assertTrue(mock_logger_error.called)
239 def test_push_results_to_db_default(self):
240 dic = self._get_env_dict(None)
241 CONST.__setattr__('results_test_db_url', self.db_url)
242 with mock.patch.dict(os.environ,
245 mock.patch('functest.utils.functest_utils.requests.post'):
246 self.assertTrue(functest_utils.
247 push_results_to_db(self.project, self.case_name,
250 self.result, self.details))
252 test_ip = ['10.1.23.4', '10.1.14.15', '10.1.16.15']
256 if FunctestUtilsTesting.readline == \
257 len(FunctestUtilsTesting.test_ip) - 1:
259 FunctestUtilsTesting.readline += 1
260 return FunctestUtilsTesting.test_ip[FunctestUtilsTesting.readline]
262 # TODO: get_resolvconf_ns
263 @mock.patch('functest.utils.functest_utils.dns.resolver.Resolver')
264 def test_get_resolvconf_ns_default(self, mock_dns_resolve):
265 attrs = {'query.return_value': ["test"]}
266 mock_dns_resolve.configure_mock(**attrs)
269 attrs = {'readline.side_effect': self.readline_side}
270 m.configure_mock(**attrs)
272 with mock.patch("six.moves.builtins.open") as mo:
274 self.assertEqual(functest_utils.get_resolvconf_ns(),
277 def _get_environ(self, var):
278 if var == 'INSTALLER_TYPE':
279 return self.installer
280 elif var == 'DEPLOY_SCENARIO':
284 def test_get_ci_envvars_default(self):
285 with mock.patch('os.environ.get',
286 side_effect=self._get_environ):
287 dic = {"installer": self.installer,
288 "scenario": self.scenario}
289 self.assertDictEqual(functest_utils.get_ci_envvars(), dic)
291 def cmd_readline(self):
292 return 'test_value\n'
294 @mock.patch('functest.utils.functest_utils.logger.error')
295 @mock.patch('functest.utils.functest_utils.logger.info')
296 def test_execute_command_args_present_with_error(self, mock_logger_info,
298 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
299 as mock_subproc_open, \
300 mock.patch('six.moves.builtins.open',
301 mock.mock_open()) as mopen:
303 FunctestUtilsTesting.readline = 0
305 mock_obj = mock.Mock()
306 attrs = {'readline.side_effect': self.cmd_readline()}
307 mock_obj.configure_mock(**attrs)
309 mock_obj2 = mock.Mock()
310 attrs = {'stdout': mock_obj, 'wait.return_value': 1}
311 mock_obj2.configure_mock(**attrs)
313 mock_subproc_open.return_value = mock_obj2
315 resp = functest_utils.execute_command(self.cmd, info=True,
316 error_msg=self.error_msg,
318 output_file=self.output_file)
319 self.assertEqual(resp, 1)
320 msg_exec = ("Executing command: '%s'" % self.cmd)
321 mock_logger_info.assert_called_once_with(msg_exec)
322 mopen.assert_called_once_with(self.output_file, "w")
323 mock_logger_error.assert_called_once_with(self.error_msg)
325 @mock.patch('functest.utils.functest_utils.logger.info')
326 def test_execute_command_args_present_with_success(self, mock_logger_info,
328 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
329 as mock_subproc_open, \
330 mock.patch('six.moves.builtins.open',
331 mock.mock_open()) as mopen:
333 FunctestUtilsTesting.readline = 0
335 mock_obj = mock.Mock()
336 attrs = {'readline.side_effect': self.cmd_readline()}
337 mock_obj.configure_mock(**attrs)
339 mock_obj2 = mock.Mock()
340 attrs = {'stdout': mock_obj, 'wait.return_value': 0}
341 mock_obj2.configure_mock(**attrs)
343 mock_subproc_open.return_value = mock_obj2
345 resp = functest_utils.execute_command(self.cmd, info=True,
346 error_msg=self.error_msg,
348 output_file=self.output_file)
349 self.assertEqual(resp, 0)
350 msg_exec = ("Executing command: '%s'" % self.cmd)
351 mock_logger_info.assert_called_once_with(msg_exec)
352 mopen.assert_called_once_with(self.output_file, "w")
354 @mock.patch('sys.stdout')
355 def test_execute_command_args_missing_with_success(self, stdout=None):
356 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
357 as mock_subproc_open:
359 FunctestUtilsTesting.readline = 2
361 mock_obj = mock.Mock()
362 attrs = {'readline.side_effect': self.cmd_readline()}
363 mock_obj.configure_mock(**attrs)
365 mock_obj2 = mock.Mock()
366 attrs = {'stdout': mock_obj, 'wait.return_value': 0}
367 mock_obj2.configure_mock(**attrs)
369 mock_subproc_open.return_value = mock_obj2
371 resp = functest_utils.execute_command(self.cmd, info=False,
375 self.assertEqual(resp, 0)
377 @mock.patch('sys.stdout')
378 def test_execute_command_args_missing_with_error(self, stdout=None):
379 with mock.patch('functest.utils.functest_utils.subprocess.Popen') \
380 as mock_subproc_open:
382 FunctestUtilsTesting.readline = 2
383 mock_obj = mock.Mock()
384 attrs = {'readline.side_effect': self.cmd_readline()}
385 mock_obj.configure_mock(**attrs)
387 mock_obj2 = mock.Mock()
388 attrs = {'stdout': mock_obj, 'wait.return_value': 1}
389 mock_obj2.configure_mock(**attrs)
391 mock_subproc_open.return_value = mock_obj2
393 resp = functest_utils.execute_command(self.cmd, info=False,
397 self.assertEqual(resp, 1)
399 def _get_functest_config(self, var):
402 @mock.patch('functest.utils.functest_utils.logger.error')
403 def test_get_dict_by_test(self, mock_logger_error):
404 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
405 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
407 mock_obj = mock.Mock()
408 attrs = {'get.return_value': [{'testcases': [self.testcase_dict]}]}
409 mock_obj.configure_mock(**attrs)
411 mock_yaml.return_value = mock_obj
413 self.assertDictEqual(functest_utils.
414 get_dict_by_test(self.testname),
417 @mock.patch('functest.utils.functest_utils.get_dict_by_test')
418 def test_get_criteria_by_test_default(self, mock_get_dict_by_test):
419 mock_get_dict_by_test.return_value = self.testcase_dict
420 self.assertEqual(functest_utils.get_criteria_by_test(self.testname),
423 @mock.patch('functest.utils.functest_utils.get_dict_by_test')
424 def test_get_criteria_by_test_failed(self, mock_get_dict_by_test):
425 mock_get_dict_by_test.return_value = None
426 self.assertIsNone(functest_utils.get_criteria_by_test(self.testname))
428 def test_get_parameter_from_yaml_failed(self):
429 self.file_yaml['general'] = None
430 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
431 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
433 self.assertRaises(ValueError) as excep:
434 mock_yaml.return_value = self.file_yaml
435 functest_utils.get_parameter_from_yaml(self.parameter,
437 self.assertTrue(("The parameter %s is not"
438 " defined in config_functest.yaml" %
439 self.parameter) in excep.exception)
441 def test_get_parameter_from_yaml_default(self):
442 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
443 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
445 mock_yaml.return_value = self.file_yaml
446 self.assertEqual(functest_utils.
447 get_parameter_from_yaml(self.parameter,
451 @mock.patch('functest.utils.functest_utils.get_parameter_from_yaml')
452 def test_get_functest_config_default(self, mock_get_parameter_from_yaml):
453 with mock.patch.dict(os.environ,
454 {'CONFIG_FUNCTEST_YAML': self.config_yaml}):
455 functest_utils.get_functest_config(self.parameter)
456 mock_get_parameter_from_yaml. \
457 assert_called_once_with(self.parameter,
460 def test_get_functest_yaml(self):
461 with mock.patch('six.moves.builtins.open', mock.mock_open()), \
462 mock.patch('functest.utils.functest_utils.yaml.safe_load') \
464 mock_yaml.return_value = self.file_yaml
465 resp = functest_utils.get_functest_yaml()
466 self.assertEqual(resp, self.file_yaml)
468 @mock.patch('functest.utils.functest_utils.logger.info')
469 def test_print_separator(self, mock_logger_info):
470 functest_utils.print_separator()
471 mock_logger_info.assert_called_once_with("======================="
472 "=======================")
475 if __name__ == "__main__":
476 logging.disable(logging.CRITICAL)
477 unittest.main(verbosity=2)