【问题标题】:Easy Thumbnails - How to test a view that contains with ThumbnailerImageField in DRFEasy Thumbnails - 如何在 DRF 中测试包含 ThumbnailerImageField 的视图
【发布时间】:2021-09-04 23:11:44
【问题描述】:

我有一个名为“Post”的模型,例如:

# 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')

然后我有一个模型的序列化器:

# serializers.py

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

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

使用缩略图序列化程序:

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

终于有一个看法了:

# views.py

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

现在在我的测试中,我尝试创建一个帖子并获取数据(我使用 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

我也尝试过使用:

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

但这最终将图像上传到了我不想要的 S3,因为它只是一个测试,它不应该将任何东西上传到云端。

我怎样才能得到封面数据的正确响应?像这样的:

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

【问题讨论】:

  • to_representation 内部,url 的结果是什么?
  • to_representation 在测试时返回一个空字符串

标签: python django django-rest-framework easy-thumbnails


【解决方案1】:

您似乎想在 setting.py 中修改 Django 的 MEDIA_ROOTMEDIA_URL 路径以进行测试。这些值可以根据环境变量指定,如下所示:

# in settings.py
import os
...
if os.environ.get("TEST_ENV", '') == 'TRUE':
    MEDIA_URL = 'http://testserver'
    # or something like that
else:
    MEDIA_URL = '<your default url>'

在开始测试之前,应该设置环境变量:

export TEST_ENV=TRUE

this blog post 可能会有所帮助。

另外,Django's docs on how to handle files with MEDIA_URL 可能会有所帮助。

this third-party package for splitting Django settings 也可能有帮助。

【讨论】:

    猜你喜欢
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 2013-05-04
    • 2016-09-24
    • 1970-01-01
    • 2012-08-26
    相关资源
    最近更新 更多