上一篇的文章響應比較熱烈,今天來寫篇進階代碼,大體分為兩部分,csv讀出所有的接口檔案和 把所有的測試結果寫進csv檔案裡
首先我先講一下,讀接口檔案
test_interface.csv接口檔案樣式:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICM38FdsYkRGZkRG9lcvx2bjxiNx8VZ6l2cs0TP35UeJRkT5lFVPpHOsJGcohVYsR2MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL5czN4UjMxETM5EzMwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
給大家解釋一下部分列的含義
url通路位址,expresult預期結果,interfaceName接口名稱,一串數字那一列(2,6,2)是參數個數,代碼裡面會用到,後面就是參數名稱及參數值了。
下面直接上代碼:
import csv
file=open("test_interface.csv","r")
table=csv.reader(file)
userinfo={}
for row in table:
url=row[1]
expresult=row[3]
interfaceName=row[5]
#上面的就是分别拿到url,預期結果,接口名稱,下面才是重點,因為每個請求參數個數會不一樣這裡要再套個循環讀取請求參數,會有一點彎彎繞
#j拿到參數個數,因為在第七列是以拿row[6]
j=int(row[6])
#這裡的意思是,i從7開始,每次加2,一直到i大于2*j+7結束,大家可以想一下對不對
for i in range(7,2*j+7,2):
#row[i]為參數名,row[i+1]為參數值
userinfo[row[i]]=row[i+1]
這樣我們就拿到請求參數全部資訊了
print(userinfo)
userinfo={}
下面是把測試結果寫到csv檔案裡面
#這段是測試代碼
file=open("test_all.csv","a")
#模拟響應回來資料是resData
resData={"接口名":"登入接口","實際響應結果":"成功","測試結論":"通過"}
#這次循環是分别拿到resData的key和value值
for key,value in resData.items():
print(key,value)
#寫進檔案裡面
file.write(str(key)+","+str(value)+",")
#每個響應寫完要換行 是以要\n
file.write("\n")
file.close()
好了,兩個主體介紹完了 上整體代碼:
import requests
import csv
class workflow_forgotpassword_final_test():
#這裡因為每個請求都會經曆這一步,是以在這裡進行封裝,每個參數意義,已經在上面介紹過了,相信大家這段都應該看得懂吧,拿到響應資料
def all_test(self,url,userinfo,expresult,interfaceName):
resData={}
response=requests.post(url,data=userinfo).text
resData["接口實際傳回值"] = str(response)
r=response.find(expresult)
if r>0:
print(interfaceName,"pass")
resData["測試結論"]="pass"
else:
print(interfaceName,"fail")
resData["測試結論"] = "fail"
#這裡resData拿到兩對值一個是接口實際傳回值,另外一個是測試結論
return resData
#這個是把測試結果寫進csv檔案
def res_report(self,interfaceName,reportFileName,resData):
#a為追加寫,w為覆寫寫
file=open(reportFileName,"w")
#第一列為接口名稱
file.write(interfaceName+",")
#後面是周遊響應回來的資料
for key,value in resData.items():
file.write(key+","+value+",")
file.write("\n")
file.close()
#主函數調用
if __name__ == '__main__':
#對象執行個體化
final_obj=workflow_forgotpassword_final_test()
file=open("test_interface.csv","r")
#定義結果檔案名稱
reportFileName="test_resAll.csv"
resData={}
table=csv.reader(file)
for row in table:
url=row[1]
expresult=row[3]
interfaceName=row[5]
#在這裡為什麼要定義一個空的userinfo,因為下面的循環,每循環一次就是一個請求的所有參數,如果這裡不是空的 ,下次整體循環的時候,就會追加了,肯定不對的
userinfo={}
# print(url,interfaceName,expresult)
j=int(row[6])
for i in range(7,2*j+7,2):
userinfo[row[i]]=row[i+1]
#拿到參數,調用發送請求,以及斷言部分
resData=final_obj.all_test(url,userinfo,expresult,interfaceName)
#結果寫進csv
final_obj.res_report(interfaceName,reportFileName,resData)
好了,大功告成,以後不管有什麼請求隻需要往test_interface.csv檔案填充就好了,最後附上結果檔案樣子:
略有瑕疵,響應資料分開了,不過可以優化的,交給大家了,這樣其實也可以用啦
最後,歡迎大家多多留言,還有最後一篇接口自動化架構的,大家期待下吧