Json Assertion - Error Assertion failure message: Value expected to match regexp - json

Doing REST API Testing using Jmeter. when I am Using JSON Path Tester in HTTP Response and provided JSON Path Expression as $..name. Getting following matches
Done,
Won't Do,
Duplicate,
Cannot Reproduce
But when I place the same JSON expression and Result in JSON Assertion, getting the error:-
Assertion error: false
Assertion failure: true
Assertion failure message: Value expected to match regexp '"Done","Won't Do","Duplicate","Cannot Reproduce"', but it did not match: '["Done","Won't Do","Duplicate","Cannot Reproduce"]'

To match multiple values
Extract all the matching values from JSON Response using JSON Extractor
Use JSR223 Assertion with following code:
int nameLength = Integer.parseInt(vars.get("Name_matchNr"));
String[] responseArray = new String[nameLength];
for (int i = 0; i < nameLength; i++) {
responseArray[i] = vars.get("Name_"+(i+1));
}
boolean test1 = Arrays.asList(responseArray).contains("Done");
boolean test2 = Arrays.asList(responseArray).contains("Won't Do");
boolean test3 = Arrays.asList(responseArray).contains("Duplicate");
boolean test4 = Arrays.asList(responseArray).contains("Cannot Reproduce");
if (test1 == false) {
AssertionResult.setFailureMessage("Done not present in Response");
AssertionResult.setFailure(true);
}
if (test2 == false) {
AssertionResult.setFailureMessage("Won't Do not present in Response");
AssertionResult.setFailure(true);
}
if (test3 == false) {
AssertionResult.setFailureMessage("Duplicate not present in Response");
AssertionResult.setFailure(true);
}
if (test4 == false) {
AssertionResult.setFailureMessage("Cannot Reproduce not present in Response");
AssertionResult.setFailure(true);
}
To match single value
Use JSON Extractor to extract the values
Use JSON Assertion to Assert the values. In Expected Value section enter any single value : "Done/Won't Do/Duplicate/Cannot Reproduce"

If this is really what you're trying to achieve, consider the following JSON Assertion configuration:
Just in case "Expected Value" textual representation:
["Done","Won't Do","Duplicate","Cannot Reproduce"]
However be informed that this form of assertion will be fragile and sensitive to any JSON changes, i.e. if the order of matches will not be the same - the assertion will fail. So I would rather recommend using one of the approaches described in The Easiest Way To Compare REST API Responses Using JMeter article.

Related

JSON decoding from stream in Kotlin

I have a server set up to send messages over a local host port. I am trying to decode the serialized json messages sent by the server and get this error.
Error decoding message: kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 55: Expected EOF after parsing, but had instead at path: $
JSON input: .....mber":13,"Timestamp":5769784} .....
The Racer State messages are formatted in JSON as follows: { “SensorId”: “value”, “RacerBibNumber” : “value”, “Timestamp” : “value” }, where the value’s are character string representations of the field values. I have also tried changing my RacerStatus Class to take String instead of Int but to a similar error. Am I missing something here? The symbol that is missing in the error was not able to be copied over so I know it's not UTF-8.
I have also added
val inputString = bytes.toString(Charsets.UTF_8)
println("Received input: $inputString")
This gets
Received input: {"SensorId":0,"RacerBibNumber":5254,"Timestamp":3000203}
with a bunch of extraneous symbols at the end.
data class RacerStatus(
var SensorId: Int,
var RacerBibNumber: Int,
var Timestamp: Int
) {
fun encode(): ByteArray {
return Json.encodeToString(serializer(), this).toByteArray()
}
companion object {
fun decode(bytes: ByteArray): RacerStatus {
print(bytes[0])
try {
val mstream = ByteArrayInputStream(bytes)
return Json.decodeFromStream<RacerStatus>(mstream)
} catch (e: SerializationException) {
println("Error decoding message: $e")
return RacerStatus(0, 0, 0)
}
// return Json.decodeFromString(serializer(), mstream.readBytes().toString())
}
}
}
So I found an answer to my question. I added a regex to include just the json components I know my json contains.
val str = bytes.toString(Charsets.UTF_8)
val re = Regex("[^A-Za-z0-9{}:,\"\"]")
return Json.decodeFromString<RacerStatus>(re.replace(str,""))
I thought that Charsets.UTF_8 would remove the misc characters but it did not. Is there a more intiuative solution? Also is there a regex that would cover all possible values in json?

Rest-Assured using Jayways Jsonpath?

I have spent a long time figuring out some JsonPath using Jayways version, my query is the following:
$.items[?(#.To[0].Mailbox == 'foobar')]..Body
However, this does not work with Rest-Assured, when executing, I am shown the following error:
java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found '[' # line 1, column 34.
$.items[?(#.To[0].Mailbox == 'foobar')]..Body
Do I need to rewrite this expression in GPath format? if so, what would that look like? or can I somehow have Rest-Assured use this preferred JsonPath expression?
here is a small [WIP] piece of code as of now, just trying to get the expression working, then I will fix up the method correctly:
public String readInbox(String emailAddress) {
Response response = given().log().all().when().get(MESSAGES_ENDPOINT);
JsonPath jsonPath = new JsonPath(response.asString());
String emailAddress = jsonPath.getString("$.items[?(#.To[0].Mailbox == 'foobar')]..Body");
System.out.println(accountVerificationEmailHyperlinkByEmailAddress);
return "";
}
resolved this by just excluding rest assured completely and using jsonPath on the response body like so:
emailBodies = JsonPath.read(given().when().get(MESSAGES_ENDPOINT).getBody().asString(), generatePayLoadForEmailPrefixOf(emailPrefix));

groovy script SOAP UI json response parse

How to parse json response using groovy script.
I am using SOAP UI and have json response as below-
{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}
Can anyone please share sample code to parse json object and post that some basic assertions check.
Thanks
Add a Script Assertion for the rest request test step with below script.
Define your expected data as shown in the snippet below as needed
It compares each key value with expected data.
JsonSlurper can be used to parse the response.
//Check if the response is not empty
assert context.response, 'Response is empty or null'
//Define expected data
def expectedData = [name: 'aaaaaaaaaaa', emailid: 'bbbbbbbbb']
def json = new groovy.json.JsonSlurper().parseText(context.response)
//Checks all elements of resource one by one and compare with expectedData
json.resource.each {k, v -> assert v == expectedData."$k" }

Get a parent value based on child value in SoapUI

In the response Json, getting an array list of items as shown.
What you see in the question is not xml, it is a json string. So, xpath does not work.
For your request test step, you can add the Script Assertion as shown below:
//Check the response
assert context.response, 'Response is empty or null'
//Expected subscription id, change it if needed
def expectedSubscriptionId = '2c92c0f95ae1445b015af2320235689f'
def parsedJson = new groovy.json.JsonSlurper().parseText(json)
def ids = [] as Set
parsedJson.each { item ->
item.amendments.each { amendment ->
if (amendment.subscriptionId == expectedSubscriptionId ) {
ids << item.id
}
}
}
assert ids.size(), "id's are not found in the response for matching subscription"
log.info "Matching id's are : ${ids}"
You may quickly try online Demo

How do I get Value from a converted String

I have this code:
"response=3&responsetext=Duplicate transaction REFID:3154223053&authcode=&transactionid=&avsresponse=&cvvresponse=&orderid=&type=auth&response_code=300"
I tried converting it into json format using this code:
def converted = "{\"" + resp.data.toString()
.replaceAll('=','\":\"')
.replaceAll('&','\",\"') + "\"}"
it returns the valid json format though I want to get a specific value from that string I tried doing:
println converted.responsetext.toString()
it has an error saying
No such property: responsetext for class: java.lang.String
You can convert request parameters to Map and if required to json string as below:
String str = "response=3&responsetext=Duplicate transaction REFID:3154223053&authcode=&transactionid=&avsresponse=&cvvresponse=&orderid=&type=auth&response_code=300"
def map = str.tokenize(/&/).collectEntries {
def entity = it.tokenize(/=/)
[ entity[0], entity[1] ]
}
assert map.responsetext == "Duplicate transaction REFID:3154223053"
// Json
println new groovy.json.JsonBuilder( map ).toPrettyString()
If you want to go ahead from what you have right now instead, then below implementation should be sufficient:
def items = new groovy.json.JsonSlurper().parseText( converted )
assert items.responsetext == "Duplicate transaction REFID:3154223053"