[Fixed]-How to test login process?

28👍

I found out that my passing of the post parameters was wrong (the dictionary must not be unpacked). I also needed to learn, that I needed to follow the redirect issued by the post request after sending the data. Then my login test worked (although the page that was target of the redirection does not exist yet).

Here’s my updated test case:

from django.contrib.auth.models import User
from django.test import TestCase

class LogInTest(TestCase):
    def setUp(self):
        self.credentials = {
            'username': 'testuser',
            'password': 'secret'}
        User.objects.create_user(**self.credentials)
    def test_login(self):
        # send login data
        response = self.client.post('/login/', self.credentials, follow=True)
        # should be logged in now
        self.assertTrue(response.context['user'].is_active)

Here’s the output:

$ python manage.py test
Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.196s

OK
Destroying test database for alias 'default'...

19👍

You don’t want to be checking "is_active" boolean, you want to be checking

response.context['user'].is_authenticated

see:
https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-in-web-requests

and:
https://docs.djangoproject.com/en/dev/ref/contrib/auth/

Leave a comment