HTTP_prot = {
"/gateway/services",
"/gateway/services",
}
--接口類型
HTTP_type = {
"POST",
"POST",
}
--參數
HTTP_body = {
'{"phone": "19012000335"}',
'{"phone": "19012000335","code": "1569"}',
-- 雙中括號里面不轉譯
}
-----------如果有多個接口,名稱、類型、參數必須按照相同的順序。
math.randomseed(os.time())
function changeData(tal,order)
local body = string.format()
end
local reqIndex =0
numLink = 0 --記錄連接數
numHTTP = 1 --記錄第幾個接口
numData = "19012"
lenthHTTP = 0
respError = 0 --變量,用於記錄錯誤請求的數量
local threads = {}
--測試開始 執行一次
function setup(thread)
-- thread:set("id", counter)
table.insert(threads, thread)
reqIndex = reqIndex +1;
thread:set("index", reqIndex);
end
--每個線程執行一次
init = function()
local r = {}
local path = "" -- 局部變量(不加local 是全局變量)
local method = "GET" -- 默認接口類型是GET
-- header 頭
-- wrk.headers["Hash"]= "85280aa135bbd0108dd6aa424565a"
-- wrk.headers["Token"]= ""
for i, v in ipairs(HTTP_prot) do -- 鍵從1 開始 非 0
path = v -- 接口路徑
method = HTTP_type[i] -- method 獲得接口類型
-----根據接口類型,判斷進入那個判斷-------
if method == "POST" then --判斷接口類型為“POST”
--POST 參數json格式
wrk.headers["content-type"]= "application/json"
--POST Token參數
wrk.body = HTTP_body[i] --獲得參數
end
if method == "GET" and HTTP_body[i] ~= "" then --判斷接口類型為“GET”,並且參數不為空
path = v .. "?" ..HTTP_body[i]
end
-- io.write(method, "---", HTTP_body[i], "----", path, "\n") -- 打印請求方式(1個線程會打印一次),參數,路徑(不含域名)
r[i] = wrk.format(method, path)
end
req = table.concat(r)
end
--每個請求執行一次在請求開始之前
request = function()
return req
end
--測試結果,每個鏈接返回都會執行一次
response = function(status, headers, body)
--判斷返回結果是否正確,如果返回結果錯誤則打印返回結果,進入LOG.txt文件
if(not string.find(body,'"code":0')) then
respError = respError + 1
file = io.open("LOG.txt","a")
file:write(body.."\n")
file:flush()
end
end
-- 測試最終結果,在測試結束執行
done = function(summary, latency, requests)
local x4 = 0
for index, thread in ipairs(threads) do
x4 = x4 + thread:get("respError")
end
local durations = summary.duration / 1000000 --執行時間,單位-秒
local errors = summary.errors.status --http status(狀態)不是200,300開頭的
local requests = summary.requests --總的請求數
local valid = requests - x4 --有效請求數 = 總的請求數 - 錯誤請求數
local connect = summary.errors.connect
local read1 = summary.errors.read
local write1 = summary.errors.write
local timeout = summary.errors.timeout
local errorRate = (x4/requests)*100
errorRate = string.format("%.1f",errorRate)
io.write("+++++++++++++++++++++++++++++++++++++\n")
io.write(" 測試持續時間: "..string.format("%.2f",durations).."s".."\n")
io.write(" 平均響應時間: "..string.format("%.2f",latency.mean / 1000).."ms".."\n")
io.write(" 最小響應時間: "..(latency.min / 1000).."ms".."\n")
io.write(" 最大響應時間: "..(latency.max / 1000).."ms".."\n")
io.write(" 全部請求數量: "..summary.requests.."\n")
io.write(" 錯誤請求數量: "..x4.."\n")
io.write(" 有效請求數量: "..valid.."\n" )
io.write(" 錯誤率: "..errorRate.."%\n")
io.write(" 每秒查詢率: "..string.format("%.2f",valid / durations).."\n" )
io.write("+++++++++++++++++++++++++++++++++++++\n")
end