使用 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)
解决方案
对于未来的用户,我已经解决了问题.您可以模拟 ImageField代码> 带有
SimpleUploadedFile
实例.
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')
相关文章