Creating pre-authentication session in django / selenium Web testing

I am trying to create a functional test for a project which a user does not need to login before accessing some urls. I did this by creating a pre-authenticated session to trick the site into thinking that the test user is already logged in.

I loaded a webdriver instance with a dummy url, create a dummy user in the dbase, set up the session at the backend and then add session cookie to the web driver as follows:-

from django.utils.importlib import import_module    

def load_dummy_url(self):
    driver.get(self.live_server_url + '/404-not-found')

def create_session_store():
    engine = import_module(settings.SESSION_ENGINE)
    store = engine.SessionStore()
    store.save()
    return store

def pre_create_login():
    user = get_user_model().objeects.create_user(email='[email protected]', first_name='user1', password='pass1')
    session_store = create_session_store()
    session_store[SESSION_KEY] = user.pk
    session_store.save()

    return session_store.session_key

def add_cookie_to_browser():
    driver.add_cookie(dict(name=settings.SESSION_COOKIE_NAME, value= pre_create_login()))

However, loading another url that requires user authentication is still redirecting to the login page as the request contains an AnonymousUser as the test site doesn't think the user is logged in.

Is there something am doing wrong here?

Note: the snippets above does not follow a good coding pattern. Its just a simple replica of the exact code.

Upvotes: 2

Views: 622

Answers (1)

Ajay Gupta
Ajay Gupta

Reputation: 1285

I faced the same problem while Selenium testing for authenticated requests. A workaround for that would be:

create a new custom url like /selenium/user_login/ and write a view which will make user logged in. Now call this url in every selenium test case and redirect to the url which you want to test.

Upvotes: 1

Related Questions