I'm new in Django rest framework and I'm trying do a unit test using Token for my API, but it kept throwing IntegrityError. I've researched many blogs to find the solution but couldn't find. Please help me solve this. Thanks in advance.
Here is the code that I've tried
from django.contrib.auth.models import User
from rest_framework.test import APITestCase, APIRequestFactory, force_authenticate
from rest_framework.authtoken.models import Token
from myapp.api.views import UserViewSet
class UserTestCase(APITestCase):
def setUp(self):
self.superuser = User.objects.create_user(username='superuser', email='[email protected]',
password='superuser',
is_staff=True)
self.factory = APIRequestFactory()
self.token = Token.objects.create(user=self.superuser)
self.token.save()
def test_list(self):
request = self.factory.get('/api/users/')
force_authenticate(request, user=self.superuser, token=self.token)
response = UserViewSet.as_view({'get': 'list'})(request)
self.assertEqual(response.status_code, 200)
usermultiple times with yourToken.objects.create(..)Token.objects.create(user=self.superuser), I gave a try by removingself.token.save()and I've also tried to put the token creation code insetUpClass()classmethod but it's still throwing the IntegrityError