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)