pythonselenium-webdriverproxypython-behave

When using Behave, is it possible to pass a variable into the 'before_all' function in the environment.py file?


I'm using Behave and I have multiple proxies to use for different testing requirements. I've got all the proxy information in my environment.py file, but I'd like to be able to do something like run behave .\features\automated_test.feature --tags=proxy1 and then in the environment.py file, proxy1 is passed into the before_all function, like before_all(proxy).

That way I can use this line chrome_options.add_argument('--proxy-server=%s' % proxy) and the chosen proxy is passed into it.

environment.py

first_bypassList = [
        "github.com",
        "stackoverflow.com"
]
first_bypassList = ';'.join(first_bypassList)

second_bypassList = [
        "microsoft.com",
        "google.com"
]
second_bypassList = ';'.join(second_bypassList)

if prox == 'first':
        bypassList = first_bypassList
        prox_server = 'firstproxy:3128'
elif prox == 'second':
        bypassList = second_bypassList
        prox_server = 'secondproxy:3128'


def before_all(context):
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--proxy-server=%s' % prox_server)
    chrome_options.add_argument("--proxy-bypass-list=%s" % bypassList)
    context.driver = webdriver.Chrome(chrome_options)
    context.driver.maximize_window()


def after_all(context):
    context.driver.close()


Solution

  • That part can be done easily if you define your before_ methods in a separate file, and then import those directly into your environment.py file.

    Here's an actual selenium behave framework that does that: (SeleniumBase)

    https://github.com/seleniumbase/SeleniumBase/tree/master/examples/behave_bdd

    The before_ methods were defined at the bottom of https://github.com/seleniumbase/SeleniumBase/blob/master/seleniumbase/behave/behave_sb.py

    The environment.py file that imports those is here:

    https://github.com/seleniumbase/SeleniumBase/blob/master/examples/behave_bdd/features/environment.py

    It uses additional command-line options to extend behave. Here's a sample run command to run tests via proxy:

    behave -D proxy=SERVER:PORT
    

    Here's one for an authenticated proxy:

    behave -D proxy=USERNAME:PASSWORD@SERVER:PORT