How do I override the response content in a JMeter WebDriver sampler test? - jmeter

How do I override the response content in a JMeter WebDriver sampler test? When I run the following code, the response that is shown in the response tab of the WebDriver Sampler is the full content of the webpage rather than what I expected to see, a string value of "a message" . Any idea on what I am doing wrong?
var pkg = JavaImporter(org.openqa.selenium)
WDS.sampleResult.sampleStart()
WDS.log.info("Start...")
WDS.browser.get('http://google.com')
WDS.sampleResult.sampleEnd()
java.lang.Thread.sleep( 500 )
WDS.sampleResult.setResponseMessage( "a message" )
WDS.sampleResult.setSuccessful(true)
To reproduce this you need to download the WebDriver plugin pack for JMeter and add a "WebDriver Sampler" step and a "Firefix Driver Config" to your Test plan.
This doesn't work either:
WDS.sampleResult.responseMessage = 'a message'
WDS.sampleResult.successful = true
Nor did this:
WDS.sampleResult.setResponseData("a message", "utf-8")
WDS.sampleResult.setSuccessful(true)
Nor did this:
var message = "Hello World".split('')
WDS.sampleResult.setResponseData( message, 'utf-8' )
WDS.sampleResult.setSuccessful(true)
I am just trying to set a value that I can retrieve in a subsequent test step.

As per code:
https://github.com/undera/jmeter-plugins/blob/master/webdriver/src/com/googlecode/jmeter/plugins/webdriver/sampler/WebDriverSampler.java
ResponseMessage and ResponseData are overwritten by sampler after calling your script code.
So you can't do what you want to.

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

Handle negative cases in JMETER, for example my expected output response is 400

How to handle negative cases in JMETER, for example my expected output response is 400("There are no records") for an GET API?
In JMETER response is coming as failure or warning.
Is JMeter only handle positive scenarios like for all GET API response code should be 200 ?
Add Response Assertion as a child of the HTTP Request sampler which returns HTTP Status Code 400
Configure it as follows:
Tick Ignore status box
Set "Field to test" to Response code
Set "Pattern matching rules" to Equals
Add 400 as a "Pattern to test"
This way JMeter will pass only if the parent HTTP Request sampler returns 400 status code, otherwise it will fail.
You can add to HTTP Request Response Assertion with Ignore status checked
HTTP Responses with statuses in the 4xx and 5xx ranges are normally regarded as unsuccessful. The "Ignore status" checkbox can be used to set the status successful before performing further checks. Note that this will have the effect of clearing any previous assertion failures, so make sure that this is only set on the first assertion.
I tried with this, by adding a BeanShell Assertion with following code.
import org.apache.jmeter.assertions.AssertionResult;
String failureMessage = "";
String ResCode = SampleResult.getResponseCode();
if (!ResCode.equals("400")) {
failureMessage = "Got Response Code" + ResCode;
AssertionResult result = new AssertionResult("Expected Response 400");
result.setFailure(true);
result.setFailureMessage(failureMessage);
prev.addAssertionResult(result);
prev.setSuccessful(false);
SampleResult.setStartNextThreadLoop(true);
} else {
//failure criteria
}

Jmeter 4 | HTTP Request sampler JAVA implementation bytes sent not captured

We are using JAVA implementation for one of the requests.In the request we are uploading a file. Request doesn't work when HTTPCLIENT4 implementation is selected.The request works fine with previous Jmeter version with HTTPCLIENT3.1 implementation. We need to capture bytes sent in results. How to capture bytes sent through JAVA implementation in HTTP Request sampler
Sent bytes is basically a combination of URL + headers + body so you can calculate it yourself using JSR223 PostProcessor and code like:
def url = sampler.getUrl().toString().length()
def headers = prev.getHeadersSize()
def body = 0;
sampler.getHTTPFiles().each {file ->
body += new File(file.getPath()).length()
}
prev.setSentBytes(url + headers + body)
Where:
sampler is an instance of HTTPSamplerProxy where you can get all files which you're sending with the request
prev is an instance of HTTPSampleResult where you can get URL and Headers and also override Sent Bytes field.
See The Groovy Templates Cheat Sheet for JMeter to see what else you can do with Groovy and how.

JMeter - Saving post data from http requst sample to the csv file

I have a Http request with Body Data which can create individual user any time when it runs for example:
{"username":"fakeuser${__RandomString(5,abcdefghijklmnofqrst1234567,userno)}","email":"fakeuser${userno}#fakedomain.com","password":"blblabla123!","passwordRepeated":"blablabla123!"}
POST Data:
{"username":"fakeuser4mf7s","email":"fakeuser4mf7s#fakedomain.com","password":"blablabla123!","passwordRepeated":"blablabla123!"}
Is there any way to grab email and password value from the Post Data and save it to the same csv file any time when specific http request sample runs.
Add JSR223 PostProcessor as a chid of the HTTP Request sampler
Put the following code into "Script" area:
import groovy.json.JsonSlurper
def request = new JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
def email = request.email
def password = request.password
new File('test.csv') << email + ',' + password + System.getProperty('line.separator')
Once you execute your test the JSR223 PostProcessor will add the values of email and password objects into test.csv file (normally it should reside in "bin" folder of your JMeter installation)
References:
Groovy: Parsing and Producing JSON
Groovy Goodness: Working with Files
Apache Groovy - Why and How You Should Use It

JMeter Thread Group Not Getting to BeanShell PostProcessor

In my JMeter test plan, I'm trying to write all errors out to a log. I'm using a BeanShell Post-Processor configured as follows
import org.apache.jmeter.services.FileServer;
if (ResponseCode != null && ResponseCode.equals("200") == false) {
Failure = true;
// displays in Results Tree
FailureMessage ="Creation of a new CAE record failed. Response code " + ResponseCode + "." ;
// Static elements
part1 = "Creation of a new record failed. Response code: ";
part2 = ". Sorry!";
// Open File(s)
FileOutputStream f = new FileOutputStream("d:\\error.csv", true);
PrintStream p = new PrintStream(f);
// Write data to file
p.println( part1 + ResponseCode + part2 );
// Close File(s)
p.close();
f.close();
}
I'm trying to do a simple test where the HTTP request is doing a POST that is passing in a json file from c:jmeter/tests/payloads where the directory no longer exists. (let's say someone accidentally deletes it...)
The issue is the test is stopping (see below) and never getting to the BeanShell to write the error out to a log file. I need to capture all error responses, and only error responses.
I'm not sure how to handle this. I've read Jmeter. BeanShell PostProcessor and others, but they doesn't address the issue of what happens when it doesn't get to the BeanShell.
Any help is appreciated!
org.apache.jorphan.util.JMeterStopThreadException: End of sequence
at org.apache.jmeter.functions.FileToString.execute(FileToString.java:105)
at org.apache.jmeter.engine.util.CompoundVariable.execute(CompoundVariable.java:142)
at org.apache.jmeter.engine.util.CompoundVariable.execute(CompoundVariable.java:118)
at org.apache.jmeter.testelement.property.FunctionProperty.getStringValue(FunctionProperty.java:101)
at org.apache.jmeter.testelement.AbstractTestElement.getPropertyAsString(AbstractTestElement.java:274)
at org.apache.jmeter.config.Argument.getValue(Argument.java:146)
at org.apache.jmeter.protocol.http.util.HTTPArgument.getEncodedValue(HTTPArgument.java:236)
at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.sendPostData(HTTPHC4Impl.java:1111)
at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.handleMethod(HTTPHC4Impl.java:453)
at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.sample(HTTPHC4Impl.java:329)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:74)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1146)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1135)
at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:434)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:261)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: File 'C:\JMeter\test\payloads\Request_1.json' does not exist
at org.apache.commons.io.FileUtils.openInputStream(FileUtils.java:299)
at org.apache.commons.io.FileUtils.readFileToString(FileUtils.java:1711)
at org.apache.commons.io.FileUtils.readFileToString(FileUtils.java:1734)
at org.apache.jmeter.functions.FileToString.execute(FileToString.java:102)
SOLUTION
Based on Dmitri's feedback, I've switched from a Beanshell PostProcessor to Beanshell Assertion. After some tweaking, I got it to work where it now writes only errors (response != 200) to an errors.csv file. Instead of appending the file from a previous run, it overwrites with each run so only the last run's errors are captured.
If anyone thinks my solution could be improved, I'd be happy to receive the feedback. Thanks again to Kiril and Dmitri.
import org.apache.jmeter.services.FileServer;
if (ResponseCode != null && ResponseCode.equals("200") == true) {
SampleResult.setResponseOK();
}
else if (!ResponseCode.equals ("200") == true ) {
Failure = true;
FailureMessage ="Creation of a new record failed. Response code " + ResponseCode + "." ; // displays in Results Tree
print ("Creation of a new record failed: Response code " + ResponseCode + "."); // goes to stdout
log.warn("Creation of a new record failed: Response code " + ResponseCode); // this goes to the JMeter log file
// Static elements or calculations
part1 = "Unable to generate a new record via POST. The response code is: \"";
part2 = "\". \n\n For response code = \'Non-HTTP ressponse\', verify the payload file still exists. \n For response code = 409, check the recordTypeId and recordGrpId combination for validity. \n For response code = 500, verify the database and its host server are reachable. ";
// Open File(s)
FileOutputStream f = new FileOutputStream(FileServer.getFileServer().getBaseDir() + "\\error.csv");
PrintStream p = new PrintStream(f);
// Write data to file
p.println( part1 + ResponseCode + part2 );
// Close File(s)
p.close();
f.close();
}
There are no ResponseCode, Failure and FailureMessage in the Beanshell PostProcessor, switch to Beanshell Assertion instead.
Your ResponseCode.equals("200") clause assumes successful response, error responses usually have response codes > 400
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for comprehensive information on Beanshell scripting in JMeter.
Jmeter overwrites your error.csv file instead of appending to it because you reopen it on every assertion call. Try to open it beforeheand, e.g. in separate Beanshell Sampler in setup thread group:
file = new FileOutputStream("error.csv", true);
bsh.shared.custom_log = new PrintStream(file)
And then use it in your beanshell assertion in a way like:
if (ResponseCode.equals("200")==false) {
bsh.shared.custom_log.println( part1 + ResponseCode + part2 );
}
Btw, AFAIK, you didn't need this part at all, because http responses with code 200 are OK by default:
if (ResponseCode != null && ResponseCode.equals("200") == true) {
SampleResult.setResponseOK();
}
I did't tested the code so there might be typos, but very similar one works for me.
Beanshell shared values are accessed under lock, so beware of possible performance issues if you writes to it heavily. With script like this and fairly short strings (50-100 chars), i'v got ~1k writes per second without significant impact on jmeter perfomance.

Resources