Python - Using pytest to skip test unless specified

后端 未结 4 880
抹茶落季
抹茶落季 2020-12-31 23:12

Background

I have am using pytest to test a web scraper that pushes the data to a database. The class only pulls the html and pushes the html to a database to be p

4条回答
  •  误落风尘
    2021-01-01 00:15

    A very simply solution is to use the -k argument. You can use the -k parameter to deselect certain tests. -k tries to match its argument to any part of the tests name or markers You can invert the match by using not (you can also use the boolean operators and and or). Thus -k 'not slow' skips tests which have "slow" in the name, has a marker with "slow" in the name, or whose class/module name contains "slow".

    For example, given this file:

    import pytest
    
    def test_true():
        assert True
    
    @pytest.mark.slow
    def test_long():
        assert False
    
    def test_slow():
        assert False
    

    When you run:

    pytest -k 'not slow'
    

    It outputs something like: (note that both failing tests were skipped as they matched the filter)

    ============================= test session starts =============================
    platform win32 -- Python 3.5.1, pytest-3.4.0, py-1.5.2, pluggy-0.6.0
    rootdir: c:\Users\User\Documents\python, inifile:
    collected 3 items
    
    test_thing.py .                                                          [100%]
    
    ============================= 2 tests deselected ==============================
    =================== 1 passed, 2 deselected in 0.02 seconds ====================
    

    Because of the eager matching you might want to do something like putting all your unittests in a directory called unittest and then marking the slow ones as slow_unittest (so as to to accidentally match a test that just so happens to have slow in the name). You could then use -k 'unittest and not slow_unittest' to match all your quick unit tests.

    More pytest example marker usage

提交回复
热议问题