使用ImageField的Django测试模型 [英] Django testing model with ImageField

查看:190
本文介绍了使用ImageField的Django测试模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试我的Django应用程序的照片模型。如何使用测试图像文件模拟ImageField?

I need to test the Photo model of my Django application. How can I mock the ImageField with a test image file?

tests.py

class PhotoTestCase(TestCase):

    def test_add_photo(self):
        newPhoto = Photo()
        newPhoto.image = # ??????
        newPhoto.save()
        self.assertEqual(Photo.objects.count(), 1)


推荐答案

对于未来的用户,我已经解决了这个问题。
您可以使用SimpleUploadedFile实例来模拟ImageField。

For future users, I've solved the problem. You can mock an ImageField with a SimpleUploadedFile instance.

test.py

from django.core.files.uploadedfile import SimpleUploadedFile

newPhoto.image = SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg')

这篇关于使用ImageField的Django测试模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆