Skip to content

Instantly share code, notes, and snippets.

@gynvael
Created June 22, 2020 18:16
Show Gist options
  • Save gynvael/603b803551e539a643f7f15039e1c54e to your computer and use it in GitHub Desktop.
Save gynvael/603b803551e539a643f7f15039e1c54e to your computer and use it in GitHub Desktop.
Testing integer validation based on another field's value in JSON Schema Draft 7 (Python 3)
import json
import jsonschema
schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [ "tens", "hundreds" ]
},
"int": {
"type": "number" # <---- Validated integer field.
}
},
"if": { # <---- Checking integer field based on type field.
"properties": {
"type": { "const": "tens" }
}
},
"then": {
"properties": {
"int": {
"type": "integer",
"minimum": 10,
"maximum": 99
}
}
},
"else": {
"properties": {
"int": {
"type": "integer",
"minimum": 100,
"maximum": 999
}
}
}, # <---- End of integer validation.
"required": [ "type", "int" ], # Boilerplate follows Zzz....
"additionalProperties": False
}
tests = [
( True, { "type": "tens", "int": 12 } ),
( False, { "type": "tens", "int": 123 } ),
( False, { "type": "hundreds", "int": 12 } ),
( True, { "type": "hundreds", "int": 123 } ),
( False, { "type": "hundreds", "int": 123, "additiona": 1234 } ),
( False, { "type": "hundreds" } )
]
for exp_res, test in tests:
try:
jsonschema.validate(test, schema)
res = True
except jsonschema.exceptions.ValidationError:
res = False
if res == exp_res:
print(" OK -->", test)
else:
print("FAILED -->", test)
@gynvael
Copy link
Author

gynvael commented Jun 22, 2020

gynvael:haven-windows>python test.py
  OK   --> {'type': 'tens', 'int': 12}
  OK   --> {'type': 'tens', 'int': 123}
  OK   --> {'type': 'hundreds', 'int': 12}
  OK   --> {'type': 'hundreds', 'int': 123}
  OK   --> {'type': 'hundreds', 'int': 123, 'additiona': 1234}
  OK   --> {'type': 'hundreds'}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment