python+requests做接口测试使用第三方库xlrd/xlwt读取和写入Excel(数据代码分离)

一、用代码做接口测试需要保存返回的数据(我使用Excel),为了不手动复制返回结果,所以有了以下的折腾,记录一下作为笔记

  1、把入参、接口用例写在Excel里,使用代码读取入参,保存到一个新的列表里,方便发送请求,发送请求时用代码读取列表里对应的参数;

  2、然后,把返回的参数保存到一个列表,再从列表里for循环遍历列表,把参数写入到复制好的Excel里

  3、保存文件,保存为与原文件相同的文件名,会自动覆盖原文件,就相当于间接实现修改一个Excel的数据

  如下代码:

# 导入相关模块,requests用于发送接口请求、xlrd用于读取Excel数据、xlutils的copy用于复制Excel、datetime用于打印当前时间
import requests
import xlrd
from xlutils import copy
import datetime

# 访问地址
url = "http://192.168.6.25:8772/qRCRList"

class Read_Write_excel(object):
    # 读取方法
    # path_excel是Excel的本地路径,read_start_hang是读取的开始行,rend_end_hang是读取的结束行,至于列,写死了
    def read_excel(self,path_excel,read_start_hang,rend_end_hang):
        # 打开目标文件
        ecl = xlrd.open_workbook(path_excel)
        # 定位sheet表
        table = ecl.sheet_by_name('sheet')
        # 创建一个列表,把读取到的参数保存到空列表里
        self.parm_list_new = []

        # 获取第三列某些行的数据
        for i in range(read_start_hang, rend_end_hang):  # 相当于 read_start_hang <= i < read_end_hang
            i3 = table.cell_value(i, 2)  # 第i行第3列的数据
            self.parm_list_new.append(i3)  # 把获取的数据加入新建的列表里
        print('打印输入参数列表:', self.parm_list_new, '
' * 2)

    # 访问方法
    def get_url(self,URL_fangwen_type,url_path):
        xuh = 1
        # 把返回的数据先保存进fanhui_parm_type列表
        self.fanhui_parm_list = []

        if URL_fangwen_type == 'get':
        # 循环把读取到的参数访问接口
        # get请求
            for parm in self.parm_list_new:
                r = requests.get(url_path, params=eval(parm))# 带参数访问URL,eval()用于去掉参数两侧的引号
                print("==============================")
                self.fanhui_parm_list.append(r.text)# 把返回结果添加到列表
                print('test_%d返回的参数' % xuh, r.text, '
')
                xuh += 1

        # post请求的form格式
        if URL_fangwen_type == 'post':
            for parm in self.parm_list_new:
                r = requests.post(url_path, data=eval(parm))# 带参数访问URL,eval()用于去掉参数两侧的引号
                self.fanhui_parm_list.append(r.text)# 把返回结果添加到列表
                print('test_%d返回的参数' % xuh, r.text, '
')
                xuh += 1

        # post请求的json格式
        if URL_fangwen_type == 'json':
            for parm in self.parm_list_new:
                r = requests.post(url_path,json=eval(parm))
                self.fanhui_parm_list.append(r.text)
                print('test_%d'%xuh,r.text,'
')
                xuh += 1

        print('返回列表',self.fanhui_parm_list)

    # 复制原表,把返回的参数写入复制好的Excel表格
    def write_excel(self,cp_excel_path,write_hang_no):

        # 使用xlrd打开Excel
        excel_open_file = xlrd.open_workbook(cp_excel_path)

        # 复制Excel并保留原格式
        self.ex_open_file_cp = copy.copy(excel_open_file)

        # 定位到表格
        cp_sheet = self.ex_open_file_cp.get_sheet(0)
        # 使用循环把返回结果写入Excel表格
        for i in self.fanhui_parm_list:
            if len(i) > 32767:
                cp_sheet.write(write_hang_no,3,'字符串长度超出32767会报错')
                continue
            cp_sheet.write(write_hang_no, 3, str(i))# 把对应的结果写入Excel
            cp_sheet.write(write_hang_no,4,str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))# 在第四列对应的行写入当前时间,写入Excel需要转成字符串否则时间会变成一串数字(时间戳)
            write_hang_no += 1
        print('写入成功!!')

    # 保存Excel方法
    def baocun_excel(self,baocun_filename):
        # 保存新的表格名字为test_tuihuo_api
        self.ex_open_file_cp.save(baocun_filename)
        print('保存新表格 %s 成功'%baocun_filename)

if __name__ == '__main__':
    # 创建一个读Excel类
    ceshi = Read_Write_excel()
    # 读取指定路径的Excel表格参数(读取当前文件 复件.xls 表格的第2到21行的第3列数据-写死的第三列)
    ceshi.read_excel('复件.xls',2,5)# 2 <= i < 21
    # for循环遍历读取并保存到列表的参数,使用参数访问接口地址
    ceshi.get_url('get',url)
    # 把返回的数据列表的数据用for循环写入 复件.xls 文件的第三列
    ceshi.write_excel('复件.xls',2)
    # 保存文件
    ceshi.baocun_excel('复件.xls')

 对应调用以上代码的另一个文件的代码:

import tianlanyiguanjiekou

class Test_API(object):

    def test_api(self,read_excel_path,start_hang,end_hang,URL_fangwen_type,fangwen_url,cp_file_path,write_start_hang):

        self.a = tianlanyiguanjiekou.Read_Write_excel()
        self.a.read_excel(read_excel_path,start_hang,end_hang)
        self.a.get_url(URL_fangwen_type,fangwen_url)
        self.a.write_excel(cp_file_path,write_start_hang)
        self.a.fanhui_parm_list.clear()
        # print('清空后的列表',self.a.fanhui_parm_list)
        # self.a.baocun_excel(baocun_filename)

    def baocun_excel_api(self,baocun_filename):
        self.a.baocun_excel(baocun_filename)


if __name__ == '__main__':

    read_excel_path = "E:\测试相关文档\接口测试用例及执行情况记录\宜关天兰退货及订单详情接口用例执行.xlsx"
    cp_excel_path = '退货及订单详情接口.xls'
    url = ['http://192.168.6.25:8772/queryRefundCommodityRecordList',http://192.168.6.25:8772/applyRefundRecordPc','http://192.168.6.25:8772/updateRefundRecordListPc']
    start_end_hang = [(2,21),(23,37),(39,45),(47,52),(54,62),(64,68),(70,82),(84,94),(96,101)]
    get,post = 'get','post'
    write_start_hang = 2
    a = Test_API()
    # 第一个
    # a.test_api(read_excel_path,start_end_hang[0][0],start_end_hang[0][1],get,url[0],cp_excel_path,start_end_hang[0][0])
    a.baocun_excel_api('退货及订单详情接口.xls')
    # a.test_api(read_excel_path,start_end_hang[8][0],start_end_hang[8][1],'json',url,cp_excel_path,start_end_hang[8][0])
    # 多个接口参数同时执行
'''    for i in range(len(start_end_hang)):
        if i == 0 or 2 <= i <= 4:
            a.test_api(read_excel_path, start_end_hang[i][0], start_end_hang[i][1], get,url[i], cp_excel_path,start_end_hang[i][0])
            a.baocun_excel_api('退货及订单详情接口.xls')

        if i == 1 or i >= 5:
            a.test_api(read_excel_path, start_end_hang[i][0], start_end_hang[i][1], post, url[i], cp_excel_path,start_end_hang[i][0])
            a.baocun_excel_api('退货及订单详情接口.xls')

        if i >= 7:
            a.test_api(read_excel_path,start_end_hang[i][0],start_end_hang[i][1],'json',url[i],cp_excel_path,start_end_hang[i][0])
            a.baocun_excel_api('退货及订单详情接口.xls')'''

    # 保存到Excel
    # a.baocun_excel_api('退货及订单详情接口.xls')

 调用文件的代码是直接复制过来的,有不符合的地方,参考即可

原文地址:https://www.cnblogs.com/will-wu/p/14668423.html