python之使用openpyxl从excel读取测试数据004

from tools.http_request import HttpRequest
import json

test_data = [{"header":{"User-Agent": "Chrome/75.0.3770.100","Content-Type": "application/json;charset=UTF-8"},
             "url" : "http://xxx/futureloan/member/login","data" :{"mobile_phone": "186025xx31", "pwd": "12345xxx8"},"title":"正常登录"},
{"header":{ "User-Agent": "Chrome/75.0.3770.100","Content-Type": "application/json;charset=UTF-8"},
             "url" : "http://xxx/futureloan/member/login","data" :{"mobile_phone": "1860251xx31", "pwd": "123456789"},"title":"密码错误登录"}
            ]
def run(test_data):#传入列表嵌套字典的数据格式
    for item in test_data:#循环执行用例
        print("正在测试的用例标题:{0}".format(item["title"]))
        res = HttpRequest().http_request("post", item["url"], item["header"], json.dumps(item["data"]))
        print("测试结果是:{0}".format(res.json()))

if __name__ == '__main__':
    run(test_data)

以上代码实现以列表嵌套字典的形式传入测试数据,运行结果:

如果测试数据很多的话,以上方法就不可取了。可以预先将测试数据写入excel,再专门写一个excel数据处理模块,代码如下:

from openpyxl import load_workbook

class DoExcel:
    def get_data(self,file_name,sheet_name):
        wb = load_workbook(file_name)
        sheet = wb[sheet_name]

        test_data = []#存放所有测试数据
        for i in  range(2,sheet.max_row+1):#第一行为标题,不获取
            row_data = {}#存放每行测试数据
            row_data['case_id'] = sheet.cell(i, 1).value  # i为行号
            row_data['module'] = sheet.cell(i, 2).value
            row_data['title'] = sheet.cell(i, 3).value
            row_data['method'] = sheet.cell(i, 4).value
            row_data['url'] = sheet.cell(i, 5).value
            row_data['data'] = sheet.cell(i, 8).value
            row_data['header'] = sheet.cell(i, 7).value
            test_data.append(row_data)#每行测试数据添加进列表
        return test_data

if __name__ == '__main__':
    test_data = DoExcel().get_data("D:\autopythonAPI_AUTO_TRAIN\test_data\test_case_futureloan.xlsx","login_case")
    print(test_data)

第一段代码就可以直接通过上面DoExcel类来获取想要的测试数据,代码可以优化为:

from tools.http_request import HttpRequest
import json
from tools.do_excel import DoExcel #引用DoExcel模块

def run(test_data):#传入列表嵌套字典的数据格式
    for item in test_data:#循环执行用例
        print("正在测试的用例标题:{0}".format(item["title"]))
        res = HttpRequest().http_request(item["method"], item["url"],json.loads(item["header"]), item["data"])
        print("测试结果是:{0}".format(res.json()))

if __name__ == '__main__':
    test_data = DoExcel().get_data("D:\autopythonAPI_AUTO_TRAIN\test_data\test_case_futureloan.xlsx","login_case")
    run(test_data)

#json.loads(item["header"])  或者eval(item["header"]) str转json
#不然会报错:'str' object has no attribute 'items'
#意思是说str类型没有items属性,items属性是字典的属性。
#此处是因为headers本应为dict,实际传入了str
原文地址:https://www.cnblogs.com/july-1016/p/14078860.html