SmileyChris / easy-thumbnails

Easy thumbnails for Django

Home Page:http://easy-thumbnails.readthedocs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to test Model that contains with ThumbnailerImageField in Django Rest Framework

adrenaline681 opened this issue · comments

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']

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/'

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.