3

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='[email protected]',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='[email protected]',password='realpassword'))

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

3
  • It may because of authentication problem Commented Sep 3, 2015 at 20:42
  • Yeah, it's because that line client.login(username='[email protected]',password='realpassword') isn't authenticating, but when I try the exact same code in shell, it authenticates! Commented Sep 3, 2015 at 20:54
  • are you using sessionauthentication or tokenauthentication or basicauthentication? Commented Sep 3, 2015 at 21:01

1 Answer 1

3

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='[email protected]', password='realpassword')
    def testClientView(self):
        self.client.login(
            username='[email protected]',password='realpassword')
        response = self.client.get('/api/v1/risks/', format='json')
        self.assertTrue(response.status_code, 200)
Sign up to request clarification or add additional context in comments.

1 Comment

This is awesome. Missing the conceptual piece that test creates its own db and that db needs to be populated. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.