POSTMAN - Schema validation is passed even for bad response data - json

tests["Valid schema"] = tv4.validate(jsonData, schema); is passed even if "error" and "responseType" is missing in the schema. How to make sure that response and schema both are matching for JSON schema.
when I hit post request on postman, the following is the Response Body in postman
{
"statusCode": 400,
"error": "Bad Request",
"message": "Email/Phone number not found",
"responseType": "EMAIL_NOT_FOUND",
"arabicMessage": "البريد الإلكتروني / رقم الهاتف غير موجود"
}
Tests in Postman
var jsonData=JSON.parse(responseBody)
var schema ={
"statusCode": {"type":"integer"},
"message": {"type":"string"},
"arabicMessage":{"type":"string"},
"data": {
"accessToken": {"type":"string"},
"userDetails": {
"_id": {"type":"string"},
"deviceType": {"type":"string"},
"countryCode": {"type":"string"},
"OTPCode": {"type":"integer"},
"invitationCode": {"type":"string"},
"availableCredits": {"type":"integer"},
"totalBookings": {"type":"integer"},
"promoCodes": {"type":"array"},
"updatedAt": {"type":"string"},
"createdAt": {"type":"string"},
"language": {"type":"string"},
"IsDeleted": {"type":"boolean"},
"IsVerified": {"type":"boolean"},
"IsBlock": {"type":"boolean"},
"customerAddresses": {"type":"array"},
"address":{"type":"string"},
"phoneVerified": {"type":"boolean"},
"currentLocation": {
"type": "Point",
"coordinates": [
{"type":"integer"},
{"type":"integer"}
]
},
"appVersion": {"type":"integer"},
"profilePicURL": {
"thumbnail": {"type":"string"},
"original": {"type":"string"}
},
"password": {"type":"string"},
"socialId": {"type":"string"},
"phoneNo": {"type":"integer"},
"email": {"type":"string"},
"LastName": {"type":"string"},
"firstName": {"type":"string"},
"__v": {"type":"integer"},
"referralCode": {"type":"string"},
"accessToken": {"type":"string"},
"deviceToken": {"type":"string"}
},
"updateAvailable": {"type":"boolean"},
"stateCallBookingIds": {"type":"array"},
"forceUpdate": {"type":"boolean"}
}
};
tests["Valid schema"] = tv4.validate(jsonData, schema);
//here the test is passing even with invalid jsonData which is the data
console.log("Validation failed: ", tv4.error);

There are lots of open issues on the Postman github account about the tv4 module.
There is a similar question on SO here, could your jsonData be different than your schema?
This is an example from a link on the tv4 github page.
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}
You could try adding those fields as required?

Just leaving this here in case it helps anyone else. tv4.validate has two additional boolean parameters: checkRecursive and banUnkownProperties.
Especially the last one can help finding errors in JSON responses when they contain attributes that weren't defined in the schema.
Reference

I prefer to use jsonSchema this way:
var strSchema =
pm.collectionVariables.get("variable_that_contains_the_schema");
pm.test("Validate SCHEMA is OK", () => {
pm.response.to.have.jsonSchema(JSON.parse(strSchema));
});
And if you want to auto-generate the schema, you can use the generate-schema plugin https://www.npmjs.com/package/generate-schema
I use to store the content of this plugin in a collection variable, on the pre-request of my collection, like this:
Then in the test tab of your request, you can call the javascript eval() to load the generate-schema source-code in the postman's test environment:
// eval will evaluate the JavaScript generateSchema code and
// initialize the js on postman environment
eval(pm.collectionVariables.get("generate-schema"));
var strSchema =
pm.collectionVariables.get("variable_that_contains_the_schema");
if (strSchema === undefined){
console.log('>>>> variable for schema not defined!');
return;
}
if(strSchema == '' | strSchema === null) {
// call function generateSchema (external)
var schema = generateSchema.json("variable_that_contains_the_schema", jsonData);
delete schema.$schema; // remove the element '$schema' --> causes error in validator
var strSchema = JSON.stringify(schema);
//save the generated schema
pm.collectionVariables.set("variable_that_contains_the_schema", strSchema);
console.log(" >> schema was generated from the response, validation will proceed on the next request.");
}
else
{
console.log(" >> schema recovered from variable.");
// Schema test ------------------------------------------------
pm.test("Validate SCHEMA is OK", () => {
pm.response.to.have.jsonSchema(JSON.parse(strSchema));
});
}

Related

how do i integrate authorize.net into my wix page?

I am using authorize.net's sandbox API to test their gateway in my wix (corvid/code) environment. Funny thing is that when i send JSON to the sandbox API i get a valid JSON response approving the (fake) transaction. however when i set it up thru wix i get data errors in my console. I have built on existing files that i have been able to run basic API responses, and more advanced auths with token responses. so the code works, just not with authorize.net. given my level of expertise, i think it might be something im doing wrong. i've done my due diligence, and there are no questions on this topic. here is my code:
///front end, from the corvid page's code
import {buyIt} from 'backend/authorizeNet';
export function button1_click(event) {
buyIt();
}
pretty basic, just calling code from my backend onClick. the filepath is correct. here is the module on the backend:
//// backend/authorizeNet.jsw
import {fetch} from 'wix-fetch';
export function buyIt() {
let data = {
"createTransactionRequest": {
"merchantAuthentication": {
"name": "***************",
"transactionKey": "****************"
},
"refId": "123456",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "5",
"payment": {
"creditCard": {
"cardNumber": "5424000000000015",
"expirationDate": "2020-12",
"cardCode": "999"
}
},
"lineItems": {
"lineItem": {
"itemId": "1",
"name": "vase",
"description": "Cannes logo",
"quantity": "18",
"unitPrice": "45.00"
}
},
"tax": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"duty": {
"amount": "8.55",
"name": "duty name",
"description": "duty description"
},
"shipping": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"poNumber": "456654",
"customer": {
"id": "99999456654"
},
"billTo": {
"firstName": "Ellen",
"lastName": "Johnson",
"company": "Souveniropolis",
"address": "14 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"shipTo": {
"firstName": "China",
"lastName": "Bayles",
"company": "Thyme for Tea",
"address": "12 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"customerIP": "192.168.1.1",
"transactionSettings": {
"setting": {
"settingName": "testRequest",
"settingValue": "false"
}
},
"userFields": {
"userField": [
{
"name": "MerchantDefinedFieldName1",
"value": "MerchantDefinedFieldValue1"
},
{
"name": "favorite_color",
"value": "blue"
}
]
}
}
}
}
return fetch("https://test.authorize.net/xml/v1/request.api", {
"method": "post",
"headers": {"Content-Type": "application/json"},
"body": data
})
.then(response => {console.log(response.json())});///if response.text is used, it gives details
}
note at the end of the backend code, calling response.json give me a json error, due to the return code contains HTML saying that i've requested invalid data. if i change it to response.text i get this in my console:
//console response with response.text
{...}
isFulfilled:
true
isRejected:
false
fulfillmentValue:
"<HTML><HEAD>\n<TITLE>Bad Request</TITLE>\n</HEAD><BODY>\n<H1>Bad Request</H1>\nYour browser sent a request that this server could not understand.<P>\nReference #7.1d60fea5.1557756725.387c74\n</BODY>\n</HTML>\n"
how do i get a good response from the API? like ive done with the same code in postman?
thanks in advance
return fetch(url, {
method: "post",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(data)
})
.then(response => console.log(response.text())
)
this got me the result i was looking for
stringify() converted my object to a JSON string. i still cannot get it to read the incoming JSON, might have to use parse...but if i read as text i get the info i want and my API is showing a successful transaction.

Nested JSON Schema Validation in Postman

I want to validate a Nested JSON Schema in Postman.
Here is the code.
const testSchema = {
"name": [
{
"first_name": "Alpha",
"last_name": "Bravo"
},
{
"first_name": "Charlie",
"last_name": "Delta"
},
],
"age": "23",
"color": "black"
};
const showData = {
"required": ["name", "age"],
"properties": {
"name": [
{
"required": ["first_name"]
}
],
},
};
pm.test("Nested Schema Test", function () {
pm.expect(tv4.validate(testSchema, showData)).to.be.true;
});
Currently, this code returns test as true.
I am unable to test the "name" array objects' keys.
Even upon passing this:
"required": ["fst_nae"] //wrong key name
it returns true.
I would just check in easy way via:
pm.test("your name", function () {
pm.expect(testSchema.name[0].first_name && testSchema.name[1].first_name
).to.eql('Alpha' && 'Charlie')
});
and you successfully validated these fields
or use this expect to organize your code of your choice
tiny validator i.e. tv4.validate is having issues in their library. Another option is to use AJV (you can search it on github).

Postman: schema validation passes even with a wrong response

I have the following schema for bellow happy path response
var responseSchema =
{
"type": "object",
"properties": {
"value": {
"type": "object",
"properties":{
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"patientGuid": {"type": "string" },
"givenName": {"type": "string" },
"familyName": {"type": "string" } ,
"combinedName" : {"type": "string" }
},
"required": ["patientGuid","givenName","familyName"]
}
}
}
}
}
};
Happy path response:
{
"value": {
"items": [
{
"patientGuid": "e9530cd5-72e4-4ebf-add8-8df51739d15f",
"givenName": "Vajira",
"familyName": "Kalum",
"combinedName": "Vajira Kalum"
}
],
"href": "http://something.co",
"previous": null,
"next": null,
"limit": 10,
"offset": 0,
"total": 1
},
"businessRuleResults": [],
"valid": true
}
I check if condition to validate whether response schema is correct:
if(responseBody !== null & responseBody.length >0)
{
var responseObject = JSON.parse(responseBody);
if(tv4.validate(responseObject, responseSchema))
{
// do something
}
else
{
// log some msg
}
}
Schema validation condition (nested if) get passed even when I get bellow bad response.
{
"value": {
"items": [],
"href": "http://something.co",
"previous": null,
"next": null,
"limit": 10,
"offset": 0,
"total": 0
},
"businessRuleResults": [],
"valid": true
}
Why response schema validation not failed as a response not has required fields?
When I ran your code and removed a property from the response data it seemed to work ok:
I would suggest a couple of things though - The tv4 module is not fantastic, it's not actively being worked on (for a couple of years I think) and there's a bunch of complaints/issue raised on the Postman project about how poor it is and asking for it to be replaced in the native app.
Have you considered creating a test to check the schema instead? This is very basic and could be easily refactored and wrapped in some logic but it would check the different value types of your response.
pm.test("Response data format is correct", () => {
var jsonData = pm.response.json()
// Check the type are correct
pm.expect(jsonData).to.be.an('object')
pm.expect(jsonData.value).to.be.an('object')
pm.expect(jsonData.value.items).to.be.an('array')
pm.expect(jsonData.value.items[0]).to.be.an('object')
// Check the value types are correct
pm.expect(jsonData.value.items[0].combinedName).to.be.a('string')
pm.expect(jsonData.value.items[0].givenName).to.be.a('string')
pm.expect(jsonData.value.items[0].familyName).to.be.a('string')
pm.expect(jsonData.value.items[0].patientGuid).to.a('string')
});
Also the syntax that you're using is the older style now and you don't need to JSON.parse(responseBody) the response body anymore as pm.response.json() is basically doing the same thing.

Rest assured, using Gpath query gives an error "The parameter "..." was used but not defined. Define parameters using the JsonPath.params(...)"

I'm new to rest-assured and I'm currently spiking it in order to implement it in our testing framework.
The problem I'm facing is to extract an object from a Json array from the REST response.
The example json I'm using:
{
"MRData": {
"xmlns": "http://ergast.com/mrd/1.4",
"series": "f1",
"url": "http://ergast.com/api/f1/2016/drivers.json",
"limit": "30",
"offset": "0",
"total": "24",
"DriverTable": {
"season": "2016",
"Drivers": [
{
"driverId": "alonso",
"permanentNumber": "14",
"code": "ALO",
"url": "http://en.wikipedia.org/wiki/Fernando_Alonso",
"givenName": "Fernando",
"familyName": "Alonso",
"dateOfBirth": "1981-07-29",
"nationality": "Spanish"
},
{
"driverId": "bottas",
"permanentNumber": "77",
"code": "BOT",
"url": "http://en.wikipedia.org/wiki/Valtteri_Bottas",
"givenName": "Valtteri",
"familyName": "Bottas",
"dateOfBirth": "1989-08-28",
"nationality": "Finnish"
}
]
}
}
}
Things i have tried so far:
This assertion is working
RestAssured.rootPath = "MRData.DriverTable.Drivers";
given()
.when()
.get("http://ergast.com/api/f1/2016/drivers.json")
.then()
.assertThat()
.body("find { find { d -> d.driverId == 'alonso' }.code }.code", equalTo("ALO"));
But I'm trying to actually get the Json of the particular array item
RestAssured.rootPath = "MRData.DriverTable.Drivers";
given()
.when()
.get("http://ergast.com/api/f1/2016/drivers.json")
.then()
.extract()
//.jsonPath().param("driverId", "alonso").get("find { d -> d.driverId == driverId }");
.path("find { d -> d.driverId == 'alonso' }");
Tried with both ways (one is commented out). But I get an error :
"The parameter "driverId" was used but not defined. Define parameters using the JsonPath.params(...)"
RestAssured.rootPath = "MRData.DriverTable.Drivers"; works only for body expectations. For extraction you have to use full path to paramter e.g. MRData.DriverTable.Drivers.find { it.#driverId == 'alonso' }

Liferay API update Data with JSON

I am working on an API for my Portal, to provide users the ability to update there data via API directly from there internal Systems.
Liferay 6.2 bundle Tomcat. (for api call testing I use soapUI)
The get Methods work fine, (I have getAll, and getByID). getByID returns a JSON Object like this:
{
"ID": "ORGANIZATIONID",
"type": "ORGANIZATIONTYPE",
"name": "ORGANIZATIONNAME",
"URI": "ORGANIZATIONNAMEURI"
"date of inclusion": "INCLUTIONDATE",
"last activities": "LASTMODIFIEDDATE",
"address": {
"name of host institution": "NAMEOFHOSTINSTITUTE",
"street1": "STREET1",
"street2" : "STREET2",
"zip": "ZIP",
"city": "CITY",
"country": "COUNTRY",
},
"url": [{"ORGANIZATIONURL"}],
"main contact": {
"first name": "FIRSTNAME",
"last name" : "LASTNAME",
"phone": "PHONE",
"email": "MAINCONTACTEMAIL"
},
"type of host institution" : "TYPEOFHOSTINSTITUTE",
"diseases": [
{
"name": "DISEASENAME1",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
},
{
"name": "DISEASENAME2",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
}
]
}
I would like to have an API for Updating the diseases information for an organization. I have created a URL service where everything is in the url as parameters, but I would like to have it that the in the url only the id parameter is send and the rest of the information in a JSON object. Like:
/api/jsonws/....-portlet...../updateregbb/organization-id/16016/
and the data:
{
"ID": "ORGANIZATIONID",
"diseases": [
{
"name": "DISEASENAME1",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
},
{
"name": "DISEASENAME2",
"number": "SAMPLECOUNT",
"gene": "GENE",
"orphacode": "ORPHA"
"icd10": "ICD",
"omim": "OMIM";
"synonym": "SYNONYM"
}
]
}
But I could not find a solution how I can read the JSON data:
#JSONWebService(value = "updateregbb", method = "POST")
public void updateregbb2(long organizationId, Map jsondata) {
#JSONWebService(value = "updateregbb", method = "POST")
public void updateregbb(long organizationId, JSONObject json) {
How can I get the Data into my function?
Thanks for the help,
Best
Robert