Wednesday, 8 September 2021

Easy Thumbnails - How to test a view that contains with ThumbnailerImageField in DRF

I have a model called "Post" that looks for example like this:

# models.py

from django.db import models
from easy_thumbnails.fields import ThumbnailerImageField

class Post(models.Model):
    name = models.CharField(max_length=255)
    cover = ThumbnailerImageField(upload_to='posts')

Then I have a serializer for the model:

# serializers.py

class PostSerializer(serializers.ModelSerializer):
    cover = ThumbnailSerializer(alias='small')

    class Meta:
        model = Post
        fields = ['id', 'name', 'cover']

Using the Thumbnail serializer:

from rest_framework import serializers from easy_thumbnails.templatetags.thumbnail import thumbnail_url

class ThumbnailSerializer(serializers.ImageField):
    """ Serializer for thumbnail creation using easy-thumbnails (Needed when using Django Rest Framework) """
    def __init__(self, alias, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.read_only = True
        self.alias = alias

    def to_representation(self, value):
        if not value:
            return None

        url = thumbnail_url(value, self.alias)
        request = self.context.get('request', None)
        if request is not None:
            return request.build_absolute_uri(url)

        return url

Finally I have a view:

# views.py

class PostView(generics.RetrieveAPIView):
    queryset = Post.objects.filter(enabled=True)
    serializer_class = PostSerializer

Now inside my test I try creating a post and fetching the data (im using PyTest):

# tests.py

def test_post_endpoint(client):
      post = Post.objects.create(
          name="Post 1",
          cover="posts/test_image.jpg",
      )

      response = client.get('/posts/')
      assert response.status_code == 200
      
      print(response.data['cover'])  
      # This prints:  http://testserver/posts/
      # Instead of:  http://testserver/posts/test_image.small.jpg

I also tried using:

cover=SimpleUploadedFile(
    name='test_image.jpg', 
    content=open(image_path, 'rb').read(), 
    content_type='image/jpeg'
)

But this ended up uploading the image to S3 which I dont want since its just a test and it should not upload anything to the cloud.

How can I get a proper response for the cover data? Something like this:

'http://testserver/posts/test_image.small.jpg'


from Easy Thumbnails - How to test a view that contains with ThumbnailerImageField in DRF

No comments:

Post a Comment