Search code examples
pythontestingpytestconftest

Can PyTest addoption be made global variables across all files?


I am trying to make user input from pytest addoption to be accessible through all files

I have a conftest.py file with code

import pytest

def pytest_addoption(parser):
    try:
        parser.addoption('--user', action='store', default='', help='Login Email for the API tests')
        parser.addoption('--pwd', action='store', default='', help='Login Password for the API tests')
    except ValueError:
        pass

@pytest.fixture
def get_user(request):
    return request.config.getoption("--user")

@pytest.fixture
def get_pwd(request):
    return request.config.getoption("--pwd")

I tried importing from conftest import get_user, get_pwd in other files, but it only imports as a function object and not as the value inputed by user.

It is because it is not just the test functions that have to use these values, but there are some more functions in the code that require these values and those functions are not able to identify the fixture values.

I want get_user an get_pwd to be globally accessible through all files in the directory. How can I do that?


Solution

  • You can define hook pytest_configure() and store those parameters as globals there.

    # your conftest.py
    
    # you should be able to import that
    username: str = None
    
    def pytest_configure(config):
       global username
       username = config.getoption('--user')
    

    pytest_configure (you probably have to search for it)

    Better solution would be to add the fixture name to your test function as a parameter, like that:

    from conftest import get_user
    
    def test_username(get_user):
        assert get_user == "my_username"
    

    pytest fixtures