首页 > 解决方案 > 受限制环境中的 Django 测试数据库

问题描述

正如标题所说,我在我的开发环境中受到限制。我无法为测试目的创建额外的数据库,只能创建本地文件。

使用environdjango的包,数据库的配置是

DATABASES = {
    'default': env.db('DATABASE_URL', default='postgres://name@localhost'),
}

正如在这个线程中发现的那样,我只需要这个配置中的“TEST”键。它没有每个默认值,所以我通过编写绕过了这个

db = env.db('DATABASE_URL', default='postgres://name@localhost')

db["TEST"] = {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}

然而,这不起作用。python manage.py test给我以下输出:

Creating test database for alias 'default'...
/usr/lib/python2.7/dist-packages/django/db/backends/postgresql/base.py:267: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the default database instead.
  RuntimeWarning
Got an error creating the test database: permission denied to create database

Type 'yes' if you would like to try deleting the test database '/home/<closed environment>/<project>/config/db.sqlite3', or 'no' to cancel: 

它仍然尝试在我无权更改自己权限的环境中创建数据库,这当然失败了。我确实将测试数据库指定为本地文件,但不知何故不使用它?我是在监督什么,还是在做完全错误的事情?

标签: pythondjangopostgresqltesting

解决方案


在玩弄之后,我找到了解决方法。

这不是很好,但它有效:\

is_test = "manage.py" in sys.argv and "test" in sys.argv

if is_test:
    db = {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
else:
    db = env.db('DATABASE_URL', default='postgres://name@localhost')

不是gr8,不可怕。


推荐阅读