I am using SOAPUI groovy script and I need a way to select a random value from a list. How can I handle this?
Example def Cities= ["London", "NY", "Berlin"....etc]
Use Random to create a random number, then use that to access the array...
import java.util.Random
Random rand = new Random();
int max = 4 // Length of array
def randomNumber = rand.nextInt(max);
return Cities[randomNumber];
You can try the following solution. It generates a random int of length()
${=org.apache.commons.lang.RandomStringUtils.randomNumeric(5)}
Related
I want to use a random value from the GET method, in the POST method.
List car = Audi, Porsche, Ford, VW, Honda, Citroen
$['carTypes'][0]['carType']['enum']
Result: [Audi]
$['carTypes'][${=(int)(Math.random()*6)}]['carType']['enum']
Result: [Porsche] (random 1 car from the list of 5 available)
I would like to get a list of random cars but not limited to just one car - random list of cars but in the range of 0 to 6, not only 1 value.
Result: [Audi,Porsche]
Result: [Ford, VW, Honda]
Result: [Citroen]
I have tried like this.
$['carTypes'][${=(int)(Math.random()*6)},${=(int)(Math.random()*6)}]['carType']['enum']
Result: [[Citroen, Honda]]
Probably 2 flat brackets [[ prevent me from using this data in the POST method, how to get rid of unnecessary brackets?
Groovy
import groovy.json.JsonOutput
Random random = new Random()
def list = ["Porsche","Ford","VW"]
def randomValue = random.nextInt(list.size())
def list2 = ["Porsche","Ford","VW"]
def randomValue2 = random.nextInt(list2.size())
def theValue = list2[randomValue2] +","+ list[randomValue]
I will be grateful for your help.
Instead of putting the above in your post step, you could create a Groovy script step in between the GET and POST requests.
In the Groovy script, you can then 'build' the string exactly how you want, including the removal of the brackets. The last line in the script should be a return statement that returns the string you built.
In the POST request, you can then 'pull' in the value from the groovy script step using the $ functionality. E.g. ${Groovy Script Name#result}
two drop downs
1)Array _ depart city contains N cities
aaa,bbb,ccc,ddd,eee,fff,......nnn
2)Array _ arrival city contains N cities
aaa,bbb,ccc,ddd,eee,fff,......nnn
want to select two cities from two strings randomly but two cities should not match
You can include following in a JSR223 Sampler
def cities =["aaa","bbb","ccc","ddd","eee","fff","test"]
//Remove a random city and assign to dep_city
cities.shuffle()
def dep_city = cities.pop()
//Remove a random city and assign to arrival_city
cities.shuffle()
def arrival_city= cities.pop()
//Setting the variables
vars.put("dep_city", dep_city)
vars.put("arrival_city", arrival_city)
SampleResult.setIgnore() //Result is not generated
Groovy is used for the scripting
Shuffle is used to randomly reorder the elements
Pop is used to remove the first element from the list
First of all I don't think your approach is correct, test needs to be repeatable and your "random" logic may lead to the situation when one test run reveals performance problem and the next one doesn't because the data is different.
So maybe it makes more sense to consider using parameterization instead, i.e. put all the cities to the CSV file and use CSV Data Set Config to read them.
If you really want your test to use random data and you have these "arrays" in form of string like in your question you can implement the randomization using any suitable JSR223 Test Element and the example code like:
def dep_array = 'aaa,bbb,ccc,ddd,eee,fff'
def arr_array = 'aaa,bbb,ccc,ddd,eee,fff'
def getRandomCity(String cities, Object prev) {
def array = cities.split(',')
def rv = array[org.apache.commons.lang3.RandomUtils.nextInt(0, array.size())]
if (prev != null) {
if (rv == prev) {
rv = getRandomCity(array.join(','), prev)
}
}
return rv
}
def dep_city = getRandomCity(dep_array, null)
def arr_city = getRandomCity(arr_array, dep_city)
vars.put('dep_city', dep_city)
vars.put('arr_city', arr_city)
You will be able to access the values as ${dep_city} and ${arr_city} later on where required
def index = [];
def randoms = [];
def size = new File("C:/Users/320027671/Desktop/JmeterPerformanceSuit/CompleteSuit/STU3/Post/index.csv").readLines().size();
File file = new File("C:/Users/320027671/Desktop/JmeterPerformanceSuit/CompleteSuit/STU3/Post/index.csv");
file.each { line ->
index << line
randoms << __Random(0,size,)
}
The script is giving error
the method does not exists
the scirpt is working uptil index << line, the problem is with random function
I assume you use groovy as language (otherwise it won't work)
You can't use JMeter functions inside JSR223
You can randomize every line using for example RandomUtils:
org.apache.commons.lang3.RandomUtils.nextInt(0, size-1);
Your approach may fail to produce "random" numbers, especially on lesser file sizes you can get duplicate values in the randoms list so I would recommend doing something like:
1.upto(size, { i ->
randoms.add(i)
})
Collections.shuffle(randoms)
This will populate randoms list with the numbers from 1 to the length of size and then calls Collection.shuffle() function in order to "randomise" the list.
Just in case check out Writing JMeter Functions in Groovy for more insights.
I have two different array with values as below:
Code = [8,9,10]
Value = [4,5,6]
I need to get the values from each array (above mentioned) randomly and assign it to different variable like below:
Code 1 = 9 , Code2=10
Value1 = 4 , Value2=6
Or is there any way in Jmeter to Pass that array to another sampler thereby assigning it to different variables.
How can we achieve it on Jmeter ? Any help / Suggestions is welcome!
Your values look utterly like JSON Arrays so my expectation is that you could handle it more easy using JSON Extractor
Just in case I'm wrong you can get random code and/or value using the following Groovy code in any of JSR223 Test Elements
import org.apache.commons.lang3.RandomUtils
def codes = vars.get('Code').findAll(/\d+/ )*.toInteger()
def values = vars.get('Value').findAll(/\d+/ )*.toInteger()
def randomCode = codes.get(RandomUtils.nextInt(0,codes.size()))
def randomValue = values.get(RandomUtils.nextInt(0,values.size()))
log.info('Random code: ' + randomCode)
log.info('Random value: ' + randomValue)
Demo:
You can use "Config Element" > "Random Variable" where you can give a range and ask for a random number within that given range.
Hope it helps.
Let's say I have this ArrayList of Maps
def map1 = [key1:value1, key2:value2, key3:value3]
def map2 = [key1:value1, key2:value2, key3:value3]
def map3 = [key1:value1, key2:value2, key3:value3]
def maps = [map1, map2, map3]
I want to sort this list based on value3 of the map.
How can I do that assuming that I'm working in Groovy?
You can create your own custom sort comparator like this in Groovy:
maps.sort { a, b -> a.key3 <=> b.key3 }
This will sort the maps based on the value of each one's key3.
You can deal with the ArrayList of maps like with any other ArrayList. Hence calling the Collections.sort(List) would take care of your issue, sorting it using the natural order of hashMaps - probably this will use identity. In case you want to provide a Comparator to provide more appropriate logic to what you have in mind you can use Collections.sort(List, Comparator).
In groovy you can call directly the .sort() on a given array, this is possible as the DefaultGroovyMethods contains several helper methods, among with several sorting related methods.
On your code:
def map1 = [key1:"1",key2:"2",key3:"3"]
def map2 = [key1:"2",key2:"3",key3:"1"]
def map3 = [key1:"3",key2:"1",key3:"2"]
def maps = [map1,map2,map3 ]
maps.sort();
maps.sort({m1, m2 -> m1.key3 <=> m2.key3})
println maps
Output:
[[key1:2, key2:3, key3:1], [key1:3, key2:1, key3:2], [key1:1, key2:2, key3:3]]
This response are based on capabilities of groovy 2.4.4.
I put some values, to make easier to understand...
You can create a comparison block (very analogous to a Comparator) and pass it to the sort() method
def map1 = [key1:11,key2:12,key3:13]
def map2 = [key1:21,key2:22,key3:23]
def map3 = [key1:31,key2:32,key3:33]
def maps = [map2,map1,map3] //map1 in second position
maps.sort({mapa, mapb -> mapa.key3.compareTo(mapb.key3)})
Would yield
[[key1:11, key2:12, key3:13], [key1:21, key2:22, key3:23], [key1:31, key2:32, key3:33]] //now they are sorted