如何使用 ImageSpecField 测试 Django 模型?

How do I test a Django model with ImageSpecField?

我得到了以下模型:

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

我没有直接在我的视图上使用房间对象,而是将它们转换为字典,使用 'background_preview_url' 键扩展。

现在我想使用序列化房间对象编写一些 Django 测试。问题是如果我这样做:

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

ImageKit 会抛出 MissingSource 错误,因为我的测试室中没有可生成预览的背景图像。

我如何在测试中更好地克服它?我应该携带带有背景图像的夹具吗? 或者我应该写第二个 serialize_for_test() 方法吗? 或者我可以用 background_preview 字段的一些测试值实例化 Room() 吗? - 我试过了,但是直接 Room(background_preview='fake_url') 没用。

谢谢。

对我有用的解决方案:

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