简体   繁体   English

在Django Rest Framework视图中测试身份验证 - 无法在测试时进行身份验证

[英]Testing authentication in Django Rest Framework Views — Cannot authenticate when testing

After struggling mightily with this issue, I've come asking for a bit of help. 在经历了这个问题的艰苦努力之后,我来寻求一些帮助。 I'm writing a test for a Django Rest Framework view, testing whether or not I can access the data whilst authenticated, and not. 我正在为Django Rest Framework视图编写一个测试,测试我是否可以在经过身份验证时访问数据,而不是。 However, even when I'm authenticated, I still get 401 UNAUTHORIZED every time. 但是,即使我经过身份验证,我仍然每次都获得401 UNAUTHORIZED Here's my tests: 这是我的测试:

from django.test import TestCase
from django.contrib.auth.models import User

from rest_framework.authtoken.models import Token
from rest_framework.test import APIRequestFactory, APIClient

from apps.core import models, admin
from apps.rest import views


class TestAPIViews(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.client = APIClient()
        self.user = User.objects.create_user('testuser', email='testuser@test.com', password='testing')
        self.user.save()
        token = Token.objects.create(user=self.user)
        token.save()

    def _require_login(self):
        self.client.login(username='testuser', password='testing')

    def test_ListAccounts_not_authenticated(self):
        request = self.factory.get('/accounts/')
        view = views.ListAccounts.as_view()
        response = view(request)
        self.assertEqual(response.status_code, 401,
            'Expected Response Code 401, received {0} instead.'.format(response.status_code))

    def test_ListAccounts_authenticated(self):
        self.client._require_login()
        print(self.user.is_authenticated()) # returns True
        request = self.factory.get('/accounts/')
        view = views.ListAccounts.as_view()
        response = view(request)
        self.assertEqual(response.status_code, 200,
            'Expected Response Code 200, received {0} instead.'.format(response.status_code))

And here is the code for my DRF View: 这是我的DRF视图的代码:

from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.db.models import Q


from apps.core import serializers, models
from apps.rest.permissions import IsAccountOwner

from rest_framework.views import APIView
from rest_framework import status, authentication, generics
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from apps.core import serializers, models

'''
Auth Mixin for Account Admin Access
'''
class AuthMixin:
    authentication_classes = (authentication.TokenAuthentication,
                              authentication.SessionAuthentication)
    permission_classes = (IsAuthenticated,)


class GenericList(AuthMixin, generics.ListAPIView):
    def get_queryset(self):
        # Stubbed out - doing nothing special right now
        qs = self.model.objects.filter()
        return qs


class ListAccounts(GenericList):
    model = models.Account
    serializer_class = serializers.AccountSerializer

As one can see, I'm calling login in the test_ListAccounts_authenticated , and then printing out whether or not I'm authenticated (Which returns True ), but I get a 401 UNAUTHORIZED Error no matter what. 可以看出,我在test_ListAccounts_authenticated调用login,然后打印出我是否经过身份验证(返回True ),但无论如何我都会获得401 UNAUTHORIZED错误。 Anything I'm missing? 我缺少什么? Thanks in advance. 提前致谢。

Instead of calling self.factory.get() , call self.client.get() . 而不是调用self.factory.get() ,而是调用self.client.get()

I'm guessing self.client.login has no effect on self.factory . 我猜self.client.loginself.factory没有影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以在测试 Django Rest Framework 时避免身份验证的需要吗 - Can I avoid the need for authentication when testing Django Rest Framework 在Django Rest Framework中使用身份验证测试POST - Testing POST with authentication in Django Rest Framework 在测试 Django REST 框架时,为什么我不能让 APIClient.credentials() 使用令牌进行身份验证? - When testing Django REST Framework, why can't I get APIClient.credentials() to authenticate using a token? 在 Django Rest Framework 中测试时获取路由器 url 名称 - get router url name when testing in Django Rest Framework 测试经过身份验证的 django-rest-framework 路由时出现 405 错误 - 405 error when testing an authed django-rest-framework route 在Django Rest Framework中进行测试时,在API Request Factory中调用View - Calling View in API Request Factory when testing in Django Rest Framework Django中的身份验证基于框架功能的视图 - Authentication in Django rest framework function based views 如何在 Django Rest 框架中禁用节流以进行测试? - How is throttling disabled for testing in Django Rest Framework? 在 Django REST Framework 中测试图片上传 - Testing image uploads in Django REST Framework 在Django Rest Framework中进行测试,是否会重现该curl请求? - Testing in Django Rest Framework, reproduce this curl request?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM