From 87afbfe6eb34e7a8c8372509c967e3c8f05b7788 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Santos?= Date: Wed, 8 Jun 2016 15:11:06 +0200 Subject: [PATCH] #218 Raise import errors on endpoint handling --- connexion/utils.py | 13 +++++++++++-- tests/test_api.py | 5 ++--- tests/test_utils.py | 15 ++++++++++++++- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/connexion/utils.py b/connexion/utils.py index 86dc2848e..414bafc0d 100644 --- a/connexion/utils.py +++ b/connexion/utils.py @@ -99,14 +99,23 @@ def get_function_from_name(function_name): """ module_name, attr_path = function_name.rsplit('.', 1) module = None + last_import_error = None while not module: + try: module = importlib.import_module(module_name) - except ImportError: + except ImportError as import_error: + last_import_error = import_error module_name, attr_path1 = module_name.rsplit('.', 1) attr_path = '{0}.{1}'.format(attr_path1, attr_path) - function = deep_getattr(module, attr_path) + try: + function = deep_getattr(module, attr_path) + except AttributeError: + if last_import_error: + raise last_import_error + else: + raise return function diff --git a/tests/test_api.py b/tests/test_api.py index 483be5449..11cde4d6e 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -1,10 +1,9 @@ import pathlib +import pytest from connexion.api import Api from swagger_spec_validator.common import SwaggerValidationError -import pytest - TEST_FOLDER = pathlib.Path(__file__).parent @@ -28,7 +27,7 @@ def test_template(): def test_invalid_operation_does_stop_application_to_setup(): - with pytest.raises(AttributeError): + with pytest.raises(ImportError): Api(TEST_FOLDER / "fakeapi/op_error_api.yaml", "/api/v1.0", {'title': 'OK'}) diff --git a/tests/test_utils.py b/tests/test_utils.py index 4270248e7..b9416685f 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -2,8 +2,8 @@ import connexion.app import connexion.utils as utils - import pytest +from mock import MagicMock def test_flaskify_path(): @@ -26,6 +26,19 @@ def test_get_function_from_name(): assert function(2.7) == 3 +def test_get_function_from_name_attr_error(monkeypatch): + """ + Test attribute error without import error on get_function_from_name. + Attribute errors due to import errors are tested on + test_api.test_invalid_operation_does_stop_application_to_setup + """ + deep_attr_mock = MagicMock() + deep_attr_mock.side_effect = AttributeError + monkeypatch.setattr("connexion.utils.deep_getattr", deep_attr_mock) + with pytest.raises(AttributeError): + utils.get_function_from_name('math.ceil') + + def test_get_function_from_name_for_class_method(): function = utils.get_function_from_name('connexion.app.App.common_error_handler') assert function == connexion.app.App.common_error_handler