How can I ensure tests with a marker are only run if explicitly asked in pytest?

前端 未结 1 1635
失恋的感觉
失恋的感觉 2021-01-20 15:43

I have some tests I marked with an appropriate marker. If I run pytest, by default they run, but I would like to skip them by default. The only option I know is to explicitl

相关标签:
1条回答
  • 2021-01-20 16:13

    A slight modification of the example in Control skipping of tests according to command line option:

    # conftest.py
    
    import pytest
    
    
    def pytest_collection_modifyitems(config, items):
        keywordexpr = config.option.keyword
        markexpr = config.option.markexpr
        if keywordexpr or markexpr:
            return  # let pytest handle this
    
        skip_mymarker = pytest.mark.skip(reason='mymarker not selected')
        for item in items:
            if 'mymarker' in item.keywords:
                item.add_marker(skip_mymarker)
    

    Example tests:

    import pytest
    
    
    def test_not_marked():
        pass
    
    
    @pytest.mark.mymarker
    def test_marked():
        pass
    

    Running the tests with the marker:

    $ pytest -v -k mymarker
    ...
    collected 2 items / 1 deselected / 1 selected
    test_spam.py::test_marked PASSED
    ...
    

    Or:

    $ pytest -v -m mymarker
    ...
    collected 2 items / 1 deselected / 1 selected
    test_spam.py::test_marked PASSED
    ...
    

    Without the marker:

    $ pytest -v
    ...
    collected 2 items
    
    test_spam.py::test_not_marked PASSED
    test_spam.py::test_marked SKIPPED
    ...
    
    0 讨论(0)
提交回复
热议问题