Django testing model with ImageField

后端 未结 8 1644
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 16:52

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         


        
8条回答
  •  再見小時候
    2020-12-07 16:59

    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())
    

提交回复
热议问题