How to use _add_error method in Slash

Best Python code snippet using slash

errors.py

Source:errors.py Github

copy

Full Screen

...205 # type: (str, ParserErrorCollection) -> None206 """Construct a new ParserContext."""207 self.errors = errors208 self.file_name = file_name209 def _add_error(self, location, error_id, msg):210 # type: (common.SourceLocation, str, str) -> None211 """212 Add an error with a source location information.213 This is usually directly from an idl.syntax or idl.ast class.214 """215 self.errors.add(location, error_id, msg)216 def _add_node_error(self, node, error_id, msg):217 # type: (yaml.nodes.Node, str, str) -> None218 """Add an error with source location information based on a YAML node."""219 self.errors.add(220 common.SourceLocation(self.file_name, node.start_mark.line, node.start_mark.column),221 error_id, msg)222 def add_unknown_root_node_error(self, node):223 # type: (yaml.nodes.Node) -> None224 """Add an error about an unknown YAML root node."""225 self._add_node_error(226 node, ERROR_ID_UNKNOWN_ROOT,227 ("Unrecognized IDL specification root level node '%s', only " +228 " (global, import, types, commands, and structs) are accepted") % (node.value))229 def add_unknown_node_error(self, node, name):230 # type: (yaml.nodes.Node, str) -> None231 """Add an error about an unknown node."""232 self._add_node_error(node, ERROR_ID_UNKNOWN_NODE,233 "Unknown IDL node '%s' for YAML entity '%s'" % (node.value, name))234 def add_duplicate_symbol_error(self, location, name, duplicate_class_name, original_class_name):235 # type: (common.SourceLocation, str, str, str) -> None236 """Add an error about a duplicate symbol."""237 self._add_error(238 location, ERROR_ID_DUPLICATE_SYMBOL, "%s '%s' is a duplicate symbol of an existing %s" %239 (duplicate_class_name, name, original_class_name))240 def add_unknown_type_error(self, location, field_name, type_name):241 # type: (common.SourceLocation, str, str) -> None242 """Add an error about an unknown type."""243 self._add_error(location, ERROR_ID_UNKNOWN_TYPE,244 "'%s' is an unknown type for field '%s'" % (type_name, field_name))245 def _is_node_type(self, node, node_name, expected_node_type):246 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode], str, str) -> bool247 """Return True if the yaml node type is expected, otherwise returns False and logs an error."""248 if not node.id == expected_node_type:249 self._add_node_error(250 node, ERROR_ID_IS_NODE_TYPE,251 "Illegal YAML node type '%s' for '%s', expected YAML node type '%s'" %252 (node.id, node_name, expected_node_type))253 return False254 return True255 def is_mapping_node(self, node, node_name):256 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode], str) -> bool257 """Return True if this YAML node is a Map."""258 return self._is_node_type(node, node_name, "mapping")259 def is_scalar_node(self, node, node_name):260 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode], str) -> bool261 """Return True if this YAML node is a Scalar."""262 return self._is_node_type(node, node_name, "scalar")263 def is_scalar_sequence(self, node, node_name):264 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode], str) -> bool265 """Return True if this YAML node is a Sequence of Scalars."""266 if self._is_node_type(node, node_name, "sequence"):267 for seq_node in node.value:268 if not self.is_scalar_node(seq_node, node_name):269 return False270 return True271 return False272 def is_sequence_mapping(self, node, node_name):273 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode], str) -> bool274 """Return True if this YAML node is a Sequence of Mappings."""275 if self._is_node_type(node, node_name, "sequence"):276 for seq_node in node.value:277 if not self.is_mapping_node(seq_node, node_name):278 return False279 return True280 return False281 def is_scalar_sequence_or_scalar_node(self, node, node_name):282 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode], str) -> bool283 # pylint: disable=invalid-name284 """Return True if the YAML node is a Scalar or Sequence."""285 if not node.id == "scalar" and not node.id == "sequence":286 self._add_node_error(287 node, ERROR_ID_IS_NODE_TYPE_SCALAR_OR_SEQUENCE,288 "Illegal node type '%s' for '%s', expected either node type 'scalar' or 'sequence'"289 % (node.id, node_name))290 return False291 if node.id == "sequence":292 return self.is_scalar_sequence(node, node_name)293 return True294 def is_scalar_or_mapping_node(self, node, node_name):295 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode], str) -> bool296 # pylint: disable=invalid-name297 """Return True if the YAML node is a Scalar or Mapping."""298 if not node.id == "scalar" and not node.id == "mapping":299 self._add_node_error(300 node, ERROR_ID_IS_NODE_TYPE_SCALAR_OR_MAPPING,301 "Illegal node type '%s' for '%s', expected either node type 'scalar' or 'mapping'" %302 (node.id, node_name))303 return False304 return True305 def is_scalar_bool_node(self, node, node_name):306 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode], str) -> bool307 """Return True if this YAML node is a Scalar and a valid boolean."""308 if not self._is_node_type(node, node_name, "scalar"):309 return False310 if not (node.value == "true" or node.value == "false"):311 self._add_node_error(312 node, ERROR_ID_IS_NODE_VALID_BOOL,313 "Illegal bool value for '%s', expected either 'true' or 'false'." % node_name)314 return False315 return True316 def get_bool(self, node):317 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode]) -> bool318 """Convert a scalar to a bool."""319 assert self.is_scalar_bool_node(node, "unknown")320 if node.value == "true":321 return True322 return False323 def get_list(self, node):324 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode]) -> List[str]325 """Get a YAML scalar or sequence node as a list of strings."""326 assert self.is_scalar_sequence_or_scalar_node(node, "unknown")327 if node.id == "scalar":328 return [node.value]329 # Unzip the list of ScalarNode330 return [v.value for v in node.value]331 def add_duplicate_error(self, node, node_name):332 # type: (yaml.nodes.Node, str) -> None333 """Add an error about a duplicate node."""334 self._add_node_error(node, ERROR_ID_DUPLICATE_NODE,335 "Duplicate node found for '%s'" % (node_name))336 def add_missing_required_field_error(self, node, node_parent, node_name):337 # type: (yaml.nodes.Node, str, str) -> None338 """Add an error about a YAML node missing a required child."""339 # pylint: disable=invalid-name340 self._add_node_error(341 node, ERROR_ID_MISSING_REQUIRED_FIELD,342 "IDL node '%s' is missing required scalar '%s'" % (node_parent, node_name))343 def add_missing_ast_required_field_error(self, location, ast_type, ast_parent, ast_name):344 # type: (common.SourceLocation, str, str, str) -> None345 """Add an error about a AST node missing a required child."""346 # pylint: disable=invalid-name347 self._add_error(348 location, ERROR_ID_MISSING_AST_REQUIRED_FIELD,349 "%s '%s' is missing required scalar '%s'" % (ast_type, ast_parent, ast_name))350 def add_array_not_valid_error(self, location, ast_type, name):351 # type: (common.SourceLocation, str, str) -> None352 """Add an error about a 'array' not being a valid type name."""353 self._add_error(location, ERROR_ID_ARRAY_NOT_VALID_TYPE,354 "The %s '%s' cannot be named 'array'" % (ast_type, name))355 def add_bad_bson_type_error(self, location, ast_type, ast_parent, bson_type_name):356 # type: (common.SourceLocation, str, str, str) -> None357 """Add an error about a bad bson type."""358 self._add_error(359 location, ERROR_ID_BAD_BSON_TYPE, "BSON Type '%s' is not recognized for %s '%s'." %360 (bson_type_name, ast_type, ast_parent))361 def add_bad_bson_scalar_type_error(self, location, ast_type, ast_parent, bson_type_name):362 # type: (common.SourceLocation, str, str, str) -> None363 """Add an error about a bad list of bson types."""364 self._add_error(location, ERROR_ID_BAD_BSON_TYPE_LIST,365 ("BSON Type '%s' is not a scalar bson type for %s '%s'" +366 " and cannot be used in a list of bson serialization types.") %367 (bson_type_name, ast_type, ast_parent))368 def add_bad_bson_bindata_subtype_error(self, location, ast_type, ast_parent, bson_type_name):369 # type: (common.SourceLocation, str, str, str) -> None370 """Add an error about a bindata_subtype associated with a type that is not bindata."""371 # pylint: disable=invalid-name372 self._add_error(location, ERROR_ID_BAD_BSON_BINDATA_SUBTYPE_TYPE,373 ("The bindata_subtype field for %s '%s' is not valid for bson type '%s'") %374 (ast_type, ast_parent, bson_type_name))375 def add_bad_bson_bindata_subtype_value_error(self, location, ast_type, ast_parent, value):376 # type: (common.SourceLocation, str, str, str) -> None377 """Add an error about a bad value for bindata_subtype."""378 # pylint: disable=invalid-name379 self._add_error(location, ERROR_ID_BAD_BSON_BINDATA_SUBTYPE_VALUE,380 ("The bindata_subtype field's value '%s' for %s '%s' is not valid") %381 (value, ast_type, ast_parent))382 def add_bad_setat_specifier(self, location, specifier):383 # type: (common.SourceLocation, str) -> None384 """Add an error about a bad set_at specifier."""385 # pylint: disable=invalid-name386 self._add_error(387 location, ERROR_ID_BAD_SETAT_SPECIFIER,388 ("Unexpected set_at specifier: '%s', expected 'startup' or 'runtime'") % (specifier))389 def add_no_string_data_error(self, location, ast_type, ast_parent):390 # type: (common.SourceLocation, str, str) -> None391 """Add an error about using StringData for cpp_type."""392 self._add_error(location, ERROR_ID_NO_STRINGDATA,393 ("Do not use mongo::StringData for %s '%s', use std::string instead") %394 (ast_type, ast_parent))395 def add_ignored_field_must_be_empty_error(self, location, name, field_name):396 # type: (common.SourceLocation, str, str) -> None397 """Add an error about field must be empty for ignored fields."""398 # pylint: disable=invalid-name399 self._add_error(400 location, ERROR_ID_FIELD_MUST_BE_EMPTY_FOR_IGNORED,401 ("Field '%s' cannot contain a value for property '%s' when a field is marked as ignored"402 ) % (name, field_name))403 def add_struct_field_must_be_empty_error(self, location, name, field_name):404 # type: (common.SourceLocation, str, str) -> None405 """Add an error about field must be empty for fields of type struct."""406 # pylint: disable=invalid-name407 self._add_error(408 location, ERROR_ID_FIELD_MUST_BE_EMPTY_FOR_STRUCT,409 ("Field '%s' cannot contain a value for property '%s' when a field's type is a struct")410 % (name, field_name))411 def add_not_custom_scalar_serialization_not_supported_error(self, location, ast_type,412 ast_parent, bson_type_name):413 # type: (common.SourceLocation, str, str, str) -> None414 # pylint: disable=invalid-name415 """Add an error about field must be empty for fields of type struct."""416 self._add_error(417 location, ERROR_ID_CUSTOM_SCALAR_SERIALIZATION_NOT_SUPPORTED,418 ("Custom serialization for a scalar is only supported for 'string'. The %s '%s' cannot"419 + " use bson type '%s', use a bson_serialization_type of 'any' instead.") %420 (ast_type, ast_parent, bson_type_name))421 def add_bad_any_type_use_error(self, location, bson_type, ast_type, ast_parent):422 # type: (common.SourceLocation, str, str, str) -> None423 # pylint: disable=invalid-name424 """Add an error about any being used in a list of bson types."""425 self._add_error(426 location, ERROR_ID_BAD_ANY_TYPE_USE,427 ("The BSON Type '%s' is not allowed in a list of bson serialization types for" +428 "%s '%s'. It must be only a single bson type.") % (bson_type, ast_type, ast_parent))429 def add_bad_cpp_numeric_type_use_error(self, location, ast_type, ast_parent, cpp_type):430 # type: (common.SourceLocation, str, str, str) -> None431 # pylint: disable=invalid-name432 """Add an error about any being used in a list of bson types."""433 self._add_error(434 location, ERROR_ID_BAD_NUMERIC_CPP_TYPE,435 ("The C++ numeric type '%s' is not allowed for %s '%s'. Only 'std::int32_t'," +436 " 'std::uint32_t', 'std::uint64_t', and 'std::int64_t' are supported.") %437 (cpp_type, ast_type, ast_parent))438 def add_bad_array_type_name_error(self, location, field_name, type_name):439 # type: (common.SourceLocation, str, str) -> None440 """Add an error about a field type having a malformed type name."""441 self._add_error(location, ERROR_ID_BAD_ARRAY_TYPE_NAME,442 ("'%s' is not a valid array type for field '%s'. A valid array type" +443 " is in the form 'array<type_name>'.") % (type_name, field_name))444 def add_array_no_default_error(self, location, field_name):445 # type: (common.SourceLocation, str) -> None446 """Add an error about an array having a type with a default value."""447 self._add_error(448 location, ERROR_ID_ARRAY_NO_DEFAULT,449 "Field '%s' is not allowed to have both a default value and be an array type" %450 (field_name))451 def add_cannot_find_import(self, location, imported_file_name):452 # type: (common.SourceLocation, str) -> None453 """Add an error about not being able to find an import."""454 self._add_error(location, ERROR_ID_BAD_IMPORT,455 "Could not resolve import '%s', file not found" % (imported_file_name))456 def add_bindata_no_default(self, location, ast_type, ast_parent):457 # type: (common.SourceLocation, str, str) -> None458 # pylint: disable=invalid-name459 """Add an error about a bindata type with a default value."""460 self._add_error(location, ERROR_ID_BAD_BINDATA_DEFAULT,461 ("Default values are not allowed for %s '%s'") % (ast_type, ast_parent))462 def add_chained_type_not_found_error(self, location, type_name):463 # type: (common.SourceLocation, str) -> None464 # pylint: disable=invalid-name465 """Add an error about a chained_type not found."""466 self._add_error(location, ERROR_ID_CHAINED_TYPE_NOT_FOUND,467 ("Type '%s' is not a valid chained type") % (type_name))468 def add_chained_type_wrong_type_error(self, location, type_name, bson_type_name):469 # type: (common.SourceLocation, str, str) -> None470 # pylint: disable=invalid-name471 """Add an error about a chained_type being the wrong type."""472 self._add_error(location, ERROR_ID_CHAINED_TYPE_WRONG_BSON_TYPE,473 ("Chained Type '%s' has the wrong bson serialization type '%s', only" +474 "'chain' is supported for chained types.") % (type_name, bson_type_name))475 def add_duplicate_field_error(self, location, field_container, field_name, duplicate_location):476 # type: (common.SourceLocation, str, str, common.SourceLocation) -> None477 """Add an error about duplicate fields as a result of chained structs/types."""478 self._add_error(479 location, ERROR_ID_CHAINED_DUPLICATE_FIELD,480 ("Chained Struct or Type '%s' duplicates an existing field '%s' at location" + "'%s'.")481 % (field_container, field_name, duplicate_location))482 def add_chained_type_no_strict_error(self, location, struct_name):483 # type: (common.SourceLocation, str) -> None484 # pylint: disable=invalid-name485 """Add an error about strict parser validate and chained types."""486 self._add_error(location, ERROR_ID_CHAINED_NO_TYPE_STRICT,487 ("Strict IDL parser validation is not supported with chained types for " +488 "struct '%s'. Specify 'strict: false' for this struct.") % (struct_name))489 def add_chained_struct_not_found_error(self, location, struct_name):490 # type: (common.SourceLocation, str) -> None491 # pylint: disable=invalid-name492 """Add an error about a chained_struct not found."""493 self._add_error(location, ERROR_ID_CHAINED_STRUCT_NOT_FOUND,494 ("Type '%s' is not a valid chained struct") % (struct_name))495 def add_chained_nested_struct_no_strict_error(self, location, struct_name, nested_struct_name):496 # type: (common.SourceLocation, str, str) -> None497 # pylint: disable=invalid-name498 """Add an error about strict parser validate and chained types."""499 self._add_error(location, ERROR_ID_CHAINED_NO_NESTED_STRUCT_STRICT,500 ("Strict IDL parser validation is not supported for a chained struct '%s'" +501 " contained by struct '%s'. Specify 'strict: false' for this struct.") %502 (nested_struct_name, struct_name))503 def add_chained_nested_struct_no_nested_error(self, location, struct_name, chained_name):504 # type: (common.SourceLocation, str, str) -> None505 # pylint: disable=invalid-name506 """Add an error about struct's chaining being a struct with nested chaining."""507 self._add_error(location, ERROR_ID_CHAINED_NO_NESTED_CHAINED,508 ("Struct '%s' is not allowed to nest struct '%s' since it has chained" +509 " structs and/or types.") % (struct_name, chained_name))510 def add_empty_enum_error(self, node, name):511 # type: (yaml.nodes.Node, str) -> None512 """Add an error about an enum without values."""513 self._add_node_error(514 node, ERROR_ID_BAD_EMPTY_ENUM,515 "Enum '%s' must have values specified but no values were found" % (name))516 def add_array_enum_error(self, location, field_name):517 # type: (common.SourceLocation, str) -> None518 """Add an error for a field being an array of enums."""519 self._add_error(location, ERROR_ID_NO_ARRAY_ENUM,520 "Field '%s' cannot be an array of enums" % (field_name))521 def add_enum_bad_type_error(self, location, enum_name, enum_type):522 # type: (common.SourceLocation, str, str) -> None523 """Add an error for an enum having the wrong type."""524 self._add_error(location, ERROR_ID_ENUM_BAD_TYPE,525 "Enum '%s' type '%s' is not a supported enum type" % (enum_name, enum_type))526 def add_enum_value_not_int_error(self, location, enum_name, enum_value, err_msg):527 # type: (common.SourceLocation, str, str, str) -> None528 """Add an error for an enum value not being an integer."""529 self._add_error(530 location, ERROR_ID_ENUM_BAD_INT_VAUE,531 "Enum '%s' value '%s' is not an integer, exception '%s'" % (enum_name, enum_value,532 err_msg))533 def add_enum_value_not_unique_error(self, location, enum_name):534 # type: (common.SourceLocation, str) -> None535 """Add an error for an enum having duplicate values."""536 self._add_error(location, ERROR_ID_ENUM_NON_UNIQUE_VALUES,537 "Enum '%s' has duplicate values, all values must be unique" % (enum_name))538 def add_enum_non_continuous_range_error(self, location, enum_name):539 # type: (common.SourceLocation, str) -> None540 """Add an error for an enum having duplicate values."""541 # pylint: disable=invalid-name542 self._add_error(location, ERROR_ID_ENUM_NON_CONTINUOUS_RANGE,543 ("Enum '%s' has non-continuous integer variables, enums must have a " +544 "continuous range of integer variables.") % (enum_name))545 def add_bad_command_namespace_error(self, location, command_name, command_namespace,546 valid_commands):547 # type: (common.SourceLocation, str, str, List[str]) -> None548 """Add an error about the namespace value not being a valid choice."""549 self._add_error(550 location, ERROR_ID_BAD_COMMAND_NAMESPACE,551 "Command namespace '%s' for command '%s' is not a valid choice. Valid options are '%s'."552 % (command_namespace, command_name, valid_commands))553 def add_bad_command_as_field_error(self, location, command_name):554 # type: (common.SourceLocation, str) -> None555 """Add an error about using a command for a field."""556 self._add_error(location, ERROR_ID_FIELD_NO_COMMAND,557 ("Command '%s' cannot be used as a field type'. Commands must be top-level"558 + " types due to their serialization rules.") % (command_name))559 def add_bad_array_of_chain(self, location, field_name):560 # type: (common.SourceLocation, str) -> None561 """Add an error about a field being an array of chain_types."""562 self._add_error(location, ERROR_ID_NO_ARRAY_OF_CHAIN,563 "Field '%s' cannot be an array of chained types" % (field_name))564 def add_bad_field_default_and_optional(self, location, field_name):565 # type: (common.SourceLocation, str) -> None566 """Add an error about a field being optional and having a default value."""567 # pylint: disable=invalid-name568 self._add_error(569 location, ERROR_ID_ILLEGAL_FIELD_DEFAULT_AND_OPTIONAL,570 ("Field '%s' can only be marked as optional or have a default value," + " not both.") %571 (field_name))572 def add_bad_struct_field_as_doc_sequence_error(self, location, struct_name, field_name):573 # type: (common.SourceLocation, str, str) -> None574 """Add an error about using a field in a struct being marked with supports_doc_sequence."""575 # pylint: disable=invalid-name576 self._add_error(location, ERROR_ID_STRUCT_NO_DOC_SEQUENCE,577 ("Field '%s' in struct '%s' cannot be used as a Command Document Sequence"578 " type. They are only supported in commands.") % (field_name, struct_name))579 def add_bad_non_array_as_doc_sequence_error(self, location, struct_name, field_name):580 # type: (common.SourceLocation, str, str) -> None581 """Add an error about using a non-array type field being marked with supports_doc_sequence."""582 # pylint: disable=invalid-name583 self._add_error(location, ERROR_ID_NO_DOC_SEQUENCE_FOR_NON_ARRAY,584 ("Field '%s' in command '%s' cannot be used as a Command Document Sequence"585 " type since it is not an array.") % (field_name, struct_name))586 def add_bad_non_object_as_doc_sequence_error(self, location, field_name):587 # type: (common.SourceLocation, str) -> None588 """Add an error about using a non-struct or BSON object for a doc sequence."""589 # pylint: disable=invalid-name590 self._add_error(location, ERROR_ID_NO_DOC_SEQUENCE_FOR_NON_OBJECT,591 ("Field '%s' cannot be used as a Command Document Sequence"592 " type since it is not a BSON object or struct.") % (field_name))593 def add_bad_command_name_duplicates_field(self, location, command_name):594 # type: (common.SourceLocation, str) -> None595 """Add an error about a command and field having the same name."""596 # pylint: disable=invalid-name597 self._add_error(location, ERROR_ID_COMMAND_DUPLICATES_FIELD,598 ("Command '%s' cannot have the same name as a field.") % (command_name))599 def add_bad_field_non_const_getter_in_immutable_struct_error(self, location, struct_name,600 field_name):601 # type: (common.SourceLocation, str, str) -> None602 """Add an error about marking a field with non_const_getter in an immutable struct."""603 # pylint: disable=invalid-name604 self._add_error(605 location, ERROR_ID_NON_CONST_GETTER_IN_IMMUTABLE_STRUCT,606 ("Cannot generate a non-const getter for field '%s' in struct '%s' since"607 " struct '%s' is marked as immutable.") % (field_name, struct_name, struct_name))608 def add_useless_variant_error(self, location):609 # type: (common.SourceLocation) -> None610 """Add an error about a variant with 0 or 1 variant types."""611 self._add_error(location, ERROR_ID_USELESS_VARIANT,612 ("Cannot declare a variant with only 0 or 1 variant types"))613 def add_variant_comparison_error(self, location):614 # type: (common.SourceLocation) -> None615 """Add an error about a struct with generate_comparison_operators and a variant field."""616 self._add_error(location, ERROR_ID_VARIANT_COMPARISON,617 ("generate_comparison_operators is not supported with variant types"))618 def add_variant_no_default_error(self, location, field_name):619 # type: (common.SourceLocation, str) -> None620 """Add an error about a variant having a default value."""621 self._add_error(622 location, ERROR_ID_VARIANT_NO_DEFAULT,623 "Field '%s' is a variant, and default values for variants aren't implemented yet" %624 (field_name))625 def add_variant_duplicate_types_error(self, location, field_name, type_name):626 # type: (common.SourceLocation, str, str) -> None627 """Add an error about a variant having more than one alternative of the same BSON type."""628 self._add_error(629 location, ERROR_ID_VARIANT_DUPLICATE_TYPES,630 ("Variant field '%s' has multiple alternatives with BSON type '%s', this is prohibited"631 " to avoid ambiguity while parsing BSON.") % (field_name, type_name))632 def add_variant_structs_error(self, location, field_name):633 # type: (common.SourceLocation, str) -> None634 """Add an error about a variant having more than one struct alternative."""635 self._add_error(location, ERROR_ID_VARIANT_STRUCTS,636 ("Variant field '%s' has multiple struct alternatives, this is prohibited"637 " to avoid ambiguity while parsing BSON subdocuments.") % (field_name, ))638 def add_variant_enum_error(self, location, field_name, type_name):639 # type: (common.SourceLocation, str, str) -> None640 """Add an error for a variant that can be an enum."""641 self._add_error(642 location, ERROR_ID_NO_VARIANT_ENUM,643 "Field '%s' cannot be a variant with an enum alternative type '%s'" % (field_name,644 type_name))645 def is_scalar_non_negative_int_node(self, node, node_name):646 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode], str) -> bool647 """Return True if this YAML node is a Scalar and a valid non-negative int."""648 if not self._is_node_type(node, node_name, "scalar"):649 return False650 try:651 value = int(node.value)652 if value < 0:653 self._add_node_error(654 node, ERROR_ID_IS_NODE_VALID_NON_NEGATIVE_INT,655 "Illegal negative integer value for '%s', expected 0 or positive integer." %656 (node_name))657 return False658 except ValueError as value_error:659 self._add_node_error(660 node, ERROR_ID_IS_NODE_VALID_INT,661 "Illegal integer value for '%s', message '%s'." % (node_name, value_error))662 return False663 return True664 def get_non_negative_int(self, node):665 # type: (Union[yaml.nodes.MappingNode, yaml.nodes.ScalarNode, yaml.nodes.SequenceNode]) -> int666 """Convert a scalar to an int."""667 assert self.is_scalar_non_negative_int_node(node, "unknown")668 return int(node.value)669 def add_duplicate_comparison_order_field_error(self, location, struct_name, comparison_order):670 # type: (common.SourceLocation, str, int) -> None671 """Add an error about fields having duplicate comparison_orders."""672 # pylint: disable=invalid-name673 self._add_error(674 location, ERROR_ID_IS_DUPLICATE_COMPARISON_ORDER,675 ("Struct '%s' cannot have two fields with the same comparison_order value '%d'.") %676 (struct_name, comparison_order))677 def add_extranous_command_type(self, location, command_name):678 # type: (common.SourceLocation, str) -> None679 """Add an error about commands having type when not needed."""680 # pylint: disable=invalid-name681 self._add_error(682 location, ERROR_ID_IS_COMMAND_TYPE_EXTRANEOUS,683 ("Command '%s' cannot have a 'type' property unless namespace equals 'type'.") %684 (command_name))685 def add_value_not_numeric_error(self, location, attrname, value):686 # type: (common.SourceLocation, str, str) -> None687 """Add an error about non-numeric value where number expected."""688 # pylint: disable=invalid-name689 self._add_error(690 location, ERROR_ID_VALUE_NOT_NUMERIC,691 ("'%s' requires a numeric value, but %s can not be cast") % (attrname, value))692 def add_server_parameter_invalid_attr(self, location, attrname, conflicts):693 # type: (common.SourceLocation, str, str) -> None694 """Add an error about invalid fields in a server parameter definition."""695 # pylint: disable=invalid-name696 self._add_error(697 location, ERROR_ID_SERVER_PARAMETER_INVALID_ATTR,698 ("'%s' attribute not permitted with '%s' server parameter") % (attrname, conflicts))699 def add_server_parameter_required_attr(self, location, attrname, required, dependant=None):700 # type: (common.SourceLocation, str, str, str) -> None701 """Add an error about missing fields in a server parameter definition."""702 # pylint: disable=invalid-name703 qualifier = '' if dependant is None else (" when using '%s' attribute" % (dependant))704 self._add_error(location, ERROR_ID_SERVER_PARAMETER_REQUIRED_ATTR,705 ("'%s' attribute required%s with '%s' server parameter") %706 (attrname, qualifier, required))707 def add_server_parameter_invalid_method_override(self, location, method):708 # type: (common.SourceLocation, str) -> None709 """Add an error about invalid method override in SCP method override."""710 # pylint: disable=invalid-name711 self._add_error(location, ERROR_ID_SERVER_PARAMETER_INVALID_METHOD_OVERRIDE,712 ("No such method to override in server parameter class: '%s'") % (method))713 def add_bad_source_specifier(self, location, value):714 # type: (common.SourceLocation, str) -> None715 """Add an error about invalid source specifier."""716 # pylint: disable=invalid-name717 self._add_error(location, ERROR_ID_BAD_SOURCE_SPECIFIER,718 ("'%s' is not a valid source specifier") % (value))719 def add_bad_duplicate_behavior(self, location, value):720 # type: (common.SourceLocation, str) -> None721 """Add an error about invalid duplicate behavior specifier."""722 # pylint: disable=invalid-name723 self._add_error(location, ERROR_ID_BAD_DUPLICATE_BEHAVIOR_SPECIFIER,724 ("'%s' is not a valid duplicate behavior specifier") % (value))725 def add_bad_numeric_range(self, location, attrname, value):726 # type: (common.SourceLocation, str, str) -> None727 """Add an error about invalid range specifier."""728 # pylint: disable=invalid-name729 self._add_error(location, ERROR_ID_BAD_NUMERIC_RANGE,730 ("'%s' is not a valid numeric range for '%s'") % (value, attrname))731 def add_missing_shortname_for_positional_arg(self, location):732 # type: (common.SourceLocation) -> None733 """Add an error about required short_name for positional args."""734 # pylint: disable=invalid-name735 self._add_error(location, ERROR_ID_MISSING_SHORTNAME_FOR_POSITIONAL,736 "Missing 'short_name' for positional arg")737 def add_invalid_short_name(self, location, name):738 # type: (common.SourceLocation, str) -> None739 """Add an error about invalid short names."""740 # pylint: disable=invalid-name741 self._add_error(location, ERROR_ID_INVALID_SHORT_NAME,742 ("Invalid 'short_name' value '%s'") % (name))743 def add_invalid_single_name(self, location, name):744 # type: (common.SourceLocation, str) -> None745 """Add an error about invalid single names."""746 # pylint: disable=invalid-name747 self._add_error(location, ERROR_ID_INVALID_SINGLE_NAME,748 ("Invalid 'single_name' value '%s'") % (name))749 def add_missing_short_name_with_single_name(self, location, name):750 # type: (common.SourceLocation, str) -> None751 """Add an error about missing required short name when using single name."""752 # pylint: disable=invalid-name753 self._add_error(location, ERROR_ID_MISSING_SHORT_NAME_WITH_SINGLE_NAME,754 ("Missing 'short_name' required with 'single_name' value '%s'") % (name))755 def add_feature_flag_default_true_missing_version(self, location):756 # type: (common.SourceLocation) -> None757 """Add an error about a default flag with a default value of true but no version."""758 # pylint: disable=invalid-name759 self._add_error(location, ERROR_ID_FEATURE_FLAG_DEFAULT_TRUE_MISSING_VERSION,760 ("Missing 'version' required for feature flag that defaults to true"))761 def add_feature_flag_default_false_has_version(self, location):762 # type: (common.SourceLocation) -> None763 """Add an error about a default flag with a default value of false but has a version."""764 # pylint: disable=invalid-name765 self._add_error(766 location, ERROR_ID_FEATURE_FLAG_DEFAULT_FALSE_HAS_VERSION,767 ("The 'version' attribute is not allowed for feature flag that defaults to false"))768 def add_reply_type_invalid_type(self, location, command_name, reply_type_name):769 # type: (common.SourceLocation, str, str) -> None770 """Add an error about a command whose reply_type refers to an unknown type."""771 # pylint: disable=invalid-name772 self._add_error(773 location, ERROR_ID_INVALID_REPLY_TYPE,774 ("Command '%s' has invalid reply_type '%s'" % (command_name, reply_type_name)))775 def add_unstable_no_api_version(self, location, command_name):776 # type: (common.SourceLocation, str) -> None777 """Add an error about a command with 'unstable' but no 'api_version'."""778 # pylint: disable=invalid-name779 self._add_error(780 location, ERROR_ID_UNSTABLE_NO_API_VERSION,781 ("Command '%s' specifies 'unstable' but has no 'api_version'" % (command_name, )))782 def add_missing_reply_type(self, location, command_name):783 # type: (common.SourceLocation, str) -> None784 """Add an error about a command with 'api_version' but no 'reply_type'."""785 # pylint: disable=invalid-name786 self._add_error(787 location, ERROR_ID_MISSING_REPLY_TYPE,788 ("Command '%s' has an 'api_version' but no 'reply_type'" % (command_name, )))789 def add_bad_field_always_serialize_not_optional(self, location, field_name):790 # type: (common.SourceLocation, str) -> None791 """Add an error about a field with 'always_serialize' but 'optional' isn't set to true."""792 # pylint: disable=invalid-name793 self._add_error(794 location, ERROR_ID_ILLEGAL_FIELD_ALWAYS_SERIALIZE_NOT_OPTIONAL,795 ("Field '%s' specifies 'always_serialize' but 'optional' isn't true.") % (field_name))796 def add_duplicate_command_name_and_alias(self, node):797 # type: (yaml.nodes.Node) -> None798 """Add an error about a command name and command alias having the same name."""799 # pylint: disable=invalid-name800 self._add_node_error(node, ERROR_ID_COMMAND_DUPLICATES_NAME_AND_ALIAS,801 "Duplicate command_name and command_alias found.")802 def add_unknown_enum_value(self, location, enum_name, enum_value):803 # type: (common.SourceLocation, str, str) -> None804 """Add an error about an unknown enum value."""805 # pylint: disable=invalid-name806 self._add_error(location, ERROR_ID_UNKOWN_ENUM_VALUE,807 "Cannot find enum value '%s' in enum '%s'." % (enum_value, enum_name))808 def add_either_check_or_privilege(self, location):809 # type: (common.SourceLocation) -> None810 """Add an error about specifing both a check and a privilege or neither."""811 # pylint: disable=invalid-name812 self._add_error(813 location, ERROR_ID_EITHER_CHECK_OR_PRIVILEGE,814 "Must specify either a 'check' and a 'privilege' in an access_check, not both.")815 def add_duplicate_action_types(self, location, name):816 # type: (common.SourceLocation, str) -> None817 """Add an error about specifying an action type twice in the same list."""818 # pylint: disable=invalid-name819 self._add_error(location, ERROR_ID_DUPLICATE_ACTION_TYPE,820 "Cannot specify an action_type '%s' more then once" % (name))821 def add_duplicate_access_check(self, location, name):822 # type: (common.SourceLocation, str) -> None823 """Add an error about specifying an access check twice in the same list."""824 # pylint: disable=invalid-name825 self._add_error(location, ERROR_ID_DUPLICATE_ACCESS_CHECK,826 "Cannot specify an access_check '%s' more then once" % (name))827 def add_duplicate_privilege(self, location, resource_pattern, action_type):828 # type: (common.SourceLocation, str, str) -> None829 """Add an error about specifying a privilege twice in the same list."""830 # pylint: disable=invalid-name831 self._add_error(832 location, ERROR_ID_DUPLICATE_PRIVILEGE,833 "Cannot specify the pair of resource_pattern '%s' and action_type '%s' more then once" %834 (resource_pattern, action_type))835 def add_empty_access_check(self, location):836 # type: (common.SourceLocation) -> None837 """Add an error about specifying one of ignore, none, simple or complex in an access check."""838 # pylint: disable=invalid-name839 self._add_error(840 location, ERROR_ID_EMPTY_ACCESS_CHECK,841 "Must one and only one of either a 'ignore', 'none', 'simple', or 'complex' in an access_check."842 )843 def add_missing_access_check(self, location, name):844 # type: (common.SourceLocation, str) -> None845 """Add an error about a missing access_check when api_version != ""."""846 # pylint: disable=invalid-name847 self._add_error(location, ERROR_ID_MISSING_ACCESS_CHECK,848 'Command "%s" has api_version != "" but is missing access_check.' % (name))849def _assert_unique_error_messages():850 # type: () -> None851 """Assert that error codes are unique."""852 error_ids = []853 for module_member in inspect.getmembers(sys.modules[__name__]):854 if module_member[0].startswith("ERROR_ID"):855 error_ids.append(module_member[1])856 error_ids_set = set(error_ids)857 if len(error_ids) != len(error_ids_set):858 raise IDLError("IDL error codes prefixed with ERROR_ID are not unique.")859# On file import, check the error messages are unique...

Full Screen

Full Screen

forms.py

Source:forms.py Github

copy

Full Screen

...30 self.section_ids = []31 self.page_ids = []32 self._errors = None33 self.full_clean()34 def _add_error(self, error_type, error):35 if self._errors['result'] is None:36 self._errors['result'] = error_type37 if (self._errors['result'] == 'SCHEMA ERROR' and38 error_type == "FORMAT ERROR"):39 self._errors['errors'] = []40 elif (self._errors['result'] == 'FORMAT ERROR' and41 error_type == "SCHEMA ERROR"):42 return43 if isinstance(error, list):44 self._errors['errors'].extend(error)45 elif isinstance(error, dict):46 self._errors['errors'].append(error)47 def _validate_schema_format(self):48 """49 Checks the outer structure of the schema and makes sure all the50 expected keys are present51 """52 if not isinstance(self.schema, dict):53 raise FormatError(54 "Expected schema to be a dictionary, got '{0}'".format(55 type(self.schema).__name__))56 schema_keys = list(self.MINIMUM_SCHEMA_KEYS)57 errors = []58 for key in self.schema:59 try:60 schema_keys.remove(key)61 except ValueError:62 errors.append(63 "Key '{0}' either doesn't belong in the schema or is "64 "duplicated".format(key))65 for key in schema_keys:66 errors.append(67 "Required key '{0}' is missing from the schema".format(key))68 if 'version' in self.schema:69 try:70 int(self.schema['version'])71 except ValueError:72 errors.append("Invalid version: '{0}' is not a number.".format(73 self.schema['version']))74 if 'fields' in self.schema:75 if not isinstance(self.schema['fields'], list):76 errors.append("'fields' property must be a list.")77 if 'sections' in self.schema:78 if not isinstance(self.schema['sections'], list):79 errors.append("'sections' property must be a list.")80 if 'pages' in self.schema:81 if not isinstance(self.schema['pages'], list):82 errors.append("'pages' property must be a list.")83 if errors:84 raise FormatError(errors)85 def _validate_fields(self):86 """ Checks that the fields are valid in the schema """87 fields = self.schema['fields']88 self.fields = {}89 for field in fields:90 errors = False91 error = {92 'type': 'FIELD',93 'id': '',94 'message': ''95 }96 try:97 error['id'] = field['id']98 except KeyError:99 raise FormatError("A field is missing the 'id' property.")100 if 'type' in field:101 try:102 field_class = FieldFactory.get_class(field['type'])103 except KeyError:104 errors = True105 error['message'] = "Invalid field type: '{0}'".format(106 field['type'])107 self._add_error("SCHEMA ERROR", copy(error))108 continue109 except Exception as e:110 error['message'] = \111 "Invalid field: '{0}'".format(e.__str__())112 self._add_error("SCHEMA ERROR", copy(error))113 continue114 else:115 try:116 Field.validate_schema(field)117 except FieldError as e:118 for field_error in e.error_list:119 error['message'] = repr(field_error)120 self._add_error("SCHEMA ERROR", copy(error))121 continue122 try:123 field_obj = field_class(field)124 except FieldError as e:125 errors = True126 for field_error in e.error_list:127 error['message'] = repr(field_error)128 self._add_error("SCHEMA ERROR", copy(error))129 if not errors:130 if field['id'] not in self.field_ids:131 self.field_ids.append(field['id'])132 self.fields.update({field['id'].__str__(): field_obj})133 else:134 error['message'] = (135 "Field '{0}' is defined more than once.".format(136 field['id']))137 self._add_error("SCHEMA ERROR", copy(error))138 def _validate_sections(self):139 """140 Checks that the sections are valid in the schema.141 Also checks that fields are used in only one section.142 """143 sections = self.schema['sections']144 self.sections = {}145 # Make local copy of the available fields146 field_ids = list(self.field_ids)147 for section in sections:148 field_list = {}149 section_keys = list(self.MINIMUM_SECTION_KEYS)150 optional_section_keys = list(self.OPTIONAL_SECTION_KEYS)151 error = {152 'id': '',153 'type': 'SECTION',154 'message': ''155 }156 try:157 error['id'] = section['id']158 except KeyError:159 raise FormatError("A section is missing the 'id' property.")160 if section['id'] not in self.section_ids:161 self.section_ids.append(section['id'])162 else:163 error['message'] = "Section '{0}' is defined more than once." \164 .format(section['id'])165 self._add_error('SCHEMA ERROR', copy(error))166 for key in section:167 if key in section_keys:168 section_keys.remove(key)169 else:170 try:171 optional_section_keys.remove(key)172 except ValueError:173 error['message'] = "Key '{0}' either doesn't belong" \174 " in the section schema or is duplicated" \175 .format(key)176 self._add_error('SCHEMA ERROR', copy(error))177 for key in section_keys:178 error['message'] = \179 "Required key '{0}' is missing from the section".format(180 key)181 self._add_error('SCHEMA ERROR', copy(error))182 try:183 section_fields = section['fields']184 for field in section_fields:185 try:186 field_ids.remove(field)187 except ValueError:188 error['message'] = \189 ("Field '{0}' either isn't valid or was already "190 "included in a previous section".format(field))191 self._add_error('SCHEMA ERROR', copy(error))192 continue193 field_list.update(194 {field.__str__(): self.fields[field.__str__()]})195 except KeyError: # Only to avoid exception.196 # We continue because it was already checked.197 continue198 new_section = Section(section)199 new_section.fields = field_list200 self.sections.update({section['id'].__str__(): new_section})201 def _validate_pages(self):202 """203 Checks that the pages are valid in the schema.204 Also checks that sections are used in only one page.205 """206 pages = self.schema['pages']207 section_ids = list(self.section_ids)208 for page in pages:209 section_list = {}210 page_keys = list(self.MINIMUM_PAGE_KEYS)211 optional_page_keys = list(self.OPTIONAL_PAGE_KEYS)212 error = {213 'id': '',214 'type': 'PAGE',215 'message': ''216 }217 try:218 error['id'] = page['id']219 except KeyError:220 raise FormatError("A page is missing the 'id' property.")221 if page['id'] not in self.page_ids:222 self.page_ids.append(page['id'])223 else:224 error['message'] = "Page '{0}' is defined more than once." \225 .format(page['id'])226 self._add_error('SCHEMA ERROR', copy(error))227 for key in page:228 if key in page_keys:229 page_keys.remove(key)230 else:231 try:232 optional_page_keys.remove(key)233 except ValueError:234 error['message'] = (235 "Key '{0}' either doesn't belong in the page "236 "schema or is duplicated".format(key))237 self._add_error('SCHEMA ERROR', copy(error))238 for key in page_keys:239 error['message'] = \240 "Required key '{0}' is missing from the page".format(241 key)242 self._add_error('SCHEMA ERROR', copy(error))243 try:244 page_sections = page['sections']245 for section in page_sections:246 try:247 section_ids.remove(section)248 except ValueError:249 error['message'] = (250 "Section '{0}' either isn't valid or was already "251 "included in a previous page".format(section))252 self._add_error('SCHEMA ERROR', copy(error))253 continue254 section_list.update(255 {section.__str__(): self.sections[section.__str__()]})256 except KeyError:257 pass258 new_page = Page(page)259 new_page.sections = section_list260 self.pages.update({page['id'].__str__(): new_page})261 def _check_item_conditionals(self, item_type):262 error_type = {263 'fields': 'FIELD',264 'sections': 'SECTION',265 'pages': 'PAGE'266 }267 for item in self.schema[item_type]:268 if 'conditionals' in item:269 conditionals = item['conditionals']270 for condition in conditionals:271 error = {272 'id': item['id'],273 'type': error_type[item_type],274 'message': ''275 }276 try:277 condition_list, compound = Condition.check_condition(278 condition)279 except ConditionError as e:280 for condition_error in e.error_list:281 error['message'] = repr(condition_error)282 self._add_error("SCHEMA ERROR", copy(error))283 continue284 for individual_condition in condition_list:285 try:286 condition_class = ConditionFactory.get_class(287 individual_condition['type'])288 except KeyError:289 error['message'] = \290 "Invalid condition type: '{0}'".format(291 individual_condition['type'])292 self._add_error("SCHEMA ERROR", copy(error))293 continue294 except Exception as e:295 error['message'] = \296 "Invalid condition: '{0}'".format(e.__str__())297 self._add_error("SCHEMA ERROR", copy(error))298 continue299 try:300 condition_class.validate_schema(301 individual_condition, compound)302 condition_field = self.fields[303 individual_condition['field'].__str__()]304 condition_class.field_allows_condition(305 condition_field)306 except ConditionError as e:307 for condition_error in e.error_list:308 error['message'] = repr(condition_error)309 self._add_error("SCHEMA ERROR", copy(error))310 except KeyError:311 error['message'] = (312 "Condition depends on invalid or undefined "313 "field '{0}'".format(314 individual_condition['field']))315 self._add_error("SCHEMA ERROR", copy(error))316 def _check_item_mappings(self, item_type):317 if item_type == 'fields':318 error_type = 'FIELD'319 ids = 'field_ids'320 maps_to = 'section'321 else:322 error_type = 'SECTION'323 ids = 'section_ids'324 maps_to = 'page'325 error = {326 'id': '',327 'type': error_type,328 'message': ''329 }330 try:331 form_item = getattr(self, maps_to + 's')332 except AttributeError as ex:333 raise Exception('Unexpected property access in Form: {0}'.format(334 ex.__str__()))335 used_ids = set()336 for item in form_item.values():337 used_ids = used_ids.union(set(getattr(item, item_type).keys()))338 all_items = set(map(str, getattr(self, ids)))339 diff = set(all_items).difference(used_ids)340 if diff:341 for d in diff:342 error['id'] = d343 error['message'] = (344 "Item has not been mapped to any {0}".format(maps_to))345 self._add_error("SCHEMA ERROR", copy(error))346 def full_clean(self):347 """348 Performs a full clean of all the Form data and populates self._errors349 and self.cleaned_data350 """351 self._errors = {352 'result': None,353 'errors': []354 }355 try:356 self._validate_schema_format()357 self._validate_fields()358 self._validate_sections()359 self._validate_pages()360 self._check_item_conditionals('fields')361 self._check_item_conditionals('sections')362 self._check_item_conditionals('pages')363 self._check_item_mappings('fields'),364 self._check_item_mappings('sections'),365 except FormatError as e:366 self._add_error('FORMAT ERROR', e.error_list)367 @property368 def errors(self):369 """370 Inspired by Django's error management. If the Form has errors we return371 them.372 """373 return self._errors374 def check_answers(self, answers):375 if not isinstance(answers, dict):376 raise FormatError(377 "Expected answers to be a 'dictionary', got {0} instead"378 .format(type(answers).__name__))379 380 answer_keys = answers.keys()...

Full Screen

Full Screen

dresser.py

Source:dresser.py Github

copy

Full Screen

...232 # process the line233 f = self.grammar[key]234 f(words)235 else:236 self._add_error(l, 'Unable to parse this line')237238 return True239240 def build_grammar(self):241 self.grammar = {}242 grammar = self.grammar243244 grammar['SMBPath'] = self.smb_path245 grammar['SMBModel'] = self.smb_model246247 grammar['Class'] = self.klass 248 grammar['BranchPattern'] = self.branch_pattern 249 grammar['LeafClass'] = self.leaf_klass 250 grammar['FlowerClass'] = self.flower_klass 251 grammar['FruitClass'] = self.fruit_klass 252253254 grammar['LengthUnit'] = self.length_unit255 grammar['DiameterUnit'] = self.diameter_unit256 grammar['AlphaUnit'] = self.alpha_unit257 grammar['AzimuthUnit'] = self.azimuth_unit258259 grammar['DefaultEdge'] = self.default_edge260261 grammar['DefaultAlpha'] = self.default_alpha262 grammar['DefaultTeta'] = self.default_teta263 grammar['DefaultPhi'] = self.default_phi264 grammar['DefaultPsi'] = self.default_psi 265266 grammar['DefaultTrunkCategory'] =self.default_trunk_category267 grammar['DefaultCategory'] = self.default_category268269 grammar['Alpha'] =self.alpha270 grammar['Phyllotaxy'] = self.phyllotaxy271272 grammar['MinLength'] = self.min_length273 grammar['MinTopDiameter'] = self.min_top_diameter274 grammar['MinBottomDiameter'] = self.min_bottom_diameter275276277 grammar['LeafLength'] = self.leaf_length278 grammar['LeafTopDiameter'] = self.leaf_topdia279 grammar['LeafBottomDiameter'] = self.leaf_botdia280 grammar['LeafAlpha'] = self.leaf_alpha281 grammar['LeafBeta'] = self.leaf_beta282283 grammar['FruitLength'] = self.fruit_length284 grammar['FruitTopDiameter'] = self.fruit_topdia285 grammar['FruitBottomDiameter'] = self.fruit_botdia286 grammar['FruitAlpha'] = self.fruit_alpha287 grammar['FruitBeta'] = self.fruit_beta288289 grammar['FlowerLength'] = self.flower_length290 grammar['FlowerTopDiameter'] = self.flower_topdia291 grammar['FlowerBottomDiameter'] = self.flower_botdia292 grammar['FlowerAlpha'] = self.flower_alpha293 grammar['FlowerBeta'] = self.flower_beta294295 grammar['DefaultTrunkCategory'] = self.def_trunk_cat296 grammar['DefaultDistance'] = self.def_dist297 grammar['NbPlantsPerLine'] = self.nbplants_line298299 grammar['MediumThreshold'] = self.med_thres300 grammar['MinThreshold'] = self.min_thres301 grammar['MaxThreshold'] = self.max_thres302303 def _add_error(self, l, note=''):304 msg = 'ERROR (%d): %s'%(self.line, ' '.join(l))305 if note:306 msg = '\n'.join([msg, ' --> %s'%note])307 self.errors.append(msg)308309 def smb_path(self, l):310 "SMBPath = path"311 p = l[2]312 if os.path.exists(p):313 self.smbpath = p314 else:315 self._add_error(l, 'Invalid path')316317 def smb_model(self, l):318 "SMBModel node = nentn105"319 if not self.smbpath:320 return321 name = l[1]322 file = l[3]+'.smb'323 absfile = os.path.join(self.smbpath, file)324 if os.path.exists(os.path.join(self.smbpath, file)):325 geom = AmapSymbol(absfile)326 if geom.isValid():327 self.dresser.symbols[name] = geom328 else:329 self._add_error(l, 'Impossible to locate symbol file')330331 332 def klass (self, l):333 "Class B = node"334 class_name = l[1]335 smb_name = l[3]336 d = self.dresser337 if smb_name in d.symbols:338 d.classes[class_name] = smb_name339 else:340 self._add_error(l, '%s is not defined'%smb_name)341342 def branch_pattern (self, l):343 "BranchPattern apple_forms = file.crv"344 self._add_error(l, 'BranchPattern is not yet implemented')345346 def leaf_klass (self, l):347 "LeafClass = Z"348 name = l[2]349 d = self.dresser350 if name in d.symbols:351 d.leaf_class = name352 else:353 self._add_error(l, '%s is not defined'%name)354 355 def flower_klass(self, l):356 "FlowerClass = Z"357 name = l[2]358 d = self.dresser359 if name in d.symbols:360 d.flower_class = name361 else:362 self._add_error(l, '%s is not defined'%name)363364 def fruit_klass (self, l):365 "FruitClass = Z"366 name = l[2]367 d = self.dresser368 if name in d.symbols:369 d.fruit_class = name370 else:371 self._add_error(l, '%s is not defined'%name)372373 def length_unit(self, l):374 "LengthUnit = 1"375 unit = l[2]376 try:377 self.dresser.length_unit = float(unit)378 except:379 self._add_error(l, 'Bad unit format')380 381382 def diameter_unit(self, l):383 "DiameterUnit = 1"384 unit = l[2]385 try:386 self.dresser.diameter_unit = float(unit)387 except:388 self._add_error(l, 'Bad unit format')389390 def alpha_unit(self, l):391 "AlphaUnit = 1"392 unit = l[2]393 try:394 self.dresser.alpha_unit = float(unit)395 except:396 self._add_error(l, 'Bad unit format')397398 def azimuth_unit(self, l):399 "AzimuthUnit = 1"400 unit = l[2]401 try:402 self.dresser.azimuth_unit = float(unit)403 except:404 self._add_error(l, 'Bad unit format')405406407 def default_edge(self, l):408 "DefaultEdge = PLUS | LESS"409 edge_type = l[2]410 if edge_type in ['PLUS', 'LESS']:411 self.default_edge = edge_type412 else:413 self._add_error(l, 'Bad edge format')414415 def default_alpha(self, l):416 angle = l[2]417 try:418 self.dresser.default_alpha = float(angle)419 except:420 self._add_error(l, 'Bad angle format')421422 def default_teta(self, l):423 angle = l[2]424 try:425 self.dresser.default_teta= float(angle)426 except:427 self._add_error(l, 'Bad angle format')428429 def default_phi(self, l):430 angle = l[2]431 try:432 self.dresser.default_phi= float(angle)433 except:434 self._add_error(l, 'Bad angle format')435436 def default_psi (self, l):437 angle = l[2]438 try:439 self.dresser.default_psi= float(angle)440 except:441 self._add_error(l, 'Bad angle format')442443444 def default_trunk_category(self, l):445 pass446447 def default_category(self, l):448 pass449450451 def alpha(self, l):452 "Alpha = Absolute | Relative" 453 _alpha = l[2]454 if _alpha in ['Absolute', 'Relative']:455 self.dresser.alpha = _alpha456 else:457 self._add_error(l, 'Should be Absolute or Relative ')458 459460 def phyllotaxy(self, l):461 angle = l[2]462 try:463 self.dresser.phyllotaxy= float(angle)464 except:465 self._add_error(l)466 467468 def min_length(self, l):469 "MinLenght A = 10"470 name = l[1]471 value = l[3]472 self.dresser.min_length[name] = float(value)473474 def min_top_diameter(self, l):475 "MinTopDiameter A = 10"476 name = l[1]477 value = l[3]478 self.dresser.min_topdia[name] = float(value)479480 def min_bottom_diameter(self, l):481 "MinBottomDiameter A = 10"482 name = l[1]483 value = l[3]484 self.dresser.min_botdia[name] = float(value)485486 def leaf_length(self, l):487 "LeafLength = 100"488 value = l[2]489 try:490 self.dresser.leaf_length= float(value)491 except:492 self._add_error(l, 'Bad format')493494 def leaf_topdia(self, l):495 value = l[2]496 try:497 self.dresser.leaf_topdia= float(value)498 except:499 self._add_error(l, 'Bad format')500501 def leaf_botdia(self, l):502 value = l[2]503 try:504 self.dresser.leaf_botdia= float(value)505 except:506 self._add_error(l, 'Bad format')507508 def leaf_alpha(self, l):509 value = l[2]510 try:511 self.dresser.leaf_alpha= float(value)512 except:513 self._add_error(l, 'Bad format')514515 def leaf_beta(self, l):516 value = l[2]517 try:518 self.dresser.leaf_beta= float(value)519 except:520 self._add_error(l, 'Bad format')521522 def fruit_length(self, l):523 "LeafLength = 100"524 value = l[2]525 try:526 self.dresser.fruit_length= float(value)527 except:528 self._add_error(l, 'Bad format')529530 def fruit_topdia(self, l):531 value = l[2]532 try:533 self.dresser.fruit_topdia= float(value)534 except:535 self._add_error(l, 'Bad format')536537 def fruit_botdia(self, l):538 value = l[2]539 try:540 self.dresser.fruit_botdia= float(value)541 except:542 self._add_error(l, 'Bad format')543544 def fruit_alpha(self, l):545 value = l[2]546 try:547 self.dresser.fruit_alpha= float(value)548 except:549 self._add_error(l, 'Bad format')550551 def fruit_beta(self, l):552 value = l[2]553 try:554 self.dresser.fruit_beta= float(value)555 except:556 self._add_error(l, 'Bad format')557558 def flower_length(self, l):559 "LeafLength = 100"560 value = l[2]561 try:562 self.dresser.flower_length= float(value)563 except:564 self._add_error(l, 'Bad format')565566 def flower_topdia(self, l):567 value = l[2]568 try:569 self.dresser.flower_topdia= float(value)570 except:571 self._add_error(l, 'Bad format')572573 def flower_botdia(self, l):574 value = l[2]575 try:576 self.dresser.flower_botdia= float(value)577 except:578 self._add_error(l, 'Bad format')579580 def flower_alpha(self, l):581 value = l[2]582 try:583 self.dresser.flower_alpha= float(value)584 except:585 self._add_error(l, 'Bad format')586587 def flower_beta(self, l):588 value = l[2]589 try:590 self.dresser.flower_beta= float(value)591 except:592 self._add_error(l, 'Bad format')593594 def def_trunk_cat(self, l):595 pass596597 def def_dist(self, l):598 pass599600 def nbplants_line(self, l):601 pass602603604 def med_thres(self, l):605 pass606 ...

Full Screen

Full Screen

validators.py

Source:validators.py Github

copy

Full Screen

...9 self._clear_data()10 self._validate_fields()11 def _validate_fields(self):12 raise NotImplementedError('Has to be implemented')13 def _add_error(self, field_name, error_message):14 self._fields[field_name] = error_message15 @property16 def has_errors(self):17 if self._fields:18 return True19 return False20 @property21 def errors(self):22 return self._fields23 def _clear_data(self):24 for key in self._data:25 self._data[key] = str(self._data[key]).replace(' ', '')26class OrderFormValidator(Validator):27 def _validate_fields(self):28 self._validate_full_name()29 self._validate_phone()30 self._validate_email()31 return None32 def _validate_full_name(self):33 FIELD_NAME = 'full_name'34 name = self._data[FIELD_NAME]35 if not name:36 self._add_error(FIELD_NAME, 'ФИО не может быть пустым')37 def _validate_phone(self):38 FIELD_NAME = 'phone'39 phone = self._data[FIELD_NAME]40 if not phone:41 self._add_error(FIELD_NAME, 'Номер телефона не может быть пустым')42 LENGTH = 1143 FIRST_NUMS = (7, 8)44 clear_phone = re.sub('[^\d]', '', phone)45 if len(clear_phone) != LENGTH:46 self._add_error(FIELD_NAME, 'Неверная длина номера телефона')47 return48 elif int(clear_phone[0]) not in FIRST_NUMS:49 self._add_error(FIELD_NAME, 'Телефон не принадлежит российскому провайдеру')50 return51 return True52 def _validate_email(self):53 FIELD_NAME = 'email'54 email = self._data[FIELD_NAME]55 if not email:56 self._add_error(FIELD_NAME, 'Адрес эл. почты не может быть пустым')57 EMAIL_REGEX = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'58 if not re.search(EMAIL_REGEX, email):59 self._add_error(FIELD_NAME, 'Неверный адрес эл. почты')60class UserRegistrationValidator(Validator):61 62 def _validate_fields(self):63 self._validate_username()64 self._validate_email()65 self._validate_passwords()66 def _validate_username(self):67 FIELD_NAME = 'username'68 username = self._data.get(FIELD_NAME, None)69 if not username:70 self._add_error(FIELD_NAME, 'Имя пользователя не может быть пустым')71 return72 users = User.objects.filter(username=username)73 if users.exists():74 self._add_error(FIELD_NAME, 'Пользователь с таким именем уже существует')75 return76 if len(username) < 4:77 self._add_error(FIELD_NAME, 'Имя пользователя не может быть меньше 5 символов')78 79 def _validate_email(self):80 FIELD_NAME = 'email'81 email = self._data[FIELD_NAME]82 if not email:83 self._add_error(FIELD_NAME, 'Адрес эл. почты не может быть пустым')84 EMAIL_REGEX = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'85 if not re.search(EMAIL_REGEX, email):86 self._add_error(FIELD_NAME, 'Неверный адрес эл. почты')87 def _validate_passwords(self):88 FIELD_NAME = 'password'89 FIELD_NAME_REPEAT = 'password_confirmation'90 pswd = self._data.get(FIELD_NAME, None)91 pswd_confirm = self._data.get(FIELD_NAME_REPEAT, None)92 if not pswd:93 self._add_error(FIELD_NAME, 'Пароль не может быть пустым')94 return95 if not pswd_confirm:96 self._add_error(FIELD_NAME_REPEAT, 'Повторите пароль')97 return98 if pswd != pswd_confirm:99 self._add_error(FIELD_NAME, 'Пароли не совпадают')100 self._add_error(FIELD_NAME_REPEAT, 'Пароли не совпадают')101class UserLoginValidator(Validator):102 def _validate_fields(self):103 self._vadlidate_username()104 self._validate_password()105 def _vadlidate_username(self):106 FIELD_NAME = 'username'107 username = self._data.get(FIELD_NAME, None)108 if not username:109 self._add_error(FIELD_NAME, 'Имя пользователя не может быть пустым')110 return111 user_list = User.objects.filter(username=username)112 if not user_list.exists():113 self._add_error(FIELD_NAME, 'Пользователя с указанным логином не существует')114 if user_list.count() > 1:115 self._add_error(FIELD_NAME, 'Несколько пользователей с указанным логином, свяжитесь с администрацией')116 def _validate_password(self):117 FIELD_NAME = 'password'118 pswd = self._data.get(FIELD_NAME, None)119 if not pswd:120 self._add_error(FIELD_NAME, 'Пароль не может быть пустым')121 return122 username = self._data.get('username', '')123 user = authenticate(username=username, password=pswd)124 if not user:125 self._add_error(FIELD_NAME, 'Проверьте введенные данные')126class UserChangeDataValidator(Validator):127 128 def __init__(self, post_data, user):129 self._user = user130 super().__init__(post_data)131 def _validate_fields(self):132 self._validate_username()133 self._validate_email()134 def _validate_username(self):135 FIELD_NAME = 'username'136 username = self._data.get(FIELD_NAME, None)137 if not username:138 self._add_error(FIELD_NAME, 'Имя пользователя не может быть пустым')139 return140 user_list = User.objects.filter(username=username).exclude(id=self._user.id)141 if user_list.exists():142 self._add_error(FIELD_NAME, 'Имя пользователя уже занято')143 def _validate_email(self):144 FIELD_NAME = 'email'145 email = self._data.get(FIELD_NAME, None)146 if not email:147 self._add_error(FIELD_NAME, 'Эл. почта не может быть пустой')148 return149 user_list = User.objects.filter(email=email).exclude(id=self._user.id)150 if user_list.exists():151 self._add_error(FIELD_NAME, 'Адрес эл. почты уже занят')152class UserChangePasswordValidator(Validator):153 def __init__(self, post_data, user):154 self._user = user155 super().__init__(post_data)156 def _validate_fields(self):157 self._validate_old_password()158 self._validate_passwords()159 def _validate_old_password(self):160 FIELD_NAME = 'old_password'161 old_pswd = self._data.get(FIELD_NAME, '')162 old_pswd = old_pswd.replace(' ', '')163 if not self._user.check_password(old_pswd):164 self._add_error(FIELD_NAME, 'Неверный старый пароль')165 def _validate_passwords(self):166 FIELD_NAME = 'password'167 FIELD_NAME_REPEAT = 'password_confirmation'168 pswd = self._data.get(FIELD_NAME, None)169 pswd_confirm = self._data.get(FIELD_NAME_REPEAT, None)170 if not pswd:171 self._add_error(FIELD_NAME, 'Пароль не может быть пустым')172 return173 if not pswd_confirm:174 self._add_error(FIELD_NAME_REPEAT, 'Повторите пароль')175 return176 if pswd != pswd_confirm:177 self._add_error(FIELD_NAME, 'Пароли не совпадают')...

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 Slash 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