Search code examples
djangodjango-rest-frameworkdjango-rest-auth

Django REST framework APIClient authenticating in shell, but not in my unit test


I'm trying to unit test an REST API viewset using the examples here. If I run the code line-by-line in manage.py shell, I can authenticate just fine and get a 200 response code. When it's in my unit test, the authentication fails!

Here's the class:

class RiskViewSetTest(unittest.TestCase):

    def setUp(self):
        pass

    def testClientView(self):
        client = APIClient()
        client.login(username='test@test.us',password='realpassword')
        response = client.get('/api/v1/risks/')
        self.assertTrue(response.status_code, 200)

If I change the assertion to:

self.assertTrue(client.login(username='test@test.us',password='realpassword'))

it also fails, whereas the same command in shell returns True.


Solution

  • If you are running the test cases, it will auto create the database to execute test. In shell you already have database and user is there, it's authenticating. So you need to create the user here and authenticate. Follow this code:

    class RiskViewSetTest(unittest.TestCase):
    
        def setUp(self):
            self.client = APIClient()
            User.objects.create_user(
                username='test@test.us', password='realpassword')
        def testClientView(self):
            self.client.login(
                username='test@test.us',password='realpassword')
            response = self.client.get('/api/v1/risks/', format='json')
            self.assertTrue(response.status_code, 200)