【问题标题】:Django ignores test database settingsDjango 忽略测试数据库设置
【发布时间】:2018-07-07 21:49:44
【问题描述】:

我在 pythonanywhere 上部署了一个运行良好的应用程序。问题是当我想运行测试 django 时,我的测试数据库设置被完全忽略了。 每次我运行测试时,我都会收到以下消息。

Creating test database for alias 'default'...                                                                                       
Got an error creating the test database: (1044, "Access denied for user 'funnshopp'@'%' to database 'test_funnshopp$funn'")

应用程序的数据库名称是 funnshopp$funn。可以看出,django 总是试图通过在数据库名称后附加test_ 来尝试创建测试数据库。别管我在DATABASES 设置里有什么

以下是我的完整设置文件(测试在我的 PC 上运行良好,我使用的是 Django 2.0,尽管我使用 Django 1.11 启动了项目)

"""
Django settings for funnshopp project.

Generated by 'django-admin startproject' using Django 1.11.7.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os
from django.urls import reverse_lazy
from django.core.exceptions import ImproperlyConfigured

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def get_env_variable(var_name):
    """Get the environment variable or return exception"""
    try:
        return os.environ[var_name]
    except KeyError:
        error_msg = "Set the {} environment variable".format(var_name)
        raise ImproperlyConfigured(error_msg)

ENV_ROLE = get_env_variable("ENV_ROLE")

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_env_variable("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
FUNN_PASS = False
if ENV_ROLE == "development":
    DEBUG = True
    FUNN_PASS = get_env_variable('FUNN_PASS')

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'asset',
    'debit',
    'communication',
    'establishment',
    'credit',
    'personnel',
    'relation',
    'debug_toolbar',
    'captcha',
    'guardian',
    'rules',
    'coverage',
    'django_extensions',
    'pure_pagination',
    'sorl.thumbnail',
    'django_addanother',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'guardian.backends.ObjectPermissionBackend',
    'rules.permissions.ObjectPermissionBackend',
)

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
]

ROOT_URLCONF = 'funnshopp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'funnshopp.wsgi.application'

INTERNAL_IPS = ('127.0.0.1', 'localhost')

DEBUG_TOOLBAR_PANELS = [
        'debug_toolbar.panels.versions.VersionsPanel',
        'debug_toolbar.panels.timer.TimerPanel',
        'debug_toolbar.panels.settings.SettingsPanel',
        'debug_toolbar.panels.headers.HeadersPanel',
        'debug_toolbar.panels.request.RequestPanel',
        'debug_toolbar.panels.sql.SQLPanel',
        'debug_toolbar.panels.staticfiles.StaticFilesPanel',
        'debug_toolbar.panels.templates.TemplatesPanel',
        'debug_toolbar.panels.cache.CachePanel',
        'debug_toolbar.panels.signals.SignalsPanel',
        'debug_toolbar.panels.logging.LoggingPanel',
        'debug_toolbar.panels.redirects.RedirectsPanel',
]

GOOGLE_RECAPTCHA_SITE_KEY = get_env_variable("GOOGLE_RECAPTCHA_SITE_KEY")
GOOGLE_RECAPTCHA_SECRET_KEY = get_env_variable("GOOGLE_RECAPTCHA_SECRET_KEY")

LOGIN_REDIRECT_URL = reverse_lazy('personnel:dashboard')
LOGIN_URL = reverse_lazy('personnel:login')
LOGOUT_URL = reverse_lazy('personnel:logout')

if ENV_ROLE == "development":
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
else:
    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '***@gmail.com'
EMAIL_HOST_PASSWORD = '*******'
DEFAULT_FROM_EMAIL = '***@gmail.com'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DEPLOYMENT_PLATFORM = get_env_variable("DEPLOYMENT_PLATFORM")
if DEPLOYMENT_PLATFORM == "heroku-plus-local":
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'funn',
            'USER': 'postgres',
            'PASSWORD': get_env_variable('FUNN_PASS'),
            'HOST': 'localhost',
            'PORT': 5432
        }
    }

else: # DEPLOYMENT_PLATFORM == "pythonanywhere"
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'USER': 'funnshopp',
            'NAME': 'funnshopp$funn',
            'PASSWORD': get_env_variable('FUNN_PASS'),
            'HOST': 'funnshopp.mysql.pythonanywhere-services.com',
            'TEST':{
                'ENGINE': 'django.db.backends.sqlite3', # for sqlite3
                'NAME':'test.db',
                # 'ENGINE': 'django.db.backends.mysql',
                # 'NAME':'funnshopp$test_default'
                },
            },
        }

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Africa/Lagos'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

AUTH_USER_MODEL = 'personnel.Person'

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

import django_heroku
django_heroku.settings(locals())

下面是pip freeze的结果

alabaster==0.7.10                                                                                                                   
Babel==2.5.1                                                                                                                        
beautifulsoup4==4.6.0                                                                                                               
certifi==2017.11.5                                                                                                                  
chardet==3.0.4                                                                                                                      
colorama==0.3.9                                                                                                                     
coverage==4.4.2                                                                                                                     
dj-database-url==0.4.2                                                                                                              
dj-static==0.0.6                                                                                                                    
Django==2.0.1                                                                                                                       
django-addanother==2.0.0                                                                                                            
django-archive==0.1.5                                                                                                               
django-braces==1.12.0                                                                                                               
django-debug-toolbar==1.9.1                                                                                                         
django-extensions==1.9.9                                                                                                            
django-guardian==1.4.9                                                                                                              
django-heroku==0.2.0                                                                                                                
django-pure-pagination==0.3.0                                                                                                       
django-recaptcha==1.3.1                                                                                                             
django-toolbelt==0.0.1                                                                                                              
django-webtest==1.9.2                                                                                                               
docutils==0.14                                                                                                                      
funcsigs==1.0.2                                                                                                                     
gunicorn==19.7.1
idna==2.6

【问题讨论】:

标签: python django


【解决方案1】:

这是一种常见且正确的行为。 Django 在测试时总是会尝试创建新的数据库,你永远不应该尝试在你的实时/生产数据库上测试你的应用程序。

您的测试应该以某种方式构建,您可以在其中创建对象然后测试它们的行为。您正在开发服务器上的 heroku 和 mysql 上使用 postgres。如果你想使用这个数据库来测试你的应用程序,你必须将 django 用户添加到你的 postgres/mysql 中,并有权创建和删除数据库/表。

您也可以通过将此设置添加到您的 settings.py 来避免这种情况(这是我不使用任何其他扩展程序时喜欢做的事情,并且 sqlite3 数据库就足够了。我通过键入 python manage.py test 来运行我的测试

if any([arg in sys.argv for arg in ['jenkins', 'test']]):
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': 'mydatabase',
        }
    }

【讨论】:

  • 没有回答问题
  • 如果你能仔细准备好我的答案,我想你会找到所有需要的答案:)
  • 通常,@mic4ael,有人会提出类似于“我如何最好地使用圣诞布丁来钉钉子”的问题。这个问题的答案可能是“把它烤到变硬”,但更好的答案是“用锤子”。在这种情况下,sebb 以第二种方式回答,因为他是正确的 - 不应针对生产数据库运行测试。
【解决方案2】:

我认为你应该改变你的 settings.py 格式,你不能在里面放 if 条件,而是根据你工作的环境使用不同的设置!

我建议您阅读此tutorial

当您拥有正确的布局时,您可以在不同的设置文件中更改数据库;)!

【讨论】:

  • 感谢这一点。我会阅读教程并实现这样的
  • @Parousia 很高兴能提供帮助,如果有用,请将答案标记为正确;)
【解决方案3】:

我通过根据Recommended Django Project Layout 此处建议的模式重新组织我的设置文件解决了这个问题。

现在我的测试在 pythonanywhere 上运行良好。

顺便说一句,我在这里创建了一个gist,它处理虚拟环境和布局的问题以及如何处理虚拟环境变量。

【讨论】:

    【解决方案4】:

    如您所知,当您运行测试时,Django 会隔离对数据库所做的更改。这就是为什么它试图创建一个被数据库引擎拒绝的数据库。您可以:

    1. 创建一个数据库,授予用户访问权限并使用--keepdb 运行测试

    2. 或授予 DB 用户访问权限以创建数据库。比如:

      ALTER USER username CREATEDB;

    【讨论】:

      猜你喜欢
      • 2017-04-12
      • 2012-12-14
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 2018-07-24
      • 2014-09-03
      相关资源
      最近更新 更多