Search code examples
djangoseleniumtestingtdd

Skip Login Process In Functional Tests


I am using allauth and have began making some functional tests. I have tested the login function and now am wanting to test other things, but I cant find a way to begin my functional tests with a pre-authenticated user. I have tried using the following code but I cant manage to get a user logged in automatically.

def create_pre_authenticated_session(self, username, email):
        session_key = create_pre_authenticated_session(username, email)

        # to set a cookie we need to first visit the domain
        self.browser.get(self.live_server_url + "/")
        self.browser.add_cookie(dict(
            name=settings.SESSION_COOKIE_NAME,
            value=session_key,
            path='/',
        ))
def create_pre_authenticated_session(username, email):
    user = User.objects.create(username=username, email=email)
    session = SessionStore()
    session[SESSION_KEY] = user.pk
    session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
    session.save()
    return session.session_key

Thank you.


Solution

  • You can use force_login method to login user

    If your site uses Django’s authentication system, you can use the force_login() method to simulate the effect of a user logging into the site. Use this method instead of login() when a test requires a user be logged in and the details of how a user logged in aren’t important.

    Unlike login(), this method skips the authentication and verification steps: inactive users (is_active=False) are permitted to login and the user’s credentials don’t need to be provided.

    self.client.force_login(user)
    

    Add the cookie to browser afterwards
    
    cookie = self.client.cookies['sessionid']
    self.browser.add_cookie({'name': 'sessionid', 'value': cookie.value, 'secure': False, 'path': '/'})
    self.browser.refresh()