简体   繁体   中英

Testing an ImageField in DRF

I am using Django Imagekit in models.py:

from imagekit.models import ProcessedImageField    
class AltroUser(models.Model):
        first_name = models.CharField(_('first name'), max_length=30)
        image = ProcessedImageField(upload_to='media/path',
                                    default='user_default.jpg',
                                    processors=[ResizeToFill(640, 640)],
                                    format='JPEG',
                                    options={'quality': 60})

serializers.py:

class UserRegistrationSerializer(Serializer):
    first_name = serializers.CharField()
    image = serializers.ImageField()

I am trying to test the image field. I have tried following methods:

def get_test_image():
    try:
        image = DjangoFile(open(os.path.join(django_settings.MEDIA_ROOT, 'user_default.jpg'),
                                mode='rb'))
        return image
    except (OSError, IOError) as e:
        return None


def get_test_image1():
    file = io.BytesIO()
    image = Image.new('RGBA', size=(100, 100), color=(155, 0, 0))
    image.save(file, 'png')
    file.name = 'test.png'
    file.seek(0)
    return SimpleUploadedFile('abc.jpg', file.read())


def get_test_image2():
    path = os.path.join(django_settings.MEDIA_ROOT, 'user_default.jpg')
    file = File(open(path, 'r+b'))
    return SimpleUploadedFile('abc.jpg', file.read())

I have tried calling the above three methods to set the value of the image key but none of them worked. For get_test_image() , I get a response "The submitted file is empty."

For get_test_image1() and get_test_image2() , I get a response "The submitted file is empty." with an exception before in the data image field '_io.BytesIO' object has no attribute 'encoding' .

I don't understand what am I missing. Please help.

Here's an example of what I'm using to generate test image:

from StringIO import StringIO
from PIL import Image
from django.core.files import File

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM