读excel测试用例;登录;做pytest 请求
1.从excel中读数据 返回【{字典}{字典}】;当传参数时,可以获得对应单元格内容
import xlrd import json from configs.configs import HOST from utils.md5 import get_md5 # 在创建excel时,将登录接口的返回结果 粘贴到excel时需要 “只粘贴文本” # 将excel 实例化 def get_excel_data(*keys): excel_data=[]# [{值},{值}] wookbook=xlrd.open_workbook('D:/python-pro/py0803/data/test_case.xls') # 通过名字读取sheet值 sheet=wookbook.sheet_by_name('Sheet1') # 获得标题存在header中 header = sheet.row_values(0) # 获得列表的总数 nrows=sheet.nrows # print(nrows)#3 # 循环读取每行的数据 for i in range(1,nrows): # 打印每行读取的数据 #将行和类放到字典中 data_dict=dict(zip(sheet.row_values(0),sheet.row_values(i))) # 将包含\n换行符的字符串做处理 for key in data_dict: value=data_dict[key] if isinstance(value,str): data_dict[key]=value.replace('\n','').replace("\\",'') # 定义一个存放传入参数key对应的value的列表 保存value值 row_data = {} for key in keys: if key in header: if key == 'url': row_data[key]=f"{HOST}{data_dict['url']}" elif key == 'body': temp = eval(data_dict['body']) temp['password']=get_md5(temp['password']) row_data[key]=temp else: row_data[key]=data_dict[key] excel_data.append(row_data) return excel_data if __name__ == '__main__': d=get_excel_data("expect") dd=eval(d[0]['expect'])['msg'] print(dd)
2.设置登录的HOST配置文件
# D:\python-pro\py0803\configs\configs.py # configs包中的config.py # 配置模块 HOST='http://'
3.发送登录请求
# D:\python-pro\py0803\libs\login.py # md5 加密 import json import requests from utils.read_excel import get_excel_data def get_login(method,url,data): resp=getattr(requests,method.lower())(url,data) resp_dic=eval(resp.text.replace('false', 'False')) # 从字符转字典 return resp_dic if __name__ == '__main__': for one in get_excel_data("method","url","body"): d=get_login(one['method'],one['url'],one['body']) print(d["msg"])
4.pytest 做比较
# D:\python-pro\py0803\libs\login.py # 比较 请求的结果和 excel中预期的结果 import pytest from libs.login import get_login from utils.read_excel import get_excel_data @pytest.mark.parametrize('method,url,body,expect', get_excel_data("method","url","body","expect")) def test_real_exp(method,url,body,expect): for one in get_excel_data("method","url","body","expect"): real = get_login(one[method],one[url],one[body])["msg"] exp = eval(one[expect])['msg'] assert real == exp
5.