Django testing model with ImageField

后端 未结 8 1640
爱一瞬间的悲伤
爱一瞬间的悲伤 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 17:18

    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
    
    0 讨论(0)
  • 2020-12-07 17:18

    For someone to try upload-image test with python 3.xx

    I fix little with Maxim Panfilov's excellent answer to make more dummy image with independent name.

    from io import BytesIO
    from PIL import Image
    from django.core.files.base import File
    
    #in your TestCase class:
    class TestClass(TestCase):
        @staticmethod
        def get_image_file(name, ext='png', size=(50, 50), color=(256, 0, 0)):
            file_obj = BytesIO()
            image = Image.new("RGBA", size=size, color=color)
            image.save(file_obj, ext)
            file_obj.seek(0)
            return File(file_obj, name=name)
    
        def test_upload_image(self):
            c= APIClient()
            image1 = self.get_image('image.png')
            image2 = self.get_image('image2.png')
            data = 
                { 
                    "image1": iamge1,
                    "image2": image2,
                }
            response = c.post('/api_address/', data ) 
            self.assertEqual(response.status_code, 201) 
    
    0 讨论(0)
提交回复
热议问题