零基础小白 接口自动化测试集锦: https://www.jianshu.com/nb/49125734
Excel读写: 参考《Excel办公自动化》集锦分享 https://www.jianshu.com/nb/49019927
接口自动化Excel封装目的为了数据参数化,以pytest list文件形式读取
第1步:判断Excel文件是否存在
- 代码参考: 验证文件是否存在,存在读取,不存在报错
#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) # int型
elif type(self.sheet_by) == str:
sheet = workbook.sheet_by_name(self.sheet_by) # str型
第3步: 单元格属性值
先学习实例--参考下图Excel数据
- 读取可口可乐公司经理信息,代码参考
head = ["company","manager"]
value1 = ["可口可乐","Shirley"]
value2 = ["百事可乐","marry"]
print(dict(zip(head,value1)))
- 读取百事可乐公司经理信息,代码参考
head = ["company","manager"]
value1 = ["可口可乐","Shirley"]
value2 = ["百事可乐","marry"]
print(dict(zip(head,value2)))
- 读取两家公司经理信息,代码参考
head = ["company","manager"]
value1 = ["可口可乐","Shirley"]
value2 = ["百事可乐","marry"]
# # print(dict(zip(head,value1)))
# print(dict(zip(head,value2)))
data_list = list()
data_list.append(dict(zip(head,value1)))
data_list.append(dict(zip(head,value2)))
print(data_list)
封装获取sheet 单元格属性值
#3、sheet内容
# 返回list,元素:字典
#格式[{'company': '可口可乐', 'manager': 'Shirley'}, {'company': '北极光', 'manager': 'marry'}]
#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)))
#4、返回结果
return self._data
Excel封装整体代码参考
import os
import xlrd ,json
from config.Conf import ConfigYaml
from config import Conf
#目的:参数化,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) # int型
elif type(self.sheet_by) == str:
sheet = workbook.sheet_by_name(self.sheet_by) # str型
#3、sheet内容
# 返回list,元素:字典
#格式[{'company': '可口可乐', 'manager': 'Shirley'}, {'company': '北极光', 'manager': 'marry'}]
#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)))
#4、返回结果
return self._data
后续分享实战--Excel封装读取数据