Add tests for utils.import_by_path

This commit is contained in:
Juda Kaleta 2013-08-22 16:09:14 +02:00
parent 8e6ec1838f
commit 5efb213a9e
2 changed files with 70 additions and 0 deletions

View file

@ -0,0 +1,35 @@
import sys
from unittest import TestCase
from django.core.exceptions import ImproperlyConfigured
from embed_video.utils import import_by_path
class ModuleImportTestCase(TestCase):
"""
Taken from Django:
https://github.com/django/django/blob/master/tests/utils_tests/test_module_loading.py
"""
def test_incorrect_path(self):
self.assertRaises(ImproperlyConfigured, import_by_path, 'wrongpath')
def test_incorrect_classname(self):
self.assertRaises(ImproperlyConfigured, import_by_path,
'embed_video.foo')
def test_import_by_path(self):
cls = import_by_path(
'embed_video.utils.import_by_path')
self.assertEqual(cls, import_by_path)
# Test exceptions raised
for path in ('no_dots_in_path', 'unexistent.path',
'utils_tests.unexistent'):
self.assertRaises(ImproperlyConfigured, import_by_path, path)
with self.assertRaises(ImproperlyConfigured) as cm:
import_by_path('unexistent.module.path', error_prefix="Foo")
self.assertTrue(str(cm.exception).startswith('Foo'))

35
embed_video/utils.py Normal file
View file

@ -0,0 +1,35 @@
from importlib import import_module
from django.core.exceptions import ImproperlyConfigured
def import_by_path(dotted_path, error_prefix=''):
"""
Import a dotted module path and return the attribute/class designated by
the last name in the path. Raise ImproperlyConfigured if something goes
wrong.
.. warning::
.. deprecated:: Django 1.6
Function :py:func:`django.utils.module_loading.import_by_path` has
been added in Django 1.6.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
raise ImproperlyConfigured("%s%s doesn't look like a module path" % (
error_prefix, dotted_path))
try:
module = import_module(module_path)
except ImportError as e:
msg = '%sError importing module %s: "%s"' % (
error_prefix, module_path, e)
raise ImproperlyConfigured(msg)
try:
attr = getattr(module, class_name)
except AttributeError:
raise ImproperlyConfigured('%sModule "%s" does not define a "%s" \
attribute/class' %
(error_prefix, module_path, class_name))
return attr