如何用必要的数据预填充测试数据库? [英] How to prepopulate test database by necessary data?
问题描述
我需要在Django项目中进行一些单元测试
.问题在于,几乎每个用例都依赖于预填充的数据库对象.
I need to do some unit tests
in my Django project. The problem is that almost every use case depends on prepopulated database objects.
例如,如果所有 pre_save
信号均成功,我想创建一个产品并进行测试.
For example, I want to create a product and test, if there were all pre_save
signals successful.
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
对象.生产数据库中有多个计划,默认情况下是其中的一个,但是测试数据库中没有计划.
I can't do that because product has to have User
object related. But I can't create a User
object because User
has to have related plan
object. There are multiple plans in my production database from which one is default but there are no plans inside test database.
为了能够进行单元测试,我需要使用来自多个应用程序的多个对象来预填充测试数据库.
So to be able to do unit tests I need to prepopulate test database with multiple objects from multiple apps.
我该怎么做?
推荐答案
您可以简单地使用django装置:-)
you can simply use django fixtures for that :-)
首先用数据填充示例数据库,然后使用 python manage.py导出数据dumpdata
first populate a sample db with data then export data with python manage.py dumpdata
然后在您的一个应用程序中创建一个名为 fixtures
的目录,并将导出的json文件放在其中(名为 tests.json
或其他名称)
then in one of your apps create a directory named fixtures
and put exported json file there (named tests.json
or something else)
在这样的测试类负载夹具中
in your test class load fixtures like this
class ProductTestCase(TestCase):
fixtures = ['tests.json', ]
结帐Django 文档
PS:结帐工厂的男孩也(@Gabriel Muj)回答
PS: checkout factory boy too (@Gabriel Muj) answer
这篇关于如何用必要的数据预填充测试数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!