Fabrizio A Fabrizio A - 1 year ago 213
Python Question

Django testing model with ImageField

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


class PhotoTestCase(TestCase):

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

Answer Source

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


from django.core.files.uploadedfile import SimpleUploadedFile

newPhoto.image = SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download