From a5ae1bb42bf60aa4674c244b4ca6e161658ebfba Mon Sep 17 00:00:00 2001 From: Bengt Thuree Date: Fri, 2 Nov 2018 11:51:38 +1100 Subject: [PATCH] Internal func _log_error_and_exit & _request_post Adds two internal functions _log_error_and_exist : prints out 0, 1 or 2 lines of text and then exit with sys.exit(1) _request_post : This is a wrapper around request.post Handles three exceptions ConnectionError, MissingSchema, InvalidURL Change-Id: If8a4d20054d958cbfb3ab651eae037a124420bd3 Signed-off-by: Bengt Thuree --- lftools/deploy.py | 23 ++++++++++++++++++ requirements-test.txt | 1 + tests/test_deploy.py | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+) diff --git a/lftools/deploy.py b/lftools/deploy.py index 7dff5d88..786e527c 100644 --- a/lftools/deploy.py +++ b/lftools/deploy.py @@ -13,8 +13,10 @@ import logging import os import re import shutil +import sys import glob2 # Switch to glob when Python < 3.5 support is dropped +import requests log = logging.getLogger(__name__) @@ -31,6 +33,27 @@ def _format_url(url): return url +def _log_error_and_exit(*msg_list): + """Print error message, and exit.""" + for msg in msg_list: + log.error(msg) + sys.exit(1) + + +def _request_post(url, data, headers): + """Execute a request post, return the resp.""" + resp = {} + try: + resp = requests.post(url, data=data, headers=headers) + except requests.exceptions.MissingSchema: + _log_error_and_exit("Not valid URL: {}".format(url)) + except requests.exceptions.ConnectionError: + _log_error_and_exit("Could not connect to URL: {}".format(url)) + except requests.exceptions.InvalidURL: + _log_error_and_exit("Invalid URL: {}".format(url)) + return resp + + def copy_archives(workspace, pattern=None): """Copy files matching PATTERN in a WORKSPACE to the current directory. diff --git a/requirements-test.txt b/requirements-test.txt index 98334e5f..b030c6c9 100644 --- a/requirements-test.txt +++ b/requirements-test.txt @@ -2,3 +2,4 @@ pytest pytest-click pytest-datafiles +pytest-mock diff --git a/tests/test_deploy.py b/tests/test_deploy.py index 039984b8..dff98c6b 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -10,8 +10,10 @@ """Test deploy command.""" import os +import sys import pytest +import requests from lftools import cli import lftools.deploy as deploy_sys @@ -38,6 +40,13 @@ def test_format_url(): assert deploy_sys._format_url(url[0]) == url[1] +def test_log_and_exit(): + """Test exit.""" + with pytest.raises(SystemExit) as excinfo: + deploy_sys._log_error_and_exit("testmsg") + assert excinfo.type == SystemExit + + @pytest.mark.datafiles( os.path.join(FIXTURE_DIR, 'deploy'), ) @@ -78,3 +87,59 @@ def test_copy_archive_pattern(cli_runner, datafiles): assert os.path.exists(os.path.join( stage_dir, 'aaa', 'aaa-cert', 'target', 'surefire-reports', 'org.opendaylight.aaa.cert.test.AaaCertMdsalProviderTest-output.txt')) + +def mocked_log_error(msg1=None, msg2=None): + """Mock local_log_error_and_exit function. + This function is modified to simply raise an Exception. + The original will print msg1 & msg2, then call sys.exit(1).""" + if 'Could not connect to URL:' in msg1: + raise ValueError('connection_error') + if 'Invalid URL:' in msg1: + raise ValueError('invalid_url') + if 'Not valid URL:' in msg1: + raise ValueError('missing_schema') + raise ValueError('fail') + + +def mocked_requests_post(*args, **kwargs): + """Mock requests.post function.""" + class MockResponse: + def __init__(self, json_data, status_code): + self.json_data = json_data + self.status_code = status_code + self.text = json_data + + def json(self): + return self.json_data + + if 'connection.error.test' in args[0]: + raise requests.exceptions.ConnectionError + if 'invalid.url.test' in args[0]: + raise requests.exceptions.InvalidURL + if 'missing.schema.test' in args[0]: + raise requests.exceptions.MissingSchema + return MockResponse(None, 404) + + +def test_local_request_post(mocker): + """Test local_request_post.""" + mocker.patch('requests.post', side_effect=mocked_requests_post) + mocker.patch('lftools.deploy._log_error_and_exit', side_effect=mocked_log_error) + + xml_doc=''' + + + test1-1027 + Close staging repository. + + + ''' + with pytest.raises(ValueError) as excinfo: + deploy_sys._request_post('connection.error.test', xml_doc, "{'Content-Type': 'application/xml'}") + assert 'connection_error' in str(excinfo.value) + with pytest.raises(ValueError) as excinfo: + deploy_sys._request_post('invalid.url.test:8081nexus', xml_doc, "{'Content-Type': 'application/xml'}") + assert 'invalid_url' in str(excinfo.value) + with pytest.raises(ValueError) as excinfo: + deploy_sys._request_post('http:/missing.schema.test:8081nexus', xml_doc, "{'Content-Type': 'application/xml'}") + assert 'missing_schema' in str(excinfo.value) -- 2.16.6