晒酷学院:https://shareku.ke.qq.com/
微信号:添加请注明晒酷学院 QQ群:979438600
Pytest的setup和teardown函数
1.setup和teardown主要分为:模块级,类级,功能级,函数级。
2.存在于测试类内部
函数级别setup()/teardown()
运行于测试方法的始末,即:运行一次测试函数会运行一次setup和teardown
import pytest
class Test_ABC:
# 函数级开始
def setup(self):
print("------->setup_method")
# 函数级结束
def teardown(self):
print("------->teardown_method")
def test_a(self):
print("------->test_a")
assert 1
def test_b(self):
print("------->test_b")
if __name__ == '__main__':
pytest.main("[-s test_abc.py"])
类级别:
运行于测试类的始末,即:在一个测试内只运行一次setup_class和teardown_class,不关心测试类内有多少个测试函数。
import pytest
class Test_ABC:
# 测试类级开始
def setup_class(self):
print("------->setup_class")
# 测试类级结束
def teardown_class(self):
print("------->teardown_class")
def test_a(self):
print("------->test_a")
assert 1
def test_b(self):
print("------->test_b")
if __name__ == '__main__':
pytest.main(["-s","test_abc.py"])
Pytest配置文件
pytest的配置文件通常放在测试目录下,名称为pytest.ini,命令行运行时会使用该配置文件中的配置.
#配置pytest命令行运行参数
[pytest]
addopts = -s ... # 空格分隔,可添加多个命令行参数 -所有参数均为插件包的参数配置测试搜索的路径
testpaths = ./scripts # 当前目录下的scripts文件夹 -可自定义
#配置测试搜索的文件名称
python_files = test*.py
#当前目录下的scripts文件夹下,以test开头,以.py结尾的所有文件 -可自定义
配置测试搜索的测试类名
python_classes = Test_*
#当前目录下的scripts文件夹下,以test开头,以.py结尾的所有文件中,以Test开头的类 -可自定义
配置测试搜索的测试函数名
python_functions = test_*
#当前目录下的scripts文件夹下,以test开头,以.py结尾的所有文件中,以Test开头的类内,以test_开头的方法 -可自定义
Pytest常用插件
插件列表网址:https://plugincompat.herokuapp.com/
包含很多插件包,大家可依据工作的需求选择使用。
1.前置条件:
文件路径:
-Test_App<br>- - test_abc.py
- - pytest.ini
pyetst.ini配置文件内容:
[pytest]
# 命令行参数
addopts = -s
# 搜索文件名
python_files = test_*.py
# 搜索的类名
python_classes = Test_*
#搜索的函数名
python_functions = test_*
2.Pytest测试报告
pytest-HTML是一个插件,pytest用于生成测试结果的HTML报告。兼容Python 2.7,3.6
安装方式:pip install pytest-html
pip install pytest-html
通过命令行方式,生成xml/html格式的测试报告,存储于用户指定路径。插件名称:pytest-html
使用方法: 命令行格式:pytest --html=用户路径/report.html
import pytest
class Test_ABC:
def setup_class(self):
print("------->setup_class")
def teardown_class(self):
print("------->teardown_class")
def test_a(self):
print("------->test_a")
assert 1
def test_b(self):
print("------->test_b")
assert 0 # 断言失败```
运行方式:
1.修改Test——App/pytest.ini文件,添加报告参数,即:addopts = -s --html=./report.html
# -s:输出程序运行信息
# --html=./report.html 在当前目录下生成report.html文件
️ 若要生成xml文件,可将--html=./report.html 改成 --html=./report.xml
2.命令行进入Test_App目录
3.执行命令: pytest
执行结果:
1.在当前目录会生成assets文件夹和report.html文件
import pytest
class Test_ABC:
def setup_class(self):
print("------->setup_class")
def teardown_class(self):
print("------->teardown_class")
def test_a(self):
print("------->test_a")
assert 1
def test_b(self):
print("------->test_b")
assert 0