Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run method only if --collect-only was used

Tags:

python

pytest

I'm trying to collect some stats of how many test cases there are per feature or team, and want to do this only during collection, not when everyone in my company runs their tests. I'm looking for a way to run a function only if --collect-only was used in the py.test command.

Goal:

  • Run some code only if --collect-only was used
  • I need access to the test items data structure (i.e. I need all of the markers that were used)

Currently, I am doing this via pytest_collection_modifyitems hook:

def pytest_collection_modifyitems(config, items):
    # This hook runs after collection
    for item in items:
        teams = [mark.name for mark in item.iter_markers() if mark.name.startswith('team_')]
        features = [mark.name for mark in item.iter_markers() if mark.name.startswith('feature_')]

        # do something with these markers

Is there a way to run this code above if and only if py.test was run with --collect-only? If anyone has suggestions on better ways to do this, please help!

Thanks!

like image 904
Dragan R. Avatar asked Oct 23 '25 18:10

Dragan R.


1 Answers

Just check whether the flag is set in the config object. Example with your hookimpl:

def pytest_collection_modifyitems(config, items):
    if config.option.collectonly:
        print("I will run only with --collectonly flag")
    else:
        print("I will run only without --collectonly flag")
like image 192
hoefling Avatar answered Oct 26 '25 08:10

hoefling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!