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:
parent
5f6e724eb1
commit
86ecb38891
@ -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):
|
||||
|
@ -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__")
|
||||
|
@ -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))
|
||||
|
Loading…
Reference in New Issue
Block a user