【问题标题】:rest-framework permission testing休息框架权限测试
【发布时间】:2023-03-18 09:13:01
【问题描述】:

我正在使用最新的 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 中是空的。 有谁知道为什么这在“生产”中有效但在单元测试中无效?

【问题讨论】:

    标签: django django-rest-framework python-unittest django-unittest


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-25
      • 2015-11-15
      • 2021-05-23
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      相关资源
      最近更新 更多