From 5efb213a9eab6ac3c1526ae999946409769fd599 Mon Sep 17 00:00:00 2001 From: Juda Kaleta Date: Thu, 22 Aug 2013 16:09:14 +0200 Subject: [PATCH] Add tests for utils.import_by_path --- embed_video/tests/tests_utils.py | 35 ++++++++++++++++++++++++++++++++ embed_video/utils.py | 35 ++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 embed_video/tests/tests_utils.py create mode 100644 embed_video/utils.py diff --git a/embed_video/tests/tests_utils.py b/embed_video/tests/tests_utils.py new file mode 100644 index 0000000..85e8a31 --- /dev/null +++ b/embed_video/tests/tests_utils.py @@ -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')) diff --git a/embed_video/utils.py b/embed_video/utils.py new file mode 100644 index 0000000..3572816 --- /dev/null +++ b/embed_video/utils.py @@ -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