Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest - How to know what markers are selected

Is there any way in pytest to know what markers are selected from the command line?

I have some tests marked as "slow" that need a heavy treatment. I want to process the treatment only if the marker slow is activated.

heavy_var = None

def setup_module(module):
    global heavy_var

    # Need help here!?
    if markers["slow"]:
        heavy_var = treatment()


def test_simple():
    pass


@pytest.mark.slow():
def test_slow():
    assert heavy_var.x == "..."

How can i know if the slow marker is selected or not? When i call pytest with -m not slow markers["slow"] will be False otherwise True.

like image 477
Nazime Lakehal Avatar asked Oct 11 '25 21:10

Nazime Lakehal


1 Answers

If you need to run some code only if tests marked with slow were selected, you can do that by filtering the test items in a module-scoped fixture that replaces the setup_module. Example:

@pytest.fixture(scope='module', autouse=True)
def init_heavy_var(request):
    for item in request.session.items:
        if item.get_closest_marker('slow') is not None:
            # found a test marked with the 'slow' marker, invoke heavy lifting
            heavy_var = treatment()
            break
like image 143
hoefling Avatar answered Oct 14 '25 11:10

hoefling