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

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

Related

google-api-ruby-client: Request serialization results in empty requests

replacement_requests = [
Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: "{{name}}", replace_text: "Joe"),
Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: "{{age}}", replace_text: "34"),
Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: "{{address}}", replace_text: "Westwood"),
]
batch_request = Google::Apis::DocsV1::BatchUpdateDocumentRequest.new(requests: replacement_requests)
Given the above code, when I pass this BatcUpdateDocumentRequest instance into my service.batch_update_document function, I receive a 400 bad request. This seems to be related to the way the batch request is being serialized.
To illustrate, if we call batch_request.to_json we receive the following:
"{\"requests\":[{},{},{}]}"
This tells me that something is going wrong during serialization, however my code seems rather canonical.
Any thoughts on why my requests are failing to be serialized?
You want to use the replaceAllText request using google-api-client with ruby.
You have already been able to put and get values for Google Document using Google Docs API.
If my understanding is correct, how about this modification? In your script, the created request body is {"requests":[{},{},{}]}. By this, the error occurs. Please modify the script as follows.
Modification points:
Use Google::Apis::DocsV1::SubstringMatchCriteria for contains_text of Google::Apis::DocsV1::ReplaceAllTextRequest
Use Google::Apis::DocsV1::Request for Google::Apis::DocsV1::ReplaceAllTextRequest.
By above modification, the request body is created.
Modified script:
text1 = Google::Apis::DocsV1::SubstringMatchCriteria.new(text: "{{name}}")
text2 = Google::Apis::DocsV1::SubstringMatchCriteria.new(text: "{{age}}")
text3 = Google::Apis::DocsV1::SubstringMatchCriteria.new(text: "{{address}}")
req1 = Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: text1 , replace_text: "Joe")
req2 = Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: text2, replace_text: "34")
req3 = Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: text3, replace_text: "Westwood")
replacement_requests = [
Google::Apis::DocsV1::Request.new(replace_all_text: req1),
Google::Apis::DocsV1::Request.new(replace_all_text: req2),
Google::Apis::DocsV1::Request.new(replace_all_text: req3)
]
batch_request = Google::Apis::DocsV1::BatchUpdateDocumentRequest.new(requests: replacement_requests)
# result = service.batch_update_document(document_id, batch_request) # When you request with "batch_request", you can use this.
Request body:
When above script is run, the following request body is created.
{"requests":[
{"replaceAllText":{"containsText":{"text":"{{name}}"},"replaceText":"Joe"}},
{"replaceAllText":{"containsText":{"text":"{{age}}"},"replaceText":"34"}},
{"replaceAllText":{"containsText":{"text":"{{address}}"},"replaceText":"Westwood"}}
]}
Note:
When the error related to the authorization occurs, please confirm the scopes and whether Docs API has been enabled.
References:
Method: documents.batchUpdate
ReplaceAllTextRequest
If this didn't work, I apologize.

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

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 - Strange Behavior when Variables used in CookieManager

JMeter Version 2.13 r1665067
So I seem to be having some trouble when using User-Defined Variables and/or JMeter Property Variables inside a CookieManager.
If I use a variable as the value for a Cookie inside the CookieManager, whether or not it's a User-Defined Var or a Property Var I have the same problem when trying to view the Cookie's value(s) inside a BeanShell Pre and PostProcessor.
If my Cookie Manager has this below: *The 1st line is when using properties variable and 2nd line is when using a var from a User Defined Variable, *FYI both lines are NOT used at the same time:
CookieManager:
NAME VALUE DOMAIN PATH
1st) MYID ${__P(propCookie)} www.mydomain.com /
OR
2nd) MYID ${userCookie} www.mydomain.com /
The propCookie variable is passed on the CLI or defined in a .properties file like below:
COMMAND-LINE --> -JpropCookie=SRV1
IN PROP FILE --> propCookie=SRV1
And the userCookie variable is defined inside a User Defined Variables Config Element like so:
NAME VALUE DESCRIPTION
userCookie ${__P(propCookie)} User var using prop variable as value
Then, when I run my test I can see in the Request Tab of the Results Tree that it is showing the Cookie and it has the correct value assigned to it, which is good... But when I attempt to view the Cookies in a BeanShell Pre/Post-Processor, it simply shows the Variable and NOT the actual value.
BeanShell PreProcessor Code
import org.apache.jmeter.protocol.http.control.Cookie;
import org.apache.jmeter.protocol.http.control.CookieManager;
log.info("### Inside BeanShell PreProcessor:");
CookieManager manager = sampler.getCookieManager();
log.info("Cookie Count = '" + manager.getCookieCount() + "'");
for (int i = 0; i < manager.getCookieCount(); i++) {
Cookie cookie = manager.get(i);
log.info("\t\t Cookie.getName() = '" + cookie.getName() + "'");
log.info("\t\t Cookie.getValue() = '" + cookie.getValue() + "'");
}
Here is the BeanShell Script's Output in the Log:
2015/04/29 14:33:00 INFO - jmeter.util.BeanShellTestElement: ### Inside BeanShell PreProcessor:
2015/04/29 14:45:58 INFO - jmeter.util.BeanShellTestElement: Cookie Count = '1'
2015/04/29 14:33:00 INFO - jmeter.util.BeanShellTestElement: Cookie.getName() = 'MYID'
2015/04/29 14:33:00 INFO - jmeter.util.BeanShellTestElement: Cookie.getValue() = '${userCookie}'
So as you can see in the output from the BeanShell, the getValue() function is printing the Variable assigned to the Cookie's value exactly like this --> "${userCookie}", and NOT what the actual Cookie's value is, which is "SRV1"...
Lastly, if I try to use the "COOKIE_" variable which is supposed to get automatically created, and I use this in BeanShell, vars.get("COOKIE_MYID"), it prints "null" every time... I have all the proper Cookie properties set in the jmeter.properties file, like these here, so I'm not sure what the problem is:
CookieManager.allow_variable_cookies=true
CookieManager.save.cookies=true
CookieManager.name.prefix=COOKIE_
I'm pretty much stumped for why this is happening so if anyone has any ideas for why this is happening, please feel free it would be greatly appreciated!
Thanks in Advance,
Matt
HTTP Request Sampler actually sets the cookie using CookieManager's getCookieHeaderForURL method which substitutes the value properly.
In Beanshell,
import org.apache.jmeter.protocol.http.control.Cookie;
import org.apache.jmeter.protocol.http.control.CookieManager;
manager = sampler.getCookieManager();
log.info(manager.getCookieHeaderForURL(new URL("http://www.google.com"))); //update the URL
This gives the cookies with updated values.
CookieManager's get & add methods are used to get & add cookies to the HTTP Cookie Manager at run time. So, getValue method gives the value as it is. getCookieHeaderForURL gets the appropriate cookies from the Cookie Manager for the domain with updated values.

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

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.

Resources