Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make FactoryBoy's ImageField generate image before save() is called?

Subj.

Right now (Factory Boy ver. 2.4.1.) with this code:

class ImageFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Image

    image = factory.django.ImageField(width=1024, height=768)

image will be None at save time, so if the Image model has save overridden and its operates with the image, it will fail. And thats exactly my case.

So - how to make image generated before save call?

like image 477
Gill Bates Avatar asked Sep 12 '14 10:09

Gill Bates


1 Answers

I've found a workaround:

from django.core.files.base import ContentFile

class ImageFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Image

    image = factory.LazyAttribute(
            lambda _: ContentFile(
                factory.django.ImageField()._make_data(
                    {'width': 1024, 'height': 768}
                ), 'example.jpg'
            )
        )
like image 57
Gill Bates Avatar answered Nov 01 '22 08:11

Gill Bates