Created
June 22, 2020 18:16
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
Author
gynvael
commented
Jun 22, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment