[Answer]-Django unittesting user login appears to be unauthorized

1👍

test_login1: You are trying to login with a non existent user, create the user first (or just use the self.user credentials!):

    def test_login1(self):
            User.objects.create_user(
                username='mark',
                email='mark@something.xy',
                password='mark'
                )
        response = self.client.post(reverse('login'), {'username': 'mark', 'password': 'mark'}, follow=True)
        self.assertEqual(response.status_code, 200)
        assert not "Failed to login" in response.content, "Failed to login!"

test_login2: Your login form uses POST method not GET! try this:

request = self.factory.post(reverse('login'))

test_login3: Wrong username, notice jaconb instead of jacob.
Also this test is expecting a redirect, since it’s testing for some content not present on the login page.
(notice the : assert "Pie" in response.content, where “Pie” is never present on the login page! you should probably check for the LOGIN_REDIRECT_URL in your settings.py)

I hope this helps!


To get “Pie” to display for authenticated users try this template tag:

{% if user.is_authenticated %}
<a>Pie</a>
{% endif %}

Leave a comment