I set up a unit test as such:

class UserViewTests(TestCase):
    def setUp(self):
        self.user_passwords = '123456'
        self.user1 = User.objects.create(username='Bobby Johnson', password=self.user_passwords)

    ...

    def test_view_user(self):
        """
        Check that you can view a user's information correctly in their profile
        """
        response = self.client.get(reverse('login'))
        self.assertContains(response, "You're not logged in yet", status_code=200)
        self.client.login(username=self.user1.username, password=self.user_passwords)
        response = self.client.get(reverse('login'))
        self.assertContains(response, "You've logged in already", status_code=200)

Only the last assertion fails, and replacing "You've logged in already" with "You're not logged in yet" in that last assertion makes the test pass, so it appears my login failed. I'm guessing this is because I'm using django-social-auth to allow OpenId logins.

How can I somehow get the unit tests to think that my user has logged in, so that user.is_authenticated is true? I just want to test that my views display correctly when a user is logged in vs otherwise, and don't particularly care about unit-testing that the login actually works.

有帮助吗?

解决方案

 self.user1 = User.objects.create(username='Bobby Johnson', password=self.user_passwords)

Should be:

self.user1 = User.objects.create_user(username='Bobby Johnson', password=self.user_passwords)

Otherwise the password is not hashed and is not usable.


You'll also need to have django.contrib.auth.backends.ModelBackend present in your authentication backends.


Then,

self.client.login(username=self.user1.username, password=self.user_passwords)

will just work.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top