python接口自动化(二)——封装需要用到的工具类
封装需要用的工具类:
1、封装读取Excel的工具类,这里选用的是pandas:
import pandas as pd path = 'test.xlsx' sheet_name = 'test_data' class with_excel: #构造函数,调用类时就运行 def __init__(self, path=None, sheet_name=None): if path and sheet_name: self.path = path self.sheet_name = sheet_name else: self.path = 'test.xlsx' self.sheet_name = 'test_data' self.data = self.open_excel() #获取表格数据 def open_excel(self): df = pd.read_excel(self.path, self.sheet_name) return df #获取表中单元格行数 def get_lines(self): lines = self.data.shape[0]#获取了最后一行的行数 return lines #获取一个单元格的内容(获取多行的内容) def get_cell_data(self, row, col): return self.data.iloc[row, col] #将表格数据转字典 def to_dict(self): test_data = [] for i in self.data.index.values: # 获取与表头对应的字典数据 row_data = self.data.loc[i].to_dict() test_data.append(row_data) return test_data if __name__ == '__main__': aa = with_excel(path, sheet_name)
2、封装处理json的工具类:
import json class open_json: def __init__(self, filename): self.data = self.read_data(filename) #打开json文件 def read_data(self, filename): with open(filename) as fp: data = json.load(fp) return data #获取对应的json数据 def get_data(self, data_id): return self.data[data_id]
3、封装mock方法
import mock #使用mock模拟接口返回数据 def mock_test(mock_method, request_data, url, method, response_data): mock_method = mock.Mock(return_value=response_data) res = mock_method(url, method, request_data) return res
4、封装requests
import requests import json class RunMethod: def post_main(self, url, data, header): if header != None: res = requests.post(url=url, data=data, headers=header) else: res = requests.post(url=url, data=data) return res def get_main(self, url, data, header): if header !=None: res = requests.get(url=url, data=data, headers=header) else: res = requests.get(url=url, data=data) return res def run_main(self, method, url, data=None, header=None): if method == 'post': res = self.post_main(url, data, header) else: res = self.get_main(url, data, header) return json.dumps(res, ensure_ascii=False, sort_keys=True, indent=4)