Is it possible to parameterize Post requests payload and then encode it to base64 in Jmeter - jmeter

The background is that I want to make a REST to Google pub/sub. Where the data need to follow this format:
Link to documentation of Pub/Sub format
My current solution is that I uses an BeanShell PreProcessor script to encode the payload to base64 before I send the request to the endpoint. This solution works, but I would like to
parameterize the data in the payload, instead of having the whole payload inserted as test data in the csv-file.
BeanShell PreProcessor used to encode the message before it is being sent:
import org.apache.jmeter.protocol.http.util.Base64Encoder;
String csv_payload = vars.get("csv_payload");
String csv_payload_encoded = Base64Encoder.encode(csv_payload);
vars.put("csv_payload_encoded", csv_payload_encoded);
Payload populated from the csv-file in Post request:
{
"messages": [
{
"data":"${csv_payload_encoded}",
}
]
}
Example of payload data stored in the csv-file that is sent in the request:
{"identId":"123456","requestId":null,"payload":{"header":{"requestid":1,"timeStamp":1617873956,"version":"0.0.0.1","eventId":0001,"creatorId":0,"messageTTL":34560},"body":{"checkid":001,"checkData":{"diagnosticsData":{"troubleSource":0,"data":"[2020-01-01 16:00:53.707961][[lat[0]][long[0]][alt[0]][canbetrust[0]][mars[0]]][signal[5]][TEM2 wake up]"}}}}}
Example of the encoded payload that the request sends to google pub/sub:
{
"messages": [
{
"data":"eyJpZGVudElkIjoiMTIzNDU2IiwicmVxdWVzdElkIjpudWxsLCJwYXlsb2FkIjp7ImhlYWRlciI6eyJyZXF1ZXN0aWQiOjEsInRpbWVTdGFtcCI6MTYxNzg3Mzk1NiwidmVyc2lvbiI6IjAuMC4wLjEiLCJldmVudElkIjowMDAxLCJjcmVhdG9ySWQiOjAsIm1lc3NhZ2VUVEwiOjM0NTYwfSwiYm9keSI6eyJjaGVja2lkIjowMDEsImNoZWNrRGF0YSI6eyJkaWFnbm9zdGljc0RhdGEiOnsidHJvdWJsZVNvdXJjZSI6MCwiZGF0YSI6IlsyMDIwLTAxLTAxIDE2OjAwOjUzLjcwNzk2MV1bW2xhdFswXV1bbG9uZ1swXV1bYWx0WzBdXVtjYW5iZXRydXN0WzBdXVttYXJzWzBdXV1bc2lnbmFsWzVdXVtURU0yIHdha2UgdXBdIn19fX19",
}
]
}
If there are any feedback I would appreciate it or any other improvements suggestion
for how I would be able to proceed in order to parameterize and encode the payload to base64 eg:
Example of

Don't use Beanshell, since JMeter 3.1 you're supposed to be using JSR223 Test Elements and Groovy language for scripting
There is __base64Encode() function available via Custom JMeter Functions plugin bundle installable using JMeter Plugins Manager
If you CSV file has references to other JMeter Functions or Variables you can resolve them by wrapping into __eval() function like:
to read the file:
${__FileToString(somefile.csv,,)}
to read the file and resolve any functions or variables in it:
${__eval( ${__FileToString(somefile.csv,,)})
to read the file, resolve any functions or variables and Base64-encode the result:
${__base64Encode(${__eval( ${__FileToString(somefile.csv,,)})},)}
Demo:

Related

I want to send the data that has been url encoding in Jmeter

I want to send a data that has been encryption.
So, I used JSR223 Sampler.
---skip---
def encrypted = Crypto.encrypt("AES/CBC/PKCS5Padding", "{"MY_SENTENCE"}", Crypto.generateSecretKey(), Crypto.generateIv())
vars.put("enc_data", encrypted);
Body Data in HTTP Request.
{ "data": "${enc_data}" }
In Results Tree
Request Body data was not url-encoding.
I want to send a data of url encoding, what should I do?
I don't know that.
I wrote Body Data in HTTP Request. So, I can't click the Parameters.
And I added Content encoding (UTF-8) it was not working too.
Either use __urlencode() function in the Body Data tab directly:
{ "data": "${__urlencode(${enc_data})}" }
JMeter Functions can be placed anywhere in the test plan and they're evaluated in the place where they're present so your ${enc_data} variable will be url-encoded in the runtime. See Apache JMeter Functions - An Introduction article for more information on JMeter Functions concept.
or call URLEncoder.encode() function in your Groovy script directly:
vars.put("enc_data", URLEncoder.encode(encrypted,"UTF-8"));

How to update Json file before sending as a request in Jmeter

In my Project, API Contract is changing frequently (every two sprints). From me it is very hard to update the payload in each 'http request' of project test cases.
I am looking for a solution to maintain a separate json file with the request. Update the request json file based on the test cases using Jmeter and send to server.
Do we have any solution for this?
Or please suggest if we have any other approach to handle this case.
sample JSON: original JSON has more than 600 lines.
{
abc:"abc",
xys:"xyz",
"abcd":[{
abc:"abc",
xys:"xyz",
abc:"abc",
xys:"xyz"
PQR:[{
abc:"abc",
xys:"xyz",
abc:"abc",
xys:"xyz",
}]}]
}
I can think of only one option:
Add JSR223 PreProcessor, it will be executed before the request
JSON file can be read using JsonSlurper
At this stage you can amend it according to your needs using Groovy language
Once you done you can construct the JSON back using JsonBuilder and write the generated new JSON back to the file
More information: Apache Groovy - Parsing and producing JSON

How can I dynamically post Request body (xml) and validate the response (xml)?

Is there a way to send the XML request dynamically and validate the XML response?
My scenario is:
I will have a CSV dataset config and inside the csv file I will have two column, the first one is for the inputXMLFilePath and the second column is the expectedXMLResposneFilePath.
So I need to have a JSR233 PreProcessor under HTTP request sampler, read the input file path convert it to the post body, and also has another JSR233 sampler for load the expected response from the expectedXMLResponseFilePath and compare it with the previous XML response. I have a snippet for JSON which is working fine. but for XML how can I do it?
You can use __FileToString() function for both use cases:
To send the XML request body, like ${__FileToString(${inputXMLFilePath},,)} (where ${inputXMLFilePath} is the variable from the CSV Data Set Config)
To validate the response using Response Assertion configured like:
Field to Test: Text Response
Pattern Matching Rules: Equals
Patterns to test: ${__FileToString(${expectedXMLResponseFilePath},,)}
You can use JMeter Functions literally at the any place of your Test Plan so their flexibility is higher than for other test elements. Also JMeter Functions are being compiled into native Java code therefore their execution speed will be higher and footprint will be less comparing to Groovy scripting.
Check out Apache JMeter Functions - An Introduction article to learn more about JMeter Functions concept.

How to pass json object in jmeter using csv file?

This is the json object
{
"addLabourerToSpecificShift":false,
"isEarlySubmit":true,
"isExistinglabourer":false,
"task":"add",
"currentDate":"2018-06-08T07:08:21.296Z",
"allSections":[
],
"labourerBean":{
"gender":0,
"enrolmentDate":"2018-06-08T07:08:21.296Z",
"epfMemberId":"2",
"firstName":"Kedar",
"lastName":"jadhav",
"dob":"1990-11-30T18:30:00.000Z",
"phone1":"1236547896",
"panNumber":"1452368545"
},
"companyRetentionBonus":0,
"isRootAdmin":true,
"from":"manage_labourers"
}
The easiest way would be formatting your JSON payload to look like a single string i.e.
{"addLabourerToSpecificShift":false,"isEarlySubmit":true,"isExistinglabourer":false,"task":"add","currentDate":"2018-06-08T07:08:21.296Z","allSections":[],"labourerBean":{"gender":0,"enrolmentDate":"2018-06-08T07:08:21.296Z","epfMemberId":"2","firstName":"Kedar","lastName":"jadhav","dob":"1990-11-30T18:30:00.000Z","phone1":"1236547896","panNumber":"1452368545"},"companyRetentionBonus":0,"isRootAdmin":true,"from":"manage_labourers"}
Then you will be able either to use CSV Data Set Config with \n Delimiter like:
and refer the value as ${json} where required.
Even easier option would be using __StringFromFile() function directly in your HTTP Request sampler Body Data tab like:
${__StringFromFile(/path/to/your/csv/file,,,)}
__StringFromFile() function reads the next line from the specified file each time it's being called so this way you will be able to parameterise your request with minimal effort

Creating dynamic Response Assertion in Jmeter

I am trying to run tests on JMeter and I expect a certain format of text in response assertion but it can change dynamically depending on the request. The response that I am expecting is something similar to as shown below :
{
"method": "<<Getting from the csv config file",
"student_id": "<<getting from the csv config file>>",
"term_id": "<<Getting from the csv Config file>>",
"crns": [{
"status_cd": "<<A numeric code from the response>>",
"section": "<<N or Y from response>>",
"message": "<<String value from response>>",
"crn": "<<Getting from the csv config file>>"
}]
}
I am not sure how to setup my response assertion to get the above format
I believe it is better to use JSON Path Assertion for JSON data. It is available via JMeter Plugins project and can be installed in a couple of clicks using JMeter Plugins Manager
See JSON Path - Getting Started and Advanced Usage of the JSON Path Extractor in JMeter to learn how to use JSON Path language for working with JSON data in JMeter

Resources