6

I use django-social-auth as my authentication mechanism and I need to test my app with logged in users. I'm trying:

from django.test import Client
c = Client()
c.login(username='myfacebook@username.com", password='myfacebookpassword')

The user which is trying to login succeeds to login from a browser. The app is already allowed to access user's data.

Any ideas how to login from a unittest when using django-social-auth as the authentication mechanism?

Thanks

AmirW
  • 816
  • 9
  • 20
  • Social Auth recently integrated a way to easily test things like that. Please, have a look at http://django-social-auth.readthedocs.org/en/master/testing_tools.html – Nezo Apr 05 '13 at 17:57
  • Does this answer your question? [Django unit test; Login using python-social-auth](https://stackoverflow.com/questions/19897225/django-unit-test-login-using-python-social-auth) – Gonçalo Peres Oct 04 '22 at 13:37

1 Answers1

2

Create a fixture with User instances

{
    "pk": 15,
    "model": "auth.user",
    "fields": {
        "username": "user",
        "first_name": "user",
        "last_name": "userov",
        "is_active": true,
        "is_superuser": false,
        "is_staff": false,
        "last_login": "2012-07-20 15:37:03",
        "groups": [],
        "user_permissions": [],
        "password": "!",
        "email": "",
        "date_joined": "2012-07-18 13:29:53"
    }
}

Create a fixture with SocialAuthUser instances like this

{
    "pk": 7,
    "model": "social_auth.usersocialauth",
    "fields": {
        "uid": "1234567",
        "extra_data": "%some account social data%",
        "user": 15,
        "provider": "linkedin"
    }
}

So you will get the user, who has the same behavior as a real user and has all the social data you need. Set the new password and then you can use the auth mechanism for log this user in:

...
user.set_password('password')
user.save()                    
logged_in = self.client.login(username='user', password='password')

and then just call the view with login required

self.client.get("some/url")

Don't forget, that django.contrib.auth.backends.ModelBackend is needed, and django.contrib.sessions should be in your INTALLED_APPS tuple

Also, the advantage of using standard auth is that you don't need to make a server request for getting oauth tokens and so on.

Thorin Schiffer
  • 2,818
  • 4
  • 25
  • 34