Search code examples
pythondjangopython-behave

How to login user during Given step using django-behave


I'm using django-behave to run behavioural tests in a Django project. In my feature file I have this given step in several scenarios:

 Given I am logged in

What I've been doing so far is use Selenium to go through the login process manually. But that takes a long time and it's not what I'm testing at this point. Plus the behave documentation says:

Requests/Twill/Selenium interaction etc should mostly go into When steps

So how should I log in a user during this Given step? Is there a way to use django.test.Client.login()? Can I just put a session into a fixture?


Solution

  • Ok, using this answer to a different question, I've gone for this:

    @given('I am logged in')
    def impl(context):
        client = context.test.client
        client.login(email='test@email.com', password='password')
    
        cookie = client.cookies['sessionid']
    
        # Selenium will set cookie domain based on current page domain.
        context.browser.get(context.get_url('/404-loads-fastest/'))
        context.browser.add_cookie({
            'name': 'sessionid',
            'value': cookie.value,
            'secure': False,
            'path': '/',
        })
    

    But it still seems kind of indirect.