Adilet Usonov
Adilet Usonov

Reputation: 136

Django testing how to make a request as logged in user?

In Django tests, I want to log in and make a request. Here the code

    def test_something(self):
        
        self.client.login(email=EMAIL, password=PASSWORD)
        response = self.client.get(reverse_lazy("my_releases"))
        self.assertEqual(response, 200)

But the code doesn't work and returns

AttributeError: 'AnonymousUser' object has no attribute 'profile'

How to make request in test as logged in user?

Upvotes: 1

Views: 994

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

As the documentation on .login(…) says:

(…)

login() returns True if it the credentials were accepted and login was successful.

Finally, you’ll need to remember to create user accounts before you can use this method.

The tests run normally on a separate database, and thus the items created while debugging, or in production, do not have effect on that.

You thus first create a user and then test it with:

from django.contrib.auth import get_user_model

# …

    def test_something(self):
        User = get_user_model()
        User.objects.create_user('my-user-name', email=EMAIL, password=PASSWORD)
        self.assertTrue(self.client.login(email=EMAIL, password=PASSWORD))
        response = self.client.get(reverse_lazy("my_releases"))
        self.assertEqual(response, 200)

The standard authentication engine works with a username and password, not with an email and password, so if you used the builtin authentication manager, you login with:

from django.contrib.auth import get_user_model

# …

    def test_something(self):
        User = get_user_model()
        User.objects.create_user('my-user-name', email=EMAIL, password=PASSWORD)
        self.assertTrue(self.client.login(username='my-user-name', password=PASSWORD))
        response = self.client.get(reverse_lazy("my_releases"))
        self.assertEqual(response, 200)

Upvotes: 2

Related Questions