JSON Schema Validator
We use json for API responses, and the task is to validate the response schema with previous release to find regression if any.
So there was a bug in the system where a json was responding as below
{
data: [
20,30,0,0,0,0,0]
}
instead of
{
data: [
20,30]
}
Automation failed to catch as the validation was only the first two values.
So, the better way to was to add schema validator.
This post contains the details of some help links which help to develop a suite.
Schema validators -> [Array reference guide] (json-schema.org/understanding-json-schema/r..)
For validating the length of array, json schema validator provides below parameters.
{
"type": "array",
"minItems": 2,
"maxItems": 3
}
If you are looking for something other than array, then information is below: Schema all details
Tools to create schema
this too doesn't provide minItems maxItems, these should be added manually as per need.
Schema validator used to verify: Schema validator
The issue was successfully found by the tool:
Found 1 error(s) Message: Array item count 22 exceeds maximum count of 2. Schema path:
#/properties/data/properties/samples/items/0/properties/data/maxItems
Now next step is to do the above things programmatically .
Adding the code snippet which was used to write script
import requests
import json
import jsonschema
from jsonschema import validate
failedtests = []
def validateJson(jsonData,schemaexpected,testcase):
try:
validate(instance=jsonData, schema=schemaexpected)
except jsonschema.exceptions.ValidationError as err:
print err
global failedtests
failedtests.append(testcase)
return False
return True
response = requests.get('https://sampleurl.com/users/v3/customers', headers=headers, params=params)
#print response.text
jsonData = json.loads(response.text)
validateJson(jsonData, jsonschema_of_customers, "check customers")