Internal func _log_error_and_exit & _request_post 88/13288/11
authorBengt Thuree <bthuree@linuxfoundation.org>
Fri, 2 Nov 2018 00:51:38 +0000 (11:51 +1100)
committerBengt Thuree <bthuree@linuxfoundation.org>
Wed, 7 Nov 2018 05:12:25 +0000 (16:12 +1100)
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 <bthuree@linuxfoundation.org>
lftools/deploy.py
requirements-test.txt
tests/test_deploy.py

index 7dff5d8..786e527 100644 (file)
@@ -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.
 
index 98334e5..b030c6c 100644 (file)
@@ -2,3 +2,4 @@
 pytest
 pytest-click
 pytest-datafiles
+pytest-mock
index 039984b..dff98c6 100644 (file)
 """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='''
+        <promoteRequest>
+            <data>
+                <stagedRepositoryId>test1-1027</stagedRepositoryId>
+                <description>Close staging repository.</description>
+            </data>
+        </promoteRequest>
+        '''
+    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)