user10551458
user10551458

Reputation: 183

how to pass the value returned by the fixture as a parameter to the function

I run the test like this:

pytest -v testing.py --parameters=10,11,12

inside the fixture, I get the command line arguments, make a list from the string, and I need to pass this list to the test as shown in the picture

code

#  content of conftest.py
import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--parameters", action="store", default='10,11,12', help="help")


@pytest.fixture
def cmdopt(request):
    return request.config.getoption("--parameters")


#  content of testing.py
import pytest


@pytest.fixture(autouse=True)
def get_params(cmdopt):
    data = cmdopt.split(',')  #  default ['10','11','12']
    return data


@pytest.mark.parametrize('parameter', 'the list that returned the fixture get_params')
def test_mytest(parameter):
    print(parameter)  # I first expect 10 then 11 then 12

How can this be implemented? Thank.

Upvotes: 1

Views: 891

Answers (1)

Samarth
Samarth

Reputation: 687

As quoted here:

Sometimes you may want to implement your own parametrization scheme or implement some dynamism for determining the parameters or scope of a fixture. For this, you can use the pytest_generate_tests hook which is called when collecting a test function. Through the passed in metafunc object you can inspect the requesting test context and, most importantly, you can call metafunc.parametrize() to cause parametrization.

So, check this out:

#  content of conftest.py
import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--parameters", action="store", default='10,11,12', help="help")


def pytest_generate_tests(metafunc):
if 'parameters' in metafunc.fixturenames:
    if metafunc.config.getoption('parameters'):
        option_value = metafunc.config.getoption('parameters')
        metafunc.parametrize("parameters", option_value.split(','))

#  content of testing.py
import pytest


def test_mytest(parameter):
    print(parameter)

Upvotes: 2

Related Questions