SmileyChris / easy-thumbnails

Easy thumbnails for Django
http://easy-thumbnails.readthedocs.org/
BSD 3-Clause "New" or "Revised" License
1.39k stars 319 forks source link

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

Open adrenaline681 opened 3 years ago

adrenaline681 commented 3 years ago

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.