python接口测试自学1
尝试写了一个简单的接口测试,基于Python3.4,主要用到了Python读取excel以及requests库的知识,也算是对这段时间Python基础知识学习的一个巩固吧。
因为还没有学习到Python中类、对象等相关知识,所以代码看起来很散,没有封装,也没有优化。如有问题,希望大家能帮忙指出。
1 import xlrd 2 import requests 3 4 #下文中将用到的全局变量 5 6 nrows = 0 7 rdict = {} 8 relist=[] 9 10 #从excel中导入数据 11 12 def imptestcase(): 13 14 fname = 'testcase.xlsx' 15 bk = xlrd.open_workbook(fname) 16 17 try: 18 sheet = bk.sheet_by_name('case1') 19 except: 20 print("no sheet in %s named sheet1" %fname) 21 22 global nrows 23 nrows = sheet.nrows 24 ncols = sheet.ncols 25 26 for i in range(0,ncols): 27 data = sheet.col_values(i) 28 global rdict 29 rdict[data[0]]=data[1:] 30 31 32 #将excel读取的数据封装成请求,并发送 33 34 def sendpost(): 35 #response = requests.post(url,json = data,headers = headers,verify=False) 36 for i in range(0,nrows-1): 37 url = rdict['url'][i] 38 39 if rdict['headers'][i]!='': 40 headers = eval(rdict['headers'][i]) #str to dict 41 else: 42 headers = {} 43 44 45 if rdict['json'][i]!='': 46 json = eval(rdict['json'][i]) #str to dict 47 else: 48 json = {} 49 if rdict['params'][i]!='': 50 params = eval(rdict['params'][i]) #str to dict 51 else: 52 params = {} 53 54 55 try: 56 r = requests.get(url,json = json,headers = headers,params = params,verify=False) 57 r.raise_for_status() 58 r.encoding=r.apparent_encoding 59 global relist 60 relist.append(r.status_code) 61 except Exception as e: 62 print(e) 63 print('请求失败') 64 65 #把返回的结果输出到html中,形成HTML报告(知识简单的展示,没有样式) 66 def output_html(): 67 fout=open('output.html','w',encoding='UTF-8', newline='') 68 fout.write('<html>') 69 fout.write('<head>') 70 fout.write('<meta charset = "UTF-8"/>') 71 fout.write('</head>') 72 fout.write('<body>') 73 fout.write('<h1>report<h1>') 74 fout.write('<table>') 75 fout.write('<tr>') 76 fout.write('<td>%s</td>' % relist) 77 fout.write('</tr>') 78 fout.write('</table>') 79 fout.write('</body>') 80 fout.write('</html>') 81 fout.close() 82 83 if __name__ == '__main__': 84 imptestcase() 85 sendpost() 86 output_html()
【excel内容】


浙公网安备 33010602011771号