wrk with lua script - generating multiple POST requests with different body

5.7k Views Asked by At

I wrote some lua script for wrk to generate multiple POST requests. My problem is that my script is working only for the first request. All further generated requests are exactly the same as the first one. I would like that user variable will be new generated for each POST request:

lowerCase = "abcdefghijklmnopqrstuvwxyz" 
characterSet = lowerCase
   
keyLength = 13
user = ""    
math.randomseed(os.time())
for i = 1, keyLength do
rand = math.random(#characterSet)
user = user .. string.sub(characterSet, rand, rand )
end


wrk.path  = "/somepath"
wrk.method = "POST"
wrk.body   = [[{"username":"]].. user .. [[,"password":"somepassword"}]]
wrk.headers["Content-Type"] = "application/json"
2

There are 2 best solutions below

2
Piglet On

I'm not familiar with wrk.

I guess you're running that code multiple times within a second. As os.time has second accuracy you'll have the same randomseed and hence the same user name within that second.

From looking into the scripting examples I'd say the script is only evaluated once or maybe once per thread. Those examples implement functions that will be called by wrk. It wouldn't make sense to define those functions for every request.

Add a print to your script to make sure.

Here is an example that counts requests. You probably can put your code into that function

function request()
   requests = requests + 1
   return wrk.request()
end
1
Staffier On

Try something like this. It should execute request3 ~50% of the time, and the other two ~25% of the time. Cheers!

names = { "Maverick", "Goose", "Viper", "Iceman", "Merlin", "Sundown", "Cougar", "Hollywood", "Wolfman", "Jester" }

request1 = function()
    headers = {}
    headers["Content-Type"] = "application/json"
    body = '{"name": ' .. names[math.random(#names)] .. '}'
    return wrk.format("POST", "/test1", headers, body)
end

request2 = function()
    headers = {}
    headers["Content-Type"] = "application/json"
    body = '{"name": ' .. names[math.random(#names)] .. '}'
    return wrk.format("POST", "/test2", headers, body)
end

request3 = function()
    headers = {}
    headers["Content-Type"] = "application/json"
    body = '{"name": ' .. names[math.random(#names)] .. '}'
    return wrk.format("GET", "/test3", headers, body)
end

requests = {}
requests[0] = request1
requests[1] = request2
requests[2] = request3
requests[3] = request3

request = function()
    return requests[math.random(0, 3)]()
end

response = function(status, headers, body)
    if status ~= 200 then
        io.write("------------------------------\n")
        io.write("Response with status: ".. status .."\n")
        io.write("------------------------------\n")
        io.write("[response] Body:\n")
        io.write(body .. "\n")
    end
end