前言

在进行测试时,可能大部分的用例都是先用excel完成,再进行导入用例管理平台的,那么在做接口自动化测试的过程中,如果要读取excel中的数据话,需要通过函数去获取excel中的数据

一、读取excel中的数据

需要读取的excel:
在这里插入图片描述

读取excel的方法:

from openpyxl import load_workbook

class ExcelUtil(object):

    def __init__(self, excel_path):
        self.wb = load_workbook(excel_path)
        # 这个是写入用例的模板
        self.template = """{"id":0,"url":"","title":"","header":"","method":"","body":"",
        "expect":"","actual":""},"""


    def read_excel(self):
        """读取excel,处理数据,并返回处理后的字典格式"""
        case = []
        for sheetname in self.wb.sheetnames:
            ws = self.wb[sheetname]
            # 一个sheet中用例的数量
            cases_num = len(list(ws.values)) - 1
            case_list = list(ws.values)
            # 去掉表头
            case_list.pop(0)
            cases_template = self.template * cases_num
            # 与用例相同长度的模板
            cases_template_list = cases_template[:-1]
            #将字符串类型转换成字典格式
            new_case_list = eval(cases_template_list)
            #print(new_case_list)
            # i:第i个用例
            for i in range(len(case_list)):
                # 每个用例中字段是8个
                new_case_list['id'] = case_list[i][0]
                new_case_list['url'] = case_list[i][1]
                new_case_list['title'] = case_list[i][2]
                new_case_list['header'] = case_list[i][3]
                new_case_list['method'] = case_list[i][4]
                new_case_list['body'] = case_list[i][5]
                new_case_list['expect'] = case_list[i][6]
                new_case_list['actual'] = case_list[i][7]

            case.append({"cases": new_case_list})

        return case

if __name__ == '__main__':
    ob = ExcelUtil("panpan.xlsx").read_excel()
    print(ob)

输出结果:

[{'cases': {'id': 1, 'url': '/api/login', 'title': '登录成功', 'header': None, 'method': 'post', 'body': '{"user":panpan,"admin":1234}', 'expect': 'sucess', 'actual': 'sucess'}}]

二、读取excel中的数据使用

    ob = ExcelUtil("panpan.xlsx").read_excel()
    print(ob)
    for i in ob:
        url = i["cases"]["url"]
        param = i["cases"]["data"]
        r = requests.post(url,json=param)
        print(r.json())

解析:将读取到的数据提取,作为参数传入调用的接口中

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐