2

我正在使用最新的 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.GET在调试时,我意识到has_permission. 有谁知道为什么这在“生产”中起作用但在单元测试中不起作用?

4

1 回答 1

1

更新到最新版本 (3.2.1) 修复了此问题。

于 2015-08-07T22:39:41.920 回答