pip_services3_commons.validate package

Submodules

Module contents

pip_services3_commons.validate.__init__

Validation frameworks exist in various languages, but since this is one of the underlying functions that is incorporated into (various) obj packages, we decided to implement it in a portable format, for identical implementation across languages.

copyright

Conceptual Vision Consulting LLC 2018-2019, see AUTHORS for more details.

license

MIT, see LICENSE for more details.

class pip_services3_commons.validate.AndRule(*rules: pip_services3_commons.validate.IValidationRule.IValidationRule)

Bases: pip_services3_commons.validate.IValidationRule.IValidationRule

Validation rule to combine __rules with AND logical operation. When all __rules returns no errors, than this rule also returns no errors. When one of the __rules return errors, than the __rules returns all errors.

Example:

schema = Schema().with_rule(AndRule(ValueComparisonRule("GTE", 1), ValueComparisonRule("LTE", 10)))

schema.validate(0)          # Result: 0 must be greater or equal to 1
schema.validate(5)          # Result: no error
schema.validate(20)         # Result: 20 must be letter or equal 10
validate(path: str, schema: <module 'pip_services3_commons.validate.Schema' from '/pip_services3_commons/validate/Schema.py'>, value: Any, results: List[pip_services3_commons.validate.ValidationResult.ValidationResult])

Validates a given args against this rule.

Parameters
  • path – a dot notation path to the args.

  • schema – a schema this rule is called from

  • value – a args to be validated.

  • results – a list with validation results to add new results.

class pip_services3_commons.validate.ArraySchema(value_type: Any = None, required: bool = None, rules: Sequence[pip_services3_commons.validate.IValidationRule.IValidationRule] = None)

Bases: pip_services3_commons.validate.Schema.Schema

Schema to validate arrays.

Example:

schema = ArraySchema(TypeCode.String)

schema.validate(["A", "B", "C"])    # Result: no errors
schema.validate([1, 2, 3])          # Result: element type mismatch
schema.validate("A")                # Result: type mismatch
get_value_type() → Any

Gets the type of array elements. Null means that elements may have any type.

Returns

the type of array elements.

set_value_type(value: Any)

Sets the type of array elements. Null means that elements may have any type.

Parameters

value – a type of array elements.

class pip_services3_commons.validate.ExcludedRule(*values: Any)

Bases: pip_services3_commons.validate.IValidationRule.IValidationRule

Validation rule to check that args is excluded from the list of constants.

Example:

schema = Schema().with_rule(ExcludedRule(1, 2, 3))

schema.validate(2)      # Result: 2 must not be one of 1, 2, 3
schema.validate(10)     # Result: no errors
validate(path: str, schema: <module 'pip_services3_commons.validate.Schema' from '/pip_services3_commons/validate/Schema.py'>, value: Any, results: List[pip_services3_commons.validate.ValidationResult.ValidationResult])

Validates a given args against this rule.

Parameters
  • path – a dot notation path to the args.

  • schema – a schema this rule is called from

  • value – a args to be validated.

  • results – a list with validation results to add new results.

class pip_services3_commons.validate.FilterParamsSchema

Bases: pip_services3_commons.validate.MapSchema.MapSchema

Schema to validate FilterParams.

class pip_services3_commons.validate.IValidationRule

Bases: abc.ABC

Interface for validation __rules. Validation rule can validate one or multiple values against complex __rules like: args is in range, one property is less than another property, enforce enumerated values and more.

This interface allows to implement custom __rules.

validate(path: str, schema: Schema, value: Any, results: List[pip_services3_commons.validate.ValidationResult.ValidationResult])

Validates a given args against this rule.

Parameters
  • path – a dot notation path to the args.

  • schema – a schema this rule is called from

  • value – a args to be validated.

  • results – a list with validation results to add new results.

class pip_services3_commons.validate.IncludedRule(*values: Any)

Bases: pip_services3_commons.validate.IValidationRule.IValidationRule

Validation rule to check that args is included into the list of constants.

Example:

schema = new Schema().with_rule(IncludedRule(1, 2, 3))

schema.validate(2)      # Result: no errors
schema.validate(10)     # Result: 10 must be one of 1, 2, 3
validate(path: str, schema: <module 'pip_services3_commons.validate.Schema' from '/pip_services3_commons/validate/Schema.py'>, value: Any, results: List[pip_services3_commons.validate.ValidationResult.ValidationResult])

Validates a given args against this rule.

Parameters
  • path – a dot notation path to the args.

  • schema – a schema this rule is called from

  • value – a args to be validated.

  • results – a list with validation results to add new results.

class pip_services3_commons.validate.MapSchema(key_type: Any = None, value_type: Any = None, required: bool = None, rules: List[pip_services3_commons.validate.IValidationRule.IValidationRule] = None)

Bases: pip_services3_commons.validate.Schema.Schema

Schema to validate maps.

Example:

schema = MapSchema(TypeCode.String, TypeCode.Integer)
schema.validate({ "key1": "A", "key2": "B" })       # Result: no errors
schema.validate({ "key1": 1, "key2": 2 })           # Result: element type mismatch
schema.validate([ 1, 2, 3 ])                        # Result: type mismatch
get_key_type() → Any

Gets the type of map keys. None means that keys may have any type.

Returns

the type of map keys.

get_value_type() → Any

Gets the type of map values. None means that values may have any type.

Returns

the type of map values.

set_key_type(value: Any)

Sets the type of map keys. None means that keys may have any type.

Parameters

value – a type of map keys.

set_value_type(value: Any)

Sets the type of map values. Null means that values may have any type.

Returns

a type of map values.

class pip_services3_commons.validate.NotRule(rule: pip_services3_commons.validate.IValidationRule.IValidationRule)

Bases: pip_services3_commons.validate.IValidationRule.IValidationRule

Validation rule negate another rule. When embedded rule returns no errors, than this rule return an error. When embedded rule return errors, than the rule returns no errors.

Example:

schema = Schema().with_rule(NotRule(ValueComparisonRule("EQ", 1)))

schema.validate(1)          # Result: error
schema.validate(5)          # Result: no error
validate(path: str, schema: <module 'pip_services3_commons.validate.Schema' from '/pip_services3_commons/validate/Schema.py'>, value: Any, results: List[pip_services3_commons.validate.ValidationResult.ValidationResult])

Validates a given args against this rule.

Parameters
  • path – a dot notation path to the args.

  • schema – a schema this rule is called from

  • value – a args to be validated.

  • results – a list with validation results to add new results.

class pip_services3_commons.validate.ObjectComparator

Bases: object

Helper class to perform comparison operations over arbitrary values.

Example:

ObjectComparator.compare(2, "GT", 1)        # Result: true
ObjectComparator.areEqual("A", "B")         # Result: false
static are_equal(value1: Any, value2: Any)bool

Checks if two values are equal. The operation can be performed over values of any type.

Parameters
  • value1 – the first args to compare

  • value2 – the second args to compare

Returns

true if values are equal and false otherwise

static are_not_equal(value1: Any, value2: Any)bool

Checks if two values are NOT equal. The operation can be performed over values of any type.

Parameters
  • value1 – the first args to compare

  • value2 – the second args to compare

Returns

true if values are NOT equal and false otherwise

static compare(value1: Any, operation: str, value2: Any)bool

Perform comparison operation over two arguments. The operation can be performed over values of any type.

Parameters
  • value1 – the first argument to compare

  • operation – the comparison operation: “==” (“=”, “EQ”), “!= ” (“<>”, “NE”); “<”/”>” (“LT”/”GT”), “<=”/”>=” (“LE”/”GE”); “LIKE”.

  • value2 – the second argument to compare

Returns

result of the comparison operation

static is_greater(value1: Any, value2: Any)bool

Checks if first args is greater than the second one. The operation can be performed over numbers or strings.

Parameters
  • value1 – the first args to compare

  • value2 – the second args to compare

Returns

true if the first args is greater than second and false otherwise.

static is_less(value1: Any, value2: Any)bool

Checks if first args is less than the second one. The operation can be performed over numbers or strings.

Parameters
  • value1 – the first args to compare

  • value2 – the second args to compare

Returns

true if the first args is less than second and false otherwise.

static match(value1: Any, regexp: Any)bool

Checks if string matches a regular expression

Parameters
  • value1 – a string args to match

  • regexp – a regular expression string

Returns

true if the args matches regular expression and false otherwise.

class pip_services3_commons.validate.ObjectSchema(allow_undefined: bool = False, required: bool = None, rules: List[pip_services3_commons.validate.IValidationRule.IValidationRule] = None)

Bases: pip_services3_commons.validate.Schema.Schema

Schema to validate user defined objects.

Example:

schema = ObjectSchema(false)
                    .with_optional_property("id", TypeCode.String)
                    .with_required_property("name", TypeCode.String)

schema.validate({ id: "1", name: "ABC" })       // Result: no errors
schema.validate({ name: "ABC" })                // Result: no errors
schema.validate({ id: 1, name: "ABC" })         // Result: id type mismatch
schema.validate({ id: 1, __name: "ABC" })        // Result: name is missing, unexpected __name
schema.validate("ABC")                          // Result: type mismatch
allow_undefined(value: bool)pip_services3_commons.validate.ObjectSchema.ObjectSchema

Sets flag to allow undefined properties

This method returns reference to this error to implement Builder pattern to chain additional calls.

Parameters

value – true to allow undefined properties and false to disallow.

Returns

this validation schema.

get_properties() → List[pip_services3_commons.validate.PropertySchema.PropertySchema]

Gets validation schemas for object properties.

Returns

the list of property validation schemas.

property is_undefined_allowed

Gets flag to allow undefined properties

:return:true to allow undefined properties and false to disallow.

set_properties(value: List[pip_services3_commons.validate.PropertySchema.PropertySchema])

Sets validation schemas for object properties.

Parameters

value – a list of property validation schemas.

with_optional_property(name: str, typ: Optional[Any, None] = None, *rules: pip_services3_commons.validate.IValidationRule.IValidationRule)pip_services3_commons.validate.ObjectSchema.ObjectSchema

Adds a validation schema for an optional object property.

Parameters
  • name – a property name.

  • typ – (optional) a property schema or type.

  • rules – (optional) a list of property validation __rules.

Returns

the validation schema

with_property(schema: pip_services3_commons.validate.PropertySchema.PropertySchema)pip_services3_commons.validate.ObjectSchema.ObjectSchema

Adds a validation schema for an object property.

This method returns reference to this error to implement Builder pattern to chain additional calls.

Parameters

schema – a property validation schema to be added.

Returns

this validation schema.

with_required_property(name: str, typ: Optional[Any, None] = None, *rules: pip_services3_commons.validate.IValidationRule.IValidationRule)pip_services3_commons.validate.ObjectSchema.ObjectSchema

Adds a validation schema for a __required object property.

Parameters
  • name – a property name.

  • typ – (optional) a property schema or type.

  • rules – (optional) a list of property validation __rules.

Returns

the validation schema

class pip_services3_commons.validate.OnlyOneExistRule(*properties: str)

Bases: pip_services3_commons.validate.IValidationRule.IValidationRule

Validation rule that check that at exactly one of the object properties is not null.

Example:

schema = Schema().with_rule(OnlyOneExistsRule("field1", "field2"))

schema.validate({ field1: 1, field2: "A" })     # Result: only one of properties field1, field2 must exist
schema.validate({ field1: 1 })                  # Result: no errors
schema.validate({ })                            # Result: only one of properties field1, field2 must exist
validate(path: str, schema: <module 'pip_services3_commons.validate.Schema' from '/pip_services3_commons/validate/Schema.py'>, value: Any, results: List[pip_services3_commons.validate.ValidationResult.ValidationResult])

Validates a given args against this rule.

Parameters
  • path – a dot notation path to the args.

  • schema – a schema this rule is called from

  • value – a args to be validated.

  • results – a list with validation results to add new results.

class pip_services3_commons.validate.OrRule(*rules: pip_services3_commons.validate.IValidationRule.IValidationRule)

Bases: pip_services3_commons.validate.IValidationRule.IValidationRule

Validation rule to combine __rules with OR logical operation. When one of __rules returns no errors, than this rule also returns no errors. When all __rules return errors, than the rule returns all errors.

Example:

schema = Schema().with_rule(OrRule(ValueComparisonRule("LT", 1), ValueComparisonRule("GT", 10)))

schema.validate(0)          # Result: no error
schema.validate(5)          # Result: 5 must be less than 1 or 5 must be more than 10
schema.validate(20)         # Result: no error
validate(path: str, schema: <module 'pip_services3_commons.validate.Schema' from '/pip_services3_commons/validate/Schema.py'>, value: Any, results: List[pip_services3_commons.validate.ValidationResult.ValidationResult])

Validates a given args against this rule.

Parameters
  • path – a dot notation path to the args.

  • schema – a schema this rule is called from

  • value – a args to be validated.

  • results – a list with validation results to add new results.

class pip_services3_commons.validate.PagingParamsSchema

Bases: pip_services3_commons.validate.ObjectSchema.ObjectSchema

Schema to validate PagingParams.

class pip_services3_commons.validate.ProjectionParamsSchema

Bases: pip_services3_commons.validate.ArraySchema.ArraySchema

Schema to validate ProjectionParams

class pip_services3_commons.validate.PropertiesComparisonRule(property1: str, operation: str, property2: str)

Bases: pip_services3_commons.validate.IValidationRule.IValidationRule

Validation rule that compares two object properties.

Example:

schema = ObjectSchema().with_rule(PropertyComparisonRule("field1", "NE", "field2"))

schema.validate({ field1: 1, field2: 2 })       # Result: no errors
schema.validate({ field1: 1, field2: 1 })       # Result: field1 shall not be equal to field2
schema.validate({})                             # Result: no errors
validate(path: str, schema: <module 'pip_services3_commons.validate.Schema' from '/pip_services3_commons/validate/Schema.py'>, value: Any, results: List[pip_services3_commons.validate.ValidationResult.ValidationResult])

Validates a given args against this rule.

Parameters
  • path – a dot notation path to the args.

  • schema – a schema this rule is called from

  • value – a args to be validated.

  • results – a list with validation results to add new results.

class pip_services3_commons.validate.PropertySchema(name: str = None, value_type: Any = None, required: bool = None, rules: List[pip_services3_commons.validate.IValidationRule.IValidationRule] = None)

Bases: pip_services3_commons.validate.Schema.Schema

Schema to validate object properties

Example:

schema = ObjectSchema().with_property(PropertySchema("id", TypeCode.String))

schema.validate({ id: "1", name: "ABC" })       # Result: no errors
schema.validate({ name: "ABC" })                # Result: no errors
schema.validate({ id: 1, name: "ABC" })         # Result: id type mismatch
get_name()str

Gets the property name.

Returns

the property name.

get_type() → Any

Gets the property type.

Returns

the property type.

set_name(value: str)

Sets the property name.

Parameters

value – a new property name.

set_type(value: Any)

Sets a new property type. The type can be defined as type, type name or TypeCode

Parameters

value – a new property type.

class pip_services3_commons.validate.Schema(required: bool = False, rules: List[pip_services3_commons.validate.IValidationRule.IValidationRule] = None)

Bases: object

Basic schema that validates values against a set of validation __rules.

This schema is used as a basis for specific schemas to validate objects, project properties, arrays and maps.

get_rules() → List[pip_services3_commons.validate.IValidationRule.IValidationRule]

Gets validation __rules to check values against.

Returns

a list with validation __rules.

is_required()bool

Gets a flag that always requires non-null values. For null values it raises a validation error.

Returns

true to always require non-null values and false to allow null values.

make_optional()pip_services3_commons.validate.Schema.Schema

Makes validated values optional. Validation for null values will be skipped.

This method returns reference to this error to implement Builder pattern to chain additional calls.

Returns

this validation schema

make_required()pip_services3_commons.validate.Schema.Schema

Makes validated values always __required (non-null). For null values the schema will raise errors.

This method returns reference to this error to implement Builder pattern to chain additional calls.

Returns

this validation schema

set_required(value: bool)

Sets a flag that always requires non-null values.

Parameters

value – true to always require non-null values and false to allow null values.

set_rules(value: List[pip_services3_commons.validate.IValidationRule.IValidationRule])

Sets validation __rules to check values against.

Parameters

value – a list with validation __rules.

validate(value: Any) → List[pip_services3_commons.validate.ValidationResult.ValidationResult]

Validates the given args and results validation results.

Parameters

value – a args to be validated.

Returns

a list with validation results.

validate_and_return_exception(correlation_id: Optional[str, None], value: Any, strict: bool = False)pip_services3_commons.validate.ValidationException.ValidationException

Validates the given args and returns a ValidationException if errors were found.

Parameters
  • correlation_id – (optional) transaction id to trace execution through call chain.

  • value – a args to be validated.

  • strict – true to treat warnings as errors.

validate_and_throw_exception(correlation_id: Optional[str, None], value: Any, strict: bool = False)

Validates the given args and throws a ValidationException if errors were found.

Parameters
  • correlation_id – (optional) transaction id to trace execution through call chain.

  • value – a args to be validated.

  • strict – true to treat warnings as errors.

with_rule(rule: pip_services3_commons.validate.IValidationRule.IValidationRule)pip_services3_commons.validate.Schema.Schema

Adds validation rule to this schema.

This method returns reference to this error to implement Builder pattern to chain additional calls.

Parameters

rule – a validation rule to be added.

Returns

this validation schema.

exception pip_services3_commons.validate.ValidationException(correlation_id: Optional[str, None], message: Optional[str, None], results: List[pip_services3_commons.validate.ValidationResult.ValidationResult])

Bases: pip_services3_commons.errors.BadRequestException.BadRequestException

Errors in schema validation.

Validation errors are usually generated based in ValidationResult. If using strict mode, warnings will also raise validation exceptions.

static compose_message(results: List[pip_services3_commons.validate.ValidationResult.ValidationResult])str

Composes human readable error message based on validation results.

Parameters

results – a list of validation results.

Returns

a composed error message.

static from_results(correlation_id: Optional[str, None], results: List[pip_services3_commons.validate.ValidationResult.ValidationResult], strict: bool)pip_services3_commons.validate.ValidationException.ValidationException

Creates a new ValidationException based on errors in validation results. If validation results have no errors, than null is returned.

Parameters
  • correlation_id – (optional) transaction id to trace execution through call chain.

  • results – list of validation results that may contain errors

  • strict – true to treat warnings as errors.

Returns

a newly created ValidationException or null if no errors in found.

static throw_exception_if_needed(correlation_id: Optional[str, None], results: List[pip_services3_commons.validate.ValidationResult.ValidationResult], strict: bool)

Throws ValidationException based on errors in validation results. If validation results have no errors, than no error is thrown.

Parameters
  • correlation_id – (optional) transaction id to trace execution through call chain.

  • results – list of validation results that may contain errors

  • strict – true to treat warnings as errors.

class pip_services3_commons.validate.ValidationResult(path: str = None, type: pip_services3_commons.validate.ValidationResultType.ValidationResultType = None, code: str = None, message: str = None, expected: Any = None, actual: Any = None)

Bases: object

Result generated by schema validation

get_actual() → Any

Gets the actual args found by schema validation.

Returns

the actual args.

get_code()str

Gets the error code.

Returns

the error code

get_expected() → Any

Gets the args expected by schema validation.

Returns

the expected args.

get_message()str

Gets the human readable message.

Returns

the result message.

get_path()str

Gets dot notation path of the validated element.

Returns

the path of the validated element.

get_type()pip_services3_commons.validate.ValidationResultType.ValidationResultType

Gets the type of the validation result: Information, Warning, or Error. See :class: ValidationResultType

Returns

the type of the validation result.

to_json() → Dict[str, Any]
class pip_services3_commons.validate.ValidationResultType(value)

Bases: enum.Enum

Types of validation results generated by validation schemas.

Error = 2
Information = 0
Warning = 1
class pip_services3_commons.validate.ValueComparisonRule(operation: Any, value: Any)

Bases: pip_services3_commons.validate.IValidationRule.IValidationRule

Validation rule that compares args to a constant.

Example:

schema = Schema().with_rule(ValueComparisonRule("EQ", 1))

schema.validate(1)          # Result: no errors
schema.validate(2)          # Result: 2 is not equal to 1
validate(path: str, schema: <module 'pip_services3_commons.validate.Schema' from '/pip_services3_commons/validate/Schema.py'>, value: Any, results: List[pip_services3_commons.validate.ValidationResult.ValidationResult])

Validates a given args against this rule.

Parameters
  • path – a dot notation path to the args.

  • schema – a schema this rule is called from

  • value – a args to be validated.

  • results – a list with validation results to add new results.