Jmeter 2.11 Randomly fails to generate integers - random

I am trying to run some tests, using jmeters random beanshell post processor, but somehow, randomly it fails to create the numbers and instead posts "variable=${variable_value}" directly in the url.
Here is the sample beanshell post processor code:
import java.util.*;
r = new Random();
b = new Random();
t = new Random();
random_param1 = r.nextInt(415000);
random_param2 = b.nextInt(200);
random_param3 = t.nextInt(25);
vars.put("random_param1",random_param1.toString());
vars.put("random_param2",random_param2.toString());
vars.put("random_param3",random_param3.toString());
And here how I set those for the url:
And the simple test results looks like this:
And this is a failed test request data:
POST test_url
POST data:
param1=%24%7Brandom_param1%7D&param2=%24%7Brandom_param2%7D&param3=%24%7Brandom_param3%7D
While the successful ones are like:
POST test_url
POST data:
param1=287341&param2=107&param3=20
Any ideas why random generation fails "randomly" like this? Should I use a specific sampler?
EDIT:

Your beanshell code contains an error in the screenshot (so in test plan), you don't set in vars:
random_param2

Related

how save value in string variable by Javascript executor in jmeter web sampler

Hi I want to store the value return by below code in JMeter webDriver Sampler . but i am getting error.
String access_token = WDS.browser.executeScript("return window.localStorage.getItem(localStorage.key(2))");
WDS.log.info("access_token : " + access_token);
OR
var access_token = WDS.browser.executeScript("return window.localStorage.getItem(localStorage.key(2))");
WDS.log.info("access_token : " + access_token);
Both above ways are not working?
In order to be able to help we need to know the details of the error "you are getting". Also it's unclear what localStorage.key(2) object stands for.
Here is an example of getting se:fkey value from https://stackoverflow.com website:
I used default language for WebDriver Sampler: javascript and the following piece of code:
WDS.sampleResult.sampleStart()
WDS.browser.get('https://stackoverflow.com')
var access_token = WDS.browser.executeScript('return window.localStorage.getItem("se:fkey")')
WDS.log.info('Got the following value from local storage: ' + access_token)
WDS.sampleResult.sampleEnd()
And it works just fine:
If you additionally need to store the value into a JMeter Variable add the following line:
WDS.vars.put('access_token', access_token)
and you will be able to access the extracted value as ${access_token} where required.
More information: The WebDriver Sampler: Your Top 10 Questions Answered

Jmeter: how to initialise header manager element globally

I wanted to use the same set of headers in multiple jmx files. So I wanted to initialise it once and have to use it across my jmx files.
Can anyone help me in meeting my requirement? Thanks in advance.
That’s not possible.
To be able to apply a Header Manager to all plan, it should have the largest scope but using Include or Module controller means reduced scope.
Thanks to scope stil, you can set your Header Manager as child of test plan and it will apply to whole requests.
You could use properties and __P function to make those configurable in user.properties
You can do this as follows:
Create a CSV file called headers.csv to hold your headers like:
header-1-name,header-1-value
header-2-name,header-2-value
and store it in "bin" folder of your JMeter installation
Add empty HTTP Header Manager to the top level of your Test Plan
Add setUp Thread Group to your Test Plan
Add JSR223 Sampler to the setUp Thread Group
Put the following code into "Script" area:
import org.apache.jmeter.protocol.http.control.Header
import org.apache.jmeter.protocol.http.control.HeaderManager
import org.apache.jmeter.threads.JMeterContext
import org.apache.jmeter.threads.JMeterContextService
import org.apache.jorphan.collections.SearchByClass
SampleResult.setIgnore()
def engine = ctx.getEngine()
def testPlanTree = org.apache.commons.lang3.reflect.FieldUtils.readDeclaredField(engine, "test", true)
def headerManagerSearch = new SearchByClass<>(HeaderManager.class)
testPlanTree.traverse(headerManagerSearch)
def headerManagers = headerManagerSearch.getSearchResults()
headerManagers.any { headerManager ->
new File('headers.csv').readLines().each { line ->
def values = line.split(',')
headerManager.add(new Header(values[0], values[1]))
}
}
If you want you can "externalize" points 3 and 4 via Test Fragment

jmeter: evaluate the values of JSON values

I am trying to test my API response using JSON assertion in JMeter, but couldn't find out on how to achieve it. The API returns 2 values, and I need to check if the difference between these two value are consistent
API response:
{
"start": "12759898",
"end": "12759907"
}
I've tried like the above, but it seems to be wrong, as its a JSONPath variable.
Could anyone guide on how to evaluate these values? is it possible to achieve this?
It looks like a job for JSR223 Assertion
Add JSR223 Assertion as a child of the request which returns the above JSON
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def start = response.start as long
def end = response.end as long
def delta = end - start
if (delta != 10) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Expected: 10, got: ' + delta)
}
If the difference between start and end will not be equal to 10 - the request will be marked as failed.
More information:
Groovy: Parsing and producing JSON
Scripting JMeter Assertions in Groovy - A Tutorial

How to measure size of response data in JMeter

How to measure size of response data of multiple http samplers in JMeter. I need to find the overall size of all the responses not for individual responses. I am trying to fetch it through a Beanshell code but it displays the size of the last sample executed:-
import java.util.io.*;
import java.lang.io.*;
int totalsize;
test = prev.getResponseDataAsString().length();
log.info("size is = "+test);
totalsize = totalsize + test;
log.info("totalsize is = "+totalsize);
Thank you.
Use JSR223 code with props and set JMeter property totalsize with 0 at start
props.put("totalsize", Integer.parseInt(prop.get("totalsize")) + test);
Following solution also worked for me on a beanshell post processor:-
import java.util.io.*;
import java.lang.io.*;
test = prev.getResponseDataAsString().length();
log.info("size is = "+test);
text = ctx.getCurrentSampler().getName();
log.info("Sampler name is " +text);
if(text.equalsIgnoreCase("Test Sampler")){
props.put("totalsize",Integer.parseInt("0"));
}else{
props.put("totalsize", (props.get("totalsize")!=null?props.get("totalsize"):0) + test);
}
log.info("totalsize is = "+props.get("totalsize"));
"test" captures the size of each of the sample requests and keeps adding it to the "totalsize". At the end of the execution I am initializing totalsize back to 0.
it's more appropriate to use prev.getBytesAsLong() to get each sampler response size. Take a look at JMeter API
To have combined size of multiple responses you could try grouping needed requests in transaction via Transaction Controller.

How to Duplicate file using JMeter

I am trying to duplicate a file using JMeter,
The scenario:
Loading a JSON file. For example, {"name":"John","age":"$age_place"}
Modify one property - age_place from 1 to 20
Save each modified iteration into a separate file
I have tried to do that with Simple Data Writer but it didn't work.
You have JSR223 Elements as Sampler or Pre processor which you can add powerful script,
The easiest is to replace age_place with your value, for example if saved in variable age_place:
f = new FileOutputStream("c:\\temp\\template.json", false);
p = new PrintStream(f);
this.interpreter.setOut(p);
print("{\"name\":\"John\",\"age\":\"age_place\"}".replaceAll("age_place", vars.get("age_place")));
f.close();
If you need to generate 20 files with different age you can do it using any of JSR223 Test Elements. Example Groovy code would look like:
def json = new groovy.json.JsonSlurper().parseText("{\"name\":\"John\",\"age\":\"\"}")
def builder = new groovy.json.JsonBuilder(json)
1.upto(20, {
builder.content.age= "${it}"
def writer = new File('file' + "${it}" + ".json").newWriter()
writer << builder.toPrettyString()
writer.close()
})
Once you execute your test it will create the following files in the "bin" folder of your JMeter installation:
file1.json - with the age of 1
file2.json - with the age of 2
...
file20.json - with the age of 20
References:
Groovy For Loop Examples
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Resources