Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何让django在单元测试期间进行身份验证_Python_Django_Unit Testing - Fatal编程技术网

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

Python 如何让django在单元测试期间进行身份验证,python,django,unit-testing,Python,Django,Unit Testing,我正在尝试测试一个*未经身份验证的/未经授权的用户访问django中的API。在API中,我有以下代码 class myAPIView(TimezoneAwareMixin, RetrieveUpdateAPIView): model = mymodel serializer_class = mymodelSerializer permission_classes = (IsAuthenticated, IsCompanyActive, HasRole) get

我正在尝试测试一个*未经身份验证的/未经授权的用户访问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并尝试以下操作

client = client_class() # no headers so its anonymous
client.get(url)
但是在测试过程中我得到了以下信息

AttributeError: 'AnonymousUser' object has no attribute 'attribute_name'
我期待一个403禁止或401未经授权

而不是回溯

我怎样才能得到正确的回答?很简单:

c = Client()
c.login(username='fred', password='secret')

您应该修改您的视图:

from django.contrib.auth.decorators import login_required

@login_required
def get_queryset(self):
    ...

我想测试***未经授权的****访问,所以我需要获得403或401。当用户经过身份验证时,这一切都很好。我想你需要添加@login\u required decorator以获得\u queryset方法。是的,decorator正在工作,它现在返回401。但是你能解释一下为什么权限类=(IsAuthenticated,…在请求到达代码之前没有首先返回它,这是因为您重写了get_queryset方法。您可以在此处阅读它:,DjangomodelPermissionsHanks Eugene!这帮了大忙,我有300个测试要编写,并且希望尽可能多地自动化测试正在运行的内容,它揭示了至少你有一只虫子。