Django使用默认db进行单元测试,而不是测试db

时间:2019-10-11 18:05:01

标签: python django

当我运行manage.py test时,django使用的是我的默认数据库,而不是测试数据库。

我误解了文档中的某些内容吗?

根据the docs,默认行为是“为测试创建单独的空白数据库”

我只是为了确保设置“ TEST:NAME”值,但是文档声明只有在我要配置测试数据库名称而不是默认test_{dbname}

时才需要
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql_psycopg2",
        "HOST": "0.0.0.0",
        "NAME": "mydb_db",
        "USER": "postgres",
        "PASSWORD": "postgres",
        "PORT": 5432,
        "TEST": {"NAME": "test_mydb_db"},
    }
}
from unittest import TestCase

class SimpleTest(TestCase):

    def test_get_user_authorized(self):
        client = Client()
        breakpoint()

>>> (Pdb) from django.db import connection
>>> (Pdb) connection.settings_dict['NAME']
'mydb_db'

如果我在单元测试中读取或创建数据,则数据来自mydb_db,而不是我期望的test_mydb_db

附加说明

正在使用docker compose设置数据库,但我认为这不会影响任何事情:

services:
  db:
    container_name: postgres
    image: postgres:9.6
    restart: always
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    ports:
      - "5432:5432"
    environment:
      POSTGRES_DB: mydb_db
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      PGPASSWORD: postgres

1 个答案:

答案 0 :(得分:1)

在这里回答我自己的问题。发布后马上想通了。 看来我错过了文档中的重要内容

SimpleTestCase必须继承自django.test.TestCase而不是unittest.TestCase才能正确创建测试数据库。

将我的代码更改为此即可解决:


from django.test import TestCase

class SimpleTest(TestCase):

def test_get_user_authorized(self):
        client = Client()
        breakpoint()
>>> (Pdb) from django.db import connection
>>> (Pdb) connection.settings_dict['NAME']
'test_mydb_db'

Docs并未明确指出使用unittest不会创建测试数据库,但是如果需要数据库,建议不要使用Django的TestCase:

  

如果测试依赖于数据库访问(例如创建或查询模型),请确保将测试类创建为django.test.TestCase而不是unittest.TestCase的子类。

     

使用unittest.TestCase避免了在事务中运行每个测试并刷新数据库的成本,但是如果您的测试与数据库交互,则其行为将根据测试运行者执行它们的顺序而变化。这可能导致单元测试在单独运行时通过,但在套件中运行时失败。