Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mark test as skipped from pytest_collection_modifyitems

Tags:

python

pytest

How can I mark a test as skipped in pytest collection process?

What I'm trying to do is have pytest collect all tests and then using the pytest_collection_modifyitems hook mark a certain test as skipped according to a condition I get from a database.

I found a solution which I don't like, I was wondering if maybe there is a better way.

def pytest_collection_modifyitems(items, config):
    ... # get skip condition from database
    for item in items:
        if skip_condition == True:
            item._request.applymarker(pytest.mark.skipif(True, reason='Put any reason here'))

The problem with this solution is I'm accessing a protected member (_request) of the class..

like image 307
Israhack Avatar asked Mar 14 '23 23:03

Israhack


2 Answers

You were almost there. You just need item.add_marker

def pytest_collection_modifyitems(config, items):
    skip = pytest.mark.skip(reason="Skipping this because ...")
    for item in items:
        if skip_condition:  # NB You don't need the == True
            item.add_marker(skip)

Note that item has an iterable attribute keywords which contains its markers. So you can use that too.

See pytest documentation on this topic.

like image 64
JSharm Avatar answered Apr 01 '23 12:04

JSharm


You can iterate over testcases (items) and skip them using a common fixture. With 'autouse=True' you shouldn't pass it in each testcase as a parameter:

@pytest.fixture(scope='function', autouse=True)
def my_common_fixture(request):
    if True:
       pytest.skip('Put any reason here')
like image 37
klapshin Avatar answered Apr 01 '23 11:04

klapshin