为什么 django TestCase 不创建测试数据库?

时间:2021-03-30 11:03:15

标签: django django-testing django-database

我正在编写一个继承自 django.test.TestCase 的 Django 测试。到处,在文档中,this tutorial 甚至在这个被接受的 SO accepted answer 中都声明在使用 Django TestCase 时,将自动创建一个测试数据库。 以前我曾与 DRF APITestCases 一起工作,并且一切顺利。这里我使用的是非常标准的方法,但 setUpTestData 类方法使用的是我的生产数据库。

我做错了什么,必须做什么才能生成测试数据库并用于测试? 请看下面我的代码。

from django.test import TestCase
from agregator.models import AgregatorProduct
from django.db.models import signals

def sample_product_one():
    sample_product_one = {
        # "id": 1,
        "name": "testProdOne",
        "dph": 21,
        "updated": datetime.now(),
        "active": True,
        "updatedinstore": False,
        "imagechanged": False,
        "isVirtualProduct": False,
        }
    return sample_product_one


class TestCreateProdToCategory(TestCase):
    """
    Test for correct creation of records
    """

    @classmethod
    @factory.django.mute_signals(signals.pre_save, signals.post_save)
    def setUpTestData(cls):
        AgregatorProduct.objects.create(
            **sample_product_one()
        )


    def test_create_prod_to_cat(self):
        product = AgregatorProduct.objects.get(id=1)
        self.assertEqual(product.id, 1)

数据库设置:

DATABASES = {
    'agregator': {
        'NAME': 'name',
        'ENGINE': 'sql_server.pyodbc',
        'HOST': 'my_ip',
        'USER': 'my_user',
        'PASSWORD': 'my_pwd',
        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',
            'isolation_level': 'READ UNCOMMITTED',
        },
    }
}

测试结果

----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\xevos\xevosadmin\agregator\tests\test_admin_actions\test_products_to_categories_admin_action.py", line 64, in test_create_prod_to_cat
    product = AgregatorProduct.objects.get(id=1)
  File "C:\xevos\xevosadmin\.venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\xevos\xevosadmin\.venv\lib\site-packages\django\db\models\query.py", line 397, in get
    raise self.model.DoesNotExist(
agregator.models.AgregatorProduct.DoesNotExist: AgregatorProduct matching query does not exist.

----------------------------------------------------------------------

这是 id 自动递增的结果,并且鉴于生产数据库中已经有产品,它的 id 为例如 151545 (AgregatorProduct matching query does not exist. 是由于很久以前在生产数据库中删除了曾经具有 id=1 的产品这一事实。)

因此测试会写入现有数据库,并且即使在测试完成后数据也会保留在那里。

1 个答案:

答案 0 :(得分:0)

要创建测试数据库,请使用 TestCase 中的 setUp 方法并使用 python manage.py test

运行它
from django.test import TestCase
from myapp.models import Animal

class AnimalTestCase(TestCase):
    def setUp(self):
        Animal.objects.create(name="lion", sound="roar")
        Animal.objects.create(name="cat", sound="meow")

    def test_animals_can_speak(self):
        """Animals that can speak are correctly identified"""
        lion = Animal.objects.get(name="lion")
        cat = Animal.objects.get(name="cat")
        self.assertEqual(lion.speak(), 'The lion says "roar"')
        self.assertEqual(cat.speak(), 'The cat says "meow"')

测试完成后会自动创建和删除数据库 https://docs.djangoproject.com/en/3.1/topics/testing/overview/#writing-tests