JMeter Modify the GET response to use in PUT - jmeter

I have two requests, the first one is GET, second is PUT. I should receive the response data from GET request, modify it a little bit and send with PUT request. So far I managed to do all, except modifying the response data.
For GET request I use Regular Expression Extractor as Preprocessor:
And currently I send the PUT request without modifying the data:
JSON structure:
{
"property1" : 1,
"property2" : "2",
"innerPropery" : {
"innerProperty1" : "value1",
"innerProperty2" : "value2",
"innerProperty3" : "value3"
}
}
I should change the innerProperty2.
Thanks!

You can do it without Regular Expression Extractor interim step.
Add JSR223 PostProcessor as a child of the getForm request
Choose groovy in the "Language" drop-down
Put the following code into "Script" area:
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def response = prev.getResponseDataAsString()
def json = new JsonSlurper().parseText(response)
def builder = new JsonBuilder(json)
builder.content.property2 = '2.1'
vars.put("response", builder.toPrettyString())
In saveForm request use ${response} as the request body
References:
Parsing and Producing JSON
Beanshell vs JSR223 vs Java JMeter Scripting: The Performance-Off You've Been Waiting For!

I have managed to do this via BeanShell PostProcessor. First I have added a new BeanShell PostProcessor: click right button on getFrom, Add -> Post Processors -> BeanShell PostProcessor. After that I opened the reated BeanSChell and have written the following code in Script field:
responseString = vars.get("response");
log.info("Received response: " + responseString);
responseString = responseString.replace("\"prop1\" : \"value2\"", "\"prop1\" : \"value2.1\"");
log.info("Response to send: " + responseString);
vars.put("modifiedResponse", responseString);
In Parameters field I have written:
response
Finally, I changed for PUT request the body from
${response}
to
${modifiedResponse}

Related

Jmeter: Json Extractor: Response from first request to be used in next Request

I have a Http request for which i am getting data from CSV data file and i am getting a response body as {"abc":"123456123"}. I have added JSON extractor as child to this Http request. I am given variable name as abc and tried json path as both $..abc or $.abc and now i have added new Http request(2) in which i want to pass variable name from json extractor in request body(2). I have used same variable name in the http request body(2) but the variable name is not passing in the new request.
I gave all the options in json path in json extractor, i am expecting that for each response {"abc":"123456123"}(this value will change for each request) json extractor should get the response value and pass in the next request body.
When i am running the script, the value is not passed in request2.
Response of request 1 :- for single thread
{"abc":"123456123"}
Json Extractor:-
name of variable : abc
JSON path:- $.abc
Request 2:-
{
"a":{
"b":[
{
"mRID":"${abc}",
"abc":[
{
"a":[
{
"n":[
{
"na":[
{
"a":"",
"a":"AF",
"value":"add"
}
]
}
],
"cr":[
{
"name":"0071",
"nameType":"r#"
},
{
"name":89923,
"nameType":"NR#"
}
],
"CS":[
{
"dateTime":"${__timeShift(yyyy-MM-dd'T'hh:mm:ss)}",
"type":"CS",
"value":"x"
}
]
}
]
}
]
}
]
}
}
I cannot reproduce your issue using Dummy Sampler and the JSON Extractor configuration you described.
Try adding Debug Sampler after the uuu request and see if there is abc variable generated and what value does it have.
Also check jmeter.log file for any suspicious entries

How to loop through JSON request in JMETER

I am using jmeter for performance testing & stuck at a point. I have to process a request with multiple users & before I process the request to an API endpoint, I have to iterate on all users & need to update the "ConsentDate" to system.DateTime. So please help me with a solution, i am a beginner to the jmeter framework.
I am trying to take help of JSR223 PreProcessor .
Please find the screen shot.
Jmeter
I am reading the json from a CSV file & My request structure looks like below,
{
"Company": {
"User": {
"u1": {
"id": "1001",
"consent": "Yes",
"consentDate": "2020-03-14T17:44:56.224Z"
},
"u2": {
"id": "1002",
"consent": "No",
"consentDate": "2020-03-14T17:44:56.224Z"
}
}
}
}
Oh, that's very easy, please find the screen shot
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
Text version of the code just in case, going forward please post code as text, not as image:
def data = new org.apache.jmeter.config.Arguments()
def request = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
def now = new Date().format("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
request.Company.User.each { user ->
user.getValue().consentDate = now
}
def body = new org.apache.jmeter.protocol.http.util.HTTPArgument('', new groovy.json.JsonBuilder(request).toPrettyString(), '', false)
body.setAlwaysEncoded(false)
data.addArgument(body)
sampler.setArguments(data)

How to use array from response1 in request2 in jmeter?

I am trying to extract a jsonArray from response of request1 and use it in request2. I am using JSONextractor the steps in this question but I am getting the array as different variables instead of 1 jsonArray.
My JsonExtractor:
Output of debug sampler:
Request:
{
"items": [
{
"id": "asd"
},
{
"id": "def"
},
{
"id": "hij"
}]
}
I don't know what I'm doing wrong that is extracting values in different variables instead of 1 jsonArray.
You can generate a JSON request body from the JMeter Variables which are coming from the JSON Extractor using JSR223 PreProcessor
Add JSR223 PreProcessor as a child of the request which you want to parameterize
Put the following code into "Script" area:
def payload = [:]
def items = []
1.upto(vars.get('userIds_matchNr') as int, { index ->
items.add([id: vars.get('userIds_' + index)])
})
payload.put('items', items)
vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())
You should be able to put the ${payload} JMeter Variable reference into the request "Body Data" tab
Demo:
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Which controller to use in Jmeter?

I want to create a controller that should run a till the condition fails. How it can be implemented in Jmeter.
The controller should contain a HTTP Request with a post body which is dynamic the request should continue till the condition fails,but i dont know where the should i apply that condition.
{
"access": {
"identifier": "9876f",
"Reproduce": "Right",
"possible": {
"id": "u7ur038",
"value": "Move"
}
}
}
If the response "Reproduce" contain "Right"then it should run again HTTP Request for new body and If the response "Reproduce" contain "Wrong"then it should stop executing.
You can use a While Controller which will contain your request.
Condition of While Controller will be:
${__jexl3("${response}" != "Wrong")}
Add as child of your HTTP Request a JSON Extractor:
Names of created variables: response
JSON Path Expressions: $..Reproduce
Match No.: 1
To reset variable for next thread loop iteration, add before While Controller a Flow Control Action and put inside it a preprocessor called User Parameters .
Click « Add Variable » and set :
Name: response
User_1: Right

How do i remove empty parameter using beanshell preprocessor in jmeter

I am trying to read a csv file that contains more that 500+ rows and each row will serve as request to API. Now my problem is that some of the parameters have empty string and i would like to set up a condition in case if parameter returns empty string then remove that parameter from request body upfront before hitting the API
Below is my json
{
"body": {
"Id1": "${Id1}",
"addressId": "${addressId}",
"languageCode": "${languageCode}",
"tempId": "${tempId}"
}
Now after reading csv i get following values in my request body
{
"body": {
"Id1": "1",
"addressId": "1233",
"languageCode": "E",
"tempId": ""
}
As you can see tempId has empty string. Now using bean-shell preprocessor i am trying to remove this but no luck
Object requestBody = sampler.getArguments().getArgument(0).getValue();
if (requestBody.get("tempId").equals("")){
sampler.getArguments.removeArgument("tempId");
}
when i look into result tree i don't see tempId being deleted from the request. I would appreciate any help
Avoid using Beanshell for deprecation and bad performance.
Use groovy instead with this code:
import org.apache.jmeter.config.Arguments;
def request = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
def newRequest = evaluate(request.inspect())
request.body.each { entry ->
if (entry.getValue().equals('')) {
newRequest.body.remove(entry.getKey())
}
}
def arguments = new Arguments();
sampler.setArguments(arguments);
sampler.addNonEncodedArgument('', new groovy.json.JsonBuilder(newRequest), '')
sampler.setPostBodyRaw(true)
See:
JsonSlurper
JsonBuilder
If you're looking to learn jmeter correctly, this book will help you.
Replace in body "tempId": "${tempId}" with ${tempIdEval} and calculate value in JSR223 script
String tempIdEval = vars.get("tempId");
vars.put("tempIdEval", (port == null ? "" : "\"tempId\": \"" + tempIdEval + "\""));
Migration to JSR223 PreProcessor+Groovy is highly recommended for performance, support of new Java features and limited maintenance of the BeanShell library.
Since you are using beanshell preprocessor, we can use like
if (vars.get("tempId")!="")
vars.put("variablename","not null");
else
vars.put("variablename","is null");
and use the "variablename" instead. You can manipulate the string as well as below.
if (${tempId}=="")
{ vars.put("json","
{
"body": {
"Id1": "${Id1}",
"addressId": "${addressId}",
"languageCode": "${languageCode}""
}
}
else
{ vars.put("json","
{
"body": {
"Id1": "${Id1}",
"addressId": "${addressId}",
"languageCode": "${languageCode}",
"tempId": "${tempId}"
}
}
Be aware that since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language
The relevant Groovy code for JSR223 PreProcessor which removes JSON attributes with empty values would be something like:
def request = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
def newRequest = evaluate(request.inspect())
request.body.each { entry ->
if (entry.getValue().equals('')) {
newRequest.body.remove(entry.getKey())
}
}
sampler.getArguments().removeAllArguments()
sampler.addNonEncodedArgument('', new groovy.json.JsonBuilder(newRequest).toPrettyString(), '')
sampler.setPostBodyRaw(true)
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Resources