pytest学习笔记
学习主要参考:
https://blog.csdn.net/lovedingd/article/details/98952868
https://www.cnblogs.com/shenh/p/11572657.html
https://www.cnblogs.com/sundawei7/p/11956618.html
安装:
2种方法:
1.
首先使用 pip 安装 pytest
pip3 install pytest
查看 pytest 是否安装成功
pip3 show pytest
2.
直接import pytest 在pycharm
然后Alt+enter进行install
比第一种方法快捷
使用 pytest 执行测试需要遵行的规则:
-
.py 测试文件必须以test_开头(或者以_test结尾)
-
测试类必须以Test开头,并且不能有 init 方法
-
测试方法必须以test_开头
-
断言必须使用 assert
试验:
import pytest # 引入pytest包
class Test_sample1:
def test_case1(self):
print("------->test case 1 ")
assert 1
def test_case2(self):
print("-------->test case 2 ")
assert 1
if __name__ == '__main__':
pytest.main("-s test_sample.py") # 调用pytest的main函数执行测试
报错:
TypeError: `args` parameter expected to be a list of strings, got: '-s test_sample.py' (type: <class 'str'>)
因需在pytest.main参数里传入list,所以修改为:
pytest.main(["-s","test_sample.py"])
学习pyetst.ini配置文件
创建pyetst.ini:
[pytest]
# 命令行参数
addopts = -s
#搜索路径
testpaths = ./Test
# 搜索文件名
python_files = test_*.py
# 搜索的类名
python_classes = Test_*
#搜索的函数名
python_functions = test_*
学习Pytest测试报告
pytest-HTML是一个插件,pytest用于生成测试结果的HTML报告。兼容Python 2.7,3.6
安装方式:pip install pytest-html
PS:要先安装,不然下面运行会报错
通过命令行方式,生成xml/html格式的测试报告,存储于用户指定路径。插件名称:pytest-html
使用方法: 命令行格式:pytest --html=用户路径/report.html
运行方式:
1.修改Test_App/pytest.ini文件,添加报告参数,
即:addopts = -s --html=./report.html
# -s:输出程序运行信息
# --html=./report.html 在当前目录下生成report.html文件 ️
若要生成xml文件,可将--html=./report.html 改成 --html=./report.xml
上面pyetst.ini 文件修改为:
[pytest]
addopts = -s --html=./report.html
python_files = test_*.py
python_classes = Test_*
python_functions = test_*
运行后产生report.html文件:
![]()


浙公网安备 33010602011771号