Why can't I test Django REST Frameworks AuthToken?
Question: 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', 'admin@test.com', '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)
    


Answer: 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.

