python - 如何创建一个自动生成所有字段的 factory_boy 工厂?

标签 python django testing

我正在尝试从 milkman 迁移 Django 代码至 factory_boy .

假设我有一个模型:

class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    number = models.IntegerField()

我写了一个工厂:

import factory

class BlogPostFactory(factory.Factory):
    class Meta:
        model = BlogPost

但是,factory_boy 默认为这些字段生成无效值:

In [17]: bp = BlogPostFactory.build()

In [18]: print "title: %r content: %r number: %r" % (bp.title, bp.content, bp.number)
title: u'' content: u'' number: None

In [19]: bp.full_clean()
ValidationError: {'content': [u'This field cannot be blank.'], 'number': [u'This field cannot be null.'], 'title': [u'This field cannot be blank.']}

但是,milkman 可以自动为这些字段生成值:

In [22]: bp = milkman.deliver(BlogPost)

In [23]: print "title: %r content: %r number: %r" % (bp.title, bp.content, bp.number)
title: 'A8pLAni9xSTY93QJzSi5yY8SGQikL7YGrcTZVViAFS72eqG2bLWHSh0lNLSA2FbH7kSCXDktCQxUO288HTXdYUcRNUikoH4LQ4QHmy6XRwrRzbbmwXL6pLW7tapJM3FTpx8oBbTUw7nCOZew73xjWsID666FKh05ychptiF2peEZHdQd6gnHqXtFkL5kyEIhFvinOCmS' content: 'RUcSHCxs' number: -709949545

我知道 factory_boy 提供了 fuzzy attributes , 但你必须明确使用它们或 use tons of model/field reflection .

是否可以使用 factory_boy 创建一个工厂,以便所有字段都自动填充合法值?

最佳答案

关于python - 如何创建一个自动生成所有字段的 factory_boy 工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24600170/

相关文章:

testing - 如何使用 jmeter 在 websocket 采样器中配置 csv 数据集?

Python - 值错误 : need more than 1 value to unpack

django - 无法在活塞中排除用户的外键字段

python - 类型错误 : this constructor takes no arguments in django

javascript - Puppeteer 仅用于 chrome 浏览器吗?

python - 如何使用多线程在Python中运行多个函数?

python - 数据帧中的多个计数和中值

python - 在Python中通过装饰器生成异常类

python - 没有替换概率的抽样

node.js - 无法使用 sinon 和 proxyquire 模拟构造函数