Rest Assured Json Path returns Exception - rest-assured

I´m reading json from a file in order to compare it to an http request body´s json.
I´m doing
JsonPath expectedJson = new JsonPath(new File("response.json"));
// some more code
assertThat().body("", equalTo(expectedJson.getMap("")));
which results in JsonPathException: Failed to parse the JSON document
This is the response.json file, which I copied from the response in Postman:
{
"screenDefinition":{
"taskId":"account-type",
"parameters":null
},
"prospect":{
"initializationType":"FIRST_HOLDER",
"jointAccount":{
"jointAccountId":655
},
"emailConfirmed":false,
"addressConfirmed":false,
"emailValidated":false,
"smsCodeAttemptsLeft":0,
"mobilePhoneValidated":false,
"paragraphsAccepted":false,
"termsConditionsAccepted":false,
"changedToAutonomousMethod":false,
"changedToIdentificationMethod":false,
"contractAccepted":false,
"prospectOnboardContactType":"NONE",
"secondAccountHolder":false,
"evidencesUploaded":false,
"uploadEvidencesLater":false
}
}
Any ideas?

That JsonPathException you got is probably caused by java.io.FileNotFoundException which means that path to your file is incorrect.
Try checking if file exists first:
File file = new File("response.json");
System.out.println("File exists: " + file.exists());
JsonPath jsonPath = new JsonPath(file);

Related

Convert JIRA Issue response type into JSON format

I am trying to fetch jira ticket information using
com.atlassian.jira:jira-rest-java-client-core:5.2.4.
I am able to fetch the ticket information but the problem here is that the extracted information is in com.atlassian.jira.rest.client.api.domain.Issue type but I need the response in JSON format.
How can i convert com.atlassian.jira.rest.client.api.domain.Issue response type into JSON format?
Response Example :
Issue {
self=https://jira-qc.test.us/rest/api/latest/issue/70704,
key=TEST-3,
id=70704,
project=BasicProject{
self=https: //jira-qc.test.us/rest/api/2/project/11112,
key=TEST,
id=11112,
name=TEST
}
}
Dependency used :
dependencies {
implementation "com.atlassian.jira:jira-rest-java-client-core:5.2.4"
}
Code used :
Issue getIssue(String issueKey) {
JiraRestClient jiraRestClient = JiraClientService.getJiraClient()
return jiraRestClient.getIssueClient().getIssue(issueKey).claim()
}

Validate Text Response using restAssured

How to validate Text Response using restAssured?
Basically I have downloaded the file In CSV format, now the response is coming in text format any suggestion how can we validate the column headers in the text?
I have got the answer.
try {
CsvSchema bootstrapSchema = CsvSchema.emptySchema().withHeader();
File file = new File(fileName) ;
MappingIterator<T> readValues = mapper.readerFor(type).with(bootstrapSchema).readValues(file);
return readValues.readAll();
} catch (Exception e) {
log.error("Error occurred while loading object list from file :{} with }
using Jackson csv formatter dependency

Gatling Load test Error : 406 not acceptable on Response

I am new to the gatling load test. And i want to load test my simple project.But I got the error on response(406 not acceptable) and my gatling code is below
import io.gatling.core.Predef._
import io.gatling.http.Predef._
class simu extends Simulation {
val httpConf = http
.baseURL("http://172.24.15.225:10050/sample")
.header(HttpHeaderNames.Accept, HttpHeaderValues.ApplicationJson)
.acceptHeader("application/json, text/plain, */*")
.acceptEncodingHeader("gzip, deflate")
.acceptLanguageHeader("en-US,en;q=0.5")
val scn = scenario("Scenario Name")
.exec(
http("request_1")
.post("http://172.24.15.225:10050/sample")
.header(HttpHeaderNames.Accept, HttpHeaderValues.ApplicationJson)
//.check(status.is(406))
.body(StringBody("""{ "inputData": "Wonderful" }""")).asJSON
)
setUp(scn.inject(atOnceUsers(30)).protocols(httpConf))
}
And the response for the above is
failed in Response
Errors ------------------------------------------------------------
status.find.in(200,304,201,202,203,204,205,206,207,208,209),
but actually found 406
someone please correct my code.
But the RestAPI(postman) returns response correctly.
finally i found an answer. There is no error in the gatling load test. But the problem is my backend coding. I have changed my response from String type into the JSON format like below
object ServiceJsonProtocol extends DefaultJsonProtocol {
implicit val RequestProtocol : RootJsonFormat[Text] = jsonFormat1(Text)//request json format
implicit val ResponseProtocol : RootJsonFormat[SampleText] = jsonFormat1(SampleText) // response json format
}
It works fine

HTTPBuilder encoding utf-8 in Grails

I have a problem using HTTPBuilder in Grails.
The code is something like this.
def http = new HTTPBuilder("theURL")
http.request(method, ContentType.JSON) {
uri.path = "theURI"
headers.'Authorization' = "OAuth $accessToken"
headers.'Accept' = "application/json"
headers.'content-type' = "application/json;charset=utf-8"
response.success = { resp, json ->
result = json
}
}
return result
Now the response is a JSON with "Cobro N�� 1234" but i need "Cobro Nº 1234"
I tried this with curl and the response is fine "Cobro Nº 1234", this made me think that the problem is the HTTPBuilder and not my API who response the request.
I think that it is a problem with the response encoding.
http.encoders.charset = Charsets.UTF_8
Try this:
headers.'content-type' = "application/JSON;charset=UTF-8" //capitalized
Either, try this:
#Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
Try adding this after your 'http' declaration:
http.encoderRegistry = new EncoderRegistry( charset: 'utf-8' )
I couldn't follow if the content you are sending needs to be encoded with UTF-8, or if the content you are receiving needs to be read with UTF-8.
I was having a problem sending content with UTF-8, and this is what I did.
http.request(Method.PUT) { request ->
// set headers here
request.entity = new StringEntity(json.toString(), "UTF-8")
}
I'm converting a net.sf.json.JSONObject to a String in order to pass it along as the body of the PUT call. I'm using StringEntity, and previously I wasn't setting the encoding on the StringEntity, but there is a constructor that takes an encoding. Now that I'm setting "UTF-8" there, it is working.

Highcharts-Export Server for Java JSON parsing issue

I configured the highchart export server for Java from the current master in GitHub. When I tried to export an image using the demo page a corrupted file was returned. I have debugged to code and found out the following message is returned as the result in validate method in ServerObjectFactory.java
String result = server.request("{\"status\":\"isok\"}");
The value of the result String is "Failed rendering:SyntaxError: Unable to parse JSON string"
What can be the cause for this issue.
Thank You
That's very strange. The syntax of the JSON string is syntactically correct. I can point out where from the error is generated.
In the highcharts-convert.js file in highcharts-ecport-convert/src/main/resources/phantomjs the incoming request is expected to be a JSON string and is parsed, see Line 469
function (request, response) {
var jsonStr = request.post,
params,
msg;
try {
params = JSON.parse(jsonStr); // L469
if (params.status) {
// for server health validation
response.statusCode = 200;
response.write('OK');
response.close();
} else {
....
Set in a console.log(jsonStr) before JSON.parse(jsonStr) . I hope this give you a clue of why it's throwing a error.

Resources