休息框架权限测试

rest-framework permission testing

我正在使用最新的 django-rest-framework 并想创建一些测试。我有一个 ModelViewSet 和一个访问 request.GET 的自定义权限。这一切都很好,但在我的单元测试中,GET 字典是空的。 这是我的代码:

class MyModelViewSet(ModelViewSet):
     ...
     permission_classes = [IsAuthenticated, CustomPermission]
     ...

permissions.py:
class CustomPermission(permissions.BasePermission):
    def has_permission(self, request, view):
       # here I access the GET to check permissions
       id = request.GET.get('id')
       obj = MyModel.objects.get(id=id)

       return request.user == obj.owner

这一切都在可浏览的 api 中按预期工作。 但是现在我写了一个单元测试:

class  ModelTestCase(APITestCase):
    def setUp(self):
        self.obj = mommy.make('MyModel') 
        self.user = mommy.make('CustomUser')       

    def test_list(self):
        self.client.force_authenticate(user=self.user)
        url = '%s?id=%s' % (reverse('mymodel-list'), self.obj.id)
        r = self.client.get(url)  # this raises the exception

这里我遇到了一个例外:

models.DoesNotExist: MyModel matching query does not exist.

调试时我发现 request.GEThas_permission 中是空的。 有谁知道为什么这在 "production" 中起作用但在单元测试中不起作用?

更新到最新版本 (3.2.1) 解决了这个问题。