validate response using jsr223 assertion - jmeter

I have passed chgId as parameter in the get HTTP request.
https://*****?chgId=405
My api response is coming as -
{
"response": {
"data": [
{
"tid": 3697,
"chgId": 405,
"amount": 8.5,
"Currency": "USD",
},
{
"tid": 3698,
"chgId": 405,
"amount": 3.33,
"Currency": "USD",
}
]
}
}
Now from the response I want to validate in JSR223 assertion that the response is correct based on the chgId field. That means in both 'data' array "chgId": 405 text should come.
Can anyone suggest?

You could do something like:
def params = org.apache.http.client.utils.URLEncodedUtils.parse(prev.getURL().toURI(), 'UTF-8')
def expected = params.find { 'chgId' }.value as int
def actual1 = new groovy.json.JsonSlurper().parse(prev.getResponseData()).response.data[0].chgId
def actual2 = new groovy.json.JsonSlurper().parse(prev.getResponseData()).response.data[1].chgId
def success = (expected == actual1 && expected == actual2)
if (!success) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('chgId mismatch')
}
where prev stands for previous SampleResult
More information:
URLEncodedUtils JavaDoc
JsonSlurper
Apache Groovy - Parsing and producing JSON
Scripting JMeter Assertions in Groovy - A Tutorial

Related

[Jmeter]-> Less Than or Greater Than assertion in Jmeter Assertion on API response field

I have an API that responds to a parameter in JSON response body:
{
"metadata":
{
"count": 12206883,
"pagesize": 100,
"page": 1,
"total_pages": 122069,
"query_time": "1129ms"
}
}
I need to put an assertion in the "query_time" field value that it should be:
<= 1000 ms
I added JSON assertion in JMeter, but it is failing with the below message:
:Value expected to match regexp '<=1000', but it did not match: '102'
Can someone tell me how we can achieve it?
I think you should consider using JSON JMESPath Assertion
Example JSON:
{
"some_attribute": [
{
"query_time": 112
}
]
}
Example assertion configuration:
Textual representation just in case:
length(some_attribute[?query_time<=`1000`])
More information:
JMESPath Functions
JMESPath Examples
The JMeter JSON JMESPath Extractor and Assertion: A Guide
Got the answer. Would like to share so that it will help others:
Extract the value with the help of JSON Extractor.
For example:
Create variable: querytime
JSON Path expression: $.metadata.query_time
Now in JSR223 Assertion, write a script: Language: Groovy
String jsonString = vars.get("querytime");
int length1=jsonString.length();
String Qtime1=jsonString.substring(0,(length1-2));
int time = Qtime1.toInteger()
log.info ("The querytime is " + time);
if (time>1000)
{
AssertionResult.setFailureMessage("The Querytime is taking more than 1000ms");
AssertionResult.setFailure(true);
}

Request : duplicateSheet with Google Spreadsheet API : badRequest: Must specify at least one request

I'm trying to duplicate a sheet using Google Spreadsheet API.
But I keep getting this error : badRequest: Must specify at least one request
I've tried a lot of things but nothing seems to work so far.
Here is what I have (ruby) :
request_body = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new {
{
"includeSpreadsheetInResponse": false,
"requests": [
{
"duplicateSheet": {
"sourceSheetId": 1*********,
"insertSheetIndex": 2,
"newSheetId": 10,
"newSheetName": "*********"
}
}
],
"responseIncludeGridData": false,
"responseRanges": [
""
]}
}
response = service.batch_update_spreadsheet(spreadsheet_id, request_body)
I know the code is not over but I really can't figure out what is missing
Does anyone know what I need ? Many thanks in advance !!!
The new object should be enclosed with open and close parenthesis.
Your code should look like this:
request_body = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new(
{
"includeSpreadsheetInResponse": false,
"requests": [
{
"duplicateSheet": {
"sourceSheetId": 1*********,
"insertSheetIndex": 2,
"newSheetId": 10,
"newSheetName": "*********"
}
}
],
"responseIncludeGridData": false,
"responseRanges": [
""
]}
)
Reference:
Ruby Object and Classes
In your script, you use the camel case. In the case of Ruby, please use the snake case as follows.
Modified script:
request_body = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new(
{
include_spreadsheet_in_response: false,
requests: [
{
duplicate_sheet: {
source_sheet_id: 1*********,
insert_sheet_index: 2,
new_sheet_id: 10,
new_sheet_name: "*********",
}
}
],
response_include_grid_data: false,
response_ranges: [""]
})
response = service.batch_update_spreadsheet(spreadsheet_id, request_body)
Note:
As other patterns, you can also use the following scripts.
Pattern 2
request = Google::Apis::SheetsV4::Request.new
request.duplicate_sheet = {
source_sheet_id: 1*********,
insert_sheet_index: 2,
new_sheet_id: 10,
new_sheet_name: "*********",
}
request_body = Google::Apis::SheetsV4::BatchUpdateSpreadsheetRequest.new
request_body.include_spreadsheet_in_response = false
request_body.response_include_grid_data = false
request_body.response_ranges = [""]
request_body.requests = [request]
response = service.batch_update_spreadsheet(spreadsheet_id, request_body)
Pattern 3
request_body = {
include_spreadsheet_in_response: false,
requests: [{duplicate_sheet: {
source_sheet_id: 1*********,
insert_sheet_index: 2,
new_sheet_id: 10,
new_sheet_name: "*********",
}}],
response_include_grid_data: false,
response_ranges: [""],
}
response = service.batch_update_spreadsheet(spreadsheet_id, request_body, {})
Note:
In this answer, it supposes that your service can be used for using the batchUpdate method. Please be careful this.
Reference:
Method: spreadsheets.batchUpdate

How to remove unwanted keys from rest-assured response object and assert remaining object data with constant variable having json string using java

In rest-assured test cases I am getting response as mentioned, where I want to remove keys such as "updated_at", "deleted_at", "created_at" and "notice" and then assert this response object with expected json string constant which contains 'settings'
{
"notice": "The Settings are updated successfully.",
"settings": {
"push_notification": {
"enabled": true,
"credentials": [{
"key": "value"
}],
"service_name": "API Testing"
},
"created_at": "2019-05-04T14:52:32.773Z",
"deleted_at": "false",
"updated_at": "2019-05-07T11:23:22.781Z"
}
}
For given response the expected json string is...
public static String SETTING_EXPECTED = "{\"push_notification\": {\"enabled\": true, \"credentials\": [{\"key\": \"value\"}], \"service_name\": \"API Testing\"}}"
Please help me with creating a common method using java which can be reuse for response assertions in all the test cases.
To delete keys from response you can use below code I am using jayway jsonpath library, you need to pass Json Response and field name jsonPath, in case your it will be "$.settings.created_at" :
public String deleteFieldNameFromResponse(String jsonResponse, String fieldToDelete)
throws ParseException, FileNotFoundException, IOException {
Object obj = null;
JSONParser parser = new JSONParser();
JsonPath jsonPath = null;
DocumentContext docCtx = null;
obj = parser.parse(jsonResponse);
docCtx = JsonPath.parse(obj);
docCtx.delete(fieldToDelete);
jsonPath = JsonPath.compile("$");
return docCtx.read(jsonPath).toString();
}

Swagger UI not rendering the correct response(Should return a JSON response)[This is for the GET request Code 200]

Swagger UI is not returning the expected JSON response in the example value. It is returning a empty list.Below are the code snippets I am using,
Gradle Dependency
compile('io.springfox:springfox-swagger-ui:2.9.2')
compile('io.springfox:springfox-swagger2:2.9.2')
Swagger Config
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.ignoredParameterTypes(HttpServletResponse.class)
.select() .apis(RequestHandlerSelectors.basePackage("com.core.controller.v2"))
.paths(PathSelectors.any())
.build()
.enable(true)
.apiInfo(apiInfo())
.securityContexts(Lists.newArrayList(securityContext()))
.securitySchemes(Lists.newArrayList(apiKey()));
Controller
#ApiOperation(value="A GET request to get a list of all contents for a given user.",
notes = "This API is used to get the contents for a given user with an NPI and Partner ID",
response = CoreContentItem.class)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Success response", response = CoreContentItem.class,responseContainer = "List"),
#ApiResponse(code = 401, message = "Unauthorized"),
#ApiResponse(code = 400, message = "Bad Request",responseContainer = "String"),
#ApiResponse(code = 403, message = "Forbidden"),
#ApiResponse(code = 500, message = "Internal Server Error, please contact system administrator")})
Swagger Output
Swagger UI for success Response
Expected JSON response
This is a sample expected JSON response
[
{
"item": {
"id": "3f94ea1a687dda4af3e2",
"category": null,
"type": "EXTERNAL",
"headline": "DO NOT DELETE - REST ASSURED All - HIGH - JV",
"summary": "DO NOT DELETE - All - HIGH - JV",
"details": null,
"mediaURL": "",
"createdOn": 1493658088000,
"modifiedOn": 1495553312000,
"priority": "HIGH",
"startDate": 1493618400000,
"endDate": 1588312800000,
"feedbackEmail": null,
"totalLikes": 0,
"totalViews": 2,
"customData": null,
"userInteraction": {
"userLiked": false,
"userDisliked": false,
"userViewed": false
},
"availableActions": [
"View",
"Done",
"Submit"
],
"externalURL": "https://www.1234.com/vegetables/armando%25e2%2580%2599s-chiles-rellenos/r/5014"
}
}
]
I found the issue. Apparently it was a model mapping exception that made the Swagger UI to return an empty list. Now I am able to see the model in example value.
enter image description here

How do i send JsonObject with nested values as Post request in REST assured

I am using rest assured -https://code.google.com/p/rest-assured/wiki/Usage
My JsonObject looks like this
{
"id": "12",
"employeeInfo": null,
"employerInfo": null,
"checkDate": 1395093997218,
"netAmount": {
"amount": 70,
"currency": "USD"
},
"moneyDistributionLineItems": [
{
"mAmount": 100,
"employeeBankAccountId": "BankAccount 1"
}
],
}
how can i send this as part of parameters using REST-assured POST?
I have tried
given().param("key1", "value1").param("key2", "value2").when().post("/somewhere").then().
body(containsString("OK"));
but that is not scalable for HUGE objects with nested values. Is there a better approach?
You just send the JSON document in the body. For example if you have your JSON document in a String called myJson then you can just do like this:
String myJson = ..
given().contentType(JSON).body(myJson).when().post("/somewhere"). ..
You can also use a POJO, input stream and byte[] instead of a String.
URL file = Resources.getResource("PublishFlag_False_Req.json");
String myJson = Resources.toString(file, Charsets.UTF_8);
Response responsedata = given().header("Authorization", AuthorizationValue)
.header("X-App-Client-Id", XappClintIDvalue)
.contentType("application/vnd.api+json")
.body(myJson)
.with()
.when()
.post(dataPostUrl);

Resources