1

I'm trying to test the Django REST frameworks AuthToken with an APITestCase, but I always get status code 400 and the message:

b'{"non_field_errors":["Unable to log in with provided credentials."]}'

Weirdly enough when I type in the exact same commands via python manage.py shell I get status code 200 and the auth token back.

What am I missing here?

Here's my code:

from rest_framework.test import APITestCase from rest_framework.authtoken.models import Token from rest_framework.test import APIClient class TestAuthToken(APITestCase): def test_login_admin(self): client = APIClient() response = client.post('/api-token-auth/', {'username':'admin','password':'password123'}) self.assertEqual(response.status_code, 200) 

UPDATE Forgot to create a user for the test database... Here's the new code:

from django.contrib.auth.models import User from rest_framework.test import APITestCase from rest_framework.authtoken.models import Token from rest_framework.test import APIClient class TestAuthToken(APITestCase): def setUp(self): self.admin = User.objects.create_user('admin', '[email protected]', 'password123') self.admin.save() self.admin.is_staff = True self.admin.save() def test_login_admin(self): client = APIClient() response = client.post('/api-token-auth/', {'username':'admin','password':'password123'}) self.assertEqual(response.status_code, 200) 

2 Answers 2

2

Are you creating the user previously in the setUp of the test case? Because django creates a testing db when you run the tests and gets empty for every class in the tests (unless you indicate that you want the data is keeped in the db between the tests), and if your code checks the db to see if the credentials are OK, it will find that doesn't exist any user with that username and password.

Sign up to request clarification or add additional context in comments.

1 Comment

That's embarassing... :D Thanks alot, it works now :)
1

I came here looking for an answer to force_authenticate not working while using a token. To those in the same case, you need to specify both user and token in the way specified in this answer https://stackoverflow.com/a/65154712/5253580

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.