dvreed77
dvreed77

Reputation: 2387

Parameterized Tests with Function Output

I'm working on some fairly complicated test scenarios with PyTest, and I was hoping to encapsulate the test setup for various scenarios in some functions and then make those scenarios available to a test using parameterization.

Here is a simplified example:

def scenario01():
    # complicated setup
    ...
    return {
        "name": "scenario01",
        "cond1": cond1,
        "cond2": cond2
    }

def scenario02():
    # complicated setup
    ...
    return {
        "name": "scenario02",
        "cond1": cond1,
        "cond2": cond2
    }

# is it ok to call these functions in the decorator
@pytest.mark.parametrize("test_data", [scenario01(), scenario02()])
def test_my_func(test_data):
    name = test_data["name"]
    cond1 = test_data["cond1"]
    cond2 = test_data["cond2"]
    assert cond1 && cond2 #this isn't important

Is there any downside to doing something like this?

I like this because, as a reader, its obvious where the fixtures are coming from and their not magically defined in some conftest.py file, but I'm not sure if there is some side effects that may be happening that I'm not aware of.

Upvotes: 0

Views: 343

Answers (1)

theY4Kman
theY4Kman

Reputation: 6125

If the functions aren't computationally expensive, there's no harm in it. If it were computationally expensive, I might move the function invocation inside the test method, like so:

@pytest.mark.parametrize("test_data", [scenario01, scenario02])
def test_my_func(scenario):
    test_data = scenario()

The issue with computationally expensive things at module level is that they'll occur during test collection, regardless of whether those tests actually end up running.

However, if the scenarios aren't expensive, I might gain a few points in readability by pulling the scenario contents into actual parametrized fixtures, and moving the name into the ParamSet's id, so it will show up in the pytest output

@pytest.mark.parametrize(("cond1", "cond2"), [
    pytest.param(data['cond1'], data['cond2'], id=data['name'])
    for data in [
        scenario01(),
        scenario02(),
    ]
])
def test_my_func(cond1, cond2):
    assert cond1 and cond2  # this isn't important

Upvotes: 1

Related Questions