Example #1
0
    def load_app(self, app_name, can_postpone=False):
        """
        Loads the app with the provided fully qualified name, and returns the
        model module.
        """
        self.handled[app_name] = None
        self.nesting_level += 1
        app_module = import_module(app_name)
        try:
            models = import_module('.models', app_name)
        except ImportError:
            self.nesting_level -= 1
            # If the app doesn't have a models module, we can just ignore the
            # ImportError and return no models for it.
            if not module_has_submodule(app_module, 'models'):
                return None
            # But if the app does have a models module, we need to figure out
            # whether to suppress or propagate the error. If can_postpone is
            # True then it may be that the package is still being imported by
            # Python and the models module isn't available yet. So we add the
            # app to the postponed list and we'll try it again after all the
            # recursion has finished (in populate). If can_postpone is False
            # then it's time to raise the ImportError.
            else:
                if can_postpone:
                    self.postponed.append(app_name)
                    return None
                else:
                    raise

        self.nesting_level -= 1
        if models not in self.app_store:
            self.app_store[models] = len(self.app_store)
            self.app_labels[self._label_for(models)] = models
        return models
Example #2
0
def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    import copy
    from djangocg.conf import settings
    from djangocg.utils.importlib import import_module
    from djangocg.utils.module_loading import module_has_submodule

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = copy.copy(site._registry)
            import_module('%s.admin' % app)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site._registry = before_import_registry

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'admin'):
                raise
    def test_deep_loader(self):
        "Modules deep inside an egg can still be tested for existence"
        egg_name = "%s/test_egg.egg" % self.egg_dir
        sys.path.append(egg_name)
        egg_module = import_module("egg_module.sub1.sub2")

        # An importable child
        self.assertTrue(module_has_submodule(egg_module, "good_module"))
        mod = import_module("egg_module.sub1.sub2.good_module")
        self.assertEqual(mod.content, "Deep Good Module")

        # A child that exists, but will generate an import error if loaded
        self.assertTrue(module_has_submodule(egg_module, "bad_module"))
        self.assertRaises(ImportError, import_module, "egg_module.sub1.sub2.bad_module")

        # A child that doesn't exist
        self.assertFalse(module_has_submodule(egg_module, "no_such_module"))
        self.assertRaises(ImportError, import_module, "egg_module.sub1.sub2.no_such_module")
    def test_shallow_loader(self):
        "Module existence can be tested inside eggs"
        egg_name = "%s/test_egg.egg" % self.egg_dir
        sys.path.append(egg_name)
        egg_module = import_module("egg_module")

        # An importable child
        self.assertTrue(module_has_submodule(egg_module, "good_module"))
        mod = import_module("egg_module.good_module")
        self.assertEqual(mod.content, "Good Module")

        # A child that exists, but will generate an import error if loaded
        self.assertTrue(module_has_submodule(egg_module, "bad_module"))
        self.assertRaises(ImportError, import_module, "egg_module.bad_module")

        # A child that doesn't exist
        self.assertFalse(module_has_submodule(egg_module, "no_such_module"))
        self.assertRaises(ImportError, import_module, "egg_module.no_such_module")
    def test_loader(self):
        "Normal module existence can be tested"
        test_module = import_module("regressiontests.utils.test_module")
        test_no_submodule = import_module("regressiontests.utils.test_no_submodule")

        # An importable child
        self.assertTrue(module_has_submodule(test_module, "good_module"))
        mod = import_module("regressiontests.utils.test_module.good_module")
        self.assertEqual(mod.content, "Good Module")

        # A child that exists, but will generate an import error if loaded
        self.assertTrue(module_has_submodule(test_module, "bad_module"))
        self.assertRaises(ImportError, import_module, "regressiontests.utils.test_module.bad_module")

        # A child that doesn't exist
        self.assertFalse(module_has_submodule(test_module, "no_such_module"))
        self.assertRaises(ImportError, import_module, "regressiontests.utils.test_module.no_such_module")

        # A child that doesn't exist, but is the name of a package on the path
        self.assertFalse(module_has_submodule(test_module, "django"))
        self.assertRaises(ImportError, import_module, "regressiontests.utils.test_module.django")

        # Don't be confused by caching of import misses
        import types  # causes attempted import of regressiontests.utils.types

        self.assertFalse(module_has_submodule(sys.modules["regressiontests.utils"], "types"))

        # A module which doesn't have a __path__ (so no submodules)
        self.assertFalse(module_has_submodule(test_no_submodule, "anything"))
        self.assertRaises(ImportError, import_module, "regressiontests.utils.test_no_submodule.anything")
Example #6
0
def is_library_missing(name):
    """Check if library that failed to load cannot be found under any
    templatetags directory or does exist but fails to import.

    Non-existing condition is checked recursively for each subpackage in cases
    like <appdir>/templatetags/subpackage/package/module.py.
    """
    # Don't bother to check if '.' is in name since any name will be prefixed
    # with some template root.
    path, module = name.rsplit('.', 1)
    try:
        package = import_module(path)
        return not module_has_submodule(package, module)
    except ImportError:
        return is_library_missing(path)
Example #7
0
def get_callable(lookup_view, can_fail=False):
    """
    Convert a string version of a function name to the callable object.

    If the lookup_view is not an import path, it is assumed to be a URL pattern
    label and the original string is returned.

    If can_fail is True, lookup_view might be a URL pattern label, so errors
    during the import fail and the string is returned.
    """
    if not callable(lookup_view):
        mod_name, func_name = get_mod_func(lookup_view)
        if func_name == '':
            return lookup_view

        try:
            mod = import_module(mod_name)
        except ImportError:
            parentmod, submod = get_mod_func(mod_name)
            if (not can_fail and submod != '' and
                    not module_has_submodule(import_module(parentmod), submod)):
                raise ViewDoesNotExist(
                    "Could not import %s. Parent module %s does not exist." %
                    (lookup_view, mod_name))
            if not can_fail:
                raise
        else:
            try:
                lookup_view = getattr(mod, func_name)
                if not callable(lookup_view):
                    raise ViewDoesNotExist(
                        "Could not import %s.%s. View is not callable." %
                        (mod_name, func_name))
            except AttributeError:
                if not can_fail:
                    raise ViewDoesNotExist(
                        "Could not import %s. View does not exist in module %s." %
                        (lookup_view, mod_name))
    return lookup_view
Example #8
0
def get_tests(app_module):
    parts = app_module.__name__.split('.')
    prefix, last = parts[:-1], parts[-1]
    try:
        test_module = import_module('.'.join(prefix + [TEST_MODULE]))
    except ImportError:
        # Couldn't import tests.py. Was it due to a missing file, or
        # due to an import error in a tests.py that actually exists?
        # app_module either points to a models.py file, or models/__init__.py
        # Tests are therefore either in same directory, or one level up
        if last == 'models':
            app_root = import_module('.'.join(prefix))
        else:
            app_root = app_module

        if not module_has_submodule(app_root, TEST_MODULE):
            test_module = None
        else:
            # The module exists, so there must be an import error in the test
            # module itself.
            raise
    return test_module