流程介绍:
1.读取excel中的用例
2.判断内容,进行发送请求
3.拿到相应,和Excel中的结果进行比较
4.把结果写入Excel中
话不多说直接看代码,需要交流的 vx:RUN_IT_LOCAL
conf.py
# 主要进行配置路径和cookies
Data_Path = r"C:\Users\admin\Desktop\api_test.xls"
Cookies = ""
excel_read_write.py
import json
import xlrd
from xlutils.copy import copy
from conf import *
class ExcelData():
# 初始化方法
def __init__(self):
#定义一个属性接收文件路径
self.data_path = Data_Path
# 使用xlrd模块打开excel表读取
self.workbook = xlrd.open_workbook(self.data_path)
# 根据工作表的名称获取工作表中的内容
# self.table = self.data.sheet_by_name(self.sheetname)
self.table = self.workbook.sheet_by_index(0)
# 获取工作表的有效行数
self.rowNum = self.table.nrows
# 获取工作表的有效列数
self.colNum = self.table.ncols
def readExcel(self, num):
# 定义一个空字典
data_dict = {}
# 获取单元格数据
data_dict["request_url"] = self.table.cell_value(num, 2)
data_dict["request_type"] = self.table.cell_value(num, 3)
data_dict["request_data"] = json.loads(self.table.cell_value(num, 4))
data_dict["expect_data"] = self.table.cell_value(num, 5)
print(data_dict)
return data_dict
def writeExcel(self, num, info="null"):
"""对excel进行修改/添加内容"""
new_workbook = copy(self.workbook)
new_table = new_workbook.get_sheet(0)
new_table.write(num, 6, info)
new_workbook.save(self.data_path)
if __name__ == "__main__":
ExcelData().readExcel(1)
ExcelData().writeExcel(1)
send_request.py
import requests
from conf import *
class SendRequest(object):
"""发送请求"""
def __init__(self):
self.headers = {
"Content-Type": "application/json",
"Cookie": Cookies
}
pass
def get_request(self, url, data):
resp = requests.get(url, params=data, headers=self.headers)
return resp.text
pass
def post_request(self, url, data):
resp = requests.post(url, data=data, headers=self.headers)
return resp.text
pass
main.py
import re
from excel_data_read_write import ExcelData
from send_request import SendRequest
class Main(object):
def __init__(self):
self.excel = ExcelData()
self.send = SendRequest()
self.rowNum = self.excel.rowNum
def run(self):
for i in range(1, self.rowNum):
data_dict = self.excel.readExcel(i)
resp = None
try:
if data_dict["request_type"] == "post":
resp = self.send.post_request(data_dict["request_url"], data_dict["request_data"])
elif data_dict["request_type"] == "get":
resp = self.send.post_request(data_dict["request_url"], data_dict["request_data"])
else:
self.excel.writeExcel(i, "request_type_error")
except:
self.excel.writeExcel(i, "fail")
try:
re.search(data_dict["expect_data"], resp).group()
print(resp)
self.excel.writeExcel(i, "pass")
except:
self.excel.writeExcel(i, "fail")
if __name__ == '__main__':
Main().run()