Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Example for Django FileField and ImageField values #52
When creating a factory for a model that has a FileField or ImageField, it would be nice to have some helper factories.
My current solution is this:
import StringIO import factory from PIL import Image from django.core.files.uploadedfile import InMemoryUploadedFile from apps.photos.models import Photo def django_image(name, size=200, color='red'): thumb = Image.new('RGB', (size, size,), color) thumb_io = StringIO.StringIO() thumb.save(thumb_io, format='JPEG') thumb_io.seek(0) return InMemoryUploadedFile(thumb_io, None, name, 'image/jpeg', thumb_io.len, None) class PhotoFactory(factory.DjangoModelFactory): FACTORY_FOR = Photo @factory.post_generation def image(self, create, extracted, **kwargs): if extracted: image_name, image = extracted else: image_name = 'image.jpg' image =django_image(image_name, **kwargs) self.image.save(image_name, image)
Indeed, that's a great idea.
I could add a couple of example image files in some module, and extra, django-compatible field declarations along.
What do you think of the following API?
class PhotoFactory(factory.DjangoModelFactory): FACTORY_FOR = Photo image = factory.django.ImageFieldFactory(data=factory.images.JPEG, name='image.jpg')
File saving, at least in Django, is some sort of post generation hook. The nice thing about my current solution, is that it allows passing in
Anyway what you have looks good. Would it function like