Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

tests.py

class PhotoTestCase(TestCase):      def test_add_photo(self):         newPhoto = Photo()         newPhoto.image = # ??????         newPhoto.save()         self.assertEqual(Photo.objects.count(), 1) 
like image 809
Fabrizio A Avatar asked Oct 10 '14 11:10

Fabrizio A


2 Answers

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') 
like image 166
Fabrizio A Avatar answered Sep 28 '22 03:09

Fabrizio A


You can use a temporary file, using tempfile. So you don't need a real file to do your tests.

import tempfile  image = tempfile.NamedTemporaryFile(suffix=".jpg").name 

If you prefer to do manual clean-up, use tempfile.mkstemp() instead.

like image 45
Purpleweb.fr Avatar answered Sep 28 '22 01:09

Purpleweb.fr