如何在单元测试期间让Django进行身份验证

2024-10-04 11:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图测试一个未经验证的用户访问django中的API。我有以下API代码

class myAPIView(TimezoneAwareMixin, RetrieveUpdateAPIView):

    model = mymodel
    serializer_class = mymodelSerializer
    permission_classes = (IsAuthenticated, IsCompanyActive, HasRole)
    get_roles = ('mymodel-view',)

    def get_queryset(self):
        """
        Allow only users within a company to see only their objects
        """

        return mymodel.objects.filter(company=self.request.user.active_company)

然后在我的测试中,我继承了TestCase并尝试以下操作

^{pr2}$

但我在测试中得到了以下信息

AttributeError: 'AnonymousUser' object has no attribute 'attribute_name'

我要的是403禁止或401未经授权

而不是回溯

我怎样才能得到正确的回答


Tags: django代码用户selfapionlygetobjects