0

I'm trying to test POSTing data to a view in django-rest-framework that requires authentication. But I can't. I've read many threads of supposed solutions, but can't find any that solves to me.

Test:

 class TodoListCreateAPIViewTestCase(APITestCase): url = reverse("todolist:add") def setUp(self): self.username = "john" self.email = "[email protected]" self.password = "you_know_nothing" self.user = User.objects.create_user(self.username, self.email, self.password) self.token = Token.objects.create(user=self.user) #checking token here def test_create_todo(self): self.client.login(email=self.email, password='you_know_nothing') client = APIClient() client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) response = self.client.post(self.url, {"list_name": "Clean the room!"}, format='json') self.assertEqual(201, response.status_code) 

View

class Addtodolist(APIView): authentication_classes = (JSONWebTokenAuthentication,TokenAuthentication) permission_classes = [IsAuthenticated, ] def post(self, request): data = request.data todolist_instance = Todolist.objects.filter(for_user=self.request.user).first() if not todolist_instance: list_serilaizer = AddtodolistSerializers(data=data, context={'user': request.user}) if list_serilaizer.is_valid(): list_serilaizer.save() return Response(data=success_response(data=list_serilaizer.data, msg='Successfully Created list!'), status=status.HTTP_200_OK) else: return Response( failure_response(data={'detail': list_serilaizer.errors()}, msg='Following errors occured'), status=status.HTTP_400_BAD_REQUEST) else: return Response( failure_response(data={'detail': 'User can have only 1 List'}, msg='User can have only 1 List'), status=status.HTTP_409_CONFLICT) 
1
  • You should have used client.post(...) instead of self.client.post(...) Commented Sep 15, 2020 at 7:36

1 Answer 1

2

Change your code like this:

from django.shortcuts import reverse from django.contrib.auth import get_user_model from rest_framework.test import APIClient, APITestCase from rest_framework.authtoken.models import Token class TodoListCreateAPIViewTestCase(APITestCase): url = reverse("todolist:add") def setUp(self): self.username = "john" self.email = "[email protected]" self.password = "you_know_nothing" self.user = get_user_model().objects.create_user(self.username, self.email, self.password) self.token = Token.objects.create(user=self.user) def test_create_todo(self): client = APIClient() client.login(username=self.username, email=self.email, password=self.password) client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) response = client.post(self.url, {"list_name": "Clean the room!"}, format='json') self.assertEqual(response.status_code, 201) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.