From 86ecb388915c17e80e58676f9f9d0c9b18fd0ba2 Mon Sep 17 00:00:00 2001 From: Young Date: Thu, 3 Sep 2015 22:25:41 +0800 Subject: [PATCH] only capture the ImportError when importing If the __init__ function raises a ImportError, it will also be catched. So we should call the __init__ function outside the try except clause instead. Change-Id: Iaa06565087848e2f36e8def8f0922a3ab692b695 --- oslo_utils/importutils.py | 5 +++-- oslo_utils/tests/fake/__init__.py | 5 +++++ oslo_utils/tests/test_importutils.py | 4 ++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/oslo_utils/importutils.py b/oslo_utils/importutils.py index 043f8172..15fd9bf6 100644 --- a/oslo_utils/importutils.py +++ b/oslo_utils/importutils.py @@ -47,9 +47,10 @@ def import_object_ns(name_space, import_str, *args, **kwargs): """ import_value = "%s.%s" % (name_space, import_str) try: - return import_class(import_value)(*args, **kwargs) + cls = import_class(import_value) except ImportError: - return import_class(import_str)(*args, **kwargs) + cls = import_class(import_str) + return cls(*args, **kwargs) def import_module(import_str): diff --git a/oslo_utils/tests/fake/__init__.py b/oslo_utils/tests/fake/__init__.py index 06cc9445..222a9b7c 100644 --- a/oslo_utils/tests/fake/__init__.py +++ b/oslo_utils/tests/fake/__init__.py @@ -21,3 +21,8 @@ class FakeDriver(): class FakeDriver2(): def __init__(self, first_arg): self.first_arg = first_arg + + +class FakeDriver3(): + def __init__(self): + raise ImportError("ImportError occurs in __init__") diff --git a/oslo_utils/tests/test_importutils.py b/oslo_utils/tests/test_importutils.py index bbdff04b..05551ef0 100644 --- a/oslo_utils/tests/test_importutils.py +++ b/oslo_utils/tests/test_importutils.py @@ -103,6 +103,10 @@ class ImportUtilsTest(test_base.BaseTestCase): first_arg=False) self.assertEqual(obj.__class__.__name__, 'FakeDriver2') + def test_import_object_ns_raise_import_error_in_init(self): + self.assertRaises(ImportError, importutils.import_object_ns, + 'tests2', 'oslo_utils.tests.fake.FakeDriver3') + def test_import_object(self): dt = importutils.import_object('datetime.time') self.assertTrue(isinstance(dt, sys.modules['datetime'].time))