Factoring out common setup code for a pytest fixture

Viewed 119

I'm writing some tests with pytest and have what I believe is a simple question but am not sure the right way to do it. I have some code like this:

@pytest.fixture
def obj1():
    ...setup object 1...
    return obj

@pytest.fixture
def obj2():
    ....setup object 2 ...
    return obj

def test_val_obj_1(obj1):
    ...some common boilerplate...
    output = some_function(obj1)
    assert output['important_key'] == some_values

def test_val_obj_2(obj2):
    ...some common boilerplate...
    output = some_function(obj2)
    assert output['important_key'] == some_values

For my two tests, the ...some common boilerplate... and some_function() are the same, and so I would prefer to have this elsewhere. Do I just define a normal function to do this? Or do I need to do something specific with fixtures? I haven't totally wrapped my head about the "parameterized" fixtures in the docs and can't figure out if that's what I'm asking about or if that's a different use case.

1 Answers

parameterized may help you, but it could depend on what is going on in boilerplate

@pytest.mark.parametrize("obj,some_value", [(obj1, some_value), (obj2, some_value)])
def test_val_obj(obj, some_value):
    ...some common boilerplate...
    output = some_function(obj)
    assert output['important_key'] == some_value
Related