user554319
user554319

Reputation:

How to parametrize a test with several pytest markers?

Say that I want to run the same test code with several pytest markers. One solution is to copy-paste the test with the markers applied:

@pytest.mark.A
def test_a():
    # same
    # code
    ...

@pytest.mark.B
def test_b():
    # same
    # code
    ...

One "hack" I found is to parametrize a dummy parameter and apply different markers using pytest.param:

@pytest.mark.parametrize("_", [
    pytest.param(None, marks=pytest.mark.A),
    pytest.param(None, marks=pytest.mark.B),
])
def test(_):
    # same
    # code
    ...

But it is clumsy and adds unused parameters. Is there a simpler way?

Upvotes: 1

Views: 1272

Answers (1)

Guy
Guy

Reputation: 50819

You can create a function that yields pytest.param and use a fake name (an empty string) in parametrize to avoid sending a parameter to the test

def add_markers():
    for mark in [pytest.mark.A, pytest.mark.B]:
        yield pytest.param(marks=mark)


@pytest.mark.parametrize('', add_markers())
def test_example():
    # code

Upvotes: 0

Related Questions