How to make the search parameters in http request as dynamic in jmeter - rest

http request: http://ipAddress:Port/SomeResource?Param1=value1&Param2=value2&......
so on.
This is a http request sample in jmeter that hits a rest api and gets response in JSON format.
Here the challenge is Param1, param2, param3 .... these search parameters number is not constant it may change depending on the call so i am making a csv file that contains rows that contain search parameters in coma separated format.
CSV file is like
param1,param2
param1,param2,param3
param1
I am using a CSV data configure to pull data from the csv file and put it in the http request
And putting this in http request like
Now if the param is null i don't want see this in http request header
so how to do this in jmeter.

Remove all "Parameters" from the HTTP Request, it should be clean
Add JSR223 PreProcessor as a child of the HTTP Request sampler you would like to parameterize
Put the following code into "Script" area:
1.upto(4, {
if (vars.get('param' + "$it") != null) {
sampler.addArgument(vars.get('param' + "$it"),'someValue')
}
})
Add JSR223 PostProcessor as a child of the request you would like to parameterize
Put the following code into "Script" area:
1.upto(4, {
vars.remove("param" + "$it")
})
That's it, you should now get what you need. You will not see the changes in JMeter GUI, you will only be able to observe them in the runtime using View Results Tree listener

Related

load and performance test of the AWS API in jmeter using two post methods

I need to test the load and performance test of the API which is hosted in the AWS API gate way. Im using two post methods to get the final result. first post method will pass the below parameters in json format in the API.
{
propno:"xxxxx",
apikey:"xxxx-xxxx",
user:"xxx"
}
by executing this i will get a reference number and status of the execution
{
reference:"ABxxxxxxxxxna",
status:"ok"
}
Then will pass this reference no in another post method to get the desired result.
{
refno:"ABxxxxxxxxxna",
apikey:"xxxx-xxxx",
user:"xxx"
}
Now i want to perform the load test in Jmeter. Any help would be appreciated.
What is your question exactly?
In JMeter you can send a POST request using HTTP Request sampler, the relevant configuration would be something like:
the refno value can be fetched using JSON Extractor configured like:
next in the second HTTP Request use ${refno} reference to the JMeter Variable
You might also need to add a HTTP Header Manager and configure it to send the Content-Type header with the value of application/json
once done you can
Add more users in the Thread Group according to your NFR/SLA/common sense/whatever
Run your test in command-line non-GUI mode
Generate HTML Reporting Dashboard and analyze the results

Jmeter - Set custom text on request tab using JSR223 sampler

I am creating a script on groovy to be able to send http requests.
To call this script I'm using the JSR223 Sampler
The thing is that I would like to reproduce as much as possible the behaviour that a HTTP Sampler has, meaning that I want to perform the request and also to fill the sampler's info (Response data, Request and Response)
Although I'm able to obtain SampleResult and set Response data and Response, does not seem to exist a method to set our own request string:
https://jmeter.apache.org/api/org/apache/jmeter/samplers/SampleResult.html
Following the docs, the closest method to do what I want is the setRequestHeaders().
If I call that method like this SampleResult.setRequestHeaders("My custom text") something like this appears on the request tab:
File C:\Users\UserName\groovy_file.groovy
Request Headers:
My custom text
Is there any way to print only the string My custom text, on the Request?
EDIT
Sampler must use a script file instead of the script field
The easiest way would be just overwriting the data using prev.samplerData() shorthand from the JSR223 PostProcessor
prev.samplerData = 'put the desired request data here'
where prev stands for the parent SampleResult class instance, check out Top 8 JMeter Java Classes You Should Be Using with Groovy article for more information on the JMeter API shorthands available for the JSR223 Test Elements.
If you don't want the PostProcessor you can still call the same function from your Groovy script like:
SamplerResult.setSamplerData('put the desired request data here')

Syntax to use parameters in Body section of HTTP Request Sampler in JMeter, using Rest API POST request with body and input from CSV file

I'm using JMeter to test a microservice and I need to use a parameter dynamically with a different value in each request. Also, the parameter is a part of a query that contains other constant values as well.
I defined user variables in the JMeter user.properties file (in JMeter bin folder):
JMeter -- bin/user.properties
# Parameters to use in JMeter
ES_HOST=127.0.0.1
ES_PORT=9200
ES_INDEX=segments
ES_TYPE=_doc
THREAD=5
CSVDATA_ROOT=C:/devtools/apache-jmeter-5.2.1/csv_data
Of course, I have User-Defined Variables:
And how my Test Plan is defined in JMeter
As you can see in the following screenshot of View Result Tree the parameter agentName I defined and shown in the HTTP Request (above) is working.
I want to define it in the body of the HTTP Request, to replace the hardcoded "John Doe" with a parameters that have a different value in each request.
"query":"SearchStartTime=2020-01-01 00:00:00.000TO2020-01-31 23:59:59.999&AgentName=John Doe"}
How can I do that?
I need a way to add a parameter to an existing string
I've already tried Using Apache JMeter to Test Elasticsearch (or any REST API) and In Jmeter, What would be syntax of parameters in Body Data section of HTTP Request Sampler, for Rest APIs and input should be generated dynamically also doesn't solve my problem.
Use same syntax as HTTP request - ${agentname} for getting variable value:
"query":"SearchStartTime=2020-01-01 00:00:00.000TO2020-01-31 23:59:59.999&AgentName=${agentname}"

AWS Api Gateway Setting the header value to a default value using http Integration

I am using AWS API Gateway and I want to set my Integration type to http. I have the integrated url as https:// xxxxxx.com which takes a header "apikey". I am not expecting the end user to pass the header rather I want to set the apikey to some constant value.
I see that there is a way to force the user to make him pass the header(by making header required under the Method Request section. However, I want to set it to default.
For example in all the requests which are internally calling the URL inside the API gateway should pass the header value as "12345".
You can add/remove/override headers with an Integration Request Mapping Template.
In the API Gateway console, chose the relevant api/resourece/method. Go to Integration Request > Mapping Templates and chose your Content-Type (if requests are going to be received without a Content-Type header, set the Content-Type for the mapping template to application/json, which is the default behaviour).
Then in the actual mapping template add the following:
{
#set($context.requestOverride.header.apikey= "testMe")
}
This will add (or overwrite if it already exists) a header called apikey with the value "testMe" to all http requests downstream.
If you take this route, then you will need to also map over any other headers, path parameters, query parameters or body that you wish to pass through.
You could loop through the headers and query parameters like this.
## First set the header you are adding
#set($context.requestOverride.header.apikey= "testMe")
## Loop through all incoming headers and set them for downstream request
#foreach($param in $input.params().header.keySet())
#set($context.requestOverride.header[$param]= $input.params().header.get($param))
#if($foreach.hasNext) #end
#end
## Loop through all incoming query parameters and set them for downstream request
#foreach($param in $input.params().querystring.keySet())
#set($context.requestOverride.querystring[$param]= $input.params().querystring.get($param))
#if($foreach.hasNext) #end
#end
As you need to ensure that the header apikey is set to a default value, you should set the override for apikey before looping through the rest of the headers as only the first override will take effect.
The relevant AWS documentation can be found here.
The other alternative would be to point your API Gateway at a Lambda and make the call from the Lambda instead.
Firstly thanks to #KMO for his help. The following is the solution:-
Enable Http Proxy Integration.
Add the headers apikey=xxxx and Accept-Encoding=identity under the same Integration
Request -> Http Headers.
Under Settings -> Binary Media Types set the following as separate Binary Media Types
'*', */*. I mean as two different lines.This step is needed to resolve the Gzip action while returning the response.
Add the Query parameter country in the URL Query String Parameters section.
In the Integration Request map the country parameter to ctry by adding the value under mapped from as method.request.querystring.country. This will ensure that the query parameter country you passed in the main URL will be fed to the downstream url as parameter ctry.
The advantage of this apporoach is that, even if you override the header apikey, the one set under the Http Headers will take the precedence.

How to send multiple json body using jmeter?

I have written a REST API and now my requirement is to send the multiple JSON body to the API using POST method from JMeter. I have a csv file with four values(1,2,3,4). And in each of the four files I have the JSON body. I used :
Step-1) added the csv file to jmeter and create a reference and named it JSON_FILE
Step-2) ${__FileToString(C:Path_to_csv_file/${__eval(${JSON_FILE})}.txt,,)}
But from this I am able to access only first file i.e which is named with one. How do I send the body of all file to the API?
Help is highly appreciated.
You won't be able to use CSV Data Set Config as it will read the next value for each thread (virtual user) and/or Thread Group iteration.
If your requirement is to send all the files bodies at once you can go for an alternative approach
Add JSR223 PreProcessor as a child of the HTTP Request sampler which you use for sending the JSON payload
Put the following code into "Script" area:
def builder = new StringBuilder()
new File('/path/to/plans.csv').readLines().each { line ->
builder.append(new File(line).text).append(System.getProperty('line.separator'))
}
sampler.getArguments().removeAllArguments()
sampler.addNonEncodedArgument('', builder.toString(), '')
sampler.setPostBodyRaw(true)
the above code iterates through entries in plans.csv file, reads the file contents into a string and concatenates them altogether. Once done it sets the HTTP Request sampler body data to the generated cumulative string.
Check out The Groovy Templates Cheat Sheet for JMeter to learn more and what else could be achieved using Groovy scripting in JMeter.
Use Body data as follows in HTTP Sampler:
{__FileToString(${JSON_FILE},,)}
You have to put all the file path in your plan.csv file. At each line, there should be a file path.
Example:
Suppose, you have 4 files with JSON body which you want to use in your HTTP sampler.
Give the file path of these 4 files in your CSV file which is plan.csv. Each line contains a file path like this:
/User/file/file1.json
/User/file/file2.json
/User/file/file3.json
/User/file/file4.json
Now, in your CSV data set config, Use the proper file name of CSV file which contains all the file path and give it a variable name like JSON_FILE.
Now, Use {__FileToString(${JSON_FILE},,)} this line in your Body data. Also use the loop count value accordingly.