Pytest Environment Global Varibale

Viewed 123

I am attempting to pass in a config environment variable in the pytest command line. I already use one for Browser type e.g. --browser chrome.

What I would like is to pass in --env and then either Staging or Live to run my tests against.

This will determine which URL I use for my selenium tests so I would need a method for BaseURL and if it's Staging then use Staging URL and if it's Live then the Live URL. I've added in the config side in conftest

def pytest_addoption(parser):
    parser.addoption("--browser")
    parser.addoption("--env", help="staging or live")


@pytest.fixture(scope="session")
def env(request):
    return request.config.getoption("--env")

The first part I am unsure about is how I handle the BaseURL side method.Currently, this gets set as one URL in the WebdriverFactory Class which grabs the driver and URL. I need a way of storing the env config and checking which one is set before pass that back.

The second part is that I want to have tests that load the relevant base URL and then log in using either the staging or Live user credentials

so :

def test_validAdminLogin(self):
    self.lp.clearUserAndPasswordFields()
    self.lp.login("**AdminUser**")

So this test will pass the roletype (adminUser) to the page object which would in turn check whether or not the Env variable that has been passed in is either set to Live or Staging and then grab the relevant user details to enter on the page here:

def login(self, username="", password=""):
    self.enter_username(username)
    self.enter_password(password)
    self.click_login_button()

I just need a pointer in how to map all this out really

1 Answers

For baseurl try adding:

  • before pytest_addoption base_url='' global variable

Then after pytest_adoption add:

def pytest_configure(config):
    global base_url
    env = config.getoption('--env')
    base_url = base_url.format(env)

Then you create a fixture and pass it to your tests eg:

@pytest.fixture():
def fixture_base_url():
    global base_url
    return base_url

In your test:

def test_function(fixture_base_url):
    browser.open(fixture_base_url)

For the second part - you want to create an open_browser fixture. The fixture would open the browser and yield the browser to the test function. eg:

def open_browser(fixture_base_url):
    # code to open browser
    yield browser
    browser.close() #after all functions finish using this fixture, control goes past `yield` and browser will be closed.

updated test function:

def test_function(open_browser):
    #code to navigate the browser
Related