コード例 #1
0
def _check_middleware_classes(app_configs=None, **kwargs):
    """
    Checks if the user has *not* overridden the ``MIDDLEWARE_CLASSES`` setting &
    warns them about the global default changes.
    """
    from django.conf import settings

    # MIDDLEWARE_CLASSES is overridden by default by startproject. If users
    # have removed this override then we'll warn them about the default changes.
    if not settings.is_overridden('MIDDLEWARE_CLASSES'):
        return [
            Warning(
                "MIDDLEWARE_CLASSES is not set.",
                hint=
                ("Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. "
                 "django.contrib.sessions.middleware.SessionMiddleware, "
                 "django.contrib.auth.middleware.AuthenticationMiddleware, and "
                 "django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. "
                 "If your project needs these middleware then you should configure this setting."
                 ),
                obj=None,
                id='1_7.W001',
            )
        ]
    else:
        return []
コード例 #2
0
def is_first_party_app_config(app_config):
    if settings.is_overridden("FIRST_PARTY_APPS"):
        return app_config.label in settings.FIRST_PARTY_APPS

    # Check if it seems to be installed in a virtualenv
    path = Path(app_config.path)
    return "site-packages" not in path.parts and "dist-packages" not in path.parts
コード例 #3
0
def check_middleware(app_configs, **kwargs):
    from debug_toolbar.middleware import DebugToolbarMiddleware

    errors = []
    gzip_index = None
    debug_toolbar_indexes = []

    # If old style MIDDLEWARE_CLASSES is being used, report an error.
    if settings.is_overridden("MIDDLEWARE_CLASSES"):
        errors.append(
            Warning(
                "debug_toolbar is incompatible with MIDDLEWARE_CLASSES setting.",
                hint="Use MIDDLEWARE instead of MIDDLEWARE_CLASSES",
                id="debug_toolbar.W004",
            )
        )
        return errors

    # Determine the indexes which gzip and/or the toolbar are installed at
    for i, middleware in enumerate(settings.MIDDLEWARE):
        if is_middleware_class(GZipMiddleware, middleware):
            gzip_index = i
        elif is_middleware_class(DebugToolbarMiddleware, middleware):
            debug_toolbar_indexes.append(i)

    if not debug_toolbar_indexes:
        # If the toolbar does not appear, report an error.
        errors.append(
            Warning(
                "debug_toolbar.middleware.DebugToolbarMiddleware is missing "
                "from MIDDLEWARE.",
                hint="Add debug_toolbar.middleware.DebugToolbarMiddleware to "
                "MIDDLEWARE.",
                id="debug_toolbar.W001",
            )
        )
    elif len(debug_toolbar_indexes) != 1:
        # If the toolbar appears multiple times, report an error.
        errors.append(
            Warning(
                "debug_toolbar.middleware.DebugToolbarMiddleware occurs "
                "multiple times in MIDDLEWARE.",
                hint="Load debug_toolbar.middleware.DebugToolbarMiddleware only "
                "once in MIDDLEWARE.",
                id="debug_toolbar.W002",
            )
        )
    elif gzip_index is not None and debug_toolbar_indexes[0] < gzip_index:
        # If the toolbar appears before the gzip index, report an error.
        errors.append(
            Warning(
                "debug_toolbar.middleware.DebugToolbarMiddleware occurs before "
                "django.middleware.gzip.GZipMiddleware in MIDDLEWARE.",
                hint="Move debug_toolbar.middleware.DebugToolbarMiddleware to "
                "after django.middleware.gzip.GZipMiddleware in MIDDLEWARE.",
                id="debug_toolbar.W003",
            )
        )

    return errors
コード例 #4
0
 def test_02_auth_password_validators(self):
     validators = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
                   {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'},
                   {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, 
                   {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}]
     self.assertTrue(settings.is_overridden('AUTH_PASSWORD_VALIDATORS'))
     self.assertEquals(list, type(settings.AUTH_PASSWORD_VALIDATORS))
     self.assertEquals(validators, settings.AUTH_PASSWORD_VALIDATORS) 
コード例 #5
0
 def test_19_templates(self):
     templates = [{'APP_DIRS': True,
                   'BACKEND': 'django.template.backends.django.DjangoTemplates',
                   'DIRS': ['/Users/tim/Documents/workspace/python/django-review/legacy/legacy/templates'],
                   'OPTIONS': {'context_processors': ['django.template.context_processors.debug',
                                                      'django.template.context_processors.request',
                                                      'django.contrib.auth.context_processors.auth',
                                                      'django.contrib.messages.context_processors.messages']}}]
     self.assertTrue(settings.is_overridden('TEMPLATES'))
     self.assertEquals(list, type(settings.TEMPLATES))
     self.assertListEqual(templates, settings.TEMPLATES) 
コード例 #6
0
 def test_07_installed_apps(self):
     installed_apps = ['django.contrib.admin',
                       'django.contrib.auth',
                       'django.contrib.contenttypes',
                       'django.contrib.sessions',
                       'django.contrib.messages',
                       'django.contrib.staticfiles',
                       'simple']
     self.assertTrue(settings.is_overridden('INSTALLED_APPS'))
     self.assertEquals(list, type(settings.INSTALLED_APPS))
     self.assertListEqual(installed_apps, settings.INSTALLED_APPS) 
コード例 #7
0
 def test_10_middleware(self):
     middleware = ['django.middleware.security.SecurityMiddleware',
                   'django.contrib.sessions.middleware.SessionMiddleware',
                   'django.middleware.common.CommonMiddleware',
                   'django.middleware.csrf.CsrfViewMiddleware',
                   'django.contrib.auth.middleware.AuthenticationMiddleware',
                   'django.contrib.messages.middleware.MessageMiddleware',
                   'django.middleware.clickjacking.XFrameOptionsMiddleware']
     self.assertTrue(settings.is_overridden('MIDDLEWARE'))
     self.assertEquals(list, type(settings.MIDDLEWARE))
     self.assertListEqual(middleware, settings.MIDDLEWARE) 
コード例 #8
0
 def test_11_nose_args(self):
     nose_args = ['--verbosity=2',
                  '--with-coverage',
                  '--cover-package=legacy,simple',
                  '--cover-erase',
                  '--cover-branches',
                  '--cover-html',
                  '--cover-html-dir=results',
                  '--cover-min-percentage=80']
     self.assertTrue(settings.is_overridden('NOSE_ARGS'))
     self.assertEquals(list, type(settings.NOSE_ARGS))
     self.assertListEqual(nose_args, settings.NOSE_ARGS) 
コード例 #9
0
    def report_redundant_settings(self):
        # false positives: if powered by env var but the default value that is the same as django default
        self.stdout.write(
            self.style.MIGRATE_LABEL('Looking for redundant settings'))

        settings_dict = module_to_dict(settings)
        default_settings = module_to_dict(global_settings)

        warnings = []
        for key, value in settings_dict.items():
            if key in default_settings and settings.is_overridden(key):
                if value == default_settings[key]:
                    warnings.append(key)
        return warnings
コード例 #10
0
 def __init__(self, params):
     params = params.copy()
     options = params.pop('OPTIONS').copy()
     options.setdefault('autoescape', True)
     options.setdefault('debug', settings.DEBUG)
     options.setdefault(
         'file_charset',
         settings.FILE_CHARSET
         if settings.is_overridden('FILE_CHARSET') else 'utf-8',
     )
     libraries = options.get('libraries', {})
     options['libraries'] = self.get_templatetag_libraries(libraries)
     super().__init__(params)
     self.engine = Engine(self.dirs, self.app_dirs, **options)
コード例 #11
0
 def test_04_databases(self):
     databases = {'default': {'ATOMIC_REQUESTS': False,
                              'AUTOCOMMIT': True,
                              'CONN_MAX_AGE': 0,
                              'ENGINE': 'django.db.backends.sqlite3',
                              'HOST': '',
                              'NAME': ':memory:',
                              'OPTIONS': {},
                              'PASSWORD': '',
                              'PORT': '',
                              'TEST': {'CHARSET': None,
                              'COLLATION': None,
                              'MIRROR': None,
                              'NAME': None},
                              'TIME_ZONE': None,
                              'USER': ''}}
     self.assertTrue(settings.is_overridden('DATABASES'))
     self.assertEquals(dict, type(settings.DATABASES))
     self.assertDictEqual(databases, settings.DATABASES)
コード例 #12
0
ファイル: django_1_7_0.py プロジェクト: 1oscar/django
def _check_middleware_classes(app_configs=None, **kwargs):
    """
    Checks if the user has *not* overridden the ``MIDDLEWARE_CLASSES`` setting &
    warns them about the global default changes.
    """
    from django.conf import settings

    # MIDDLEWARE_CLASSES is overridden by default by startproject. If users
    # have removed this override then we'll warn them about the default changes.
    if not settings.is_overridden('MIDDLEWARE_CLASSES'):
        return [
            Warning(
                "MIDDLEWARE_CLASSES is not set.",
                hint=("Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. "
                      "django.contrib.sessions.middleware.SessionMiddleware, "
                      "django.contrib.auth.middleware.AuthenticationMiddleware, and "
                      "django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. "
                      "If your project needs these middleware then you should configure this setting."),
                obj=None,
                id='1_7.W001',
            )
        ]
    else:
        return []
コード例 #13
0
def get_first_party_app_labels():
    if not settings.is_overridden("FIRST_PARTY_APPS"):
        return None
    return {AppConfig.create(name).label for name in settings.FIRST_PARTY_APPS}
コード例 #14
0
 def test_20_test_runner(self):
     self.assertTrue(settings.is_overridden('TEST_RUNNER'))
     self.assertEquals(str, type(settings.TEST_RUNNER))
     self.assertEquals('django_nose.NoseTestSuiteRunner', settings.TEST_RUNNER) 
コード例 #15
0
def check_middleware(app_configs, **kwargs):
    from debug_toolbar.middleware import DebugToolbarMiddleware

    errors = []
    gzip_index = None
    debug_toolbar_indexes = []

    if all(not check_template_config(config) for config in settings.TEMPLATES):
        errors.append(
            Warning(
                "At least one DjangoTemplates TEMPLATES configuration needs "
                "to use django.template.loaders.app_directories.Loader or "
                "have APP_DIRS set to True.",
                hint=("Include django.template.loaders.app_directories.Loader "
                      'in ["OPTIONS"]["loaders"]. Alternatively use '
                      "APP_DIRS=True for at least one "
                      "django.template.backends.django.DjangoTemplates "
                      "backend configuration."),
                id="debug_toolbar.W006",
            ))

    # If old style MIDDLEWARE_CLASSES is being used, report an error.
    if settings.is_overridden("MIDDLEWARE_CLASSES"):
        errors.append(
            Warning(
                "debug_toolbar is incompatible with MIDDLEWARE_CLASSES setting.",
                hint="Use MIDDLEWARE instead of MIDDLEWARE_CLASSES",
                id="debug_toolbar.W004",
            ))
        return errors

    # Determine the indexes which gzip and/or the toolbar are installed at
    for i, middleware in enumerate(settings.MIDDLEWARE):
        if is_middleware_class(GZipMiddleware, middleware):
            gzip_index = i
        elif is_middleware_class(DebugToolbarMiddleware, middleware):
            debug_toolbar_indexes.append(i)

    if not debug_toolbar_indexes:
        # If the toolbar does not appear, report an error.
        errors.append(
            Warning(
                "debug_toolbar.middleware.DebugToolbarMiddleware is missing "
                "from MIDDLEWARE.",
                hint="Add debug_toolbar.middleware.DebugToolbarMiddleware to "
                "MIDDLEWARE.",
                id="debug_toolbar.W001",
            ))
    elif len(debug_toolbar_indexes) != 1:
        # If the toolbar appears multiple times, report an error.
        errors.append(
            Warning(
                "debug_toolbar.middleware.DebugToolbarMiddleware occurs "
                "multiple times in MIDDLEWARE.",
                hint="Load debug_toolbar.middleware.DebugToolbarMiddleware only "
                "once in MIDDLEWARE.",
                id="debug_toolbar.W002",
            ))
    elif gzip_index is not None and debug_toolbar_indexes[0] < gzip_index:
        # If the toolbar appears before the gzip index, report an error.
        errors.append(
            Warning(
                "debug_toolbar.middleware.DebugToolbarMiddleware occurs before "
                "django.middleware.gzip.GZipMiddleware in MIDDLEWARE.",
                hint="Move debug_toolbar.middleware.DebugToolbarMiddleware to "
                "after django.middleware.gzip.GZipMiddleware in MIDDLEWARE.",
                id="debug_toolbar.W003",
            ))
    return errors
コード例 #16
0
 def test_21_time_zone(self):
     self.assertTrue(settings.is_overridden('TIME_ZONE'))
     self.assertEquals(str, type(settings.TIME_ZONE))
     self.assertEquals('UTC', settings.TIME_ZONE) 
コード例 #17
0
 def test_24_wsgi_application(self):
     self.assertTrue(settings.is_overridden('WSGI_APPLICATION'))
     self.assertEquals(str, type(settings.WSGI_APPLICATION))
     self.assertEquals('legacy.wsgi.application', settings.WSGI_APPLICATION) 
コード例 #18
0
 def test_24_use_tz(self):
     self.assertTrue(settings.is_overridden('USE_TZ'))
     self.assertEquals(bool, type(settings.USE_TZ))
     self.assertTrue(settings.USE_TZ) 
コード例 #19
0
 def test_03_base_dir(self):
     self.assertTrue(settings.is_overridden('BASE_DIR'))
     self.assertEquals(str, type(settings.BASE_DIR))
     self.assertEquals('/Users/tim/Documents/workspace/python/django-review/legacy/legacy', settings.BASE_DIR) 
コード例 #20
0
def set_read_only():
    global read_only
    if settings.is_overridden("DJANGO_READ_ONLY"):
        read_only = settings.DJANGO_READ_ONLY
    else:
        read_only = bool(os.environ.get("DJANGO_READ_ONLY", ""))
コード例 #21
0
ファイル: tests.py プロジェクト: 6ft/django
 def test_override(self):
     self.assertFalse(settings.is_overridden('TEMPLATE_LOADERS'))
     with override_settings(TEMPLATE_LOADERS=[]):
         self.assertTrue(settings.is_overridden('TEMPLATE_LOADERS'))
コード例 #22
0
 def test_override(self):
     self.assertFalse(settings.is_overridden('TEMPLATE_LOADERS'))
     with override_settings(TEMPLATE_LOADERS=[]):
         self.assertTrue(settings.is_overridden('TEMPLATE_LOADERS'))
コード例 #23
0
 def test_06_fixture_dirs(self):
     self.assertTrue(settings.is_overridden('FIXTURE_DIRS'))
     self.assertEquals(tuple, type(settings.FIXTURE_DIRS))
     self.assertTupleEqual(('/Users/tim/Documents/workspace/python/django-review/legacy/legacy/fixtures',), settings.FIXTURE_DIRS) 
コード例 #24
0
 def test_05_debug(self):
     self.assertTrue(settings.is_overridden('DEBUG'))
     self.assertEquals(bool, type(settings.DEBUG))
     self.assertFalse(settings.DEBUG) 
コード例 #25
0
 def test_22_use_i18n(self):
     self.assertTrue(settings.is_overridden('USE_I18N'))
     self.assertEquals(bool, type(settings.USE_I18N))
     self.assertTrue(settings.USE_I18N) 
コード例 #26
0
 def test_18_static_url(self):
     self.assertTrue(settings.is_overridden('STATIC_URL'))
     self.assertEquals(str, type(settings.STATIC_URL))
     self.assertEquals('/static/', settings.STATIC_URL) 
コード例 #27
0
ファイル: django_1_6_0.py プロジェクト: 2roy999/django
def _check_test_runner(app_configs=None, **kwargs):
    """
    Checks if the user has *not* overridden the ``TEST_RUNNER`` setting &
    warns them about the default behavior changes.

    If the user has overridden that setting, we presume they know what they're
    doing & avoid generating a message.
    """
    from django.conf import settings

    # We need to establish if this is a project defined on the 1.5 project template,
    # because if the project was generated on the 1.6 template, it will have be been
    # developed with the new TEST_RUNNER behavior in mind.

    # There's no canonical way to do this; so we leverage off the fact that 1.6
    # also introduced a new project template, removing a bunch of settings from the
    # default that won't be in common usage.

    # We make this determination on a balance of probabilities. Each of these factors
    # contributes a weight; if enough of them trigger, we've got a likely 1.6 project.
    weight = 0

    # If TEST_RUNNER is explicitly set, it's all a moot point - if it's been explicitly set,
    # the user has opted into a specific set of behaviors, which won't change as the
    # default changes.
    if not settings.is_overridden('TEST_RUNNER'):
        # Strong markers:
        # SITE_ID = 1 is in 1.5 template, not defined in 1.6 template
        try:
            settings.SITE_ID
            weight += 2
        except AttributeError:
            pass

        # BASE_DIR is not defined in 1.5 template, set in 1.6 template
        try:
            settings.BASE_DIR
        except AttributeError:
            weight += 2

        # TEMPLATE_LOADERS defined in 1.5 template, not defined in 1.6 template
        if settings.is_overridden('TEMPLATE_LOADERS'):
            weight += 2

        # MANAGERS defined in 1.5 template, not defined in 1.6 template
        if settings.is_overridden('MANAGERS'):
            weight += 2

        # Weaker markers - These are more likely to have been added in common usage
        # ADMINS defined in 1.5 template, not defined in 1.6 template
        if settings.is_overridden('ADMINS'):
            weight += 1

        # Clickjacking enabled by default in 1.6
        if 'django.middleware.clickjacking.XFrameOptionsMiddleware' not in set(settings.MIDDLEWARE_CLASSES):
            weight += 1

    if weight >= 6:
        return [
            Warning(
                "Some project unittests may not execute as expected.",
                hint=("Django 1.6 introduced a new default test runner. It looks like "
                      "this project was generated using Django 1.5 or earlier. You should "
                      "ensure your tests are all running & behaving as expected. See "
                      "https://docs.djangoproject.com/en/dev/releases/1.6/#new-test-runner "
                      "for more information."),
                obj=None,
                id='1_6.W001',
            )
        ]
    else:
        return []
コード例 #28
0
 def test_23_use_l10n(self):
     self.assertTrue(settings.is_overridden('USE_L10N'))
     self.assertEquals(bool, type(settings.USE_L10N))
     self.assertTrue(settings.USE_L10N) 
コード例 #29
0
def _check_test_runner(app_configs=None, **kwargs):
    """
    Checks if the user has *not* overridden the ``TEST_RUNNER`` setting &
    warns them about the default behavior changes.

    If the user has overridden that setting, we presume they know what they're
    doing & avoid generating a message.
    """
    from django.conf import settings

    # We need to establish if this is a project defined on the 1.5 project template,
    # because if the project was generated on the 1.6 template, it will have be been
    # developed with the new TEST_RUNNER behavior in mind.

    # There's no canonical way to do this; so we leverage off the fact that 1.6
    # also introduced a new project template, removing a bunch of settings from the
    # default that won't be in common usage.

    # We make this determination on a balance of probabilities. Each of these factors
    # contributes a weight; if enough of them trigger, we've got a likely 1.6 project.
    weight = 0

    # If TEST_RUNNER is explicitly set, it's all a moot point - if it's been explicitly set,
    # the user has opted into a specific set of behaviors, which won't change as the
    # default changes.
    if not settings.is_overridden('TEST_RUNNER'):
        # Strong markers:
        # SITE_ID = 1 is in 1.5 template, not defined in 1.6 template
        try:
            settings.SITE_ID
            weight += 2
        except AttributeError:
            pass

        # BASE_DIR is not defined in 1.5 template, set in 1.6 template
        try:
            settings.BASE_DIR
        except AttributeError:
            weight += 2

        # TEMPLATE_LOADERS defined in 1.5 template, not defined in 1.6 template
        if settings.is_overridden('TEMPLATE_LOADERS'):
            weight += 2

        # MANAGERS defined in 1.5 template, not defined in 1.6 template
        if settings.is_overridden('MANAGERS'):
            weight += 2

        # Weaker markers - These are more likely to have been added in common usage
        # ADMINS defined in 1.5 template, not defined in 1.6 template
        if settings.is_overridden('ADMINS'):
            weight += 1

        # Clickjacking enabled by default in 1.6
        if 'django.middleware.clickjacking.XFrameOptionsMiddleware' not in set(
                settings.MIDDLEWARE_CLASSES):
            weight += 1

    if weight >= 6:
        return [
            Warning(
                "Some project unittests may not execute as expected.",
                hint=
                ("Django 1.6 introduced a new default test runner. It looks like "
                 "this project was generated using Django 1.5 or earlier. You should "
                 "ensure your tests are all running & behaving as expected. See "
                 "https://docs.djangoproject.com/en/dev/releases/1.6/#discovery-of-tests-in-any-test-module "
                 "for more information."),
                obj=None,
                id='1_6.W001',
            )
        ]
    else:
        return []
コード例 #30
0
 def test_08_language_code(self):
     self.assertTrue(settings.is_overridden('LANGUAGE_CODE'))
     self.assertEquals(str, type(settings.LANGUAGE_CODE))
     self.assertEquals('en-us', settings.LANGUAGE_CODE) 
コード例 #31
0
ファイル: tests.py プロジェクト: ricardoffv/django-pizza
 def test_override(self):
     self.assertFalse(settings.is_overridden('ALLOWED_HOSTS'))
     with override_settings(ALLOWED_HOSTS=[]):
         self.assertTrue(settings.is_overridden('ALLOWED_HOSTS'))
コード例 #32
0
 def test_09_login_url(self):
     self.assertTrue(settings.is_overridden('LOGIN_URL'))
     self.assertEquals(str, type(settings.LOGIN_URL))
     self.assertEquals('/login/', settings.LOGIN_URL) 
コード例 #33
0
ファイル: tests.py プロジェクト: guyi2020/blog
 def test_override(self):
     self.assertFalse(settings.is_overridden('ALLOWED_HOSTS'))
     with override_settings(ALLOWED_HOSTS=[]):
         self.assertTrue(settings.is_overridden('ALLOWED_HOSTS'))
コード例 #34
0
 def test_17_static_root(self):
     self.assertTrue(settings.is_overridden('STATIC_ROOT'))
     self.assertEquals(str, type(settings.STATIC_ROOT))
     self.assertEquals('/Users/tim/Documents/workspace/python/django-review/legacy/legacy/staticfiles', settings.STATIC_ROOT)