Beispiel #1
0
    def MapTo(self, subject, key, value):
        """Map key-value pair to an objects attribute.

    Args:
      subject: _ObjectMapper of object that will receive new attribute.
      key: Key of attribute.
      value: Value of new attribute.

    Raises:
      UnexpectedAttribute when the key is not a validated attribute of
      the subject value class.
    """
        assert isinstance(subject.value, validation.ValidatedBase)

        try:
            attribute = subject.value.GetValidator(key)
        except validation.ValidationError, err:
            raise yaml_errors.UnexpectedAttribute(err)
Beispiel #2
0
  def MapTo(self, subject, key, value):
    """Map key-value pair to an objects attribute.

    Args:
      subject: _ObjectMapper of object that will receive new attribute.
      key: Key of attribute.
      value: Value of new attribute.

    Raises:
      UnexpectedAttribute when the key is not a validated attribute of
      the subject value class.
    """
    assert isinstance(subject.value, validation.ValidatedBase)

    try:
      attribute = subject.value.GetValidator(key)
    except validation.ValidationError as err:
      raise yaml_errors.UnexpectedAttribute(err)

    if isinstance(value, _ObjectMapper):
      # Now know what class the new instance should be.
      # Time to construct it from the attributes expected type.
      value.set_value(attribute.expected_type())
      value = value.value
    elif isinstance(value, _ObjectSequencer):
      # Now know what class new instances within the sequence should be.
      value.set_constructor(self._GetRepeated(attribute))
      value = value.value

    subject.see(key)
    try:
      subject.value.Set(key, value)
    except validation.ValidationError as e:
      # Some errors may have problematic encoding or other issues.
      # Re-raising an error in this block would be very hard to debug
      # for the time being so instead, on error, the value is merely
      # obscured.
      try:
        error_str = str(e)
      except Exception:
        error_str = '<unknown>'

      try:
        value_str = str(value)
      except Exception:
        value_str = '<unknown>'

      # Update error message with a better message.
      e.message = ("Unable to assign value '%s' to attribute '%s':\n%s" %
                   (value_str, key, error_str))
      raise e
    except Exception as e:
      try:
        error_str = str(e)
      except Exception:
        error_str = '<unknown>'

      try:
        value_str = str(value)
      except Exception:
        value_str = '<unknown>'

      # Raise a more generic exception message.
      message = ("Unable to assign value '%s' to attribute '%s':\n%s" %
                 (value_str, key, error_str))
      raise validation.ValidationError(message, e)