本文共 2028 字,大约阅读时间需要 6 分钟。
Pytest中的标记(mark)功能是一款强大的测试管理工具,它允许你为测试用例或测试类添加标签,从而实现测试分组和精确控制测试执行顺序。通过合理配置标签,你可以轻松实现只执行特定标签下的测试用例,或者同时执行多个标签的测试用例。
在Pytest中使用标记功能,可以按照以下步骤操作:
注册测试标签:通过修改pytest.ini配置文件,注册所需的测试标签名。例如,你可以在配置文件中添加以下内容:
[pytest]markers = [ "system_test:系统测试标签", "login_module: 登录模块标签"]
标注测试用例:在每个测试用例前面使用@pytest.mark.标签名注解,标注所需的测试标签。例如:
import pytestclass TestDemo01: @pytest.mark.system_test def test_case_01(self): print('执行TestDemo01 test_case_01') assert True @pytest.mark.login_module def test_case_02(self): print('执行TestDemo01 test_case_02') assert True执行测试时指定标签:在运行Pytest时,通过命令行参数指定要执行的测试标签。例如:
pytest -s -v -m "system_test or login_module"
or连接两个标签,表示同时执行两个标签下的测试用例。and连接两个标签,表示同时满足两个标签的测试用例才会执行。not关键字。为了更直观地理解标签分组执行的效果,我们可以创建以下测试用例:
test_demo_mark_01.py文件:
import pytestclass TestDemo01: @pytest.mark.system_test def test_case_01(self): print('执行TestDemo01 test_case_01') assert True @pytest.mark.login_module def test_case_02(self): print('执行TestDemo01 test_case_02') assert Truetest_demo_mark_02.py文件:
import pytestclass TestDemo02: @pytest.mark.login_module @pytest.mark.system_test def test_case_01(self): print('执行TestDemo02 test_case_01') assert True def test_case_02(self): print('执行TestDemo02 test_case_02') assert True通过观察,可以看出每个测试用例都标注了两个标签。当运行Pytest时,可以通过指定特定的标签组合来执行相应的测试用例。
在run_case.py文件中,你可以通过以下方式指定要执行的测试标签组合:
import pytest# 只执行system_test分组下的测试用例pytest.main(['-s', '-v', '-m', 'system_test'])# 执行system_test或login_module分组下的测试用例pytest.main(['-s', '-v', '-m', 'system_test or login_module'])# 同时执行system_test和login_module分组下的测试用例pytest.main(['-s', '-v', '-m', 'system_test and login_module'])# 排除login_module分组下的测试用例pytest.main(['-s', '-v', '-m', 'not login_module'])
通过这些命令,你可以灵活地控制测试用例的执行顺序和范围,从而实现精确的测试管理和执行。
Pytest的标记功能为测试管理提供了强大的工具。通过合理配置标签,你可以实现测试用例的分组执行、精确控制测试顺序以及灵活管理测试环境。只要熟练掌握这些功能,你就能显著提升测试效率,减少测试覆盖率的遗漏问题。希望这篇文章能为你提供实用的帮助!
转载地址:http://mnafk.baihongyu.com/