diff options
Diffstat (limited to 'functest/tests/unit/utils')
-rw-r--r-- | functest/tests/unit/utils/test_decorators.py | 135 | ||||
-rw-r--r-- | functest/tests/unit/utils/test_functest_logger.py | 48 | ||||
-rw-r--r-- | functest/tests/unit/utils/test_functest_utils.py | 65 | ||||
-rw-r--r-- | functest/tests/unit/utils/test_openstack_utils.py | 50 |
4 files changed, 198 insertions, 100 deletions
diff --git a/functest/tests/unit/utils/test_decorators.py b/functest/tests/unit/utils/test_decorators.py new file mode 100644 index 00000000..f8bd9a54 --- /dev/null +++ b/functest/tests/unit/utils/test_decorators.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python + +# Copyright (c) 2017 Orange and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.org/licenses/LICENSE-2.0 + +"""Define the class required to fully cover decorators.""" + +from datetime import datetime +import errno +import json +import logging +import os +import unittest + +import mock + +from functest.utils import decorators +from functest.utils import functest_utils + +__author__ = "Cedric Ollivier <cedric.ollivier@orange.com>" + +VERSION = 'master' +DIR = '/dev' +FILE = '{}/null'.format(DIR) +URL = 'file://{}'.format(FILE) + + +class DecoratorsTesting(unittest.TestCase): + # pylint: disable=missing-docstring + + logging.disable(logging.CRITICAL) + + _case_name = 'base' + _project_name = 'functest' + _start_time = 1.0 + _stop_time = 2.0 + _result = 'PASS' + _build_tag = VERSION + _node_name = 'bar' + _deploy_scenario = 'foo' + _installer_type = 'debian' + + def setUp(self): + os.environ['INSTALLER_TYPE'] = self._installer_type + os.environ['DEPLOY_SCENARIO'] = self._deploy_scenario + os.environ['NODE_NAME'] = self._node_name + os.environ['BUILD_TAG'] = self._build_tag + + def test_wraps(self): + self.assertEqual(functest_utils.push_results_to_db.__name__, + "push_results_to_db") + + def _get_json(self): + stop_time = datetime.fromtimestamp(self._stop_time).strftime( + '%Y-%m-%d %H:%M:%S') + start_time = datetime.fromtimestamp(self._start_time).strftime( + '%Y-%m-%d %H:%M:%S') + data = {'project_name': self._project_name, + 'stop_date': stop_time, 'start_date': start_time, + 'case_name': self._case_name, 'build_tag': self._build_tag, + 'pod_name': self._node_name, 'installer': self._installer_type, + 'scenario': self._deploy_scenario, 'version': VERSION, + 'details': {}, 'criteria': self._result} + return json.dumps(data) + + @mock.patch('{}.get_db_url'.format(functest_utils.__name__), + return_value='http://127.0.0.1') + @mock.patch('{}.get_version'.format(functest_utils.__name__), + return_value=VERSION) + @mock.patch('requests.post') + def test_http_shema(self, *args): + self.assertTrue(functest_utils.push_results_to_db( + self._project_name, self._case_name, self._start_time, + self._stop_time, self._result, {})) + args[1].assert_called_once_with() + args[2].assert_called_once_with() + args[0].assert_called_once_with( + 'http://127.0.0.1', data=self._get_json(), + headers={'Content-Type': 'application/json'}) + + @mock.patch('{}.get_db_url'.format(functest_utils.__name__), + return_value="/dev/null") + def test_wrong_shema(self, mock_method=None): + self.assertFalse(functest_utils.push_results_to_db( + self._project_name, self._case_name, self._start_time, + self._stop_time, self._result, {})) + mock_method.assert_called_once_with() + + @mock.patch('{}.get_version'.format(functest_utils.__name__), + return_value=VERSION) + @mock.patch('{}.get_db_url'.format(functest_utils.__name__), + return_value=URL) + def _test_dump(self, *args): + with mock.patch.object(decorators, 'open', mock.mock_open(), + create=True) as mock_open: + self.assertTrue(functest_utils.push_results_to_db( + self._project_name, self._case_name, self._start_time, + self._stop_time, self._result, {})) + mock_open.assert_called_once_with(FILE, 'a') + handle = mock_open() + call_args, _ = handle.write.call_args + self.assertIn('POST', call_args[0]) + self.assertIn(self._get_json(), call_args[0]) + args[0].assert_called_once_with() + args[1].assert_called_once_with() + + @mock.patch('os.makedirs') + def test_default_dump(self, mock_method=None): + self._test_dump() + mock_method.assert_called_once_with(DIR) + + @mock.patch('os.makedirs', side_effect=OSError(errno.EEXIST, '')) + def test_makedirs_dir_exists(self, mock_method=None): + self._test_dump() + mock_method.assert_called_once_with(DIR) + + @mock.patch('{}.get_db_url'.format(functest_utils.__name__), + return_value=URL) + @mock.patch('os.makedirs', side_effect=OSError) + def test_makedirs_exc(self, *args): + self.assertFalse( + functest_utils.push_results_to_db( + self._project_name, self._case_name, self._start_time, + self._stop_time, self._result, {})) + args[0].assert_called_once_with(DIR) + args[1].assert_called_once_with() + + +if __name__ == "__main__": + logging.basicConfig() + unittest.main(verbosity=2) diff --git a/functest/tests/unit/utils/test_functest_logger.py b/functest/tests/unit/utils/test_functest_logger.py deleted file mode 100644 index 42e41a14..00000000 --- a/functest/tests/unit/utils/test_functest_logger.py +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env python - -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Apache License, Version 2.0 -# which accompanies this distribution, and is available at -# http://www.apache.org/licenses/LICENSE-2.0 - -import logging -import unittest - -import mock - -from functest.utils import functest_logger -from functest.utils.constants import CONST - - -class OSUtilsLogger(unittest.TestCase): - - logging.disable(logging.CRITICAL) - - def setUp(self): - with mock.patch('__builtin__.open', mock.mock_open()): - with mock.patch('functest.utils.functest_logger.os.path.exists', - return_value=True), \ - mock.patch('functest.utils.functest_logger.' - 'json.load'), \ - mock.patch('functest.utils.functest_logger.' - 'logging.config.dictConfig') as m: - self.logger = functest_logger.Logger('os_utils') - self.assertTrue(m.called) - with mock.patch('functest.utils.functest_logger.os.path.exists', - return_value=False), \ - mock.patch('functest.utils.functest_logger.' - 'logging.basicConfig') as m: - self.logger = functest_logger.Logger('os_utils') - self.assertTrue(m.called) - - def test_is_debug_false(self): - CONST.CI_DEBUG = False - self.assertFalse(self.logger.is_debug()) - - def test_is_debug_true(self): - CONST.CI_DEBUG = "True" - self.assertTrue(self.logger.is_debug()) - - -if __name__ == "__main__": - unittest.main(verbosity=2) diff --git a/functest/tests/unit/utils/test_functest_utils.py b/functest/tests/unit/utils/test_functest_utils.py index eb241e5d..57e0c465 100644 --- a/functest/tests/unit/utils/test_functest_utils.py +++ b/functest/tests/unit/utils/test_functest_utils.py @@ -11,11 +11,11 @@ import logging import os import time import unittest -import urllib2 from git.exc import NoSuchPathError import mock import requests +from six.moves import urllib from functest.tests.unit import test_utils from functest.utils import functest_utils @@ -41,8 +41,8 @@ class FunctestUtilsTesting(unittest.TestCase): self.status = 'test_status' self.details = 'test_details' self.db_url = 'test_db_url' - self.success_rate = 2.0 - self.criteria = 'test_criteria==2.0' + self.criteria = 50 + self.result = 75 self.start_date = 1482624000 self.stop_date = 1482624000 self.start_time = time.time() @@ -54,38 +54,39 @@ class FunctestUtilsTesting(unittest.TestCase): self.cmd = 'test_cmd' self.output_file = 'test_output_file' self.testname = 'testname' - self.testcase_dict = {'name': 'testname', 'criteria': self.criteria} + self.testcase_dict = {'case_name': 'testname', + 'criteria': self.criteria} self.parameter = 'general.openstack.image_name' self.config_yaml = 'test_config_yaml-' self.db_url_env = 'http://foo/testdb' self.file_yaml = {'general': {'openstack': {'image_name': 'test_image_name'}}} - @mock.patch('urllib2.urlopen', - side_effect=urllib2.URLError('no host given')) + @mock.patch('six.moves.urllib.request.urlopen', + side_effect=urllib.error.URLError('no host given')) def test_check_internet_connectivity_failed(self, mock_method): self.assertFalse(functest_utils.check_internet_connectivity()) mock_method.assert_called_once_with(self.url, timeout=self.timeout) - @mock.patch('urllib2.urlopen') + @mock.patch('six.moves.urllib.request.urlopen') def test_check_internet_connectivity_default(self, mock_method): self.assertTrue(functest_utils.check_internet_connectivity()) mock_method.assert_called_once_with(self.url, timeout=self.timeout) - @mock.patch('urllib2.urlopen') + @mock.patch('six.moves.urllib.request.urlopen') def test_check_internet_connectivity_debian(self, mock_method): self.url = "https://www.debian.org/" self.assertTrue(functest_utils.check_internet_connectivity(self.url)) mock_method.assert_called_once_with(self.url, timeout=self.timeout) - @mock.patch('urllib2.urlopen', - side_effect=urllib2.URLError('no host given')) + @mock.patch('six.moves.urllib.request.urlopen', + side_effect=urllib.error.URLError('no host given')) def test_download_url_failed(self, mock_url): self.assertFalse(functest_utils.download_url(self.url, self.dest_path)) - @mock.patch('urllib2.urlopen') + @mock.patch('six.moves.urllib.request.urlopen') def test_download_url_default(self, mock_url): - with mock.patch("__builtin__.open", mock.mock_open()) as m, \ + with mock.patch("six.moves.builtins.open", mock.mock_open()) as m, \ mock.patch('functest.utils.functest_utils.shutil.copyfileobj')\ as mock_sh: name = self.url.rsplit('/')[-1] @@ -278,7 +279,7 @@ class FunctestUtilsTesting(unittest.TestCase): as mock_logger_error: functest_utils.push_results_to_db(self.project, self.case_name, self.start_date, self.stop_date, - self.criteria, self.details) + self.result, self.details) mock_logger_error.assert_called_once_with("Please set env var: " + str("\'" + env_var + "\'")) @@ -310,7 +311,7 @@ class FunctestUtilsTesting(unittest.TestCase): push_results_to_db(self.project, self.case_name, self.start_date, self.stop_date, - self.criteria, self.details)) + self.result, self.details)) mock_logger_error.assert_called_once_with(test_utils. RegexMatch("Pushing " "Result to" @@ -333,7 +334,7 @@ class FunctestUtilsTesting(unittest.TestCase): push_results_to_db(self.project, self.case_name, self.start_date, self.stop_date, - self.criteria, self.details)) + self.result, self.details)) self.assertTrue(mock_logger_error.called) def test_push_results_to_db_default(self): @@ -348,7 +349,7 @@ class FunctestUtilsTesting(unittest.TestCase): push_results_to_db(self.project, self.case_name, self.start_date, self.stop_date, - self.criteria, self.details)) + self.result, self.details)) readline = 0 test_ip = ['10.1.23.4', '10.1.14.15', '10.1.16.15'] @@ -370,7 +371,7 @@ class FunctestUtilsTesting(unittest.TestCase): attrs = {'readline.side_effect': self.readline_side} m.configure_mock(**attrs) - with mock.patch("__builtin__.open") as mo: + with mock.patch("six.moves.builtins.open") as mo: mo.return_value = m self.assertEqual(functest_utils.get_resolvconf_ns(), self.test_ip[1:]) @@ -398,7 +399,8 @@ class FunctestUtilsTesting(unittest.TestCase): mock_logger_error): with mock.patch('functest.utils.functest_utils.subprocess.Popen') \ as mock_subproc_open, \ - mock.patch('__builtin__.open', mock.mock_open()) as mopen: + mock.patch('six.moves.builtins.open', + mock.mock_open()) as mopen: FunctestUtilsTesting.readline = 0 @@ -427,7 +429,8 @@ class FunctestUtilsTesting(unittest.TestCase): ): with mock.patch('functest.utils.functest_utils.subprocess.Popen') \ as mock_subproc_open, \ - mock.patch('__builtin__.open', mock.mock_open()) as mopen: + mock.patch('six.moves.builtins.open', + mock.mock_open()) as mopen: FunctestUtilsTesting.readline = 0 @@ -502,7 +505,7 @@ class FunctestUtilsTesting(unittest.TestCase): @mock.patch('functest.utils.functest_utils.logger.error') def test_get_dict_by_test(self, mock_logger_error): - with mock.patch('__builtin__.open', mock.mock_open()), \ + with mock.patch('six.moves.builtins.open', mock.mock_open()), \ mock.patch('functest.utils.functest_utils.yaml.safe_load') \ as mock_yaml, \ mock.patch('functest.utils.functest_utils.get_testcases_' @@ -530,7 +533,7 @@ class FunctestUtilsTesting(unittest.TestCase): def test_get_parameter_from_yaml_failed(self): self.file_yaml['general'] = None - with mock.patch('__builtin__.open', mock.mock_open()), \ + with mock.patch('six.moves.builtins.open', mock.mock_open()), \ mock.patch('functest.utils.functest_utils.yaml.safe_load') \ as mock_yaml, \ self.assertRaises(ValueError) as excep: @@ -542,7 +545,7 @@ class FunctestUtilsTesting(unittest.TestCase): self.parameter) in excep.exception) def test_get_parameter_from_yaml_default(self): - with mock.patch('__builtin__.open', mock.mock_open()), \ + with mock.patch('six.moves.builtins.open', mock.mock_open()), \ mock.patch('functest.utils.functest_utils.yaml.safe_load') \ as mock_yaml: mock_yaml.return_value = self.file_yaml @@ -560,22 +563,6 @@ class FunctestUtilsTesting(unittest.TestCase): assert_called_once_with(self.parameter, self.config_yaml) - def test_check_success_rate_default(self): - with mock.patch('functest.utils.functest_utils.get_criteria_by_test') \ - as mock_criteria: - mock_criteria.return_value = self.criteria - resp = functest_utils.check_success_rate(self.case_name, - self.success_rate) - self.assertEqual(resp, 'PASS') - - def test_check_success_rate_failed(self): - with mock.patch('functest.utils.functest_utils.get_criteria_by_test') \ - as mock_criteria: - mock_criteria.return_value = self.criteria - resp = functest_utils.check_success_rate(self.case_name, - 3.0) - self.assertEqual(resp, 'FAIL') - # TODO: merge_dicts def test_get_testcases_file_dir(self): @@ -585,7 +572,7 @@ class FunctestUtilsTesting(unittest.TestCase): "functest/ci/testcases.yaml") def test_get_functest_yaml(self): - with mock.patch('__builtin__.open', mock.mock_open()), \ + with mock.patch('six.moves.builtins.open', mock.mock_open()), \ mock.patch('functest.utils.functest_utils.yaml.safe_load') \ as mock_yaml: mock_yaml.return_value = self.file_yaml diff --git a/functest/tests/unit/utils/test_openstack_utils.py b/functest/tests/unit/utils/test_openstack_utils.py index 7f3995d0..a7df264c 100644 --- a/functest/tests/unit/utils/test_openstack_utils.py +++ b/functest/tests/unit/utils/test_openstack_utils.py @@ -418,21 +418,45 @@ class OSUtilsTesting(unittest.TestCase): mock_logger_info.assert_called_once_with("OS_IDENTITY_API_VERSION is " "set in env as '%s'", '3') - def test_get_keystone_client(self): + @mock.patch('functest.utils.openstack_utils.get_session') + @mock.patch('functest.utils.openstack_utils.keystoneclient.Client') + @mock.patch('functest.utils.openstack_utils.get_keystone_client_version', + return_value='3') + @mock.patch('functest.utils.openstack_utils.os.getenv', + return_value='public') + def test_get_keystone_client_with_interface(self, mock_os_getenv, + mock_keystoneclient_version, + mock_key_client, + mock_get_session): mock_keystone_obj = mock.Mock() mock_session_obj = mock.Mock() - with mock.patch('functest.utils.openstack_utils' - '.get_keystone_client_version', return_value='3'), \ - mock.patch('functest.utils.openstack_utils' - '.keystoneclient.Client', - return_value=mock_keystone_obj) \ - as mock_key_client, \ - mock.patch('functest.utils.openstack_utils.get_session', - return_value=mock_session_obj): - self.assertEqual(openstack_utils.get_keystone_client(), - mock_keystone_obj) - mock_key_client.assert_called_once_with('3', - session=mock_session_obj) + mock_key_client.return_value = mock_keystone_obj + mock_get_session.return_value = mock_session_obj + self.assertEqual(openstack_utils.get_keystone_client(), + mock_keystone_obj) + mock_key_client.assert_called_once_with('3', + session=mock_session_obj, + interface='public') + + @mock.patch('functest.utils.openstack_utils.get_session') + @mock.patch('functest.utils.openstack_utils.keystoneclient.Client') + @mock.patch('functest.utils.openstack_utils.get_keystone_client_version', + return_value='3') + @mock.patch('functest.utils.openstack_utils.os.getenv', + return_value='admin') + def test_get_keystone_client_no_interface(self, mock_os_getenv, + mock_keystoneclient_version, + mock_key_client, + mock_get_session): + mock_keystone_obj = mock.Mock() + mock_session_obj = mock.Mock() + mock_key_client.return_value = mock_keystone_obj + mock_get_session.return_value = mock_session_obj + self.assertEqual(openstack_utils.get_keystone_client(), + mock_keystone_obj) + mock_key_client.assert_called_once_with('3', + session=mock_session_obj, + interface='admin') @mock.patch('functest.utils.openstack_utils.os.getenv', return_value=None) |