一、使用方法
- 注册标签名
- 在测试用例/测试类前面加上:
@pytest.mark.标签名
打标记范围:测试用例、测试类、模块文件
二、注册方式
方式1、单个标签:
在conftest.py
添加如下代码:
def pytest_configure(config):
# demo是标签名
config.addinivalue_line("markers", "demo:示例运行")
方式2、多个标签:
在conftest.py
添加如下代码:
def pytest_configure(config):
marker_list = ["testdemo", "demo", "smoke"] # 标签名集合
for markers in marker_list:
config.addinivalue_line("markers", markers)
方式3、添加pytest.ini
配置文件(在你项目的任意一个文件下,新建一个file
,文件命名为pytest.ini
)
[pytest]
markers=
smoke:this is a smoke tag
demo:demo
testdemo:testdemo
三、使用方法
import pytest
@pytest.mark.testdemo
def test_demo01():
print("函数级别的test_demo01")
@pytest.mark.smoke
def test_demo02():
print("函数级别的test_demo02")
@pytest.mark.demo
class TestDemo:
def test_demo01(self):
print("test_demo01")
def test_demo02(self):
print("test_demo02")
四、运行方式
1、命令行模式
通过标记表达式执行
pytest -m demo
这条命令会执行被装饰器@pytest.mark.demo装饰的所有测试用例
生成html报告:
pytest -m demo --html=Report/report.html
生成xml报告:
pytest -m demo --junitxml=Report/report.xml
运行指定模块:
pytest -m demo --html=Report/report.html TestCases/test_pytest.py
运行指定测试目录
pytest -m demo --html=Report/report.html TestCases/
通过节点id来运行:
pytest TestCases/test_pytest.py::TestDemo::test_demo01
通过关键字表达式过滤执行
pytest -k "MyClass and not method"
这条命令会匹配文件名、类名、方法名匹配表达式的用例
获取用例执行性能数据
获取最慢的10个用例的执行耗时
pytest --durations=10
2、新建run.py
文件运行,代码如下:
pytest.main(["-m","demo","--html=Report/report.html"])
五、注意事项
使用以下代码对进行标记时候未起作用。
if __name__ == "__main__":
pytest.main(["-m", "demo"])
原因:
1、Pycharm运行导入unittest框架时,执行的的命令是“Run ‘Unittests in XXX’ ”,如下图所示:
2、此时执行顺序为:Class->def setup ->def test_1 ->def tearDown
3、如果执行的命令为“Run XXX”,那么会先执行class后,就执行“if name == ‘main’ ”
4、在代码“"if name == ‘main’ ”区域,右击“run xxx”即可,具体步骤参考第二个链接(有用的解决方案)
4.1 首先删除Pycharm该文件的配置,pychrm-“run”-“Edit Configurations”-"Python tests"下删除该文件的配置信息,再点击“if name == ‘main’ ”旁边的三角按钮,鼠标移到Run…就可以看到两个运行方式了
先用Run XXX方式运行下,然后到pychrm-“run”-“Edit Configurations”-"Python tests"下点击保存按钮,保存该配置