Obtain pod_name by CONST instead of get function
[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_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(
164                 "\n"
165                 "****************************************\n"
166                 "\t %(p)s/%(n)s results \n\n"
167                 "****************************************\n"
168                 "DB:\t%(db)s\n"
169                 "pod:\t%(pod)s\n"
170                 "version:\t%(v)s\n"
171                 "scenario:\t%(s)s\n"
172                 "status:\t%(c)s\n"
173                 "build tag:\t%(b)s\n"
174                 "details:\t%(d)s\n"
175                 % {'p': self.project,
176                     'n': self.case_name,
177                     'db': CONST.__getattribute__('results_test_db_url'),
178                     'pod': self.node_name,
179                     'v': self.version,
180                     's': self.scenario,
181                     'c': self.status,
182                     'b': self.build_tag,
183                     'd': self.details})
184
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}
190         dic.pop(var, None)
191         return dic
192
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,
197                              dic,
198                              clear=True), \
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: " +
205                                                       str("\'" + env_var +
206                                                           "\'"))
207
208     def test_push_results_to_db_missing_installer(self):
209         self._test_push_results_to_db_missing_env('INSTALLER_TYPE')
210
211     def test_push_results_to_db_missing_scenario(self):
212         self._test_push_results_to_db_missing_env('DEPLOY_SCENARIO')
213
214     def test_push_results_to_db_missing_nodename(self):
215         self._test_push_results_to_db_missing_env('NODE_NAME')
216
217     def test_push_results_to_db_missing_buildtag(self):
218         self._test_push_results_to_db_missing_env('BUILD_TAG')
219
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,
224                              dic,
225                              clear=True), \
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,
232                                                 self.start_date,
233                                                 self.stop_date,
234                                                 self.result, self.details))
235             mock_logger_error.assert_called_once_with(test_utils.
236                                                       RegexMatch("Pushing "
237                                                                  "Result to"
238                                                                  " DB"
239                                                                  "(\S+\s*) "
240                                                                  "failed:"))
241
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,
246                              dic,
247                              clear=True), \
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,
254                                                 self.start_date,
255                                                 self.stop_date,
256                                                 self.result, self.details))
257             self.assertTrue(mock_logger_error.called)
258
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,
263                              dic,
264                              clear=True), \
265                 mock.patch('functest.utils.functest_utils.requests.post'):
266             self.assertTrue(functest_utils.
267                             push_results_to_db(self.project, self.case_name,
268                                                self.start_date,
269                                                self.stop_date,
270                                                self.result, self.details))
271     readline = 0
272     test_ip = ['10.1.23.4', '10.1.14.15', '10.1.16.15']
273
274     @staticmethod
275     def readline_side():
276         if FunctestUtilsTesting.readline == \
277                 len(FunctestUtilsTesting.test_ip) - 1:
278             return False
279         FunctestUtilsTesting.readline += 1
280         return FunctestUtilsTesting.test_ip[FunctestUtilsTesting.readline]
281
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)
287
288         m = mock.Mock()
289         attrs = {'readline.side_effect': self.readline_side}
290         m.configure_mock(**attrs)
291
292         with mock.patch("six.moves.builtins.open") as mo:
293             mo.return_value = m
294             self.assertEqual(functest_utils.get_resolvconf_ns(),
295                              self.test_ip[1:])
296
297     def _get_environ(self, var):
298         if var == 'INSTALLER_TYPE':
299             return self.installer
300         elif var == 'DEPLOY_SCENARIO':
301             return self.scenario
302         return var
303
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)
310
311     def cmd_readline(self):
312         return 'test_value\n'
313
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,
317                                                      mock_logger_error):
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:
322
323             FunctestUtilsTesting.readline = 0
324
325             mock_obj = mock.Mock()
326             attrs = {'readline.side_effect': self.cmd_readline()}
327             mock_obj.configure_mock(**attrs)
328
329             mock_obj2 = mock.Mock()
330             attrs = {'stdout': mock_obj, 'wait.return_value': 1}
331             mock_obj2.configure_mock(**attrs)
332
333             mock_subproc_open.return_value = mock_obj2
334
335             resp = functest_utils.execute_command(self.cmd, info=True,
336                                                   error_msg=self.error_msg,
337                                                   verbose=True,
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)
344
345     @mock.patch('functest.utils.functest_utils.logger.info')
346     def test_execute_command_args_present_with_success(self, mock_logger_info,
347                                                        ):
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:
352
353             FunctestUtilsTesting.readline = 0
354
355             mock_obj = mock.Mock()
356             attrs = {'readline.side_effect': self.cmd_readline()}
357             mock_obj.configure_mock(**attrs)
358
359             mock_obj2 = mock.Mock()
360             attrs = {'stdout': mock_obj, 'wait.return_value': 0}
361             mock_obj2.configure_mock(**attrs)
362
363             mock_subproc_open.return_value = mock_obj2
364
365             resp = functest_utils.execute_command(self.cmd, info=True,
366                                                   error_msg=self.error_msg,
367                                                   verbose=True,
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")
373
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:
378
379             FunctestUtilsTesting.readline = 2
380
381             mock_obj = mock.Mock()
382             attrs = {'readline.side_effect': self.cmd_readline()}
383             mock_obj.configure_mock(**attrs)
384
385             mock_obj2 = mock.Mock()
386             attrs = {'stdout': mock_obj, 'wait.return_value': 0}
387             mock_obj2.configure_mock(**attrs)
388
389             mock_subproc_open.return_value = mock_obj2
390
391             resp = functest_utils.execute_command(self.cmd, info=False,
392                                                   error_msg="",
393                                                   verbose=False,
394                                                   output_file=None)
395             self.assertEqual(resp, 0)
396
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:
401
402             FunctestUtilsTesting.readline = 2
403             mock_obj = mock.Mock()
404             attrs = {'readline.side_effect': self.cmd_readline()}
405             mock_obj.configure_mock(**attrs)
406
407             mock_obj2 = mock.Mock()
408             attrs = {'stdout': mock_obj, 'wait.return_value': 1}
409             mock_obj2.configure_mock(**attrs)
410
411             mock_subproc_open.return_value = mock_obj2
412
413             resp = functest_utils.execute_command(self.cmd, info=False,
414                                                   error_msg="",
415                                                   verbose=False,
416                                                   output_file=None)
417             self.assertEqual(resp, 1)
418
419     def _get_functest_config(self, var):
420         return var
421
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') \
426                 as mock_yaml:
427             mock_obj = mock.Mock()
428             attrs = {'get.return_value': [{'testcases': [self.testcase_dict]}]}
429             mock_obj.configure_mock(**attrs)
430
431             mock_yaml.return_value = mock_obj
432
433             self.assertDictEqual(functest_utils.
434                                  get_dict_by_test(self.testname),
435                                  self.testcase_dict)
436
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),
441                          self.criteria)
442
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))
447
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') \
452                 as mock_yaml, \
453                 self.assertRaises(ValueError) as excep:
454             mock_yaml.return_value = self.file_yaml
455             functest_utils.get_parameter_from_yaml(self.parameter,
456                                                    self.test_file)
457             self.assertTrue(("The parameter %s is not"
458                              " defined in config_functest.yaml" %
459                              self.parameter) in excep.exception)
460
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') \
464                 as mock_yaml:
465             mock_yaml.return_value = self.file_yaml
466             self.assertEqual(functest_utils.
467                              get_parameter_from_yaml(self.parameter,
468                                                      self.test_file),
469                              'test_image_name')
470
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,
478                                         self.config_yaml)
479
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') \
483                 as mock_yaml:
484             mock_yaml.return_value = self.file_yaml
485             resp = functest_utils.get_functest_yaml()
486             self.assertEqual(resp, self.file_yaml)
487
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                                                  "=======================")
493
494
495 if __name__ == "__main__":
496     logging.disable(logging.CRITICAL)
497     unittest.main(verbosity=2)