Fixed import utils code

Added exception paththrough in case module cannot be loaded.

Change-Id: Ia429c25d550e11f95a6b7f62636e239eeb4022b8
This commit is contained in:
Alexei Kornienko 2013-09-24 12:54:25 +03:00
parent 9b2d8cc883
commit 4898aea328
8 changed files with 33 additions and 7 deletions

View File

@ -68,9 +68,7 @@ def itersubclasses(cls, _seen=None):
def try_append_module(name, modules): def try_append_module(name, modules):
if name not in modules: if name not in modules:
module = importutils.try_import(name) modules[name] = importutils.import_module(name)
if module is not None:
modules[name] = module
def import_modules_from_package(package): def import_modules_from_package(package):
@ -81,9 +79,7 @@ def import_modules_from_package(package):
path = [os.path.dirname(__file__), '..'] + package.split('.') path = [os.path.dirname(__file__), '..'] + package.split('.')
path = os.path.join(*path) path = os.path.join(*path)
for filename in os.listdir(path): for filename in os.listdir(path):
module_name = '%s.%s' % (package, filename) if filename.startswith('__') or not filename.endswith('.py'):
if filename.endswith('.py') and not filename.startswith('__'):
module_name = module_name[:-3]
elif os.path.isfile(os.path.join(path, filename)):
continue continue
module_name = '%s.%s' % (package, filename[:-3])
try_append_module(module_name, sys.modules) try_append_module(module_name, sys.modules)

0
tests/fixtures/__init__.py vendored Normal file
View File

0
tests/fixtures/import/__init__.py vendored Normal file
View File

5
tests/fixtures/import/broken.py vendored Normal file
View File

@ -0,0 +1,5 @@
'''This module is broken and cannot be imported.
'''
import missing.module.fromnowhere # noqa

View File

6
tests/fixtures/import/package/a.py vendored Normal file
View File

@ -0,0 +1,6 @@
'''Usual module.
'''
class Bazz:
pass

7
tests/fixtures/import/package/b.py vendored Normal file
View File

@ -0,0 +1,7 @@
'''Normal module that can be imported sucessfuly.
'''
class Bar:
def __init__(self, foo):
self._foo = foo

View File

@ -71,3 +71,15 @@ class ImportModulesTestCase(test.NoDBTestCase):
modules = {} modules = {}
utils.try_append_module('rally.version', modules) utils.try_append_module('rally.version', modules)
self.assertTrue('rally.version' in modules) self.assertTrue('rally.version' in modules)
def test_try_append_broken_module(self):
modules = {}
self.assertRaises(ImportError,
utils.try_append_module,
'tests.fixtures.import.broken',
modules)
def test_import_modules_from_package(self):
utils.import_modules_from_package('tests.fixtures.import.package')
self.assertTrue('tests.fixtures.import.package.a' in sys.modules)
self.assertTrue('tests.fixtures.import.package.b' in sys.modules)