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='uid.sawyer@gmail.com',
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)
Finally, I got it. I didn't notice that I had created Token in signals wherein each User creation Token was created. Thanks @Willem Van Onsem