設計原理
基於http協議接口的測試設計,莫過於Python的requests庫,簡單粗暴易理解。
設計模式
采用python的flask框架,搭建一套接口自動化測試平台。
測試用例維護:采用Excel
測試結果保存:采用MongoDb存儲,HTML頁面展示
相關核心代碼介紹:
- Excel模板如下:
看Excel的定義命名,基本理解,每個參數的含義
介紹:
B1:要測試的接口地址
B2:該測試接口的請求參數,以“#”分隔【便於分割】
B3:登錄的URL,若測試不需要登錄
B4:登錄的json串,以字典的形式展現
注:CaseNo、Except——result、Commit,是必填的 - 從Excel讀取及處理數據,代碼如下:
import xlrd import os # **************************************************************** # Excel模版設置 # self.interFace = 0 #Excel中測試用例接口對應為第1列 # self.interFaceArgList = 1 #Excel中測試用例接口參數列表對應為第2列 # self.loginChoice = 2 #Excel中測試用例接口是否需要登錄為第3列 # self.loginJson = 3 #Excel中測試用例接口是否需要登錄為第4列 # self.titleIndex = 4 #Excel中測試用例標題行索引為第5列 # self.caseBegin = 5 #Excel中測試用例開始行索引為第6列 # **************************************************************** class ExcelSheet: def __init__(self, sFile, interFace=0, interFaceArgList=1, loginInterFace=2, loginJson = 3, titleIndex=4, caseBegin=5): try: excel = xlrd.open_workbook(sFile) except Exception as e: print e exit() self.sheet = excel.sheet_by_index(0) # 查詢Excel的第一個sheet self.interFace = interFace self.interFaceArgList = interFaceArgList self.loginInterFace = loginInterFace self.titleIndex = titleIndex self.caseBegin = caseBegin self.loginJson = loginJson def sheet_name(self): return self.sheets.name def nrows(self): return self.sheet.nrows def ncols(self): return self.sheet.ncols def cellxy(self, rowx, colx): # type: (object, object) -> object cell_value = self.sheet.cell(rowx, colx).value # 對數字的處理 if self.sheet.cell(rowx, colx).ctype in (2, 3) and int(cell_value) == cell_value: cell_value = int(cell_value) return cell_value # interFace 測試接口URL def get_interFace(self): return self.cellxy(self.interFace, 1) # interFace接口的參數List def get_interFaceArgList(self): return self.cellxy(self.interFaceArgList, 1).split("#") # 測試用例的參數項 def get_titleIndex(self): return self.sheet.row_values(self.titleIndex) # 登錄的接口地址 def get_loginInterFace(self): return self.cellxy(self.loginInterFace, 1) # 獲取登錄接口參數的json def get_loginJson(self): return str(self.cellxy(self.loginJson, 1)) # 返回單行用例的數據字典 def get_by_line(self, line): tempdict = dict() data = dict() if line < self.caseBegin: return False else: for col in range(self.ncols()): if self.cellxy(self.titleIndex, col) in self.get_interFaceArgList(): if self.cellxy(line, col) != 'X': data[self.cellxy(self.titleIndex, col)] = self.cellxy(line, col) else: tempdict[self.cellxy(self.titleIndex, col)] = self.cellxy(line, col) tempdict["data"] = data return tempdict
-
requests的post和get請求代碼:
import requests def postRequest(url, data, cookie): header={"Content-Type":"application/json"} if cookie: return requests.post(url, data=data, cookies=cookie, headers = header) else: return requests.post(url, data=data, headers = header) def postRequest(url, cookie): header={"Content-Type":"application/json"} if cookie: return requests.get(url, cookies=cookie, headers = header) else: return requests.get(url, headers = header)
- 檢查返回為頁面還是json串:
def checkReturnResult(req_result): try: realResult = eval(req_result) except: return False else: return req_result
- 測試結果存儲MongoDB:
# -*- coding: utf-8 -*- import pymongo class ConMongoDb: #讀取配置文件 def __init__(self): MongoIP="192.168.X.XXX" MongoPort=27017 #鏈接MongoDb self.conn = pymongo.Connection(MongoIP, MongoPort) #選擇數據庫 self.db = self.conn.test self.collection = self.db.SocketTest ''' # ************************************************** # InsertMongo:往MongoDb插入數據 # ************************************************** ''' def InsertMongo(self, Lst): self.collection.insert(Lst)
def close(self):
return self.conn.disconnect() - 測試用例執行代碼:
import time ExcelSheet = ExcelSheet("104137PC.xlsx") interFace = ExcelSheet.get_interFace() interFaceArgList = ExcelSheet.get_interFaceArgList() titleIndex = ExcelSheet.get_titleIndex() loginInterFace = ExcelSheet.get_loginInterFace() # 判斷是否需要登錄 if loginInterFace: if "username" not in titleIndex or "password" not in titleIndex: print "Test Case File not include username or password" exit() else: # 獲取登錄接口參數的json loginJson = ExcelSheet.get_loginJson() caseList = list() for line in range(5, ExcelSheet.nrows()): lineContent = ExcelSheet.get_by_line(line) # 獲取登錄后的cookie if loginInterFace: # 需要登錄,用戶名密碼,替換 loginJson = loginJson.replace("#username#", lineContent["username"]) loginJson = loginJson.replace("#password#", str(lineContent["password"])) result = postRequest(loginInterFace, eval(loginJson), False) print result.text cookie = result.cookies else: cookie = False # reqtype 不填默認post if lineContent.has_key("reqtype"): if lineContent["reqtype"].upper() == "POST": interFaceResult = postRequest(interFace, lineContent["data"], cookie) else: interFaceResult = postRequest(interFace, cookie) else: interFaceResult = postRequest(interFace, lineContent["data"], cookie) req_result = interFaceResult.text # 非頁面,可直接比較,也可以轉換成字典進行某個value進行比較 if checkReturnResult(req_result): if checkReturnResult(req_result) == lineContent["Except_result"]: TestResult = "PASS" else: TestResult = "FAIL" #如果返回是頁面的話,就查找特殊標志詞 else: if ineContent["Except_result"] in req_result: TestResult = "PASS" else: TestResult = "FAIL" lineContent["result"] = TestResult caseList.append(lineContent) TestDate = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) content = {"interFace": interFace, "caseList": caseList, "testdate": TestDate} MyngoCls = ConMongoDb() MyngoCls.InsertMongo(content) MyngoCls.close()
整個流程梳理:
- 用例Excel的讀取解析
- python的requests模塊運用
- 返回值的判斷處理
- 用例執行結果的存儲
- 用例測試的入口