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

时间:2014-07-06 20:45:00

标签: python django testing

我尝试将Django代码从milkman迁移到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.']}

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

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创建工厂,以便所有字段都自动填充合法值?

1 个答案:

答案 0 :(得分:1)