Search code examples
pythondjangodjango-imagekit

How do I test a Django model with ImageSpecField?


I got a following model:

class Room(models.Model):
    order = models.SmallIntegerField()
    name = models.CharField(max_length=20)
    background = models.ImageField(upload_to='room_background', blank=False, null=False)
    background_preview = ImageSpecField(source='background', processors=[ResizeToFit(300, 400)])

    def serialize(self):
        room_dict = model_to_dict(self)
        room_dict['background_preview_url'] = self.background_preview.url
        return room_dict

I'm not using room object directly on my views, instead I convert them to dict, extending with the 'background_preview_url' key.

Now I want to write some Django tests, using serialized room objects. The issue is that if I just do:

test_room = Room(order=1)
test_room.save
test_room.serialize()

The ImageKit throws a MissingSource error, as there's no background image in my test room to generate preview from.

How do I better overcome that in my tests? Should I carry a fixture with the backgroud images? Or should I write second serialize_for_test() method? Or maybe I can instanciate the Room() with some test value for the background_preview field? - I tried this but the direct Room(background_preview='fake_url') didn't work.

Thanks.


Solution

  • The solution, which worked for me:

    from django.core.files.uploadedfile import SimpleUploadedFile
    
    test_room.image = SimpleUploadedFile(name='foo.gif', content=b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00')
    test_room.save