How to use _create_schema method in pandera

Best Python code snippet using pandera_python

fundamental_schemas.py

Source:fundamental_schemas.py Github

copy

Full Screen

...6class Schema(ABC):7 def __init__(self, **options: Any):8 self._options = options9 def __repr__(self) -> str:10 return str(self._create_schema())11 def validate(self, instance) -> None:12 custom_validator.validate(13 instance=instance,14 schema=self._create_schema(),15 )16 @abstractmethod17 def _create_core_of_schema(self) -> Dict[str, Any]:18 """19 This function create the core of the schema. Core is not a complete schema, it can't be validated.20 To pass validation, _create_schema adds basic schema parts and optional parameters (e.g 'enum', 'minItems'),21 creating a complete schema prepared for validation.22 """23 pass24 def _create_schema(self) -> Dict[str, Any]:25 return {**self._create_core_of_schema(), **self._options}26 @staticmethod27 def _assert_that_schema_has_correct_type(schema):28 if not isinstance(schema, Schema):29 raise ValidationError(f'Passed schema has invalid format:\n'30 f'{pprint.pformat(schema, indent=4, sort_dicts=False)}\n'31 f'\n'32 f'Instead you should use predefined schema, like: Int(), Str(), Map(), etc.\n'33 f'You can see examples in following files:\n'34 f' schemas/tests/test_fundamental_schemas.py\n'35 f' schemas/tests/test_custom_schemas.py\n'36 f'\n'37 f'You can check all available types here:\n'38 f' schemas/package/schemas/predefined.py')39class AllOf(Schema):40 """41 AllOf: (AND) The instance must be valid for all of the subschemas42 Documentation: http://json-schema.org/understanding-json-schema/reference/combining.html#allof43 """44 def __init__(self, *items, **options: Any):45 super().__init__(**options)46 self.__items = list(items)47 def _create_core_of_schema(self) -> Dict[str, Any]:48 items_as_dicts = []49 for schema in self.__items:50 self._assert_that_schema_has_correct_type(schema)51 items_as_dicts.append(schema._create_schema())52 return {53 'allOf': items_as_dicts54 }55class AnyOf(Schema):56 """57 AnyOf: (OR) The instance must be valid for any (one or more) of the given subschemas58 Documentation: http://json-schema.org/understanding-json-schema/reference/combining.html#anyof59 """60 def __init__(self, *items, **options: Any):61 super().__init__(**options)62 self.__items = list(items)63 def _create_core_of_schema(self) -> Dict[str, Any]:64 items_as_dicts = []65 for schema in self.__items:66 self._assert_that_schema_has_correct_type(schema)67 items_as_dicts.append(schema._create_schema())68 return {69 'anyOf': items_as_dicts70 }71class Any_(Schema):72 """73 Accepts everything. Can be used to skip instance checking.74 """75 def _create_core_of_schema(self) -> Dict[str, Any]:76 return {}77class Array(Schema):78 def __init__(self, item: Schema, *items: Schema, unique_items=False, **options: Any):79 """80 Ensures that given instance is an array and contains items of required types, e.g.:81 - Array(Int()) -> read as array of ints. [0, 1, 2, 1024],82 - Array(Str()) -> read as array of strings. ['a', 'b', 'c'],83 - Array(Str(), Int()) -> read as array of ints and strings. [0, 'a', 1, 'b'] - mixing of types is allowed,84 - Array(Any(), maxItems=0) -> if you want to validate always an empty array.85 Documentation: http://json-schema.org/understanding-json-schema/reference/array.html86 :param unique_items: Duplicated items in array are treated as error.87 """88 super().__init__(**options)89 self.__items: List[Schema] = [item, *items]90 self.__unique_items = unique_items91 def _create_core_of_schema(self) -> Dict[str, Any]:92 items_as_dicts = []93 for schema in self.__items:94 self._assert_that_schema_has_correct_type(schema)95 items_as_dicts.append(schema._create_schema())96 common_part_of_schema = {97 'type': 'array',98 'uniqueItems': self.__unique_items,99 }100 if len(items_as_dicts) > 1:101 return {102 **common_part_of_schema,103 'items': {104 'oneOf': items_as_dicts,105 },106 }107 return {108 **common_part_of_schema,109 'items': items_as_dicts[0],110 }111class ArrayStrict(Schema):112 """113 Array Strict checks that the nth element in the instance, matches the nth type specified in the schema.114 example_array = [0, 'string', True]115 example_schema : ArrayStrict(Int(), String(), Bool())116 example_array[0] -> Int(),117 example_array[1] -> String(),118 example_array[2] -> Bool()119 The ArrayStrict is the equivalent of a jsonschema tuple-validation:120 http://json-schema.org/understanding-json-schema/reference/array.html#tuple-validation121 The options available for Array can be used in ArrayStrict:122 http://json-schema.org/understanding-json-schema/reference/array.html123 """124 def __init__(self, *items, **options: Any):125 super().__init__(**options)126 self.__items = list(items)127 def _create_core_of_schema(self) -> Dict[str, Any]:128 items_as_dicts = self.__items.copy()129 for index, schema in enumerate(items_as_dicts):130 self._assert_that_schema_has_correct_type(schema)131 items_as_dicts[index] = schema._create_schema()132 return {133 'type': 'array',134 'prefixItems': items_as_dicts,135 "minItems": len(items_as_dicts),136 'maxItems': len(items_as_dicts),137 }138class Bool(Schema):139 """140 Documentation: http://json-schema.org/understanding-json-schema/reference/boolean.html141 """142 def _create_core_of_schema(self) -> Dict[str, Any]:143 return {'type': 'boolean'}144class Date(Schema):145 """146 Date format used in HIVE ('%Y-%m-%dT%H:%M:%S').147 """148 def _create_core_of_schema(self) -> Dict[str, Any]:149 return {'type': 'hive-datetime'}150class Float(Schema):151 """152 Documentation: http://json-schema.org/understanding-json-schema/reference/numeric.html#number153 """154 def _create_core_of_schema(self) -> Dict[str, Any]:155 return {'type': 'number'}156class Int(Schema):157 """158 Validates normal JSON ints (e.g. 1, 42, -100), and also converted to strings159 (e.g. '1', '42', '-100'). All Hive APIs use this int format.160 """161 def __init__(self, **options: Any):162 super().__init__(**self.__replace_overridden_options(options))163 @staticmethod164 def __replace_overridden_options(options: Dict[str, Any]):165 validators_to_change = ['multipleOf', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum']166 return {f'HiveInt.{k}' if k in validators_to_change else k: v for k, v in options.items()}167 def _create_core_of_schema(self) -> [str, Any]:168 return {'type': 'hive-int'}169class Json(Schema):170 def _create_core_of_schema(self) -> Dict[str, Any]:171 return {'type': 'json'}172class Map(Schema):173 def __init__(self, schema: Dict, required_keys: Optional[List[str]] = None,174 allow_additional_properties: bool = False, **options: Any):175 """176 Validates JSON objects (in Python they are called dicts).177 :param schema: Collection of properties. Each of the individual properties has a key178 (represents the name of the key in instance), and schema (represents the required type,179 for the previously specified key).180 :param required_keys: The keys contained in this parameter are required for successful validation.181 The other keys specified in the schema are optional, their absence will not affect the validation process.182 :param allow_additional_properties: By default map does not accept additional undefined properties.183 All instance elements not defined in the schema will be reported as a 'ValidationError'.184 Set this parameter to True, it will allow the correct validation of additional properties in the instance.185 :param options: Other options that can be given in the form of a dictionary.186 Documentation: http://json-schema.org/understanding-json-schema/reference/object.html187 """188 super().__init__(**options)189 self.__allow_additional_properties: bool = allow_additional_properties190 self.__schema = schema191 self.__required_keys: List[str] = list(self.__schema.keys()) if required_keys is None else required_keys192 def _create_core_of_schema(self) -> Dict[str, Any]:193 items_as_dicts = self.__schema.copy()194 for key, schema in self.__schema.items():195 self._assert_that_schema_has_correct_type(schema)196 items_as_dicts[key] = schema._create_schema()197 return {198 'type': 'object',199 'properties': items_as_dicts,200 'required': self.__required_keys,201 'additionalProperties': self.__allow_additional_properties202 }203class Null(Schema):204 """205 Documentation: http://json-schema.org/understanding-json-schema/reference/null.html206 """207 def _create_core_of_schema(self) -> Dict[str, Any]:208 return {'type': 'null'}209class OneOf(Schema):210 """211 OneOf: (XOR) The instance must be valid for exactly one of the given subschemas.212 Documentation: http://json-schema.org/understanding-json-schema/reference/combining.html#oneof213 """214 def __init__(self, *items, **options: Any):215 super().__init__(**options)216 self.__items = list(items)217 def _create_core_of_schema(self) -> Dict[str, Any]:218 items_as_dicts = []219 for schema in self.__items:220 self._assert_that_schema_has_correct_type(schema)221 items_as_dicts.append(schema._create_schema())222 return {223 'oneOf': items_as_dicts224 }225class Str(Schema):226 """227 Documentation: http://json-schema.org/understanding-json-schema/reference/string.html228 """229 def _create_core_of_schema(self) -> Dict[str, Any]:...

Full Screen

Full Screen

arguments.py

Source:arguments.py Github

copy

Full Screen

...47 if self._example:48 description += f" <i>[{self._example}]</i>"49 return description50 def _build_schema(self) -> dict:51 schema = self._create_schema()52 if self._allowed:53 schema["allowed"] = self._allowed54 return schema55 @abstractmethod56 def _create_schema(self) -> dict:57 ...58 def __repr__(self):59 return f'Arg(name="{self.name}", description="{self._build_description()}")'60class Integer(Arg):61 BOT_ARG_TYPE = "integer"62 def __init__(self, *args, minimum=None, maximum=None, **kwargs):63 """64 :param minimum: минимальное значение аргумента.65 :param maximum: максимальное значение аргумента.66 """67 super().__init__(*args, **kwargs)68 self.minimum = minimum69 self.maximum = maximum70 def _create_schema(self) -> dict:71 schema = {72 "type": self.BOT_ARG_TYPE,73 }74 if self.maximum:75 schema["max"] = self.maximum76 if self.minimum:77 schema["min"] = self.minimum78 return schema79class String(Arg):80 BOT_ARG_TYPE = "string"81 def __init__(self, *args, regex=None, **kwargs):82 """83 :param regex: Регулярное выражение, которому должно соответствовать значение аргумента84 """85 super().__init__(*args, **kwargs)86 self.regex = regex87 def _create_schema(self) -> dict:88 schema = {89 "type": self.BOT_ARG_TYPE,90 }91 if self.regex:92 schema["regex"] = self.regex93 return schema94class ListArg(Arg):95 BOT_ARG_TYPE = "list"96 def _create_schema(self) -> dict:97 return {"type": "list"}98class MyUser(Integer):99 """ID пользователя телеграм, у которого есть доступ к командам клиента"""100 def __init__(self, *args, **kwargs):101 super().__init__(*args, **kwargs)102 self._extra_info = dict(is_granter=True)103class Actuator(String):104 """Актуатор бота"""105 def __init__(self, *args, **kwargs):106 super().__init__(*args, **kwargs)107 self._extra_info = dict(is_actuator=True)108class Granter(MyUser):109 """ID пользователя с правами на актуатор"""110 # TODO: повтор!...

Full Screen

Full Screen

user.py

Source:user.py Github

copy

Full Screen

1"""User JSON schema."""2import jsonschema3from .message import _create_schema4_sendmail_schema = {5 "$schema": "http://json-schema.org/draft-04/schema#",6 "type": "object",7 "definitions": {8 **_create_schema['definitions'],9 },10 "properties": {11 "message": {12 "type": "object",13 "properties": {14 **_create_schema['properties'],15 }16 },17 "saveToSentItems": {18 "type": "boolean",19 },20 },21 "required": [22 "message",23 ],24}...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pandera automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful