I have a service which is returning the below json payload:
{
"location-details": {
"fromPostalCode": "1508XB",
"fromGeoCoordinates": "116532,496398",
"toPostalCode": "1511MA",
"toGeoCoordinates": "120427,493380"
},
"commute-distance": "5817.799",
"commute-time": "370.0152"
}
I have created a MUNIT test suite for the same where i am using the assert that utility to assert the payload. Snippet given below:
<munit:validation >
<munit-tools:assert-that doc:name="Assert That Status Code is 200" doc:id="1c2e536b-513e-4b76-958b-2ea864a64805" expression="#[attributes.statusCode]" is="#[MunitTools::equalTo(200)]" message="The HTTP Status code is not correct!" />
<munit-tools:assert-that doc:name="Assert That - Payload is Expected" doc:id="f4b811fa-ff11-4746-93cc-f87576504808" expression="#[payload]" is="#[MunitTools::getResourceAsString('SuccessResponse.json')]" message="The response payload is not correct!"/>
</munit:validation>
But this is throwing an below error and its not working:
...38 more
Caused by: org.mule.runtime.api.el.ExpressionExecutionException: Unable to convert '{
"location-details": {
"fromPostalCode": "1508XB",
"fromGeoCoordinates": "116532,496398",
"toPostalCode": "1511MA",
"toGeoCoordinates": "120427,493380"
},
"commute-distance": "5817.799",
"commute-time": "370.0152"
}' with class 'java.lang.String' to class 'Matcher', while writing Java at org.mule.munit.tools.util.GetResourceFunctions.getResourceAsString.
at org.mule.weave.v2.el.WeaveExpressionLanguage.doEvaluate(WeaveExpressionLanguage.scala:139)
at org.mule.weave.v2.el.WeaveExpressionLanguage.evaluate(WeaveExpressionLanguage.scala:236)
You are missing the matcher component in your expression, please change it as below and try again:
<munit-tools:assert-that doc:name="Assert Payload is Correct" doc:id="5b45470f-05e8-406e-9d44-877ff1506220" expression='#[output application/json --- write(payload, "application/json")]' is="#[output application/json --- MunitTools::equalTo(MunitTools::getResourceAsString('json\SuccessResponse.json'))]" message="The message is not correct"/>
This will work for sure !!
I had to use readUrl instead of MunitTools::getResourceAsString to compare two JSON objects in MUNIT 2.1
<munit-tools:assert-that doc:name="Assert That - JSON compare" doc:id="2fab5bf0-a710-4619-a7a9-262a867e0ad9" expression="#[payload]" is="#[MunitTools::equalTo(readUrl('classpath://sample_data/test_payload.json', 'application/json'))]" message="payload is not correct" />
Related
I am using Chrome extension - Postman app to test my webservice. Below is the template of my webservice -
#POST
#Path("/usertransaction/get/amount")
#Produces("application/json")
#Consumes("application/json")
public List<ABCForm> getAmount(List<ABCForm> abclist, Date asOfDate) {
.
.
.
}
I have set header as application/json;charset=UTF-8 and request body as below -
[
{
"ccc":"1",
"qqq":"22",
"acac":"24",
"abc":"100"
}
],
"asOfDate":"05/05/2018"
I am aware that its not a valid JSON. But even if i resolve JSON issue, it still throws the same exception. I am looking for proper JSON through which request could be made and resolve this exception.Any help would be appreciated.
I'm trying to send a json payload in quartz scheduler. I have the header set to Content-type:application/json, but for some reason my json string is throwing an error: Uncaught error, unexpected token in json.
The original json that I'm sending to a graphql service looks like this:
{
GetAllAuthors{
id
name
}
}
But to make it work in quartz, I need to mimic a rest API call, which is why I tried using the following:
{ "query":{{""{\nGetAllAuthors {\nid\nname\n}\n\n}""}} }
The above is also giving me the "Uncaught error, unexpected token in json" error. Is there something that I'm missing or overlooking?
PS: I tried using an online json formatter and when I try to validate the above json, I get the following error:
Error: Parse error on line 2:
{ "query": { { "" {\ nGetA
--------------^
Expecting 'STRING', '}', got '{'
That's not valid Json. This is how it might look if it were:
{
"GetAllAuthors": [
"id",
"name"
]
}
but I suspect you're trying for something like this:
{
"GetAllAuthors": {
"id": 123,
"name": "James Brown"
}
}
Play here until you get it right: https://jsonlint.com/
Edit: I've not worked with GraphQL, but this page shows how a (non JSON) GraphQL query might be transferred over Http by POSTing JSON or GETting using querystrings: https://graphql.org/learn/serving-over-http/
I figured this out by testing through Mozilla's network tab - the correct format is:
{"query":"{\n GetAllAuthors{\n id\n name\n}\n}\n","variables":null, "operationName":null}
I set up a POST ressource in API Gateway which invokes a Lamdba function, fine.
In the "integration request", for text/plain Content-type, I defined the following mapping :
#set($messageStr = $util.urlEncode($input.body))
{
"message" : "$messageStr"
}
Problem is : whenever I POST data with JSON reserved characters, the integration request mapping thows
{"message": "Could not process payload"}
Example : blablabla will be correctly passed through to lambda, not {blablabla nor a:e ...
This seems like that method urlEncode expects JSON data.
Any idea how to pass whatever body as pure text ?
Thanks
I'm guessing I've missed something silly so I apologize in advance.
I'm trying to run the example found at the following URL in mock mode: https://github.com/apigee-127/a127-samples/blob/master/weather-basic/api/swagger/swagger.yaml
The JSON response looks like it's being escaped and it's causing the response validator to fail:
{
"message": "Response validation failed: invalid content type (text/plain). These are valid: application/json",
"failedValidation": true,
"originalResponse": "{\"base\":\"Sample text\",\"clouds\":{\"all\":1},\"cod\":1,\"coord\":{\"lat\":1,\"lon\":1},\"dt\":1,\"id\":1,\"main\":{\"humidity\":1,\"pressure\":1,\"temp_max\":1,\"temp_min\":1,\"temp\":1},\"name\":\"Sample text\",\"sys\":{\"country\":\"Sample text\",\"id\":1,\"message\":1,\"sunrise\":1,\"sunset\":1,\"type\":1},\"weather\":[{\"description\":\"Sample text\",\"icon\":\"Sample text\",\"id\":1,\"main\":\"Sample text\"}],\"wind\":{\"deg\":1,\"speed\":1}}"
}
Any ideas would be awesome!
You need to send something like this res.json({});
Send as json object don't stringify your result object ,
var result = {name:"asdf",id:1212}
res.json(result);
I am using Play scala WS to send a REST api call to a web server and sometimes get an exception error. Json is sent to the server and the response from the server could be one of the following.
Server returns a valid Json response.
Server returns "No valid Json found"
Server returns an error web page that triggers the exception error com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
How do I modify the code below to get the contents of the web page without the exception error?
import play.api.libs.ws._
var tempText = Helpers.await(WS.url("localhost:9000/someApi").post(jsonToSend)).body
println(tempText)
tempJson = Json.parse(tempText)
println(tempJson)
Much depends on how "correct" that downstream API server is.
In a perfect world, we could probably assert the following facts:
Success case => HTTP status is 200, HTTP Content-Type header is application/json
"No valid Json found" => HTTP status is 404 or similar non-200, HTTP Content-Type header is application/json
"Error web page" => HTTP status is not 200, Content-Type is text/html
If the above assertions are all true, then we can simply put a little bit of "protection" around our response-handling rather than just jumping in and trying to parse it as JSON:
val futureOptionalResult = WS.url("localhost").post("...").map { response =>
response.status match {
case 200 => {
println(response.body)
println(response.json)
Some(response.json)
}
case _ => {
println(s"Not OK: ${response.status} - body is: ${response.body}")
None
}
}
}
Some notes:
Doing it asynchronously is just as easy as using an await and scales better
response.json returns the same thing as your explicit Json.parse on the body
I'm returning an Option[JsValue] that holds the returned JSON if it worked
If the above assumptions are not true, deeper inspection of the Content-Type header, finer-grained switching on the status value and/or other attributes of the response will probably be needed. Good luck!