Example #1
0
    def test_migration_path(self):
        test_apps = [
            'migrations.migrations_test_apps.normal',
            'migrations.migrations_test_apps.with_package_model',
        ]

        base_dir = os.path.dirname(os.path.dirname(__file__))

        with override_settings(INSTALLED_APPS=test_apps):
            for app in test_apps:
                app_cache.load_app(app)
                migration = migrations.Migration('0001_initial', app.split('.')[-1])
                expected_path = os.path.join(base_dir, *(app.split('.') + ['migrations', '0001_initial.py']))
                writer = MigrationWriter(migration)
                self.assertEqual(writer.path, expected_path)
Example #2
0
    def test_egg5(self):
        """Loading an app from an egg that has an import error in its models module raises that error"""
        egg_name = '%s/brokenapp.egg' % self.egg_dir
        sys.path.append(egg_name)
        self.assertRaises(ImportError, app_cache.load_app, 'broken_app')
        raised = None
        try:
            app_cache.load_app('broken_app')
        except ImportError as e:
            raised = e

        # Make sure the message is indicating the actual
        # problem in the broken app.
        self.assertTrue(raised is not None)
        self.assertTrue("modelz" in raised.args[0])
Example #3
0
    def test_invalid_models(self):
        try:
            module = app_cache.load_app("invalid_models.invalid_models")
        except Exception:
            self.fail('Unable to load invalid model module')

        get_validation_errors(self.stdout, module)
        self.stdout.seek(0)
        error_log = self.stdout.read()
        actual = error_log.split('\n')
        expected = module.model_errors.split('\n')

        unexpected = [err for err in actual if err not in expected]
        missing = [err for err in expected if err not in actual]
        self.assertFalse(unexpected, "Unexpected Errors: " + '\n'.join(unexpected))
        self.assertFalse(missing, "Missing Errors: " + '\n'.join(missing))
Example #4
0
 def setUp(self):
     self.old_sys_path = sys.path[:]
     sys.path.append(os.path.dirname(os.path.abspath(upath(__file__))))
     for app in settings.INSTALLED_APPS:
         app_cache.load_app(app)
Example #5
0
def setup(verbosity, test_labels):
    import django
    from django.conf import settings
    from django.core.apps import app_cache
    from django.test import TransactionTestCase, TestCase

    print("Testing against Django installed in '%s'" % os.path.dirname(django.__file__))

    # Force declaring available_apps in TransactionTestCase for faster tests.
    def no_available_apps(self):
        raise Exception("Please define available_apps in TransactionTestCase "
                        "and its subclasses.")
    TransactionTestCase.available_apps = property(no_available_apps)
    TestCase.available_apps = None

    state = {
        'INSTALLED_APPS': settings.INSTALLED_APPS,
        'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
        'TEMPLATE_DIRS': settings.TEMPLATE_DIRS,
        'LANGUAGE_CODE': settings.LANGUAGE_CODE,
        'STATIC_URL': settings.STATIC_URL,
        'STATIC_ROOT': settings.STATIC_ROOT,
    }

    # Redirect some settings for the duration of these tests.
    settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
    settings.ROOT_URLCONF = 'urls'
    settings.STATIC_URL = '/static/'
    settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static')
    settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),)
    settings.LANGUAGE_CODE = 'en'
    settings.SITE_ID = 1

    if verbosity > 0:
        # Ensure any warnings captured to logging are piped through a verbose
        # logging handler.  If any -W options were passed explicitly on command
        # line, warnings are not captured, and this has no effect.
        logger = logging.getLogger('py.warnings')
        handler = logging.StreamHandler()
        logger.addHandler(handler)

    # Load all the ALWAYS_INSTALLED_APPS.
    with warnings.catch_warnings():
        warnings.filterwarnings('ignore', 'django.contrib.comments is deprecated and will be removed before Django 1.8.', DeprecationWarning)
        app_cache.populate()

    # Load all the test model apps.
    test_modules = get_test_modules()

    # Reduce given test labels to just the app module path
    test_labels_set = set()
    for label in test_labels:
        bits = label.split('.')
        if bits[:2] == ['django', 'contrib']:
            bits = bits[:3]
        else:
            bits = bits[:1]
        test_labels_set.add('.'.join(bits))

    for modpath, module_name in test_modules:
        if modpath:
            module_label = '.'.join([modpath, module_name])
        else:
            module_label = module_name
        # if the module (or an ancestor) was named on the command line, or
        # no modules were named (i.e., run all), import
        # this module and add it to INSTALLED_APPS.
        if not test_labels:
            module_found_in_labels = True
        else:
            match = lambda label: (
                module_label == label or  # exact match
                module_label.startswith(label + '.')  # ancestor match
            )

            module_found_in_labels = any(match(l) for l in test_labels_set)

        if module_found_in_labels:
            if verbosity >= 2:
                print("Importing application %s" % module_name)
            app_cache.load_app(module_label)
            if module_label not in settings.INSTALLED_APPS:
                settings.INSTALLED_APPS.append(module_label)

    return state
Example #6
0
 def test_egg4(self):
     """Loading an app with no models from under the top-level egg package generates no error"""
     egg_name = '%s/omelet.egg' % self.egg_dir
     sys.path.append(egg_name)
     models = app_cache.load_app('omelet.app_no_models')
     self.assertTrue(models is None)
Example #7
0
 def test_egg3(self):
     """Models module can be loaded from an app located under an egg's top-level package"""
     egg_name = '%s/omelet.egg' % self.egg_dir
     sys.path.append(egg_name)
     models = app_cache.load_app('omelet.app_with_models')
     self.assertFalse(models is None)
Example #8
0
 def test_egg2(self):
     """Loading an app from an egg that has no models returns no models (and no error)"""
     egg_name = '%s/nomodelapp.egg' % self.egg_dir
     sys.path.append(egg_name)
     models = app_cache.load_app('app_no_models')
     self.assertTrue(models is None)
Example #9
0
 def test_egg1(self):
     """Models module can be loaded from an app in an egg"""
     egg_name = '%s/modelapp.egg' % self.egg_dir
     sys.path.append(egg_name)
     models = app_cache.load_app('app_with_models')
     self.assertFalse(models is None)