Django单元测试,自定义权限和request.user.username

时间:2019-06-12 19:26:14

标签: python django unit-testing

我需要限制对我在视图中定义的API的访问。这是我的views.py

rom rest_framework import generics
from rest_framework import permissions
from .serializers import LocationSerializer, PartSerializer, PartLocationSerializer, SiteSerializer
from .models import Location, Part, PartLocation, Site, SPIUser


class SPIPermission(permissions.BasePermission):
    """
    blah blah blah ...
    """
    def has_permission(self, request, view):
        try:
            username = request.user.username
            SPIUser.objects.get(username=username)
        except SPIUser.DoesNotExist:
            return False
        if not request.user.is_authenticated:
            return False
        return True


class LocationList(generics.ListCreateAPIView):
    # using get_queryset().order_by('id') prevents UnorderedObjectListWarning
    queryset = Location.objects.get_queryset().order_by('id')
    serializer_class = LocationSerializer
    permission_classes = (SPIPermission,)

我想在单元测试中证明您必须是SPIUser才能访问这些api端点,因此我编写了一个简单的单元测试,如下所示:

from .models import Location, Part, PartLocation, Site, SPIUser
from .urls import urlpatterns
from my.APITestCase import RemoteAuthenticatedTest
from django.db.models import ProtectedError
from django.test import TransactionTestCase
from django.urls import reverse
from rest_framework import status
import django.db.utils
import os


class ViewTestCases(RemoteAuthenticatedTest):

    def test_spi_permission(self):

        url = reverse('spi:locationlist')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        SPIUser.objects.create(username=self.username)
        response = self.client.get(url)
        self.assertNotEquals(response.status_code, status.HTTP_403_FORBIDDEN)

此测试失败,并显示以下错误消息:

Failure
Traceback (most recent call last):
  File "/apps/man/apman/spi/tests.py", line 21, in test_spi_permission
    self.assertNotEquals(response.status_code, status.HTTP_403_FORBIDDEN)
AssertionError: 403 == 403

我注意到has_permission中的那一行...

username = request.user.username

...始终将username设置为''。因此has_permission将始终返回False

我的单元测试ViewTestCases继承了类RemoteAuthenticatedTest,其定义如下:

from rest_framework.test import APIClient,APITestCase
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token


class RemoteAuthenticatedTest(APITestCase):
    client_class = APIClient

    def setUp(self):
        self.username = 'mister_neutron'
        self.password = 'XXXXXXXXXXX'
        self.user = User.objects.create_user(username= self.username,
                                             email='mister_neutron@example.com',
                                             password=self.password)
        #authentication user
        self.client.login(username=self.username, password=self.password)
        Token.objects.create(user=self.user)
        super(RemoteAuthenticatedTest, self).setUp()

所以我认为request.user.username将是mister_neutron。 我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

哎呀。我忘记了我正在使用RemoteUser身份验证,因此在进行身份验证时,我需要像这样设置REMOTE_USER

        response = self.client.get(url, REMOTE_USER=self.username)