【问题标题】:How do I test a Django model with ImageSpecField?如何使用 ImageSpecField 测试 Django 模型?
【发布时间】:2015-07-29 11:46:52
【问题描述】:

我有以下型号:

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

我没有直接在我的视图上使用房间对象,而是将它们转换为 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') 不起作用。

谢谢。

【问题讨论】:

    标签: python django django-imagekit


    【解决方案1】:

    对我有用的解决方案:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      相关资源
      最近更新 更多