简体   繁体   English

Django测试的数据库配置

[英]Database config for Django testing

I am building an app using Django and Postgres.我正在使用 Django 和 Postgres 构建一个应用程序。 I managed to do migrations and I want to test it.我设法做了迁移,我想测试它。 When I test with sqlite everything works fine, but when I run tests with postgres I'm getting this error:当我使用 sqlite 进行测试时,一切正常,但是当我使用 postgres 运行测试时,出现此错误:

Creating test database for alias 'default'...
Got an error creating the test database: permission denied to create database

I've checked user's permissions and I'm sure that this user have permission to create database.我检查了用户的权限,我确定该用户有权创建数据库。

My database config looks like this:我的数据库配置如下所示:

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#     }
# }

DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.postgresql_psycopg2',
         'NAME': '***',
         'USER': '***',
         'PASSWORD': '***',
         'HOST': '****',
         'PORT': '****',
     }
 }

My postgres db is on a server.我的 postgres 数据库在服务器上。

My questions are:我的问题是:

  • What is the right way to config my db and run tests?配置数据库和运行测试的正确方法是什么?
  • Should I be using sqlite for testing?我应该使用 sqlite 进行测试吗?
  • If so how my code should look like, so I don't have to comment configs?如果是这样,我的代码应该是什么样子,这样我就不必评论配置了?

It looks like your DB user doesn't have permission to create a new database.看起来您的数据库用户没有创建新数据库的权限。 Please, take a look here .请看这里 This command-line utility allows you to create a user and set their permissions.此命令行实用程序允许您创建用户并设置其权限。

Example:例子:

createuser my_user --createdb -W --username postgres

Note : you are creating user "my_user" on behalf of PostgreSQL admin role which is postgres by default.注意:您正在代表 PostgreSQL 管理员角色创建用户“my_user”,默认情况下是postgres

Answering your questions:回答你的问题:

  1. You may have several configs for different stages, eg development, testing, production.您可能有多个针对不同阶段的配置,例如开发、测试、生产。
  2. You could use both SQLite and Postgres databases for testing purposes to some extent.在某种程度上,您可以同时使用 SQLite 和 Postgres 数据库进行测试。 You should be awarded, though, if your app relies on some specific features available only in Postgres, then using SQLite for testing doesn't make sense.但是,如果您的应用程序依赖于仅在 Postgres 中可用的某些特定功能,那么您应该获得奖励,那么使用 SQLite 进行测试就没有意义。 I personally prefer using the same database for all stages.我个人更喜欢在所有阶段使用相同的数据库。 You could also use docker if you don't want to install DB server on your machine.如果您不想在计算机上安装数据库服务器,也可以使用 docker。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM