数据驱动
- 2021 年 5 月 31 日
- 筆記
- python编写测试框架
一、yaml数据驱动
1、目标
目标 掌握使用yaml进行数据驱动
2、定义数据文件
#TestLogin.yml
—
“case”: “test_login_1”
“url”: “authorizations”
“data”:
username: “python”
password: “12345678”
“expect”: “‘user_id’: 1, ‘username’: ‘python'”
—
“case”: “test_login_2”
“url”: “authorizations”
“data”:
username: “test123”
password: “test123”
“expect”: “无法使用提供的认证信息登录”
3、@pytest.mark.parametrize实现参数化
#登录 login_yml = “TestLogin.yml” data_path = Conf.get_data_path() filename = data_path+os.sep + login_yml #print(filename) def get_login_info(): return YamlReader(filename).data_all()
@pytest.mark.parametrize(“login”,get_login_info()) def test_1(login): url = login[“url”]data = login[“data”] print(“测试用例中login的返回值:%s%s” % (url, data)) #my_log().info(“test_1”) if __name__ == “__main__”: pytest.main([“-s”,”analysis_yaml_data.py”])
二、Excel数据驱动
1、Excel用例格式设计
直接使用功能测试 功能用例图片 分析并增加额外的测试项 分析接口测试需求 增加后的图片
2、读取Excel
(1)读取
#1、导入包,xlrd
import xlrd
#2、创建workbook对象
book = xlrd.open_workbook(“testdata.xlsx”)
#3、sheet对象
#索引
#sheet = book.sheet_by_index(0)
#名称
sheet = book.sheet_by_name(“美多商城接口测试”)
#4、获取行数和列数
rows = sheet.nrows #行数
cols = sheet.ncols #列数
#5、读取每行的内容
for r in range(rows):
r_values = sheet.row_values(r)
#print(r_values)
#6、读取每列的内容
for c in range(cols):
c_values = sheet.col_values(c)
#print(c_values)
#7、读取固定列的内容
print(sheet.cell(1,1))
(2)定义数据
class DataConfig:
#定义列属性
case_id = “用例ID”
case_model = “模块”
case_name = “接口名称”
url = “请求URL”
pre_exec = “前置条件”
method = “请求类型”
params_type = “请求参数类型”
params = “请求参数”
expect_result = “预期结果”
actual_result = “实际结果”
is_run = “是否运行”
headers = “headers”
cookies = “cookies”
code = “status_code”
db_verify = “数据库验证”
(3)封装Excel工具类
import os
import xlrd
#目的:参数化,pytest list
#自定义异常、
class SheetTypeError:
pass
#1、验证文件是否存在,存在读取,不存在报错
class ExcelReader:
def __init__(self,excel_file,sheet_by):
if os.path.exists(excel_file):
self.excel_file = excel_file
self.sheet_by = sheet_by
self._data=list()
else:
raise FileNotFoundError(“文件不存在”)
#2、读取sheet方式,名称,索引
def data(self):
#存在不读取,不存在读取
if not self._data:
workbook = xlrd.open_workbook(self.excel_file)
if type(self.sheet_by) not in [str,int]:
raise SheetTypeError(“请输入Int or Str”)
elif type(self.sheet_by) == int:
sheet = workbook.sheet_by_index(self.sheet_by)
elif type(self.sheet_by) == str:
sheet = workbook.sheet_by_name(self.sheet_by)
#3、读取sheet内容 #返回list,元素:字典
#格式[{“a”:”a1″,”b”:”b1″},{“a”:”a2″,”b”:”b2″}]
#1.获取首行的信息
title = sheet.row_values(0)
#2.遍历测试行,与首行组成dict,放在list
#1 循环,过滤首行,从1开始
for col in range(1,sheet.nrows):
col_value = sheet.row_values(col)
#2 与首组成字典,放list
self._data.append(dict(zip(title, col_value)))
#3、结果返回
return self._data
if __name__ == “__main__”:
reader = ExcelReader(“../data/testdata.xlsx”,”美多商城接口测试”)
print(reader.data())
(4)封装获取接口数据
class Data:
def __init__(self,filename):
self.reader = ExcelReader(filename).data
def get_run_data(self):
”””
获取运行用例,过滤is_run字段,只取yes
# run_list=[]
# for data in self.reader:
# if str(data[is_run]).lower()==”y”:
# run_list.append(data)
“””
is_run = data_config.is_run
#使用列表推导式:等同于上面注释代码
run_list=[data for data in self.reader if str(data[is_run]).lower()==”y”]
return run_list
(5)参数化运行
def run_list():
get_data = Data(data_config.case_file)
return get_data.get_run_data()
def run_api(url,method,data=None,json=None,headers=None,cookies=None):
request = RequestUtil.Request()
if str(method).lower()==”get”:
res = request.get(url, data=data,json=json,headers=headers,cookies=cookies)
elif str(method).lower() == “post”:
res = request.post(url, data=data,json=json,headers=headers,cookies=cookies)
else:
print(“错误请求method”)
return “-1”
return res
@pytest.mark.parametrize(“case”, run_list())
def test_run(case):
url = case[config.url]
method = case[config.method]
request_data = case[config.params]
expect = case[config.expect_result]
headers = case[config.headers]
cookies = case[config.cookies]
case_id = case[config.case_id]
case_name =case[config.case_name]
status_code = case[config.status]
params_type = case[config.params_type]
log.info(“运行用例名称:%s”%case_name)
if cookies:
cookie = json.loads(cookies)
else:
cookie = cookies
if headers:
header = json.loads(headers)
else:
header = headers
if str(params_type).lower() == “json”:
if len(str(request_data).strip()) is not 0:
request_data = json.loads(request_data)
res = run_api(url, method, json=request_data, headers=header, cookies=cookie)
else:
res = run_api(url, method, data=request_data, headers=header, cookies=cookie)
AssertUtil().assert_code(res[“status_code”], status_code)
AssertUtil().assert_in_body(str(res[“result”]),expect)