Тестирование аутентификации в Django Rest Framework Views - невозможно проверить подлинность при тестировании

После серьезной борьбы с этой проблемой, я прошу немного помочь. Я пишу тест для представления Django Rest Framework, проверяя, могу ли я получить доступ к данным во время аутентификации, а не. Однако, даже когда я аутентифицирован, я все равно получаю 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='[email protected]', 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:

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, несмотря ни на что. Что-нибудь мне не хватает? Спасибо заранее.

Ответы

Ответ 1

Вместо вызова self.factory.get() вызовите self.client.get().

Я предполагаю, что self.client.login не влияет на self.factory.