【问题标题】:django rest detail_route testingdjango rest detail_route 测试
【发布时间】:2017-12-16 12:07:48
【问题描述】:

美好的一天!
我对 detail_route 有这样的看法:

class PostView(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

    @detail_route(methods=['POST'])
    def like(self, request, pk=None):
        post = self.get_object()
        post.like(request.user)
        return Response({'result': 'success'})

所以,like 函数的 url 是 /api/posts/{id}/like

我尝试像这样使用django.test.TestCase 对其进行测试:

post = Post.objects.first()
url = reverse('api:post-detail', args=[post.id])
url = urljoin(url, 'like')
response = self.client.post(url, content_type='application/json', follow=True)

我必须使用follow=True,因为我得到代码 300 重定向,但是当我需要 POST 时,重定向返回给我 GET 请求。 我尝试使用 APIClient 和 APIRequestFactory 并得到相同的错误或 myapp.models.DoesNotExist
坦克请注意!

【问题讨论】:

    标签: python django unit-testing testing django-rest-framework


    【解决方案1】:

    你得到 300 分这一事实应该表明你做错了。

    与其反转主 URL,然后手动加入详细路由扩展,不如直接反转到所需的完整 URL。正如the docs for detail_route 所示,该装饰器为您提供<model>-<detail-method> 形式的命名路由。所以:

    url = reverse('api:post-like', args=[post.id])
    response = self.client.post(url, content_type='application/json')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 2016-02-15
      • 2014-11-13
      • 1970-01-01
      • 2015-04-19
      • 2016-06-25
      相关资源
      最近更新 更多