Merge "Use separate timeouts for connection and reading."
[functest.git] / functest / tests / unit / utils / test_functest_utils.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2016 Orange and others.
4 #
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
9
10 import logging
11 import pkg_resources
12 import os
13 import time
14 import unittest
15
16 import mock
17 import requests
18 from six.moves import urllib
19
20 from functest.tests.unit import test_utils
21 from functest.utils import functest_utils
22 from functest.utils.constants import CONST
23
24
25 class FunctestUtilsTesting(unittest.TestCase):
26
27     def setUp(self):
28         self.url = 'http://www.opnfv.org/'
29         self.timeout = 5
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'
43         self.criteria = 50
44         self.result = 75
45         self.start_date = 1482624000
46         self.stop_date = 1482624000
47         self.start_time = time.time()
48         self.stop_time = time.time()
49         self.readline = -1
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'
53         self.cmd = 'test_cmd'
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':
64                                                     'test_image_name'}}}
65
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)
71
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)
76
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)
82
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))
87
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')\
92                 as mock_sh:
93             name = self.url.rsplit('/')[-1]
94             dest = self.dest_path + "/" + name
95             self.assertTrue(functest_utils.download_url(self.url,
96                                                         self.dest_path))
97             m.assert_called_once_with(dest, 'wb')
98             self.assertTrue(mock_sh.called)
99
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,
103                              {},
104                              clear=True):
105             self.assertEqual(functest_utils.get_installer_type(),
106                              "Unknown_installer")
107             mock_logger_error.assert_called_once_with("Impossible to retrieve"
108                                                       " the installer type")
109
110     def test_get_installer_type_default(self):
111         with mock.patch.dict(os.environ,
112                              {'INSTALLER_TYPE': 'test_installer'},
113                              clear=True):
114             self.assertEqual(functest_utils.get_installer_type(),
115                              self.installer)
116
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,
120                              {},
121                              clear=True):
122             self.assertEqual(functest_utils.get_scenario(),
123                              "os-nosdn-nofeature-noha")
124             mock_logger_info.assert_called_once_with("Impossible to retrieve "
125                                                      "the scenario.Use "
126                                                      "default "
127                                                      "os-nosdn-nofeature-noha")
128
129     def test_get_scenario_default(self):
130         with mock.patch.dict(os.environ,
131                              {'DEPLOY_SCENARIO': 'test_scenario'},
132                              clear=True):
133             self.assertEqual(functest_utils.get_scenario(),
134                              self.scenario)
135
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)
139
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)
143
144     def test_get_version_with_dummy_build_tag(self):
145         CONST.__setattr__('BUILD_TAG', 'whatever')
146         self.assertEqual(functest_utils.get_version(), 'unknown')
147
148     def test_get_version_unknown(self):
149         CONST.__setattr__('BUILD_TAG', 'unknown_build_tag')
150         self.assertEqual(functest_utils.get_version(), "unknown")
151
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,
155                              {},
156                              clear=True):
157             self.assertEqual(functest_utils.get_pod_name(),
158                              "unknown-pod")
159             mock_logger_info.assert_called_once_with("Unable to retrieve "
160                                                      "the POD name from "
161                                                      "environment. Using "
162                                                      "pod name 'unknown-pod'")
163
164     def test_get_pod_name_default(self):
165         with mock.patch.dict(os.environ,
166                              {'NODE_NAME': 'test_node_name'},
167                              clear=True):
168             self.assertEqual(functest_utils.get_pod_name(),
169                              self.node_name)
170
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(
184                 "\n"
185                 "****************************************\n"
186                 "\t %(p)s/%(n)s results \n\n"
187                 "****************************************\n"
188                 "DB:\t%(db)s\n"
189                 "pod:\t%(pod)s\n"
190                 "version:\t%(v)s\n"
191                 "scenario:\t%(s)s\n"
192                 "status:\t%(c)s\n"
193                 "build tag:\t%(b)s\n"
194                 "details:\t%(d)s\n"
195                 % {'p': self.project,
196                     'n': self.case_name,
197                     'db': CONST.__getattribute__('results_test_db_url'),
198                     'pod': self.node_name,
199                     'v': self.version,
200                     's': self.scenario,
201                     'c': self.status,
202                     'b': self.build_tag,
203                     'd': self.details})
204
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}
210         dic.pop(var, None)
211         return dic
212
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,
217                              dic,
218                              clear=True), \
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: " +
225                                                       str("\'" + env_var +
226                                                           "\'"))
227
228     def test_push_results_to_db_missing_installer(self):
229         self._test_push_results_to_db_missing_env('INSTALLER_TYPE')
230
231     def test_push_results_to_db_missing_scenario(self):
232         self._test_push_results_to_db_missing_env('DEPLOY_SCENARIO')
233
234     def test_push_results_to_db_missing_nodename(self):
235         self._test_push_results_to_db_missing_env('NODE_NAME')
236
237     def test_push_results_to_db_missing_buildtag(self):
238         self._test_push_results_to_db_missing_env('BUILD_TAG')
239
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,
244                              dic,
245                              clear=True), \
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,
252                                                 self.start_date,
253                                                 self.stop_date,
254                                                 self.result, self.details))
255             mock_logger_error.assert_called_once_with(test_utils.
256                                                       RegexMatch("Pushing "
257                                                                  "Result to"
258                                                                  " DB"
259                                                                  "(\S+\s*) "
260                                                                  "failed:"))
261
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,
266                              dic,
267                              clear=True), \
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,
274                                                 self.start_date,
275                                                 self.stop_date,
276                                                 self.result, self.details))
277             self.assertTrue(mock_logger_error.called)
278
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,
283                              dic,
284                              clear=True), \
285                 mock.patch('functest.utils.functest_utils.requests.post'):
286             self.assertTrue(functest_utils.
287                             push_results_to_db(self.project, self.case_name,
288                                                self.start_date,
289                                                self.stop_date,
290                                                self.result, self.details))
291     readline = 0
292     test_ip = ['10.1.23.4', '10.1.14.15', '10.1.16.15']
293
294     @staticmethod
295     def readline_side():
296         if FunctestUtilsTesting.readline == \
297                 len(FunctestUtilsTesting.test_ip) - 1:
298             return False
299         FunctestUtilsTesting.readline += 1
300         return FunctestUtilsTesting.test_ip[FunctestUtilsTesting.readline]
301
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)
307
308         m = mock.Mock()
309         attrs = {'readline.side_effect': self.readline_side}
310         m.configure_mock(**attrs)
311
312         with mock.patch("six.moves.builtins.open") as mo:
313             mo.return_value = m
314             self.assertEqual(functest_utils.get_resolvconf_ns(),
315                              self.test_ip[1:])
316
317     def _get_environ(self, var):
318         if var == 'INSTALLER_TYPE':
319             return self.installer
320         elif var == 'DEPLOY_SCENARIO':
321             return self.scenario
322         return var
323
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)
330
331     def cmd_readline(self):
332         return 'test_value\n'
333
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,
337                                                      mock_logger_error):
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:
342
343             FunctestUtilsTesting.readline = 0
344
345             mock_obj = mock.Mock()
346             attrs = {'readline.side_effect': self.cmd_readline()}
347             mock_obj.configure_mock(**attrs)
348
349             mock_obj2 = mock.Mock()
350             attrs = {'stdout': mock_obj, 'wait.return_value': 1}
351             mock_obj2.configure_mock(**attrs)
352
353             mock_subproc_open.return_value = mock_obj2
354
355             resp = functest_utils.execute_command(self.cmd, info=True,
356                                                   error_msg=self.error_msg,
357                                                   verbose=True,
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)
364
365     @mock.patch('functest.utils.functest_utils.logger.info')
366     def test_execute_command_args_present_with_success(self, mock_logger_info,
367                                                        ):
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:
372
373             FunctestUtilsTesting.readline = 0
374
375             mock_obj = mock.Mock()
376             attrs = {'readline.side_effect': self.cmd_readline()}
377             mock_obj.configure_mock(**attrs)
378
379             mock_obj2 = mock.Mock()
380             attrs = {'stdout': mock_obj, 'wait.return_value': 0}
381             mock_obj2.configure_mock(**attrs)
382
383             mock_subproc_open.return_value = mock_obj2
384
385             resp = functest_utils.execute_command(self.cmd, info=True,
386                                                   error_msg=self.error_msg,
387                                                   verbose=True,
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")
393
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:
398
399             FunctestUtilsTesting.readline = 2
400
401             mock_obj = mock.Mock()
402             attrs = {'readline.side_effect': self.cmd_readline()}
403             mock_obj.configure_mock(**attrs)
404
405             mock_obj2 = mock.Mock()
406             attrs = {'stdout': mock_obj, 'wait.return_value': 0}
407             mock_obj2.configure_mock(**attrs)
408
409             mock_subproc_open.return_value = mock_obj2
410
411             resp = functest_utils.execute_command(self.cmd, info=False,
412                                                   error_msg="",
413                                                   verbose=False,
414                                                   output_file=None)
415             self.assertEqual(resp, 0)
416
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:
421
422             FunctestUtilsTesting.readline = 2
423             mock_obj = mock.Mock()
424             attrs = {'readline.side_effect': self.cmd_readline()}
425             mock_obj.configure_mock(**attrs)
426
427             mock_obj2 = mock.Mock()
428             attrs = {'stdout': mock_obj, 'wait.return_value': 1}
429             mock_obj2.configure_mock(**attrs)
430
431             mock_subproc_open.return_value = mock_obj2
432
433             resp = functest_utils.execute_command(self.cmd, info=False,
434                                                   error_msg="",
435                                                   verbose=False,
436                                                   output_file=None)
437             self.assertEqual(resp, 1)
438
439     def _get_functest_config(self, var):
440         return var
441
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') \
446                 as mock_yaml:
447             mock_obj = mock.Mock()
448             attrs = {'get.return_value': [{'testcases': [self.testcase_dict]}]}
449             mock_obj.configure_mock(**attrs)
450
451             mock_yaml.return_value = mock_obj
452
453             self.assertDictEqual(functest_utils.
454                                  get_dict_by_test(self.testname),
455                                  self.testcase_dict)
456
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),
461                          self.criteria)
462
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))
467
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') \
472                 as mock_yaml, \
473                 self.assertRaises(ValueError) as excep:
474             mock_yaml.return_value = self.file_yaml
475             functest_utils.get_parameter_from_yaml(self.parameter,
476                                                    self.test_file)
477             self.assertTrue(("The parameter %s is not"
478                              " defined in config_functest.yaml" %
479                              self.parameter) in excep.exception)
480
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') \
484                 as mock_yaml:
485             mock_yaml.return_value = self.file_yaml
486             self.assertEqual(functest_utils.
487                              get_parameter_from_yaml(self.parameter,
488                                                      self.test_file),
489                              'test_image_name')
490
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,
498                                         self.config_yaml)
499
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') \
503                 as mock_yaml:
504             mock_yaml.return_value = self.file_yaml
505             resp = functest_utils.get_functest_yaml()
506             self.assertEqual(resp, self.file_yaml)
507
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                                                  "=======================")
513
514
515 if __name__ == "__main__":
516     logging.disable(logging.CRITICAL)
517     unittest.main(verbosity=2)