Search code examples
pythonpytestfixturesconftest

Pytest fixture command line returning function object instead of value


I am trying to take a command line input for testing. Instead of returning the input as a string, python fixture is returning a function object

My contest.py file has this code:

def pytest_addoption(parser):
    parser.addoption('--n', action='store', default='mark', help='user name')
    parser.addoption('--pwd', action='store', default='pwd', help='password')


@pytest.fixture
def get_name(request) -> str:
    return request.config.getoption('--n')

@pytest.fixture
def get_pwd(request) -> str:
    return request.config.getoption('--pwd')

and my example test is:

def test_names():
    print(get_name)
    assert get_name == 'mark'
    

def test_pwd():
    print(get_pwd)
    assert get_pwd == 'p'

The return is an error and when I try to print get_pwd and get_name, it prints:

<function get_name at 0x7f8431fcdc10> <function get_pwd at 0x7f8431fcda60>

I have used same code before and it has returned the input value but here it is returning function object.

my command line input is:

pytest -s test.py --n=mark --pwd=p

How can I get it to return the command line input instead of the function object?


Solution

  • You need to give the fixture as a test parameter

    def test_names(get_name):
        print(get_name)
        assert get_name == 'mark'
    
    
    def test_pwd(get_pwd):
        print(get_pwd)
        assert get_pwd == 'p'
    

    Output

    test.py::test_names PASSED                                               [ 50%]mark
    
    test.py::test_pwd PASSED                                                 [100%]p