gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:30:25 25 4
gpt4 key购买 nike

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

例如,我想创建一个产品并测试,如果所有 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 ProductTestCase(TestCase):
fixtures = ['tests.json', ]

结帐 django docs

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

关于django - 如何通过必要的数据预填充测试数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com