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 SimpleUploadedFile
newPhoto.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 tempfile
image = 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 mock
from django.core.files import File
file_mock = mock.MagicMock(spec=File, name='FileMock')
and then use in your tests
newPhoto.image = file_mock
If you don't want to create an actual file in the filesystem, you can use this 37-byte GIF instead, small enough to a be a bytes literal in your code:
from django.core.files.uploadedfile import SimpleUploadedFile
small_gif = (
b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04'
b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02'
b'\x02\x4c\x01\x00\x3b'
)
uploaded = SimpleUploadedFile('small.gif', small_gif, content_type='image/gif')