Skip to content

Instantly share code, notes, and snippets.

@wcp1231
Created November 22, 2015 05:15
Show Gist options
  • Save wcp1231/2bbc18401d0860769a63 to your computer and use it in GitHub Desktop.
Save wcp1231/2bbc18401d0860769a63 to your computer and use it in GitHub Desktop.
wrk + lua 行为压测脚本

周末想用 lua 写一个简单的行为 dsl ,通过 wrk 进行压力测试的,就现学 lua 大概写了一个。使用方式就是简单的

wrk -s script.lua http://localhost:3000

写起来就是底下 script.lua 的那个样子。蛋疼的是 wrk 的 POST body 只支持字符串,所以就得把 table 转成一个 json ,似乎 lua 没有原生的库支持。

还有就是这样的 dsl 似乎不太灵活,不能很好的模拟用户行为。

我先去研究一下其他的工具看看,比如:

https://www.shopify.com/technology/17605604-announcing-go-lua http://locust.io/

local function assign(dist, source)
for k,v in pairs(source) do dist[k] = v end
end
M = {}
local actions = {}
actions.__mt = {}
actions.__mt.__index = {
method = 'GET',
path = '/',
headers = {},
body = {},
}
function M.def_action(name)
return function(options)
setmetatable(options, actions.__mt)
actions[name] = options
end
end
function M.action(name)
local action = {}
setmetatable(action, { __index=actions[name] })
return action
end
M_prototype = {}
function M_prototype:prepare(options)
self.__prepare = options
self.__actions_list = options
end
function M_prototype:actions(options)
self.__actions = options
self.__actions_list = self.__actions_list or options
end
function M_prototype:next_action()
local idx = self.__idx
if idx > #self.__actions_list then
idx = 1
self.__actions_list = self.__actions
end
local action = self.__actions_list[idx]
self.__idx = idx + 1
self.__current_before = action.before
self.__current_after = action.after
self.headers = self.headers or {}
assign(self.headers, action.headers)
self.body = {}
assign(self.body, action.body)
self.method = action.method
self.path = action.path
end
function M_prototype:request()
self:next_action()
if self.__current_before ~= nil then
self.__current_before(self)
end
return self.method, self.path, self.headers, self.body
end
function M_prototype:response(status, headers, body)
if self.__current_after ~= nil then
self.__current_after(self, status, headers, body)
end
end
function M.m(o)
o = o or {}
o.__idx = 1
setmetatable(o, M_prototype)
M_prototype.__index = M_prototype
return o
end
dofile('dsl.lua')
M.def_action "login" {
path = '/v1.1/users/login',
method = 'POST',
after = function(self, status, headers, body)
token = body['data']['token']
self.header['Authorization'] = 'Bearer '..token
end
}
M.def_action "dashboard" {
path = '/v1.1/home/dashboard',
}
M.def_action "saveTraininglog" {
path = '/v1.1/home/saveTraininglog',
method = 'POST',
before = function(self)
self.body['workout'] = "xxxxx"
end
}
m = M.m()
m:prepare {
M.action "login"
}
m:actions {
M.action "dashboard",
M.action "saveTraininglog",
}
function request()
-- TODO table to string
return wrk.format(m:request())
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment