我正在尝试使用 Django 应用程序目录 (mysite/polls/tests.py) 中的 tests.py 文件做一个简单的 Django 测试,但每次运行“python manage.py test polls”时,我都会得到错误:
C:\Python27\python.exe "C:\Program Files (x86)\JetBrains\PyCharm 3.0\helpers\pycharm\django_test_manage.py" test polls "C:\Users\<myname>\PycharmProjects\mysite"
Testing started at 8:40 PM ...
Creating test database for alias 'default'...
Type 'yes' if you would like to try deleting the test database 'test_<database>', or 'no' to cancel: Got an error creating the test database: permission denied to create database
根据我的阅读,显然 Heroku PG 使用共享数据库,所以我没有创建/销毁数据库的权限,而这是测试所必需的。对此有明显的解决方案吗?我仍在本地驱动器上进行开发,因此我们将不胜感激。我知道测试是编程的重要组成部分,所以我希望能够尽快实现一种测试方法。
我正在尝试使用 TestCase
django 类进行测试。
我在用什么:
1) Heroku Postgres 爱好开发计划
2) Postgres 9.3.3
3) Python 2.7.6
4) Django 1.6.1
编辑:
因此,在做了更多研究之后,我发现我可以覆盖 settings.py 中的 DATABASES
dict 变量以使用 SQLite 在本地进行测试(当“test”是 shell 中的参数时),但我仍然更喜欢 PostgreSQL 实现,因为根据我的阅读,PostgreSQL 更严格(我是它的粉丝)。
对于任何对我找到的半解决方案感兴趣的人(由 Stackoverflow 的另一位成员提供):
if 'test' in sys.argv:
DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'}
不要忘记导入 sys
。
最佳答案
您没有理由需要为测试创建数据库。相反,如果未定义 DATABASE_URL 环境变量,请将测试更改为访问本地数据库。这是我在 Node.js 中所做的,我在其中拥有本地测试和开发数据库以及 Heroku 提供的生产数据库:
if (typeof(process.env.DATABASE_URL) !== 'undefined') {
dbUrl = url.parse(process.env.DATABASE_URL);
}
else if (process.env.NODE_ENV === 'test') {
dbUrl = url.parse('tcp://postgres:postgres@127.0.0.1:5432/test');
}
else {
dbUrl = url.parse('tcp://postgres:postgres@127.0.0.1:5432/db');
}
关于python - Django 测试错误 "Permission denied to create database"- 使用 Heroku Postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21978562/