通过使用pytest.markhelper您可以轻松地在测试函数上设置元数据。也就是说, 通过@pytest.mark能够控制需要执行满足哪些特征的测试 ,例如在执行test前增加修饰@pytest.mark.website。
标记mark只能用于测试,对fixture没有影响。有关fixture的作用,下篇中再介绍。
一些内置的mark
注册mark
您可以在pytest.ini文件像这样的文件:
[pytest] markers=slow:标识测试速度极慢的那些测试
或者在你的pyproject.toml项目像这样表达:
在未知标记上引发错误
未注册的标记(例如 @pytest.mark.name_of_the_mark的修饰器)将始终发出警告,以避免由于键入错误的名称而默默地做一些令人惊讶的事情。 When the --strict-markers command-line flag is passed, any unknown marks applied with the @pytest.mark.name_of_the_mark decorator will trigger an error. You can enforce this validation in your project by adding --strict-markers to addopts:
举例
然后,可以将测试运行限制为仅运行标有webtest的测试:
pytest -v -m webtest
测试结果如下:
或者反过来,还可以运行除webtest之外的所有测试:
pytest -v -m "not webtest"
小结1
注意到上面的“selected”了吗?在Pytest中,借助mark可以筛选要测试的部分测试,从而加速测试工作。
标记整个类或模块¶
你可以用pytest.mark带类的装饰器将标记应用于其所有测试方法:
有兴趣的朋友可以参考引文中内容作更系列全面学习。
引用
https://docs.pytest.org/en/stable/example/markers.html#mark-examples
查看更多关于pytest用法之使用mark对测试方法分类的详细内容...