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
This commit is contained in:
Young 2015-09-03 22:25:41 +08:00
parent 5f6e724eb1
commit 86ecb38891
3 changed files with 12 additions and 2 deletions

View File

@ -47,9 +47,10 @@ def import_object_ns(name_space, import_str, *args, **kwargs):
""" """
import_value = "%s.%s" % (name_space, import_str) import_value = "%s.%s" % (name_space, import_str)
try: try:
return import_class(import_value)(*args, **kwargs) cls = import_class(import_value)
except ImportError: except ImportError:
return import_class(import_str)(*args, **kwargs) cls = import_class(import_str)
return cls(*args, **kwargs)
def import_module(import_str): def import_module(import_str):

View File

@ -21,3 +21,8 @@ class FakeDriver():
class FakeDriver2(): class FakeDriver2():
def __init__(self, first_arg): def __init__(self, first_arg):
self.first_arg = first_arg self.first_arg = first_arg
class FakeDriver3():
def __init__(self):
raise ImportError("ImportError occurs in __init__")

View File

@ -103,6 +103,10 @@ class ImportUtilsTest(test_base.BaseTestCase):
first_arg=False) first_arg=False)
self.assertEqual(obj.__class__.__name__, 'FakeDriver2') 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): def test_import_object(self):
dt = importutils.import_object('datetime.time') dt = importutils.import_object('datetime.time')
self.assertTrue(isinstance(dt, sys.modules['datetime'].time)) self.assertTrue(isinstance(dt, sys.modules['datetime'].time))