django rest detail_route测试

时间:2017-07-12 07:37:58

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

美好的一天!
我有一个像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函数的网址为/ 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请求。 我尝试过使用APIClientAPIRequestFactory并得到同样的错误或myapp.models.DoesNotExist
坦克引起你的注意!

1 个答案:

答案 0 :(得分:2)

The fact that you get a 300 at all should be a sign that you're doing something wrong.

Rather than reversing the main URL and then joining the detail route extension manually, you should reverse directly to the full URL you want. As the docs for detail_route show, that decorator gives you a named route in the form <model>-<detail-method>. So:

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