前提:需要安装pytest和pytest-html(生成html测试报告)
pip install pytest
pip install pytest-html
安装成功展示:
1.命名规则
Pytest单元测试中的类名和方法名必须是以test开头,执行中只能找到test开头的类
和方法,比unittest 更加严谨
setup和teardown运行于测试方法的始末,即:运行一次测试函数会运行一次
setup_class和 teardown_class运行于测试方法的始末,但是不管有多少测试函数都只执行一次
案例:
import pytest
class TestClass:
def setup_class(self):
print('测试前执行一次')
def setup(self):
print('start')
def test01(self):
print('test01')
def test02(self):
print('test02')
def teardown(self):
print('end')
def teardown_class(self):
print('测试后执行一次')
if __name__ == '__main__':
pytest.main(['-s'])
2.Pytest生成自带的html测试报告
前提条件:需要下载pytest-html模块(python自带的生成测试报告模块)
pip install pytest-html
案例一:
pytest.main(“模块.py”)【运行指定模块下,运行所有test开头的类和测试用例】
pytest.main(["--html=./report.html","模块.py"])
案例二:
运行指定模块指定类指定用例,冒号分割,并生成测试报告
pytest.main([‘--html=./report.html’,‘模块.py::类名::用例名'])
案例三:
直接执行pytest.main() 【自动查找当前目录下,以test开头的文件或者以test结尾的py文件】
pytest.main([‘--html=./report.html’])
如果没有找到以test开头的文件或者以test结尾的py文件展示如下图:
pytest调用语句
pytst.main(['-x','--html=./report.html'])
-x出现一条测试用例失败就退出测试
-x出现一条测试用例失败就退出测试
-v: 丰富信息模式, 输出更详细的用例执行信息
-s:显示print内容
-q: 简化结果信息,不会显示每个用例的文件名
扩展:跳充
使用@pytest.mark.skip()跳过该用例(函数)
跳过test01用例展示:
3.pytest的运行方式
. 点号,表示用例通过
F 表示失败 Failure
E 表示用例中存在异常 Error
s 表示跳过用例
4.文件读取
读取csv文件
import csv #导入csv模块
class ReadCsv():
def read_csv(self):
item =[] #定义一个空列表
c = csv.reader