操作Excel
1
END
![7b4b1241d10b31ae0cf6ae4a88eea782.gif](https://img-blog.csdnimg.cn/img_convert/7b4b1241d10b31ae0cf6ae4a88eea782.gif)
前言
在进行接口自动化测试的过程中,一个无法避免的问题就是:参数化。在利用Python进行接口自动化测试的时候,一般会选择Excel来做测试数据的管理,可以利用openpyxl、xrld或者是xlwt开源包对Excel中的数据进行操作。
在common包中创建operate_excel.py文件,对Excel中的数据进行操作(包括读取,写入以及保存)的方法进行封装,提高代码的通用性。
2说明通过官网中的官方文档,可以查看到如何使用Python读取Excel中的数据,http://www.python-excel.org/
环境:python 3.7
安装:pip install xrld
3流程操作Excel的数据流程,和平常手动去操作Excel是一样的,打开工作簿(Workbook)、选择工作表(sheets)、操作单元格(cell)、保存数据(save)、关闭文件(close)。
4编写operate_excel.py
# -*- coding: utf-8 -*-"""# @Time : 2020/7/23 15:16# @Author : tjc# @File : operate_excel.py"""import xlrdimport xlwtfrom xlutils.copy import copyclass OperateExcel(object): """初始化数据""" def __init__(self, file_name, sheet_name): self.workbook = None self.file_name = file_name self.sheet_name = sheet_name def read_data(self): """ 读取表格中的数据 """ test_data = [] workbook = xlrd.open_workbook(self.file_name) # 打开excel sheet = workbook.sheet_by_name(self.sheet_name) # 获取工作簿 header = sheet.row_values(0) # 获取标题行数据 for i in range(1, sheet.nrows): # 跳过标题行,从第二行开始取数据 d = dict(zip(header, sheet.row_values(i))) # 将标题和每行数据组装成字典 test_data.append(d) return test_data # 列表嵌套字典格式,每个元素是一个字典 def get_data(self, data_list, title): """获取测试需要的数据""" for case_data in data_list: if title == case_data['title']: # 如果字典数据中case_name与参数一致 return case_data # 如果查询不到会返回None def write_data(self, row, actual, response_time, result): """写入测试结果数据""" workbook = xlwt.Workbook(self.file_name) copy_workbook = copy(workbook) #复制一份表格,避免污染原始数据 sheet1 = copy_workbook.get_sheet(0) sheet1.write(row, 10, actual) sheet1.write(row, 11, response_time) sheet1.write(row, 12, result) copy_workbook.save('D://testdata1.xlsx') self.close_file() def close_file(self): """关闭并保存文件""" self.workbook.save(self.file_name) self.workbook.close()"""测试"""if __name__ == '__main__': Excel = OperateExcel(contains.test_data, "coupon") all_data = Excel.read_data() # 读取excel,testdata工作簿的所有数据 case_data = Excel.get_data(all_data, '编辑优惠券') # 查找用例的数据 Excel.write_data(2, 100, 100, 100) print(all_data) print(case_data['data']) print(case_data['url'])
5数据
存放Excel中的测试数据模板,actual列中写入实际测试接口返回的信息,result列中写入接口响应的状态码,response_time列中写入接口响应的时间。
![1938a19f6b425d35a3cca519495441f0.gif](https://img-blog.csdnimg.cn/img_convert/1938a19f6b425d35a3cca519495441f0.gif)
![568a866fd1b581a17b631931c6034643.gif](https://img-blog.csdnimg.cn/img_convert/568a866fd1b581a17b631931c6034643.gif)