pytest 学习笔记二:兼容unittest、执行方式、生成报告

1、官方文档上说pytest兼容unittest时,不支持setUpModule 和 tearDownModule,但实际验证是可以的。

验证的场景是py文件中,只有一个测试类,

经验证有多个测试类,使用pytest时,setUpModule 和 tearDownModule 也不生效。

所以不知道不支持的是什么场景?

2、生成html报告

安装pytest-html

 需要在cmd中执行命令:py.test test_class.py --html=./report.html

因为同时存在python2 和python3,所以如果用python2执行时,命令如下:

py -2 -m py.test test_class.py --html=./report.html 

当前目录生成report.html报告

 或者:pytest.main("-s xxx  --html=./report.html) 

注意: pytest.main("-s xxx  --html=./report.html)  加上 -s 时,控制台中会输出print内容,但是生成的html报告中不显示print内容。

           所以正式执行所有用例时,不要加上-s ,调试时可以加上。

3、执行用例的匹配原则

它默认使用检查以test_ *.py 或*_test.py命名的文件名,如果是类需要用Test开头,在文件内部查找以test_打头的方法或函数,并执行它们。

4、执行方式:

可以在cmd中通过命令执行,还有在main函数中执行:

 pytest.main("-s Electric_test.py")  执行某个文件
 pytest.main(" -s -v -m webtest")    执行某个用例 这个用例被标记为 webtest
@pytest.mark.webtest   #标记为webtest
def test_Electric_018(self):
pass

如果多个用例被标记为webtest,则执行所有被标记的。
或者: pytest.main("-s -v Electric_test.py::TestElectric::test_Electric_018")

5、main()中使用参数列表:

pytest.main()中参数为string时,执行后会有如下告警:
passing a string to pytest.main() is deprecated, pass a list of arguments instead.

消除告警方法:使用参数列表:
pytest.main(["-s","./testcase/WEB" ,"--html={x}".format(x=report)]) 
或者:
argv=[]
argv.append("-s")
argv.extend(['./testcase/WEB',"--html={x}".format(x=report)]) # extend() 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
pytest.main(argv)


6、


 
原文地址:https://www.cnblogs.com/who-care/p/8892122.html