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

编程入门 行业动态 更新时间:2024-10-27 16:23:58
本文介绍了如何用必要的数据预填充测试数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要在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

更多推荐

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

本文发布于:2023-08-05 20:42:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1307952.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何用   数据库   测试   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!