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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (21)

我需要限制访问我在视图中定义的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。我在这做错了什么?

提问于
用户回答回答于

我忘记了我正在使用RemoteUser身份验证,因此当我创建我需要设置时REMOTE_USER

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

扫码关注云+社区

领取腾讯云代金券