一、配置文件
1. pytest配置文件主要用于定位测试文件及测试类和方法,更便捷的执行测试;
配置文件只允许使用以下三个文件名称:
pytest.ini
tox.ini
setup.cfg
2. 配置文件内容
[pytest] ------------------------------表示该文件为pytest的配置文件
addopts = -s -v---------------------执行用例的参数
testpaths = ./scripts --------------执行用例的存放目录,表示当前文件目录下的scripts文件夹
python_files = test_*.py ---------测试文件名称类型的匹配
python_classes = Test* ----------测试类名称的匹配
python_functions = test_*--------测试方法名称的匹配
二、配置文件执行实例
1. 新建一个测试用例的py文件,文件名称为test_add_001.py,并将它放入文件夹scripts中,内容如下:
import time
def add(a,b):
return a + b
# 定义一个pytest类
class Test_add:
# 添加类级别的初始化操作方法
def setup_class(self):
print("测试类的开始执行时间:" + time.strftime("%Y-%M-%D %H:%M:S"))
# 添加类级别的销毁操作方法
def teardown_class(self):
print("测试类的结束执行时间:" + time.strftime("%Y-%M-%D %H:%M:S"))
# 添加方法级别的初始化用于打印该用例开始执行的时间
def setup(self):
print("测试用例的开始执行时间:" + time.strftime("%Y-%M-%D %H:%M:S"))
# 定义一个pytest方法
def test_add_001(self):
result = add(5,8)
print(result)
assert result == 13
def test_add_002(self):
result = add(105,9)
print(result)
# 添加方法级别的销毁用于打印该用例开始执行的时间
def teardown(self):
print("测试用例的执行结束时间:"+ time.strftime("%Y-%M-%D %H:%M:S"))
2. 在文件夹scripts的上级目录中新建一个与scripts平级的配置文件pytest.ini,内容如下
[pytest]
addopts = -s -v
testpaths = ./scripts
python_files = test_*.py
python_classes = Test*
python_functions = test_*
3. 执行测试用例
直接执行pytest命令即可执行相应测试用例