Package: json-checker
json_checkeris a library for validating Python data structures,
such as those obtained from JSON (or something else) to Python data-types.
json_checker has a parameter (soft=True) that allows you validate all json and
raise all errors after validation done, it`s very profitable from API testing:>>>importrequests>>>>>>fromjson_checkerimportChecker>>>>>>>>>deftest_api():>>>res=requests.get(API_URL).json()>>>assertChecker(EXPECTED_RESPONSE,soft=True).validate(res)==resInstallation$pipinstalljson_checkerExampleHere is a quick example to get a feeling ofjson_checker,
validating a list of entries with personal information:>>>fromjson_checkerimportChecker>>>current_data={'first_key':1,'second_key':'2'}>>>expected_schema={'first_key':int,'second_key':str}>>>checker=Checker(expected_schema)>>>result=checker.validate(current_data)>>>assertresult==current_dataIf data is valid,Checker.validatewill return the validated dataIf data is invalid,Checkerwill raiseCheckerError.Howjson_checkervalidates dataTypesIfChecker(...)encounters a type (such asint,str),
it will check if the corresponding piece of data is an instance of that type,
otherwise it will raiseCheckerError.>>>fromjson_checkerimportChecker>>>Checker(int).validate(123)123>>>Checker(int).validate('123')Traceback(mostrecentcalllast):...checker_exceptions.TypeCheckerError:currentvalue'123'(str)isnotintLists, similar containersIfChecker(...)encounters an instance oflist,tuple,setorfrozenset, it will validate contents of corresponding data container
against schemas listed inside that container:
if paramsoftis True validate all data,
and if have not valid data raise exception after validation>>>Checker([int]).validate([1,1,0,1])[1,1,0,1]>>>Checker([str],soft=True).validate((1,2,3))Traceback(mostrecentcalllast):...checker_exceptions.CheckerError:ListCheckerErrors:currentvalue1(int)isnotstrcurrentvalue2(int)isnotstrcurrentvalue3(int)isnotstr>>>Checker([str]).validate((1,2,3))Traceback(mostrecentcalllast):...checker_exceptions.ListCheckerError:currentvalue1(int)isnotstrDictionariesIfChecker(...)encounters an instance ofdict, it will validate data
key-value pairs:>>>current_dict={'first_key':1,'second_key':'2'}>>>checker=Checker({'first_key':int,'second_key':int})>>>checker.validate(current_dict)Traceback(mostrecentcalllast):...checker_exceptions.DictCheckerError:Fromkey="second_key"currentvalue'2'(str)isnotintOperators Or, And, OptionalKeyIf you needed validate data from some conditions, use And operator
for example current data must be int instance and greater than 0 and less 99
try it:>>>fromjson_checkerimportChecker,And>>>checker=Checker(And(int,lambdax:0<x<99))>>>checker.validate(12)12>>>checker.validate(100)Traceback(mostrecentcalllast):...checker_exceptions.CheckerError:NotvaliddataAnd(int,<lambda>),functionerrorIf you need validation not required data value, use Or operator
for example current data must be int or None
try it:>>>fromjson_checkerimportChecker,Or>>>checker=Checker(Or(int,None))>>>checker.validate(122)122>>>checker.validate('666')Traceback(mostrecentcalllast):...checker_exceptions.CheckerError:NotvaliddataOr('int',None),currentvalue'666'(str)isnotint,currentvalue'666'(str)isnotNoneIf you need validate no required dict key, use OptionalKey>>>fromjson_checkerimportChecker,OptionalKey>>>expected_schema={'key1':str,OptionalKey('key2'):int}>>>Checker(expected_schema).validate({'key1':'value'}){'key1':'value'}>>>Checker(expected_schema).validate({'key1':'value','key2':'value2'})Traceback(mostrecentcalllast):...checker_exceptions.DictCheckerError:Fromkey="OptionalKey(key2)"currentvalue'value2'(str)isnotintMore logs for debug>>>importlogging>>>fromjson_checkerimportChecker>>>logging.basicConfig(level=logging.DEBUG)>>>Checker({'k':str},soft=True).validate({'k':1})DEBUG:json_checker.app:Checkersettings:ignore_extra_keys=False,soft=TrueDEBUG:json_checker.app:DictChecker({'k':<class'str'>} (dict)) start with: {'k': 1}DEBUG:json_checker.app:TypeChecker(str)startwith:1DEBUG:json_checker.app:TypeChecker(str)errorcurrentvalue1(int)isnotstrDEBUG:json_checker.app:DictChecker({'k':<class'str'>} (dict)) error From key="k": current value 1 (int) is not strTraceback(mostrecentcalllast):...CheckerError:Fromkey="k":currentvalue1(int)isnotstr