Pytest----如何使用mark

語言: CN / TW / HK

【原文鏈接】

一、常見的內置markers

  • usefixtures - 為測試函數或者測試類知名使用那些fixture
  • filterwarnings - 為一個測試函數過濾一個指定的告警
  • skip - 跳過一個測試函數
  • skipif - 如果滿足條件就跳過測試函數
  • xfail - 標記用例失敗
  • parametrize - 參數化

二、查看所有markers

如下,可以查看到當前環境中的所有markers ```bash $ pytest --markers @pytest.mark.forked: Always fork for this test.

@pytest.mark.flaky(reruns=1, reruns_delay=0): mark test to re-run up to 'reruns' times. Add a delay of 'reruns_delay' seconds between re-runs.

@pytest.mark.hypothesis: Tests which use hypothesis.

@pytest.mark.allure_label: allure label marker

@pytest.mark.allure_link: allure link marker

@pytest.mark.allure_description: allure description

@pytest.mark.allure_description_html: allure description html

@pytest.mark.filterwarnings(warning): add a warning filter to the given test. see http://docs.pytest.org/en/stable/warnings.html#pytest-mark-filterwarnings

@pytest.mark.skip(reason=None): skip the given test function with an optional reason. Example: skip(reason="no way of currently testing this") skips the test.

@pytest.mark.skipif(condition, ..., *, reason=...): skip the given test function if any of the conditions evaluate to True. Example: skipif(sys.platform == 'win32') skip s the test if we are on the win32 platform. See http://docs.pytest.org/en/stable/reference.html#pytest-mark-skipif

@pytest.mark.xfail(condition, ..., *, reason=..., run=True, raises=None, strict=xfail_strict): mark the test function as an expected failure if any of the conditions eva luate to True. Optionally specify a reason for better reporting and run=False if you don't even want to execute the test function. If only specific exception(s) are expe cted, you can list them in raises, and if the test fails in other ways, it will be reported as a true failure. See http://docs.pytest.org/en/stable/reference.html#pytes t-mark-xfail

@pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in different arguments in turn. argvalues generally needs to be a list of valu es if argnames specifies only one name or a list of tuples of values if argnames specifies multiple names. Example: @parametrize('arg1', [1,2]) would lead to two calls o f the decorated test function, one with arg1=1 and another with arg1=2.see http://docs.pytest.org/en/stable/parametrize.html for more info and examples.

@pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixtures. see http://docs.pytest.org/en/stable/fixture.html#usefix tures

@pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible.

@pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible.

```

三、註冊自定義marks

方式一:在pytest.ini中按照如下格式聲明即可,冒號之前為註冊的mark名稱,冒號之後為此mark的説明 bash [pytest] markers = smoke: smoke tests test: system tests 此時test_demo.py代碼如下 ```python import pytest

@pytest.mark.smoke def test_func(): assert 1==1

@pytest.mark.test def test_func2(): assert 1==1

def test_func3(): assert 1==1 使用pytest -m smoke執行結果如下,發現此時即只執行了標記為smoke的一個用例,這就是和自定義mark的使用方法bash $ pytest -m smoke ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 rootdir: D:\src\blog\tests, configfile: pytest.ini plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0 collected 3 items / 2 deselected / 1 selected

test_demo.py . [100%]

=================================================================== 1 passed, 2 deselected in 0.04s ====================================================================

方式二:在conftest.py文件中重寫pytest_configure函數即可,比如如下,註冊兩個mark:smoke和testpython def pytest_configure(config): config.addinivalue_line( "markers", "smoke: smoke test" ) config.addinivalue_line( "markers", "test: system test" ) test_demo.py代碼如下:python import pytest

@pytest.mark.smoke def test_func(): assert 1==1

@pytest.mark.test def test_func2(): assert 1==1

def test_func3(): assert 1==1 通過pytest -m test 執行結果如下:bash $ pytest -m test ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 rootdir: D:\src\blog\tests plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0 collected 3 items / 2 deselected / 1 selected

test_demo.py . [100%]

=================================================================== 1 passed, 2 deselected in 0.02s ====================================================================

```

四、對未註冊mark的限制

默認情況下,對未註冊mark直接使用是會產生一條告警信息,比如這裏把pytest.ini和conftest.py都刪除掉,只剩test_demo.py一個文件

test_demo.py代碼如下 ```python import pytest

@pytest.mark.smoke def test_func(): assert 1==1

@pytest.mark.test def test_func2(): assert 1==1

def test_func3(): assert 1==1 直接使用 pytest -m smoke 執行結果如下,可以發現這裏產生了兩條告警,這就是因為這兩條告警未在pytest.ini或者conftest.py中進行註冊的原因,在實際項目開發中如果在執行測試的時候發現了這種大片告警打印,解決辦法就是在pytest.ini或者conftest.py將這些告警報出的mark都進行註冊即可bash $ pytest -m smoke ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 rootdir: D:\src\blog\tests plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0 collected 3 items / 2 deselected / 1 selected

test_demo.py . [100%]

=========================================================================== warnings summary =========================================================================== test_demo.py:3 D:\src\blog\tests\test_demo.py:3: PytestUnknownMarkWarning: Unknown pytest.mark.smoke - is this a typo? You can register custom marks to avoid this warning - for deta ils, see http://docs.pytest.org/en/stable/mark.html @pytest.mark.smoke

test_demo.py:7 D:\src\blog\tests\test_demo.py:7: PytestUnknownMarkWarning: Unknown pytest.mark.test - is this a typo? You can register custom marks to avoid this warning - for detai ls, see http://docs.pytest.org/en/stable/mark.html @pytest.mark.test

-- Docs: http://docs.pytest.org/en/stable/warnings.html ============================================================= 1 passed, 2 deselected, 2 warnings in 0.02s ==============================================================

如果希望強制限制必須先註冊再使用mark,則可以在pytest.ini中加上如下配置即可bash [pytest] addopts = --strict-markers 比如test_demo.py代碼:python import pytest

@pytest.mark.smoke def test_func(): assert 1==1

@pytest.mark.test def test_func2(): assert 1==1

def test_func3(): assert 1==1 此時繼續使用pytest -m smoke執行結果如下,發現此時已經報錯了,即強制限制必須對mark進行註冊bash $ pytest -m smoke ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 rootdir: D:\src\blog\tests, configfile: pytest.ini plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0 collected 0 items / 1 error

================================================================================ ERRORS ================================================================================ __________ ERROR collecting test_demo.py _____________ 'smoke' not found in markers configuration option ======================================================================= short test summary info ======================================================================== ERROR test_demo.py !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! =========================================================================== 1 error in 0.14s ===========================================================================

```