如何通过必要的数据预填充测试数据库?

How to prepopulate test database by necessary data?

我需要在我的 Django 项目中做一些 unit tests。问题是几乎每个用例都依赖于预先填充的数据库对象。

例如,我想创建一个产品并测试,如果所有 pre_save 信号都成功。

from django.contrib.auth.models import User
from django.test import TestCase

from .models import Product


class ProductTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create(username='test_user')
        self.product = Product.objects.create(name='Test product',user=self.user)


    def test_product_exists(self):
        self.assertIsNotNone(self.product)

    def product_is_active_by_default(self):
        ...

我不能那样做,因为产品必须与 User 对象相关。但是我无法创建 User 对象,因为 User 必须有相关的 plan 对象。我的生产数据库中有多个计划,其中一个是默认计划,但测试数据库中没有计划。

因此,为了能够进行单元测试,我需要使用来自多个应用程序的多个对象预填充测试数据库。

我该怎么做?

你可以简单地使用 django fixtures :-)

首先使用数据填充示例数据库,然后使用 python manage.py dumpdata

导出数据

然后在您的一个应用程序中创建一个名为 fixtures 的目录,并将导出的 json 文件放在那里(名为 tests.json 或其他名称)

在你的测试中class像这样加载装置

class ProductTestCase(TestCase):
    fixtures = ['tests.json', ]

结帐 django docs

PS: 结账工厂男孩 (@Gabriel Muj) 回答

我不建议使用夹具,因为每次更改模型时都需要维护它们。这是使用此库 https://factoryboy.readthedocs.io/en/latest/ 创建测试对象的更好方法,它更灵活。