python - 在 Django Rest Framework Views 中测试身份验证——测试时无法进行身份验证

标签 python django django-rest-framework

在为这个问题苦苦挣扎之后,我来寻求一些帮助。我正在为 Django Rest Framework View 编写测试,测试我是否可以在经过身份验证的情况下访问数据。但是,即使我通过了身份验证,我仍然每次都会收到 401 UNAUTHORIZED。这是我的测试:

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))

这是我的 DRF View 的代码:

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

如您所见,我在 test_ListAccounts_authenticated 中调用登录,然后打印出我是否已通过身份验证(返回 True),但我无论如何都会得到一个 401 UNAUTHORIZED 错误。有什么我想念的吗?提前致谢。

最佳答案

不是调用 self.factory.get(),而是调用 self.client.get()

我猜 self.client.loginself.factory 没有影响。

关于python - 在 Django Rest Framework Views 中测试身份验证——测试时无法进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20528798/

相关文章:

Django:删除静态文件的 'Vary: cookie' 响应 header

django - 在 Django Rest Framework 中发布外键关系

python - 对于某些数字,IntegerField 值会转换为字符串

django - 扩展模板中的 UnicodeDecodeError

sql - 为什么 Django 显式地在唯一字段上创建索引

django - 未找到 'openapi-schema' 的反向。 'openapi-schema' 不是有效的 View 函数或模式名称

python - 包括额外的上下文值 Django Rest Framework

java - 从 python 运行 bat 文件会返回错误,而直接从 cmd 运行

python - 函数参数 - Python

python - Azure Python 下载存储 blob 返回 'The condition specified using HTTP conditional header(s) is not met.'