使用 TokenAuthentication 进行类的 Django 单元测试

问题描述 投票:0回答:1

这是我第一次写单元测试 所以在我的 Django 项目中,我有来自views.py的这个类

    class AllClientProfilesView(generics.ListAPIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    serializer_class = ClientProfileSerializer

    def get_queryset(self):
    return ClientProfile.objects.all()

我的测试代码是

 class AllClientProfilesViewTest(APITestCase):
    def setUp(self):
    call_command('flush', interactive=False)
    self.user = User.objects.create_user(id='2' , phone_number=506879765)
    self.token = Token.objects.create(user=self.user)
    self.profile1 = ClientProfile.objects.create(name='Profile 1', )
    self.profile2 = ClientProfile.objects.create(name='Profile 2', )
    self.profile3 = ClientProfile.objects.create(name='Profile 3', )
    def test_view_requires_authentication(self):
    url = reverse('myURL')
    response = self.client.get(url)
    self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

    def test_get_all_client_profiles(self):
    url = reverse('myURL') 
    self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.token.key}')
    response = self.client.get(url)
    self.assertEqual(response.status_code, status.HTTP_200_OK)

    expected_profiles = ClientProfile.objects.all()
    self.assertEqual(len(response.data), expected_profiles.count())

    for data, expected_profile in zip(response.data, expected_profiles):
    serializer = ClientProfileSerializer(expected_profile)
    self.assertEqual(data, serializer.data)

但是当我运行它时,我收到了这个错误,我不知道如何修复它 返回Database.Cursor.execute(自身,查询,参数) django.db.utils.IntegrityError:唯一约束失败:authtoken_token.user_id

python django sqlite unit-testing django-rest-framework
1个回答
0
投票

您可能有信号或覆盖的保存方法来创建用户令牌。因此,

self.token = Token.objects.create(user=self.user)
当您运行此行时,数据库会发送错误,因为您的用户已经拥有令牌。

只需更改为

self.token, _ = Token.objects.get_or_create(user=self.user)

© www.soinside.com 2019 - 2024. All rights reserved.