Remove an HTTP Request PATH Variable if null - jmeter

I have this script in JMeter, PUT method,
how can i remove a path variable if the value from the input data is blank?
I know i can remove this if the parameter were in the Parameter tab of the HTTP request using the remove Arguments, the thing is I have a value in the body data so I have to put the URL parameters in the path that's why remove arguments is not working anymore.
code:
if ("${thisfromCSV}" == "") {
sampler.getArguments().removeArgument("thisParameter");
}
this works if the parameter is located at the Parameters tab of the HTTP Request

Add JSR223 PreProcessor as a child of the HTTP Request you would like to modify
Put the following code into "Script" area:
def url = new URL("http://example.com" + sampler.getPath())
def params = url.query.split('&').collectEntries({ param ->
param.split('=').collect {
URLDecoder.decode(it, 'UTF-8')
}
})
if (vars.get('thisfromCSV') == '') {
params.remove('thisParameter')
}
def query = params.collect { k, v -> "$k=$v" }.join('&')
sampler.setPath(url.path + '?' + query)
That's it, the code will remove thisParameter from the Sampler's URL query string in case of thisfromCSV variable is empty.
See Apache Groovy - Why and How You Should Use It for more information on using Groovy scripting in JMeter tests.

Related

Jmeter - How to put each member of the forEach loop into variable

Based on this thread - Jmeter - how to return multiple ID(s) based on the array (match JSON path with array)
I managed to get ID's, for every single member of the array.
Now I need to alternate the code and to have a variable for every single ID.
What i tried is:
vars.get('array').replace("[", "").replace("]", "").split(", ").each { country ->
def result = new groovy.json.JsonSlurper().parse(prev.getResponseData()).payload.find { entry -> entry.name == country.trim() }
vars.put("tim" + ${__counter(,)}, result.id as String);
}
But, I am only able to get a single variable.
What should I do in order to save every single result.id, into variables like:
tim1, tim2, tim3...
Don't inline JMeter Functions or Variables into Groovy scripts.
As per JMeter Documentation:
The JSR223 test elements have a feature (compilation) that can significantly increase performance. To benefit from this feature:
Use Script files instead of inlining them. This will make JMeter compile them if this feature is available on ScriptEngine and cache them.
Or Use Script Text and check Cache compiled script if available property.
When using this feature, ensure your script code does not use JMeter variables or JMeter function calls directly in script code as caching would only cache first replacement. Instead use script parameters.
So I would rather recommend amending your code as follows:
vars.get('array').replace("[", "").replace("]", "").split(", ").eachWithIndex { country, index ->
def result = new groovy.json.JsonSlurper().parse(prev.getResponseData()).payload.find { entry -> entry.name == country.trim() }
if (result != null) {
vars.put("tim" + (index + 1), result.id as String);
}
}
Demo:
More information: Apache Groovy - Why and How You Should Use It

Is it possible to remove empty query string parameters in jMeter?

I want to test an endpoint using jmeter, that has a copule of query string parameters, one of which is optional, loading the values from a CSV file. The problem is, can I avoid sending the query string parameter if I don't have a value for it?
It is but it will require some Groovy coding
Add JSR223 PreProcessor as a child of the request which query string you want to modify (or according to JMeter Scoping Rules if you want to apply the approach to more than one request)
Put the following code into "Script" area:
def newData = new org.apache.jmeter.config.Arguments()
0.upto(sampler.getArguments().size() - 1, { idx ->
def arg = sampler.getArguments().getArgument(idx)
if (!arg.getValue().equals('')) {
newData.addArgument(arg)
}
})
sampler.setArguments(newData)
That's it, the PreProcessor will be executed before the HTTP Request sampler and will remove all arguments which don't have their respective values

How to remove the characters �� from the JSON response using Jmeter?

Below is the JSON Response from the Server, How to remove the characters �� from the below Response using Jmeter
Response :
{"_id":"5d56cc5c31acfd001298e863","test_id":"5d56cc593801370012bdb2bb","display_order":"1","question_type":"MULTIPLE CHOICE","isbn":"9780393630749","status":"added","question":{"_id":"5d56cc5c31acfd001298e864","questionId":"5d4262bb56c1d800122fcb48","QuestionTitle":{"key":"","value":"","valueRTF":"","valueHtml":"��������\n
I have written the groovy Script. but it is not removing the char.
def response = prev.getResponseDataAsString();
def var1= response.replaceAll("\�", "");
and I need to use this Var1 in another request.
Most probably you're seeing these question marks due to encoding problems, try setting file.encoding property to UTF-8 in system.properties file and restart JMeter, most probably you will see normal text instead of the question marks.
If for some reason the above hint is not applicable I would recommend replacing the whole valueHtml attribute value using JsonBuilder, the relevant code would be something like:
def builder = new groovy.json.JsonBuilder(new groovy.json.JsonSlurper().parse(prev.getResponseData()))
builder.content.question.QuestionTitle.valueHtml = ''
vars.put('Var1', builder.toPrettyString())
As the result you will have the same JSON structure with empty valueHtml attribute.
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
As it is a JSON Response, add JSON Extractor Post Processor to the Parent Sampler from where the Response is expected. Extract whole JSON with following settings:
Now, use a JSR223 Sampler, with following code in script area:
String var1 = vars.get("jsonOutput");
log.info("Output: " + var1);
String replaceString=var1.replace('?','-'); // replace with whatever you want to, I am replacing it with '-'
log.info("Output: " + replaceString);
vars.put("NewString", replaceString);
Afterwards, you can use ${NewString} wherever you want.

how to extract value from request in Jmeter

Hi I am passing an email which is a time function like below
email = ${__time(MMddyy)}_${__time(HMS)}#yopmail.com
The value of this function changes eveytime I call the variable email.
I would like to store this value that is generated from this function into a variable and use that in other requests.
So currently I am getting two different emails in two different http requests since there is some time lag between my two http requests.
what I would like to do is .. store the email that is being sent in first http request by extracting the value from the request and pass it in the second http request.
POST data:
email=062915_160738%40yopmail.com
I know the way to extract from html response.. but is there any way to extract from request in jmeter?
If so can someone pls tell me how to achieve this?
thank you
Add a Beanshell PostProcessor as a child of the request which sends that POST request
Put the following code into the PostProcessor's "Script" area
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
Arguments argz = ctx.getCurrentSampler().getArguments();
for (int i = 0; i < argz.getArgumentCount(); i++) {
Argument arg = argz.getArgument(i);
if (arg.getName().equals("email")) {
vars.put("EMAIL", arg.getValue());
break;
}
}
Refer generated value as ${EMAIL} where required.
Clarification:
above code will extract the value of email request parameter (if any) and store it to EMAIL JMeter Variable
ctx - shorthand to JMeterContext class instance
vars = shorthand to JMeterVariables class instance
Arguments and Argument - you can figure that out from JMeterContext JavaDoc
See How to use BeanShell: JMeter's favorite built-in component guide for more information on Beanshell scripting in JMeter.
Instead of the entire email, you can store the timestamp value in a variable and then use this timestamp variable to create email anywhere you want.
This way you will can have same email every where.
Add a Beanshell PostProcessor & Add following script:
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
Arguments argz = ctx.getCurrentSampler().getArguments();
for (int i = 0; i < argz.getArgumentCount(); i++) {
Argument arg = argz.getArgument(i);
String req_body = arg.getValue();
vars.put("req_Json",req_body);
}
here we get the output in json format:
${req_Json}=
"email":"062915_160738%40yopmail.com",
"name":"abc xyz"
Now using jp#gc Json Path Extractor extract the value of email
Json expression = $['email']
and store the value in email_value_extacted
now use the variable ${email_value_extacted} anywhere you want to use.
finally,
${email_value_extacted} = 062915_160738%40yopmail.com
Is it HTTP Sampler? If so, just put into beanshell postprocessor:
String prevQuery = prev.getQueryString(); //your request text
System.out.println(prevQuery );
Also works for any samplers:
String prevQuery = prev.getSamplerData();
You can use Regular Expression extractor to extract the e-mail address from the request URL.
Add Regular Expression Extractor as a child of sampler which sends the post request.
In the Regular Expression Extractor select URL in Response Filed to check instead of Body.
You should be able to extract e-mail id from the request in this way.

How can we set the value to the header dynamically in SOAPUi?

I'm new to SoapUI. I wanted to know how can we add 2 property value into one Header value.
For instance, I got some response like in XML format:
<Response xmlns="Http://SomeUrl">
<access_token>abc</access_token>
<scope>scope1</scope>
<token_type>Bearer</token_type>
</Response>
I want to send both access_token & token type to a single header value like:
"Authorization":"Bearer abc"
I am not getting how to do this using property transfer step.
Can anyone please help me?
You can use XPath concat function to concatenate the both values in one variable in your property transfer steps, in your case you can use the follow XPath:
concat(//*:token_type," ",//*:access_token)
concat function concatenates two or more strings, //*:token_type gets the Bearer value and //*:access_token gets the abc.
Hope this helps,
Add a script step after the step returning what you describe above.
def tokenType = context.expand('${STEP RETURNING STUFF#Response#//Response/token_type}');
def token = context.expand('${STEP RETURNING STUFF#Response#//Response/access_token}');
//add header to all steps
for (def stepEntry : testRunner.testCase.testSteps) {
if (!(stepEntry.value instanceof com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep)) {
continue;
}
def headers = stepEntry.value.httpRequest.requestHeaders;
headers.remove("Authorization");
headers.put("Authorization", token_type + " " + token);
stepEntry.value.httpRequest.requestHeaders = headers;
}
Here is another way without using additional property transfer step, but uses script assertion
Add a script assertion for the request test step.
Use below code into that script, modify element XPath are required
def element1Xpath = '//*:token_type'
def element2Xpath = '//*:access_token'
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def response = groovyUtils.getXmlHolder(messageExchange.responseContentAsXml)
def field1 = response.getNodeValue(element1Xpath)
def field2 = response.getNodeValue(element2Xpath)
if (!field1) { throw new Error ("${element1Xpath} is either empty or null") }
if (!field1) { throw new Error ("${element2Xpath} is either empty or null") }
context.testCase.setPropertyValue('TEMP_PROPERTY', "${field1} ${field2}")
Now the expected value(merged) is available in a property 'TEMP_PROPERTY'. You may rename the property name as you wish in the last line of the code.
You may the new wherever it is needed within the test case.

Resources