环境安装:
pytest-html
pytest-xdist
pytest-ordering
pytest-rerunfailures
allure-pytest
requests
终端执行:pip install -r requirement.txt
1 发现用例
2 执行用例
3 结果判定
4 生成报告
pytest默认测试用例规则及基础应用
1 模块名必须以test_开头或者_test结尾
2 测试类必须以Test开头,并且不能带有init方法
3 测试用例必须以test_开头
执行:
1 使用命令执行
在终端 pytest
执行的参数:
-v -s 输出详细的调试信息;
-n=3 多线程运行(插件:pytest-xdist)多线程使执行时间缩短
-reruns num 失败重跑
–maxfail=2 出现多少次失败才终止
–html
-k 指定用例
2 使用主函数main方式执行
if name == ‘main’:
pytest.main([“-vs”])
3 通过全局配置文件pytest.ini文件执行
注意:一般放在项目的根目录下,名称必须时pytest.ini
编码格式为ANSI(如果报错则改)
pytest.ini 可以改变默认的测试用例规则
主函数命令行都会加载配置文件
测试用例前后置,固件
1 setup/teardown 在每个用例之前执行一次,每个用例都要执行的
2 setup_class/teardown_class 每个类执行之前之后
3 部分用例需要前置后置,使用fixture实现
@pytest.fixture()
1 scope:作用域 function class package/session
function :1 如果fixture有通过return和yield返回的值的话,那么可以把这个值传递到测试用例中,值通过固件名称传递
class: 手动调用的方式是在类的上面加上@pytest.mark.usefixture()
seesion:conftest.py
2 autouse:自动执行所有类里面的case
3 params:实现参数化
4 name:给fixture取别名,一旦使用别名,固件名称不能在使用
testcase.py
import time
import pytest
# 读取数据
def read_data():
return ["a","jack","ma"]
@pytest.fixture(scope="function",params=read_data(),name='db')
def exc_sql(request): # request固定写法用例接受参数
# print(request.param) #
print("查询sql")
yield request.param
print("关闭数据库!")
class Test:
@pytest.mark.skip(reason="no reason")
def test_test(self):
print("this is case1")
time.sleep(3)
def test_case2(self):
print("this is second case")
def test_case3(self,db):
print("third case2")
print("需要查询sql where"+db)
# raise Exception("this is a exception!")
def test_case4(self):
print("game over")
if __name__ == '__main__':
pytest.main()
run.py
import os
import time
import pytest
if __name__ == '__main__':
pytest.main()
time.sleep(3)
os.system("allure generate ./temp -o ./reports --clean")
import yaml
import os
currentfile_dir = os.path.dirname(__file__)
basedir = os.path.dirname(currentfile_dir)
testdata_path=os.path.join(basedir,'test_data/testdata.yaml')
print(testdata_path)
# 读取yaml
def read_yaml_file(file_path):
caselist=[]
with open(file_path,'r',encoding='utf-8') as f:
try:
data = yaml.load(f,Loader=yaml.FullLoader)
return data
except yaml.YAMLError as e:
print(f"Error reading YAML file: {e}")
# for i in data:
# caselist.append(i['name'],i['age'])
# return data
if __name__ == '__main__':
data_file = testdata_path
res = read_yaml_file(data_file)
for i in res:
print(i)
如果希望在另外一个py文件中调用需要结合conftest.py文件使用
conftest.py:专门用于存放fixture的配置文件,名称固定不变
在conftest.py文件里面所有的方法都不需要导包
conftest文件可以有多个,并且文件里面的多个fixture可以被一个用例使用
fixture的session级别最高
fixture的class
setupclass
setup
总结:
pytest执行run.py
if name == ‘main’:
pytest.main() 过程
1 查找当前目录下的conftest.py文件
2 查询当前目录下的pytest.ini 文件
3 查询用例目录下conftest.py文件
4 查询是否有setup和teardown
5 再根据pytest.ini文见中测试用例规则然后执行
数据驱动
parametrize()实现
@pytest.parametrize(args_name,args_value)
args_name: 参数名称,用于将参数值传递给函数
args_value: 参数值:(列表和字典列表,元组和字典元组)
有n个值 用例执行n次
如果有嵌套可以将参数名称直接拆开使用