Random number in Lua script Load Impact - random

I'm trying to create a random number generator in Lua. I found out that I can just use math.random(1,100) to randomize a number between 1 and 100 and that should be sufficient.
But I don't really understand how to use the randomize number as variables in the script.
Tried this but of course it didn't work.
$randomCorr = math.random(1,100);
http.request_batch({
{"POST", "https://store.thestore.com/priceAndOrder/selectProduct", headers={["Content-Type"]="application/json;charset=UTF-8"}, data="{\"ChoosenPhoneModelId\":4,\"PricePlanId\":\"phone\",\"CorrelationId\":\"$randomCorr\",\"DeliveryTime\":\"1 vecka\",\"$$hashKey\":\"006\"},\"ChoosenAmortization\":{\"AmortizationLength\":0,\"ChoosenDataPackage\":{\"Description\":\"6 GB\",\"PricePerMountInKr\":245,\"DataAmountInGb\":6,\"$$hashKey\":\"00W\"},\"ChoosenPriceplan\":{\"IsPostpaid\":true,\"Title\":\"Fastpris\",\"Description\":\"Fasta kostnader till fast pris\",\"MonthlyAmount\":0,\"AvailiableDataPackages\":null,\"SubscriptionBinding\":0,\"$$hashKey\":\"00K\"}}", auto_decompress=true},
{"GET", "https://store.thestore.com/api/checkout/getproduct?correlationId=$randomCorr", auto_decompress=true},
})

In Lua, you can not start a variable name with $. This is where your main issue is at. Once the $ is removed from your code, we can easily see how to refer to variables in Lua.
randomCorr = math.random(100)
print("The random number:", randomCorr)
randomCorr = math.random(100)
print("New Random Number:", randomCorr)
Also, concatenation does not work the way you are implying it into your Http array. You have to concatenate the value in using .. in Lua
Take a look at the following example:
ran = math.random(100)
data = "{\""..ran.."\"}"
print(data)
--{"14"}
The same logic can be implied into your code:
data="{\"ChoosenPhoneModelId\":4,\"PricePlanId\":\"phone\",\"CorrelationId\":\""..randomCorr.."\",\"DeliveryTime\":\"1 vecka\",\"$$hashKey\":\"006\"},\"ChoosenAmortization\":{\"AmortizationLength\":0,\"ChoosenDataPackage\":{\"Description\":\"6 GB\",\"PricePerMountInKr\":245,\"DataAmountInGb\":6,\"$$hashKey\":\"00W\"},\"ChoosenPriceplan\":{\"IsPostpaid\":true,\"Title\":\"Fastpris\",\"Description\":\"Fasta kostnader till fast pris\",\"MonthlyAmount\":0,\"AvailiableDataPackages\":null,\"SubscriptionBinding\":0,\"$$hashKey\":\"00K\"}}"
Or you can format the value in using one of the methods provided by the string library
Take a look at the following example:
ran = math.random(100)
data = "{%q}"
print(string.format(data,ran))
--{"59"}
The %q specifier will take whatever you put as input, and safely surround it with quotations
The same logic can be applied to your Http Data.

Here is a corrected version of the code snippet:
local randomCorr = math.random(1,100)
http.request_batch({
{"POST", "https://store.thestore.com/priceAndOrder/selectProduct", headers={["Content-Type"]="application/json;charset=UTF-8"}, data="{\"ChoosenPhoneModelId\":4,\"PricePlanId\":\"phone\",\"CorrelationId\":\"" .. randomCorr .. "\",\"DeliveryTime\":\"1 vecka\",\"$$hashKey\":\"006\"},\"ChoosenAmortization\":{\"AmortizationLength\":0,\"ChoosenDataPackage\":{\"Description\":\"6 GB\",\"PricePerMountInKr\":245,\"DataAmountInGb\":6,\"$$hashKey\":\"00W\"},\"ChoosenPriceplan\":{\"IsPostpaid\":true,\"Title\":\"Fastpris\",\"Description\":\"Fasta kostnader till fast pris\",\"MonthlyAmount\":0,\"AvailiableDataPackages\":null,\"SubscriptionBinding\":0,\"$$hashKey\":\"00K\"}}", auto_decompress=true},
{"GET", "https://store.thestore.com/api/checkout/getproduct?correlationId=" .. randomCorr, auto_decompress=true},
})
There is something called $$hashKey also, in the quoted string. Not sure if that is supposed to be referencing a variable or not. If it is, it also needs to be concatenated into the resulting string, using the .. operator (just like with the randomCorr variable).

Related

How to call Lua table value explicitly when using integer counter (i,j,k) in a for loop to make the table name/address?

I have to be honest that I don't quite understand Lua that well yet. I am trying to overwrite a local numeric value assigned to a set table address (is this the right term?).
The addresses are of the type:
project.models.stor1.inputs.T_in.default, project.models.stor2.inputs.T_in.default and so on with the stor number increasing.
I would like to do this in a for loop but cannot find the right expression to make the entire string be accepted by Lua as a table address (again, I hope this is the right term).
So far, I tried the following to concatenate the strings but without success in calling and then overwriting the value:
for k = 1,10,1 do
project.models.["stor"..k].inputs.T_in.default = 25
end
for k = 1,10,1 do
"project.models.stor"..j..".T_in.default" = 25
end
EDIT:
I think I found the solution as per https://www.lua.org/pil/2.5.html:
A common mistake for beginners is to confuse a.x with a[x]. The first form represents a["x"], that is, a table indexed by the string "x". The second form is a table indexed by the value of the variable x. See the difference:
for k = 1,10,1 do
project["models"]["stor"..k]["inputs"]["T_in"]["default"] = 25
end
You were almost close.
Lua supports this representation by providing a.name as syntactic sugar for a["name"].
Read more: https://www.lua.org/pil/2.5.html
You can use only one syntax in time.
Either tbl.key or tbl["key"].
The limitation of . is that you can only use constant strings in it (which are also valid variable names).
In square brackets [] you can evaluate runtime expressions.
Correct way to do it:
project.models["stor"..k].inputs.T_in.default = 25
The . in models.["stor"..k] is unnecessary and causes an error. The correct syntax is just models["stor"..k].

ruby, assign the var that is not nill

I have in the html the location variable sometimes is used with a class called "result-hood" sometimes is used with another class called "nearby"
location = result.search('span.result-hood').text[2..-2]
location2 = result.search('span.nearby').text[2..-2]
so if one of the above classes is not used the result is nill, my question is how to get always the one that is not nill, I was thinking about the ternary operator "?" , but don't know how to use it.
Thanks,
You want the || ("or") operator:
location || location2
It returns the left side if that is not nil or false, and otherwise it returns the right side.
CSS supports logical or operations using a comma as the delimiter, so your selector can just be:
location = result.search('span.result-hood,span.nearby').text[2..-2]
XPath also supports logical or operator itself, the equivalent XPath would look like
location = result.search('//span[#class="result-hood"]|//span[#class="nearby"]').text[2..-2]
Ternary operator in ruby:
loc = location.nil? ? location2 : location
Hope this works.
Since you're looking for one or the other you can reduce this code to:
location = result.search('span.result-hood').text[2..-2]
|| result.search('span.nearby').text[2..-2]
Where that search operation could be fairly expensive, so why run it twice when you might need to run it only once. Now that you've minimized it like this you can take it a step further:
location = %w[ span.result-hood span.nearby ].map do |selector|
result.search(selector).text[2..-2]
end.compact.first
This looks a little complicated but what it does is convert each selector into the text extracted from result.search(...).text[2..-2] and then take the first non-nil value.
That technically computes all possible bits of text before extracting, so you can make it "lazy" and evaluate each one in sequence instead, stopping at the first match:
location = %w[ span.result-hood span.nearby ].lazy.map do |selector|
result.search(selector).text[2..-2]
end.select(&:itself).first
The nice thing about this approach is you can clean it up a little by declaring a constant in advance:
LOCATIONS = %w[ span.result-hood span.nearby ]
Then later you have more minimal code like this that will automatically accommodate any changes made to that array both in terms of precedence and addition of others:
location = LOCATIONS.lazy.map do |selector|
result.search(selector).text[2..-2]
end.select(&:itself).first

"for var = 1, 2" in Lua

What does this kind of loop do in Lua?
for count = 1, 2 do
-- do stuff
end
The variable count isn't used in the body of the loop.
It executes the body of the loop twice.
There's no need to refer to count inside the loop unless you need to know its current value.
for count = 1,5 do
print("Hello")
end
prints
Hello
Hello
Hello
Hello
Hello
In this case count is "dummy variable" - "dummy" in that a variable is used fulfill a certain construct even though the variable is not used. (Another common name for such a usage is _, although count arguably adds a little more semantic intent.)
Such a dummy variable is used because LUA loops require a variable / assignment in the grammar construct. However, there is no requirement that the variable is used - hence a "dummy".
.. A numeric for [loop] has the following syntax:
for var=exp1,exp2,exp3 do
something
end
That loop will execute something for each value of var from exp1 to exp2, using exp3 as the step to increment var. This third expression [exp3] is optional; when absent, Lua assumes one [1] as the step value.

Multiple unique random values in a single request in JMeter

I am trying to make an HTTP request in JMeter that contains multiple random numbers within a fixed range (specifically 0-50). With each request, I need to send out about 45 different integers, so on any given request, there are six integers within said range that are not included. Obviously {__Random()} doesn't work, as it will inevitably generate some equal values. My idea, and please bear with me because I am very new to this, was to create an array with the integers, such as:
String line = "0, 1, 2, 3, 4, 5.....";
String[] numbers = line.split(",");
and then assign them fixed variable names to include in the request. I can do this with counter with CSV data, but I'm unsure about how to do this with an array.
vars.put("VAR_" + counter, line);
VAR_1 = 1
VAR_2 = 2
and so on...
then shuffle the array (which I do not know how to do in Beanshell) and generate something like:
VAR_1 = 16
VAR_2 = 27
...
to send with the next request.
If anyone could help me with this, or suggest a simpler way, I would great appreciate it. Thanks.
To shuffle the list just use Collections.shuffle() method
Consider using JSR223 Test Elements and Groovy language instead of Beanshell as it is:
More Java compliant
Has better performance
Has built-in support of JSON, XML and some "syntax sugar" which minimises and simplifies code
Check out Groovy Is the New Black article for more details
I figured it out. It's kind of ugly and cumbersome, but fairly simple and does exactly what I needed it to do. In JSR223 PreProcessor, my code is
def list = [0,1,2,3,4,5,.....];
Collections.shuffle(list);
String VAR_1 = Integer.toString(list.getAt(0));
vars.put("VAR_1", VAR_1);
String VAR_2 = Integer.toString(list.getAt(1));
vars.put("VAR_2", VAR_2);
String VAR_3 = Integer.toString(list.getAt(2));
and so on.....
I had to input the 50 variables manually. I'm sure there was a simpler way, but I'm quite satisfied. Thanks for the suggestions.

removing duplicates from list of strings (output from Twilio call - Ruby)

I'm trying to display total calls from a twilio object as well as unique calls.
The total calls is simple enough:
# set up a client to talk to the Twilio REST API
#sub_account_client = Twilio::REST::Client.new(#account_sid, #auth_token)
#subaccount = #sub_account_client.account
#calls = #subaccount.calls
#total_calls = #calls.list.count
However, I'm really struggling to figure out how to display unique calls (people sometimes call back form the same number and I only want to count calls from the same number once). I'm thinking this is a pretty simple method or two but I've burnt quite a few hours trying to figure it out (still a ruby noob).
Currently I've been working it in the console as follows:
#sub_account_client = Twilio::REST::Client.new(#account_sid, #auth_token)
#subaccount = #sub_account_client.account
#subaccount.calls.list({})each do |call|
#"from" returns the phone number that called
print call.from
end
This returns the following strings:
+13304833615+13304833615+13304833615+13304833615+13304567890+13304833615+13304833615+13304833615
There are only two unique numbers there so I'd like to be able to return '2' for this.
Calling class on that output shows strings. I've used "insert" to add a space then have done a split(" ") to turn them into arrays but the output is the following:
[+13304833615][+13304833615][+13304833615][+13304833615][+13304567890][+13304833615][+13304833615][+13304833615]
I can't call 'uniq' on that and I've tried to 'flatten' as well.
Please enlighten me! Thanks!
If what you have is a string that you want to manipulate the below works:
%{+13304833615+13304833615+13304833615+13304833615+13304567890+13304833615+13304833615+13304833615}.split("+").uniq.reject { |x| x.empty? }.count
=> 2
However this is more ideal:
#subaccount.calls.list({}).map(&:from).uniq.count
Can you build an array directly instead of converting it into a string first? Try something like this perhaps?
#calllist = []
#subaccount.calls.list({})each do |call|
#"from" returns the phone number that called
#calllist.push call.from
end
you should then be able to call uniq on #calllist to shorten it to the unique members.
Edit: What type of object is #subaccount.calls.list anyway?
uniq should work for creating a unique list of strings. I think you may be getting confused by other non-related things. You don't want .split, that's for turning a single string into an array of word strings (default splits by spaces). Which has turned each single number string, into an array containing only that number. You may also have been confused by performing your each call in the irb console, which will return the full array iterated on, even if your inner loop did the right thing. Try the following:
unique_numbers = #subaccount.calls.list({}).map {|call| call.from }.uniq
puts unique_numbers.inspect

Resources