一个死的简单实用程序,用于验证对象是否具有某个结构。
simple-schema-validator的Python项目详细描述
简单模式验证器
一个死的简单实用程序,用于验证对象是否具有某个结构。在我们的一些项目中使用。
基本用法
pip install simple_schema_validator
例如:
假设我们有一个返回以下数据的api:
{"user":1,"profile":{"email":"some@user.com","name":"Some User","age":20},"tokens":{"jwt":"...","refresh":"...","firebase":"...",}}
我们正在编写一个简单的集成测试,以确保响应具有一定的结构。
然后我们可以使用模式验证器,如so:
fromsimple_schema_validatorimportschema_validatordata=get_data_from_api()schema={'user':Any,'profile':{'email':Any,'name':Any,'age':Any},'tokens':{'jwt':Any,'refresh':Any,'firebase':Any}}validation=schema_validator(schema,data)ifnotresult:print(f'Keys in data, but not in schema: {validation.additional_keys}')print(f'Keys in schema, but not in data: {validation.missing_keys}')print(f'Keys with different type from schema {validation.type_errors}')
missing_keys
是schema
中所需的键,但在data
中找不到。additional_keys
是存在于data
中的那些键,但不是schema
所必需的。validation_errors
是那些键,它们在data
中的类型与在schema
中定义的不同。
嵌套键用“点”表示-profile.email
、tokens.jwt
等。
类型检查
util支持简单的模式类型检查。
目前,架构中支持的类型是:
int
float
str
bool
typing.Any
(来自pythontyping
库)simple_schema_validator.types.Optional
(自定义类型,在包中定义)
如果类型是Any
,则不进行类型检查。
如果存在类型不匹配,则错误将放在结果的type_errors
属性中,该属性是类型错误的列表。
单一类型错误的一般格式为:
{'path':'the.path.to.the.value.in.data','expected':the_expected_type_as_defined_in_the_schema,'actual':the_actual_type_of_the_value}
下面是一个示例:
fromsimple_schema_validatorimportschema_validator,typesschema={'user':str,'profile':{'email':str,'name':str,'age':int},'tokens':{'jwt':str,'refresh':str,'firebase':str}}data={'user':'Some User','profile':{'email':'someuser@hacksoft.io','name':'Some User','age':"29"},'tokens':{'jwt':'some token value','refresh':'some token value','firebase':'some token value'}}result=schema_validator(schema,data)assertbool(result)isFalseassertresult.type_errors==[{'path':'profile.age','expected':int,'actual':str}]
可选类型
架构验证器支持可选类型。
您可以执行以下操作:
fromsimple_schema_validatorimportschema_validator,typesschema={'a':types.Optional[int]}data_1={'a':None}data_2={'a':1}data_3={'a':'some_string'}assertbool(schema_validator(schema,data_1))isTrueassertbool(schema_validator(schema,data_2))isTrueassertbool(schema_validator(schema,data_3))isFalse
此外,您可以在架构中定义可选分支:
fromsimple_schema_validatorimportschema_validator,typesschema={'a':types.Optional[{'b':int}]}data_1={'a':None}data_2={'a':1}data_3={'a':{'b':1}}data_4={'a':{'b':'some_string'}}assertbool(schema_validator(schema,data_1))isTrueassertbool(schema_validator(schema,data_2))isFalseassertbool(schema_validator(schema,data_3))isTrueassertbool(schema_validator(schema,data_4))isFalse
示例
例如,检查项目的examples文件夹或测试。