Skip to content Skip to sidebar Skip to footer

Py.test : Can Multiple Markers Be Applied At The Test Function Level?

I have seen from the pytest docs that we can apply multiple markers at once on the Class or module level. I didn't find documentation for doing it at the test function level. Has

Solution 1:

For functions you just repeat the decorator:

@pytest.mark.webtest
@pytest.mark.slowtest
def test_something(...):
    ...

If you want to reuse that for several tests you should remember that decorators are just functions returning decorated thing, so several decorators is just a composition:

defcompose_decos(decos):
    defcomposition(func):
        for deco inreversed(decos):
            func = deco(func)
        return func
    return composition

all_marks = compose_decos(pytest.mark.webtest, pytest.mark.slowtest)

@all_marksdeftest_something(...):
    ...

Or you can use general purpose composition such as my funcy library has:

from funcy importcomposeall_marks= compose(pytest.mark.webtest, pytest.mark.slowtest)

Note that this way you can compose any decorators, not only pytest marks.

Solution 2:

Haven't tried this myself. However, from a quick look at the source, I think class MarkDecorator is what you want. Try:

mark_names=["marker1", "marker2", "marker3"]
my_marks = pytest.MarkDecorator(*mark_names)
marked_test_function = my_marks(test_function)

The *mark_names just unpacks mark_names into the constructor arguments of MarkDecorator. MarkDecorator.__call__ then applies the stored marks (self.args) to the parameter, here test_function, to provide a marked test function.

You can also use def unmarked_test_function() ... and test_function=my_marks(unmarked_test_function) so you don't have to change names.

Added explanation: I got this from pytest.mark, which turns out to be a MarkGenerator singleton. MarkGenerator creates MarkDecorator classes, which are then applied as decorators. The above code simulates that process manually, stuffing multiple markers.

Post a Comment for "Py.test : Can Multiple Markers Be Applied At The Test Function Level?"