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

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);
}

Related

Reference regex string In JSON response

How to reference regex string In the JSON response
url value(consumer(regex('/connectors/(.*?)/status')))
So that if I request '/connectors/foo/status' I get { "name": "foo" }
Please read the docs - https://docs.spring.io/spring-cloud-contract/docs/current/reference/html/project-features.html#contract-dsl-referencing-request-from-response
You'd need to do
response {
body(name: fromRequest().path(1))
}

Need to form custom request in jmeter

I am in need to create a custom request in jmeter which looks like the below format:
{
"items": [
{
"id": "1",
"productId": 1234
}
{
"id": "2",
"productId": 1218
}
....
}
Here I have to generate some random number in between 10-15 and create the id blocks(based on the random number).
Could someone please help how can I form the request accordingly and achieve this in jmeter.
Thanks in advance.
Add JSR223 PreProcessor as a child of the request which need to send this generated value
Put the following code into "Script" area
import groovy.json.JsonBuilder
import org.apache.commons.lang3.RandomUtils
def items = []
def itemsNo = RandomUtils.nextInt(10, 16)
1.upto(itemsNo) { id ->
def productId = RandomUtils.nextInt(1111, 10000)
def item = [:]
item.put('id', id as String)
item.put('productId', productId)
items.add(item)
}
def payload = new JsonBuilder([items: items]).toPrettyString()
vars.put('payload',payload)
Use ${payload} JMeter Variable where you need to refer the generated JSON
Demo:
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

GraphQL doesn't consider dynamic arrays of strings valid strings

I have a query that works when manually typed:
queryName(where: { ids: ["1234567890123456789", "1234567890123456790"] }, offset: 0, max: 10) {
but when the same values are passed in a variable:
const idArr = ["1234567890123456789", "1234567890123456790"];
...
queryName(where: { ids: ${idArr} }, offset: 0, max: 10) {
I get the error:
Uncaught GraphQLError: Syntax Error: Expected Name, found Int "1234567890123456789"
Can anyone explain this?
Using string interpolation like that will result in the following value being inserted inside your string:
"1234567890123456789,1234567890123456790"
This is not valid GraphQL syntax and so results in a syntax error. Instead of using string interpolation, you should use GraphQL variables to provide dynamic values along with your query:
query ($idArr: [ID!]!) {
queryName(where: { ids: $idArr }, offset: 0, max: 10) {
...
}
}
Note that the type of the variable will depend on the argument where it's being used, which depends on whatever schema you're actually querying.
How you include the variables along with your request depends on the client you're using to make that request, which is not clear from your post. If you're using fetch or some other simple HTTP client, you just include the variables alongside the query as another property in the payload you send to the server:
{
"query": "...",
"variables": {
...
}
}

validate response using jsr223 assertion

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

How to pass GraphQLEnumType in mutation as a string value

I have following GraphQLEnumType
const PackagingUnitType = new GraphQLEnumType({
name: 'PackagingUnit',
description: '',
values: {
Carton: { value: 'Carton' },
Stack: { value: 'Stack' },
},
});
On a mutation query if i pass PackagingUnit value as Carton (without quotes) it works. But If i pass as string 'Carton' it throws following error
In field "packagingUnit": Expected type "PackagingUnit", found "Carton"
Is there a way to pass the enum as a string from client side?
EDIT:
I have a form in my front end, where i collect the PackagingUnit type from user along with other fields. PackagingUnit type is represented as a string in front end (not the graphQL Enum type), Since i am not using Apollo Client or Relay, i had to construct the graphQL query string by myself.
Right now i am collecting the form data as JSON and then do JSON.stringify() and then remove the double Quotes on properties to get the final graphQL compatible query.
eg. my form has two fields packagingUnitType (An GraphQLEnumType) and noOfUnits (An GraphQLFloat)
my json structure is
{
packagingUnitType: "Carton",
noOfUnits: 10
}
convert this to string using JSON.stringify()
'{"packagingUnitType":"Carton","noOfUnits":10}'
And then remove the doubleQuotes on properties
{packagingUnitType:"Carton",noOfUnits:10}
Now this can be passed to the graphQL server like
newStackMutation(input: {packagingUnitType:"Carton", noOfUnits:10}) {
...
}
This works only if the enum value does not have any quotes. like below
newStackMutation(input: {packagingUnitType:Carton, noOfUnits:10}) {
...
}
Thanks
GraphQL queries can accept variables. This will be easier for you, as you will not have to do some tricky string-concatenation.
I suppose you use GraphQLHttp - or similar. To send your variables along the query, send a JSON body with a query key and a variables key:
// JSON body
{
"query": "query MyQuery { ... }",
"variables": {
"variable1": ...,
}
}
The query syntax is:
query MyMutation($input: NewStackMutationInput) {
newStackMutation(input: $input) {
...
}
}
And then, you can pass your variable as:
{
"input": {
"packagingUnitType": "Carton",
"noOfUnits": 10
}
}
GraphQL will understand packagingUnitType is an Enum type and will do the conversion for you.

Resources