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 PhotoT
Solution:
from StringIO import StringIO
# in python 3: from io import StringIO
from PIL import Image
from django.core.files.base import File
And create a static method in your TestCase class:
@staticmethod
def get_image_file(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)):
file_obj = StringIO()
image = Image.new("RGBA", size=size, color=color)
image.save(file_obj, ext)
file_obj.seek(0)
return File(file_obj, name=name)
Example:
instance = YourModel(name=value, image=self.get_image_file())