我有简单的视图测试。我想简单测试'/ users /'但我的应用程序要求用户登录的问题。这在这里解释
Django Unittests Client Login: fails in test suite, but not in Shell
login_ret = self._client.login(username=self._username,
password=self._password)
它按预期工作。因此,我按照此处的说明创建测试用户,并正确登录。现在,我希望通过此代码
获取'/ user /'的响应ret = self._client.get('/users/')
并返回
状态代码:403
内容:{“详细信息”:“您无权执行此操作。”}
它接缝不会保留登录方法的会话。
这里有什么问题?
这是完整的代码
self._client = Client()
self._username = 'testuser'
self._email = 'test@test.com'
self._password = 'test'
self._test_user = User.objects.create_user(self._username,
self._email,
self._password)
login_ret = self.client.login(username=self._username,
password=self._password)
self.assertEqual(login_ret, True)
我刚刚创建了基本的Django REST API应用程序并添加了auth模块,因此完整的视图代码是这样的(rest_api是应用程序的名称)
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_api.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
serializers.py
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
models.py为空