对比可以发现,test_3 执行前,先执行了conftest中的代码 4.markpytest支持自定义一些标签,在执行脚本的时候,执行指定某些标签或者非某些标签的用例
首先查看pytest 自带的markers
pytest --markers@pytest.mark.no_cover: disable coverage for this test.@pytest.mark.run: specify ordering information for when tests should run in relation to one another. Provided by pytest-ordering. See also: http://pytest-ordering.readthedocs.org/@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.parametrize(argnames, argvalues): call a test function multiple times passing in different arguments in turn. @pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixtures. see https://docs.pytest.org/en/latest/fixture.html#usefixtures@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.可以看到之前提到的一些,如:
参数化用的@pytest.mark.parametrizefixture用的@pytest.mark.usefixtures失败重跑用的@pytest.mark.flaky(reruns=1, reruns_delay=0)等等我们可以自定义写mark
新增pytest.ini,内容如下:
[pytest]markers= P0: level P0 P1: level p1 P2: level p2 dong: testcase created by dong mandy: testcase created by mandy cm: testcase about cm pd: testcase about pd再次执行
pytest --markers@pytest.mark.P0: level P0@pytest.mark.P1: level p1@pytest.mark.P2: level p2@pytest.mark.dong: testcase created by dong@pytest.mark.mandy: testcase created by mandy@pytest.mark.cm: testcase about cm@pytest.mark.pd: testcase about pd@pytest.mark.no_cover: disable coverage for this test.@pytest.mark.run: specify ordering information for when tests should run in relation to one another. Provided by pytest-ordering. See also: http://pytest-ordering.readthedocs.org/@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....之前自定义的标签,已经加入了
那么如何使用这些标签呢?
import pytest@pytest.mark.dong@pytest.mark.P1@pytest.mark.cmclass Test1(object): def test_1(self): print("this is test1") assert 1==1 @pytest.mark.P0 def test_2(selfs): print("this is test2") assert 1+2 ==3@pytest.mark.mandy@pytest.mark.P0class Test2(object): def test_3(self): print("this is test3") assert 3+1 ==4可以看到在脚本中加上了我们自定义的标签,如果向指定执行部分标签的用例执行方法:
pytest -sq -m "P0" demo_mark.py ---仅执行P0级的用例结果如下,和预期的一致,仅运行P0级的用例
P0
同时也支持一些逻辑
pytest -sq -m "P0 and cm" demo_mark.py ---运行cm模块的P0级用例预期结果:仅运行 test_2