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 []
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
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
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)
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)
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)
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)
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)
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
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)
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)
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 []
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}
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)
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
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)
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)
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)
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)
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", ""))
def test_override(self): self.assertFalse(settings.is_overridden('TEMPLATE_LOADERS')) with override_settings(TEMPLATE_LOADERS=[]): self.assertTrue(settings.is_overridden('TEMPLATE_LOADERS'))
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)
def test_05_debug(self): self.assertTrue(settings.is_overridden('DEBUG')) self.assertEquals(bool, type(settings.DEBUG)) self.assertFalse(settings.DEBUG)
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)
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)
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 []
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)
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 []
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)
def test_override(self): self.assertFalse(settings.is_overridden('ALLOWED_HOSTS')) with override_settings(ALLOWED_HOSTS=[]): self.assertTrue(settings.is_overridden('ALLOWED_HOSTS'))
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)
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)