我正在尝试在要求用户进行身份验证的URL上测试get请求。如果用户未经身份验证,则必须返回 HTTP_401 UNAUTHORIZED 错误作为响应状态代码。为此,我创建了一个测试用例,在该用例中,我尝试在没有身份验证的情况下触发get请求。
TestCase
class PublicTagsApiTests(TestCase):
"""Test the publicly available tags API"""
def setUp(self):
self.client = APIClient()
def test_login_required(self):
"""Test that login is required for retrieving tags"""
res = self.client.get(reverse('recipe:tag-list'))
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
但是测试失败并返回错误:
TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是'AnonymousUser'
查看
class TagViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
"""Manage tags in the database"""
authentication_classes = (TokenAuthentication,)
permission = (IsAuthenticated,)
queryset = Tag.objects.all()
serializer_class = serializers.TagSerializer
def get_queryset(self):
"""Return objects for the current authenticated user only"""
return self.queryset.filter(user=self.request.user).order_by('-name')
序列化器
class TagSerializer(serializers.ModelSerializer):
"""Serializer for tag objects"""
class Meta:
model = Tag
fields = ('id','name')
read_only_fields = ('id',)
如何修改视图以通过测试?
答案 0 :(得分:0)
在TagViewSet中尝试更改:
permission = (IsAuthenticated,)
收件人:
permission_classes = [IsAuthenticated]