vendredi 27 juillet 2018

Can we pass conditional parameters to fixture functions in pytest?

I want to pass a list as a parameter to fixture based on a if condition. Is there a way to do this?

For example, please see the following code.

What I want to achieve is that if I pass odd as the num type in command line argument in pytest, the list passed as parameter to the fixture should be odd numbers and even numbers for argument even.

P.S I am using pytest-xdist to run this tests multiple times, hence I use sys.stderr to print output.

filename: conftest.py

def pytest_addoption(parser):
    parser.addoption('--type', action='store', help='Number of times to repeat each test')  

filename: test_file.py

import pytest, sys

lis = []

@pytest.fixture()
def nested_fixture(pytestconfig):
    global lis
    numtype = str(pytestconfig.getoption("type"))

    if numtype == "odd":
        lis.append(1)
        lis.append(3)

    if numtype == "even":
        lis.append(2)
        lis.append(4)

    return lis

@pytest.fixture(params = nested_fixture)
def fixture_function(request):
    return request.param


def test_function(fixture_function):
    print >> sys.stderr , fixture_function

I execute this using the following command in terminal

pytest -sv -n 2 --type odd

Aucun commentaire:

Enregistrer un commentaire