Search code examples
djangodjango-rest-frameworkdjango-testsdjango-unittest

Django - how to write test for DRF ImageField


I have the following serializer:

from rest_framework.serializers import Serializer, ImageField

class MySerializer(Serializer):
    avatar = ImageField()

how can I write a unit test for it? I used the Django TestCase, but it raises an error.

from django.test import TestCase

class MySerializerTest(TestCase):

    def setUp(self):
        self.data = {}
        ...

    def test_image(self):
        import tempfile
        self.data['avatar'] = tempfile.NamedTemporaryFile(suffix=".jpg").file
        r_data = json.dumps(self.data)
        j_data = json.loads(r_data)
        serializer = MySerializer(data=j_data)
        if not serializer.is_valid():
            import pprint
            pprint.pprint(serializer.errors)
        self.assertEqual(serializer.is_valid(), True)

but it raises the following error:

TypeError: Object of type 'BufferedRandom' is not JSON serializable

What's my mistake? how can I write a test for image field?


Solution

  • I suggest to use SimpleUploadedFile class from django and create and image using Pillow package. See the example below.

    from PIL import Image
    
    from django.core.files.uploadedfile import SimpleUploadedFile
    from django.test import TestCase
    from django.utils.six import BytesIO
    
    
    class MySerializerTest(TestCase):
        ...
    
        def test_image(self):
            image = BytesIO()
            Image.new('RGB', (100, 100)).save(image, 'JPEG')
            image.seek(0)
    
            self.data['avatar'] = SimpleUploadedFile('image.jpg', image.getvalue())
            serializer = MySerializer(data=self.data)
            self.assertEqual(serializer.is_valid(), True)