Django Rest Framework-如何测试ViewSet? [英] Django Rest Framework - How to test ViewSet?

查看:66
本文介绍了Django Rest Framework-如何测试ViewSet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在测试ViewSet时遇到麻烦:

I'm having trouble testing a ViewSet:

class ViewSetTest(TestCase):
    def test_view_set(self):
        factory = APIRequestFactory()
        view = CatViewSet.as_view()
        cat = Cat(name="bob")
        cat.save()

        request = factory.get(reverse('cat-detail', args=(cat.pk,)))
        response = view(request)

我试图在此处复制语法:

I'm trying to replicate the syntax here:

http://www.django-rest-framework.org/api-guide/testing#forcing-authentication

但是我认为他们的AccountDetail视图与我的ViewSet不同,所以我从最后一行得到了这个错误:

But I think their AccountDetail view is different from my ViewSet, so I'm getting this error from the last line:

AttributeError: 'NoneType' object has no attributes 'items'

这里是否有正确的语法,还是我在混淆概念?我的APIClient测试工作正常,但是我在这里使用工厂,因为我最终想添加 request.user = some_user。

Is there a correct syntax here or am I mixing up concepts? My APIClient tests work, but I'm using the factory here because I would eventually like to add "request.user = some_user". Thanks in advance!

哦,客户端测试正常:

def test_client_view(self):
    response = APIClient().get(reverse('cat-detail', args=(cat.pk,)))
    self.assertEqual(response.status_code, 200)


推荐答案

我认为我找到了正确的语法,但没有找到确保它是否是常规的(对Django来说仍然是新的):

I think I found the correct syntax, but not sure if it is conventional (still new to Django):

def test_view_set(self):
    request = APIRequestFactory().get("")
    cat_detail = CatViewSet.as_view({'get': 'retrieve'})
    cat = Cat.objects.create(name="bob")
    response = cat_detail(request, pk=cat.pk)
    self.assertEqual(response.status_code, 200)

因此现在通过了,我可以分配request.user,这使我可以自定义CatViewSet下的检索方法以考虑用户。

So now this passes and I can assign request.user, which allows me to customize the retrieve method under CatViewSet to consider the user.

这篇关于Django Rest Framework-如何测试ViewSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆