How to use the output of a fixture as input to a function as parametrize pytest

1.1k views Asked by At

My aim is to pass a value to the fixture from test_add and the fixture in returns a list of tuples which will be required to pass it as parametrize to the test_add function.

Below is the code iam trying for which not working

File : conftest.py

@pytest.fixture
def testme(request):
    in_value = request.param
    return [(1*in_value,1),(3*in_value,2),(4*in_value,5)]

File : test_demo.py

@pytest.mark.parametrize("testme",[(10)])
@pytest.mark.parametrize("input_a,input_b",testme)
def test_add(input_a,input_b):
    print(input_a+input_b)

Thanks in advance for all the help.

1

There are 1 answers

0
MrBean Bremen On

The problem is that you can't access a fixture directly in pytest.mark.parametrize, so this won't work. The closest you can go this way probably is to run all parametrized tests in the same test:

@pytest.mark.parametrize("testme", [10], indirect=True)
def test_add(testme):
    for (input_a, input_b) in testme:
        print(input_a, input_b)

If you want to really parametrize the tests, you have to do the parametrization at run time using pytest_generate_tests. You cannot use a fixture to provide the needed parameter in this case. One possibility is to use a custom marker that contains this value, and a function to generate the parameters from this value at run time:

def pytest_generate_tests(metafunc):
    # read the marker value, if the marker is set
    mark = metafunc.definition.get_closest_marker("in_value")
    if mark is not None and mark.args:
        in_value = mark.args[0]
        # make sure the needed arguments are there
        if metafunc.fixturenames[:2] == ["input_a", "input_b"]:
            metafunc.parametrize("input_a,input_b", get_value(in_value))

def get_value(in_value):
    return [(1 * in_value, 1), (3 * in_value, 2), (4 * in_value, 5)]

@pytest.mark.in_value(10)
def test_add(input_a, input_b):
    print(input_a, input_b)

In this case you also want to register your custom marker in your conftest.py to avoid warnings:

def pytest_configure(config):
    config.addinivalue_line("markers",
                            "in_value: provides the value for....")