python自學1——接口測試
嘗試寫了一個簡單的接口測試,基於Python3.4,主要用到了Python讀取excel以及requests庫的知識,也算是對這段時間Python基礎知識學習的一個鞏固吧。
因為還沒有學習到Python中類、對象等相關知識,所以代碼看起來很散,沒有封裝,也沒有優化。如有問題,希望大家能幫忙指出。
import xlrd
import requests
#下文中將用到的全局變量
nrows = 0
rdict = {}
relist=[]
#從excel中導入數據
def imptestcase():
fname = ‘testcase.xlsx‘
bk = xlrd.open_workbook(fname)
try:
sheet = bk.sheet_by_name(‘case1‘)
except:
print("no sheet in %s named sheet1" %fname)
global nrows
nrows = sheet.nrows
ncols = sheet.ncols
for i in range(0,ncols):
data = sheet.col_values(i)
global rdict
rdict[data[0]]=data[1:]
#將excel讀取的數據封裝成請求,並發送
def sendpost():
#response = requests.post(url,json = data,headers = headers,verify=False)
for i in range(0,nrows-1):
url = rdict[‘url‘][i]
if rdict[‘headers‘][i]!=‘‘:
headers = eval(rdict[‘headers‘][i]) #str to dict
else:
headers = {}
if rdict[‘json‘][i]!=‘‘:
json = eval(rdict[‘json‘][i]) #str to dict
else:
json = {}
if rdict[‘params‘][i]!=‘‘:
params = eval(rdict[‘params‘][i]) #str to dict
else:
params = {}
try:
r = requests.get(url,json = json,headers = headers,params = params,verify=False)
r.raise_for_status()
r.encoding=r.apparent_encoding
global relist
relist.append(r.status_code)
except Exception as e:
print(e)
print(‘請求失敗‘)
#把返回的結果輸出到html中,形成HTML報告(知識簡單的展示,沒有樣式)
def output_html():
fout=open(‘output.html‘,‘w‘,encoding=‘UTF-8‘, newline=‘‘)
fout.write(‘<html>‘)
fout.write(‘<head>‘)
fout.write(‘<meta charset = "UTF-8"/>‘)
fout.write(‘</head>‘)
fout.write(‘<body>‘)
fout.write(‘<h1>report<h1>‘)
fout.write(‘<table>‘)
fout.write(‘<tr>‘)
fout.write(‘<td>%s</td>‘ % relist)
fout.write(‘</tr>‘)
fout.write(‘</table>‘)
fout.write(‘</body>‘)
fout.write(‘</html>‘)
fout.close()
if __name__ == ‘__main__‘:
imptestcase()
sendpost()
output_html()
【excel內容】
python自學1——接口測試