平時工作中開發在做自測或前後端聯調測試時會使用一些工具來進行,如postman,jmeter等。
但工具都是有自身局限的,今天小編就以資料驅動的架構思維來手工編碼進行接口自動化測試(基于python requests子產品)。
設計思路:
1、 先設計好要測試資料,包括請求體裡的 url,method,headers,params,body_data 等資料。
2、 測試資料放哪裡?放檔案,放excel,還是放資料庫裡,可以根據不同的業務需求來進行設計,我這裡以excel表格為例進行說明。
3、怎麼對測試資料進行讀取和寫入,達到測試接口的目标,要麼隻是需要有預期結果和測試結果,需要進行編寫代碼來完成。
測試資料設計如下:

host: 通路的ip位址或域名
url: 接口的url位址
method: http接口的通路方法,get還是post,或是put等
headers: 接口的header資訊
params: 接口的參數資訊
data_tpye: 接口body的資料類型,是data還是json
body_data: 接口的body資料
assert: 斷言
test result: 測試結果
核心代碼如下:
1、讀取excel檔案,擷取行數和table。
#!/usr/bin/env python
#-- coding: utf-8 -
import xlrd
def ReadExcel(fileName,SheetName="Sheet1"):
data = xlrd.open_workbook(fileName)
table = data.sheet_by_name(SheetName)
nrows = table.nrows
return nrows,table
2、 封裝 http 請求,根據http請求的傳回值與斷言進行對比,向excel表中test result字段回寫測試結果
import requests
import json
import os.path
import xlrd
from xlutils.copy import copy
from comm.ReadExcel import ReadExcel
for i in range(1, ReadExcel(fileName)[0]):
host = ReadExcel(fileName)[1].row_values(i)[2]
url = ReadExcel(fileName)[1].row_values(i)[3]
method = ReadExcel(fileName)[1].row_values(i)[4]
headers = ReadExcel(fileName)[1].row_values(i)[5]
params = ReadExcel(fileName)[1].row_values(i)[6]
data_type = ReadExcel(fileName)[1].row_values(i)[7]
body_data = ReadExcel(fileName)[1].row_values(i)[8]
ex_assert = ReadExcel(fileName)[1].row_values(i)[9]
testresult = ReadExcel(fileName)[1].row_values(i)[10]
p_ex_assert = eval(ex_assert)
try:
if headers == "":
h_headers = None
else:
h_headers = eval(headers)
if params == "":
p_params = None
else:
p_params = params
if body_data == "":
b_body_data = None
else:
b_body_data = eval(body_data)
if data_type == "":
data_type = None
elif data_type == "json" :
body = json.dumps(b_body_data)
elif data_type == "data":
body = b_body_data
else:
body = b_body_data
re = s.request(method=method, url=host + url, headers=h_headers,params=p_params,data=body,verify=False)
if p_ex_assert['success'] == str(re.json()['success']):
workbook = xlrd.open_workbook(fileName)
new_workbook = copy(workbook)
new_worksheet = new_workbook.get_sheet(0)
new_worksheet.write(i, 10, 'pass')
new_workbook.save(fileName)
print("pass")
else:
workbook = xlrd.open_workbook(fileName)
new_workbook = copy(workbook)
new_worksheet = new_workbook.get_sheet(0)
new_worksheet.write(i, 10, 'fail')
new_workbook.save(fileName)
print("fail")
except Exception as e:
print(e)
SendRequests()