使用postgresql 9.3运行Django单元测试,这甚至可能吗?

时间:2015-03-18 12:26:55

标签: django postgresql

在sqlite上运行Django 1.7的单元测试是没有道理的。几行配置行,你很高兴。有了Postgres,这几乎是不可能的。

我创建测试数据库,将数据库和Schema的所有者设置为用户测试,将所有数据库授予测试,我们应该好好去吧?但不!

postgres=# create user testing with password '*****';
postgres=# create database project_test;
postgres=# grant all on database project_test to testing;
postgres=# alter database project_test owner to testing;
postgres=# \c project_test;
postgres=# alter schema public owner to testing;

(project) $python manage.py test
Creating test database for alias 'default'...
Got an error creating the test database: permission denied to create database

Type 'yes' if you would like to try deleting the test database 'project_test', or 'no' to cancel: yes
Destroying old test database 'default'...
Got an error recreating the test database: permission denied to create database

postgres=# grant create on tablespace pg_default to testing;

带我回到

Type 'yes' if you would like to try deleting the test database 'project_test', or 'no' to cancel: yes
Destroying old test database 'default'...
Got an error recreating the test database: database "project_test" does not exist

似乎django希望放弃数据库,这使得扳手正在投入使用。

我有一个脚本来擦除数据库并重新创建看起来像这样的结构

set -e
python manage.py dbshell <<EOF
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
EOF

这很好用。我知道最好的做法是测试你在生产中运行的同一个引擎,但我看到所有的测试都在sqlite上进行,这对我来说不起作用,因为我现在正在使用citext列并且想要测试具有该列类型的代码的行为。

我如何达到我可以用postgres测试的地步?

1 个答案:

答案 0 :(得分:1)

我的设置就像你在问题中谈到的那样。

DATABASES = {
'default': {
    #'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'ENGINE': 'django.contrib.gis.db.backends.postgis',
    'NAME': '#####',
    'USER': '#####',
    'PASSWORD': DJANGO_DB_PASSWORD

这在测试中使用了postgres数据库,但是,你需要记住它只使用模式,你不能使用真正的数据库值运行单元测试。

我确实必须在postgres中创建数据库才能使用它。

不确定这是否对您有帮助。