Django testing model with ImageField Django testing model with ImageField django django

Django testing model with 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 SimpleUploadedFilenewPhoto.image = SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg')


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

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

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


Tell the mock library to create a mock object based on Django's File class

import mockfrom django.core.files import Filefile_mock = mock.MagicMock(spec=File, name='FileMock')

and then use in your tests

newPhoto.image = file_mock