Wilfred Hughes
Wilfred Hughes

Reputation: 31171

How do I create a factory_boy Factory that generates all fields automatically?

I'm trying to migrate Django code from milkman to factory_boy.

Suppose I have a model:

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

I write a factory:

import factory

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

However, factory_boy generates invalid values for these fields by default:

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.']}

However, milkman can generate values for these fields automatically:

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

I know that factory_boy provides fuzzy attributes, but you have to explicitly use them or use tons of model/field reflection.

Is it possible to create a Factory with factory_boy such that all fields are automatically populated with legal values?

Upvotes: 2

Views: 1253

Answers (1)

Lara
Lara

Reputation: 2236

You can use the Extra Fields:

http://factoryboy.readthedocs.org/en/latest/orms.html#extra-fields

Upvotes: 1

Related Questions