Python google.protobuf.message.Message() Examples

The following are 30 code examples of google.protobuf.message.Message(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module google.protobuf.message , or try the search function .
Example #1
Source File: reflection_test.py    From botchallenge with MIT License 6 votes vote down vote up
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(message.Message, metaclass=reflection.GeneratedProtocolMessageType):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2]) 
Example #2
Source File: reflection.py    From botchallenge with MIT License 6 votes vote down vote up
def __init__(cls, name, bases, dictionary):
    """Here we perform the majority of our work on the class.
    We add enum getters, an __init__ method, implementations
    of all Message methods, and properties for all fields
    in the protocol type.

    Args:
      name: Name of the class (ignored, but required by the
        metaclass protocol).
      bases: Base classes of the class we're constructing.
        (Should be message.Message).  We ignore this field, but
        it's required by the metaclass protocol
      dictionary: The class dictionary of the class we're
        constructing.  dictionary[_DESCRIPTOR_KEY] must contain
        a Descriptor object describing this protocol message
        type.
    """
    descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]
    _InitMessage(descriptor, cls)
    superclass = super(GeneratedProtocolMessageType, cls)
    superclass.__init__(name, bases, dictionary) 
Example #3
Source File: recipe_api.py    From recipes-py with Apache License 2.0 6 votes vote down vote up
def new_context(self, **section_pb_values):
    """Creates a new LUCI_CONTEXT file with the provided section values, all
    unmentioned sections in the current context will be copied over. The
    environment variable will NOT not be switched to the newly created context.

    Args:
      * section_pb_values (Dict[str, message.Message]) - A mapping of
        section_key to the new message value for that section.

    Returns the path (str) to the newly created LUCI_CONTEXT file. Returns None
    if section_pb_values is empty (i.e. No change to current context).
    """
    section_values = {
      key: jsonpb.MessageToDict(pb_val)
      for key, pb_val in iteritems(section_pb_values)
    }
    with luci_context.stage(_leak=True, **section_values) as file_path:
      return file_path 
Example #4
Source File: test_api.py    From recipes-py with Apache License 2.0 6 votes vote down vote up
def environ(self, *proto_msgs, **kwargs):
    """Sets environment data for this test case."""
    ret = self.test(None)

    to_apply = []

    for msg in proto_msgs:
      if not isinstance(msg, PBMessage):
        raise ValueError(
            'Positional arguments for api.properties must be protobuf messages.'
            ' Got: %r (type %r)' % (msg, type(msg)))
      to_apply.append(jsonpb.MessageToDict(
          msg, preserving_proto_field_name=True))

    to_apply.append(kwargs)

    for dictionary in to_apply:
      for key, value in dictionary.iteritems():
        if not isinstance(value, (int, float, basestring)):
          raise ValueError(
              'Environment values must be int, float or string. '
              'Got: %r=%r (type %r)' % (key, value, type(value)))
        ret.environ[key] = str(value)

    return ret 
Example #5
Source File: reflection_test.py    From lambda-packs with MIT License 6 votes vote down vote up
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    # TODO(xiaofeng): This test fails with cpp implemetnation in the call
    # of six.with_metaclass(). The other two callsites of with_metaclass
    # in this file are both excluded from cpp test, so it might be expected
    # to fail. Need someone more familiar with the python code to take a
    # look at this.
    if api_implementation.Type() != 'python':
      return
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2]) 
Example #6
Source File: protobuf_to_dict.py    From perceptron-benchmark with Apache License 2.0 6 votes vote down vote up
def dict_to_protobuf(pb_klass_or_instance, values, type_callable_map=REVERSE_TYPE_CALLABLE_MAP, \
    strict=True):
    """Populates a protobuf model from a dictionary.

    :param pb_klass_or_instance: a protobuf message class, or an protobuf instance
    :type pb_klass_or_instance: a type or instance of a subclass of google.protobuf.message.Message
    :param dict values: a dictionary of values. Repeated and nested values are
       fully supported.
    :param dict type_callable_map: a mapping of protobuf types to callables for setting
       values on the target instance.
    :param bool strict: complain if keys in the map are not fields on the message.
    """
    if isinstance(pb_klass_or_instance, Message):
        instance = pb_klass_or_instance
    else:
        instance = pb_klass_or_instance()
    return _dict_to_protobuf(instance, values, type_callable_map, strict) 
Example #7
Source File: proto.py    From steam with MIT License 6 votes vote down vote up
def proto_to_dict(message):
    """Converts protobuf message instance to dict

    :param message: protobuf message instance
    :return: parameters and their values
    :rtype: dict
    :raises: :class:`.TypeError` if ``message`` is not a proto message
    """
    if not isinstance(message, _ProtoMessageType):
        raise TypeError("Expected `message` to be a instance of protobuf message")

    data = {}

    for desc, field in message.ListFields():
        if desc.type == desc.TYPE_MESSAGE:
            if desc.label == desc.LABEL_REPEATED:
                data[desc.name] = list(map(proto_to_dict, field))
            else:
                data[desc.name] = proto_to_dict(field)
        else:
            data[desc.name] = list(field) if desc.label == desc.LABEL_REPEATED else field

    return data 
Example #8
Source File: python_message.py    From lambda-packs with MIT License 6 votes vote down vote up
def _AddMessageMethods(message_descriptor, cls):
  """Adds implementations of all Message methods to cls."""
  _AddListFieldsMethod(message_descriptor, cls)
  _AddHasFieldMethod(message_descriptor, cls)
  _AddClearFieldMethod(message_descriptor, cls)
  if message_descriptor.is_extendable:
    _AddClearExtensionMethod(cls)
    _AddHasExtensionMethod(cls)
  _AddEqualsMethod(message_descriptor, cls)
  _AddStrMethod(message_descriptor, cls)
  _AddReprMethod(message_descriptor, cls)
  _AddUnicodeMethod(message_descriptor, cls)
  _AddByteSizeMethod(message_descriptor, cls)
  _AddSerializeToStringMethod(message_descriptor, cls)
  _AddSerializePartialToStringMethod(message_descriptor, cls)
  _AddMergeFromStringMethod(message_descriptor, cls)
  _AddIsInitializedMethod(message_descriptor, cls)
  _AddMergeFromMethod(cls)
  _AddWhichOneofMethod(message_descriptor, cls)
  _AddReduceMethod(cls)
  # Adds methods which do not depend on cls.
  cls.Clear = _Clear
  cls.DiscardUnknownFields = _DiscardUnknownFields
  cls._SetListener = _SetListener 
Example #9
Source File: python_message.py    From sklearn-theano with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _AddMessageMethods(message_descriptor, cls):
  """Adds implementations of all Message methods to cls."""
  _AddListFieldsMethod(message_descriptor, cls)
  _AddHasFieldMethod(message_descriptor, cls)
  _AddClearFieldMethod(message_descriptor, cls)
  if message_descriptor.is_extendable:
    _AddClearExtensionMethod(cls)
    _AddHasExtensionMethod(cls)
  _AddClearMethod(message_descriptor, cls)
  _AddEqualsMethod(message_descriptor, cls)
  _AddStrMethod(message_descriptor, cls)
  _AddUnicodeMethod(message_descriptor, cls)
  _AddSetListenerMethod(cls)
  _AddByteSizeMethod(message_descriptor, cls)
  _AddSerializeToStringMethod(message_descriptor, cls)
  _AddSerializePartialToStringMethod(message_descriptor, cls)
  _AddMergeFromStringMethod(message_descriptor, cls)
  _AddIsInitializedMethod(message_descriptor, cls)
  _AddMergeFromMethod(cls)
  _AddWhichOneofMethod(message_descriptor, cls) 
Example #10
Source File: reflection_test.py    From sklearn-theano with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    # TODO(xiaofeng): This test fails with cpp implemetnation in the call
    # of six.with_metaclass(). The other two callsites of with_metaclass
    # in this file are both excluded from cpp test, so it might be expected
    # to fail. Need someone more familiar with the python code to take a
    # look at this.
    if api_implementation.Type() != 'python':
      return
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2]) 
Example #11
Source File: reflection_test.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    # TODO(xiaofeng): This test fails with cpp implemetnation in the call
    # of six.with_metaclass(). The other two callsites of with_metaclass
    # in this file are both excluded from cpp test, so it might be expected
    # to fail. Need someone more familiar with the python code to take a
    # look at this.
    if api_implementation.Type() != 'python':
      return
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2]) 
Example #12
Source File: messages.py    From gax-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_messages(module):
    """Return a dictionary of message names and objects.

    Args:
        module (module): A Python module; dir() will be run against this
            module to find Message subclasses.

    Returns:
        dict[str, Message]: A dictionary with the Message class names as
            keys, and the Message subclasses themselves as values.
    """
    answer = collections.OrderedDict()
    for name in dir(module):
        candidate = getattr(module, name)
        if inspect.isclass(candidate) and issubclass(candidate, Message):
            answer[name] = candidate
    return answer 
Example #13
Source File: protobuf.py    From gax-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setdefault(pb_or_dict, key, value):
    """Set the key on the object to the value if the current value is falsy.

    Because protobuf Messages do not distinguish between unset values and
    falsy ones particularly well, this method treats any falsy value
    (e.g. 0, empty list) as a target to be overwritten, on both Messages
    and dictionaries.

    Args:
        pb_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
            object.
        key (str): The key on the object in question.
        value (Any): The value to set.

    Raises:
        TypeError: If pb_or_dict is not a Message or Mapping.
    """
    if not get(pb_or_dict, key, default=None):
        set(pb_or_dict, key, value) 
Example #14
Source File: python_message.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def _AddMessageMethods(message_descriptor, cls):
  """Adds implementations of all Message methods to cls."""
  _AddListFieldsMethod(message_descriptor, cls)
  _AddHasFieldMethod(message_descriptor, cls)
  _AddClearFieldMethod(message_descriptor, cls)
  if message_descriptor.is_extendable:
    _AddClearExtensionMethod(cls)
    _AddHasExtensionMethod(cls)
  _AddEqualsMethod(message_descriptor, cls)
  _AddStrMethod(message_descriptor, cls)
  _AddReprMethod(message_descriptor, cls)
  _AddUnicodeMethod(message_descriptor, cls)
  _AddByteSizeMethod(message_descriptor, cls)
  _AddSerializeToStringMethod(message_descriptor, cls)
  _AddSerializePartialToStringMethod(message_descriptor, cls)
  _AddMergeFromStringMethod(message_descriptor, cls)
  _AddIsInitializedMethod(message_descriptor, cls)
  _AddMergeFromMethod(cls)
  _AddWhichOneofMethod(message_descriptor, cls)
  # Adds methods which do not depend on cls.
  cls.Clear = _Clear
  cls.DiscardUnknownFields = _DiscardUnknownFields
  cls._SetListener = _SetListener 
Example #15
Source File: reflection.py    From botchallenge with MIT License 5 votes vote down vote up
def __new__(cls, name, bases, dictionary):
    """Custom allocation for runtime-generated class types.

    We override __new__ because this is apparently the only place
    where we can meaningfully set __slots__ on the class we're creating(?).
    (The interplay between metaclasses and slots is not very well-documented).

    Args:
      name: Name of the class (ignored, but required by the
        metaclass protocol).
      bases: Base classes of the class we're constructing.
        (Should be message.Message).  We ignore this field, but
        it's required by the metaclass protocol
      dictionary: The class dictionary of the class we're
        constructing.  dictionary[_DESCRIPTOR_KEY] must contain
        a Descriptor object describing this protocol message
        type.

    Returns:
      Newly-allocated class.
    """
    descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]
    bases = _NewMessage(bases, descriptor, dictionary)
    superclass = super(GeneratedProtocolMessageType, cls)

    new_class = superclass.__new__(cls, name, bases, dictionary)
    setattr(descriptor, '_concrete_class', new_class)
    return new_class 
Example #16
Source File: checker.py    From training_results_v0.6 with Apache License 2.0 5 votes vote down vote up
def _create_checker(proto_type):  # type: (Type[Message]) -> Callable[[FuncType], FuncType]
    def decorator(py_func):  # type: (FuncType) -> FuncType
        @functools.wraps(py_func)
        def checker(proto, ctx=DEFAULT_CONTEXT):  # type: (Message, C.CheckerContext) -> Any
            if not isinstance(proto, proto_type):
                raise RuntimeError(
                    'You cannot pass an object that is not of type {}'.format(
                        proto_type.__name__))
            return getattr(C, py_func.__name__)(
                proto.SerializeToString(), ctx)
        return cast(FuncType, checker)
    return decorator 
Example #17
Source File: compare.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def assertProtoEqual(self, a, b, check_initialized=True,
                     normalize_numbers=False, msg=None):
  """Fails with a useful error if a and b aren't equal.

  Comparison of repeated fields matches the semantics of
  unittest.TestCase.assertEqual(), ie order and extra duplicates fields matter.

  Args:
    self: googletest.TestCase
    a: proto2 PB instance, or text string representing one
    b: proto2 PB instance -- message.Message or subclass thereof
    check_initialized: boolean, whether to fail if either a or b isn't
      initialized
    normalize_numbers: boolean, whether to normalize types and precision of
      numbers before comparison.
    msg: if specified, is used as the error message on failure
  """
  if isinstance(a, six.string_types):
    a = text_format.Merge(a, b.__class__())

  for pb in a, b:
    if check_initialized:
      errors = pb.FindInitializationErrors()
      if errors:
        self.fail('Initialization errors: %s\n%s' % (errors, pb))
    if normalize_numbers:
      NormalizeNumberFields(pb)

  self.assertMultiLineEqual(text_format.MessageToString(a),
                            text_format.MessageToString(b),
                            msg=msg) 
Example #18
Source File: json.py    From interop with Apache License 2.0 5 votes vote down vote up
def default(self, obj):
        if isinstance(obj, message.Message):
            # Object is protobuf. Convert to python json representation.
            return json.loads(json_format.MessageToJson(obj))
        else:
            return super().default(obj) 
Example #19
Source File: reflection_test.py    From sklearn-theano with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testSerializeUninitializedSubMessage(self):
    proto = unittest_pb2.TestRequiredForeign()

    # Sub-message doesn't exist yet, so this succeeds.
    proto.SerializeToString()

    proto.optional_message.a = 1
    self._CheckRaises(
        message.EncodeError,
        proto.SerializeToString,
        'Message protobuf_unittest.TestRequiredForeign '
        'is missing required fields: '
        'optional_message.b,optional_message.c')

    proto.optional_message.b = 2
    proto.optional_message.c = 3
    proto.SerializeToString()

    proto.repeated_message.add().a = 1
    proto.repeated_message.add().b = 2
    self._CheckRaises(
        message.EncodeError,
        proto.SerializeToString,
        'Message protobuf_unittest.TestRequiredForeign is missing required fields: '
        'repeated_message[0].b,repeated_message[0].c,'
        'repeated_message[1].a,repeated_message[1].c')

    proto.repeated_message[0].b = 2
    proto.repeated_message[0].c = 3
    proto.repeated_message[1].a = 1
    proto.repeated_message[1].c = 3
    proto.SerializeToString() 
Example #20
Source File: reflection_test.py    From sklearn-theano with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testHandWrittenReflection(self):
    # Hand written extensions are only supported by the pure-Python
    # implementation of the API.
    if api_implementation.Type() != 'python':
      return

    FieldDescriptor = descriptor.FieldDescriptor
    foo_field_descriptor = FieldDescriptor(
        name='foo_field', full_name='MyProto.foo_field',
        index=0, number=1, type=FieldDescriptor.TYPE_INT64,
        cpp_type=FieldDescriptor.CPPTYPE_INT64,
        label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
        containing_type=None, message_type=None, enum_type=None,
        is_extension=False, extension_scope=None,
        options=descriptor_pb2.FieldOptions())
    mydescriptor = descriptor.Descriptor(
        name='MyProto', full_name='MyProto', filename='ignored',
        containing_type=None, nested_types=[], enum_types=[],
        fields=[foo_field_descriptor], extensions=[],
        options=descriptor_pb2.MessageOptions())
    class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = mydescriptor
    myproto_instance = MyProtoClass()
    self.assertEqual(0, myproto_instance.foo_field)
    self.assertTrue(not myproto_instance.HasField('foo_field'))
    myproto_instance.foo_field = 23
    self.assertEqual(23, myproto_instance.foo_field)
    self.assertTrue(myproto_instance.HasField('foo_field')) 
Example #21
Source File: message_factory.py    From sklearn-theano with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def GetPrototype(self, descriptor):
    """Builds a proto2 message class based on the passed in descriptor.

    Passing a descriptor with a fully qualified name matching a previous
    invocation will cause the same class to be returned.

    Args:
      descriptor: The descriptor to build from.

    Returns:
      A class describing the passed in descriptor.
    """
    if descriptor.full_name not in self._classes:
      descriptor_name = descriptor.name
      if str is bytes:  # PY2
        descriptor_name = descriptor.name.encode('ascii', 'ignore')
      result_class = reflection.GeneratedProtocolMessageType(
          descriptor_name,
          (message.Message,),
          {'DESCRIPTOR': descriptor, '__module__': None})
          # If module not set, it wrongly points to the reflection.py module.
      self._classes[descriptor.full_name] = result_class
      for field in descriptor.fields:
        if field.message_type:
          self.GetPrototype(field.message_type)
      for extension in result_class.DESCRIPTOR.extensions:
        if extension.containing_type.full_name not in self._classes:
          self.GetPrototype(extension.containing_type)
        extended_class = self._classes[extension.containing_type.full_name]
        extended_class.RegisterExtension(extension)
    return self._classes[descriptor.full_name] 
Example #22
Source File: reflection.py    From sklearn-theano with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def MakeClass(descriptor):
  """Construct a class object for a protobuf described by descriptor.

  Composite descriptors are handled by defining the new class as a member of the
  parent class, recursing as deep as necessary.
  This is the dynamic equivalent to:

  class Parent(message.Message):
    __metaclass__ = GeneratedProtocolMessageType
    DESCRIPTOR = descriptor
    class Child(message.Message):
      __metaclass__ = GeneratedProtocolMessageType
      DESCRIPTOR = descriptor.nested_types[0]

  Sample usage:
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(proto2_string)
    msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])
    msg_class = reflection.MakeClass(msg_descriptor)
    msg = msg_class()

  Args:
    descriptor: A descriptor.Descriptor object describing the protobuf.
  Returns:
    The Message class object described by the descriptor.
  """
  attributes = {}
  for name, nested_type in list(descriptor.nested_types_by_name.items()):
    attributes[name] = MakeClass(nested_type)

  attributes[GeneratedProtocolMessageType._DESCRIPTOR_KEY] = descriptor

  return GeneratedProtocolMessageType(str(descriptor.name), (message.Message,),
                                      attributes) 
Example #23
Source File: reflection.py    From sklearn-theano with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ParseMessage(descriptor, byte_str):
  """Generate a new Message instance from this Descriptor and a byte string.

  Args:
    descriptor: Protobuf Descriptor object
    byte_str: Serialized protocol buffer byte string

  Returns:
    Newly created protobuf Message object.
  """
  result_class = MakeClass(descriptor)
  new_msg = result_class()
  new_msg.ParseFromString(byte_str)
  return new_msg 
Example #24
Source File: message_factory.py    From botchallenge with MIT License 5 votes vote down vote up
def GetPrototype(self, descriptor):
    """Builds a proto2 message class based on the passed in descriptor.

    Passing a descriptor with a fully qualified name matching a previous
    invocation will cause the same class to be returned.

    Args:
      descriptor: The descriptor to build from.

    Returns:
      A class describing the passed in descriptor.
    """
    if descriptor.full_name not in self._classes:
      descriptor_name = descriptor.name
      if sys.version_info[0] < 3:  ##PY25
##!PY25      if str is bytes:  # PY2
        descriptor_name = descriptor.name.encode('ascii', 'ignore')
      result_class = reflection.GeneratedProtocolMessageType(
          descriptor_name,
          (message.Message,),
          {'DESCRIPTOR': descriptor, '__module__': None})
          # If module not set, it wrongly points to the reflection.py module.
      self._classes[descriptor.full_name] = result_class
      for field in descriptor.fields:
        if field.message_type:
          self.GetPrototype(field.message_type)
      for extension in result_class.DESCRIPTOR.extensions:
        if extension.containing_type.full_name not in self._classes:
          self.GetPrototype(extension.containing_type)
        extended_class = self._classes[extension.containing_type.full_name]
        extended_class.RegisterExtension(extension)
    return self._classes[descriptor.full_name] 
Example #25
Source File: reflection_test.py    From botchallenge with MIT License 5 votes vote down vote up
def testSerializeUninitializedSubMessage(self):
    proto = unittest_pb2.TestRequiredForeign()

    # Sub-message doesn't exist yet, so this succeeds.
    proto.SerializeToString()

    proto.optional_message.a = 1
    self._CheckRaises(
        message.EncodeError,
        proto.SerializeToString,
        'Message protobuf_unittest.TestRequiredForeign '
        'is missing required fields: '
        'optional_message.b,optional_message.c')

    proto.optional_message.b = 2
    proto.optional_message.c = 3
    proto.SerializeToString()

    proto.repeated_message.add().a = 1
    proto.repeated_message.add().b = 2
    self._CheckRaises(
        message.EncodeError,
        proto.SerializeToString,
        'Message protobuf_unittest.TestRequiredForeign is missing required fields: '
        'repeated_message[0].b,repeated_message[0].c,'
        'repeated_message[1].a,repeated_message[1].c')

    proto.repeated_message[0].b = 2
    proto.repeated_message[0].c = 3
    proto.repeated_message[1].a = 1
    proto.repeated_message[1].c = 3
    proto.SerializeToString() 
Example #26
Source File: test_utils_messages.py    From gax-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_messages(self):
        answer = messages.get_messages(date_pb2)

        # Ensure that Date was exported properly.
        assert answer['Date'] is date_pb2.Date

        # Ensure that no non-Message objects were exported.
        for value in answer.values():
            assert issubclass(value, Message) 
Example #27
Source File: test_protocol.py    From ga4gh-schemas with Apache License 2.0 5 votes vote down vote up
def testPostMethods(self):
        for postMethod in protocol.postMethods:
            self.assertEqual(len(postMethod), 3)
            self.assertIsInstance(postMethod[0], unicode)
            self.assertTrue(issubclass(postMethod[1], message.Message))
            self.assertTrue(issubclass(postMethod[2], message.Message)) 
Example #28
Source File: test_protocol.py    From ga4gh-schemas with Apache License 2.0 5 votes vote down vote up
def testGetProtocolClasses(self):
        classes = protocol.getProtocolClasses()
        self.assertGreater(len(classes), 0)
        for clazz in classes:
            self.assertTrue(issubclass(clazz, message.Message)) 
Example #29
Source File: test_api.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def luci_context(self, **section_pb_values):
    """Sets the LUCI_CONTEXT for this test case.

    Args:
      * section_pb_values(Dict[str, message.Message]): A mapping of section_key
      to the proto value for that section.
    """
    ret = self.test(None)
    for section_key, pb_val in iteritems(section_pb_values):
      if not isinstance(pb_val, message.Message): # pragma: no cover
          raise ValueError(
              'Expected section value in LUCI_CONTEXT to be proto message;'
              'Got: %r=%r (type %r)' % (section_key, pb_val, type(pb_val)))
      ret.luci_context[section_key] = jsonpb.MessageToDict(pb_val)
    return ret 
Example #30
Source File: python_message.py    From sklearn-theano with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __new__(cls, name, bases, dictionary):
    """Custom allocation for runtime-generated class types.

    We override __new__ because this is apparently the only place
    where we can meaningfully set __slots__ on the class we're creating(?).
    (The interplay between metaclasses and slots is not very well-documented).

    Args:
      name: Name of the class (ignored, but required by the
        metaclass protocol).
      bases: Base classes of the class we're constructing.
        (Should be message.Message).  We ignore this field, but
        it's required by the metaclass protocol
      dictionary: The class dictionary of the class we're
        constructing.  dictionary[_DESCRIPTOR_KEY] must contain
        a Descriptor object describing this protocol message
        type.

    Returns:
      Newly-allocated class.
    """
    descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]
    _AddClassAttributesForNestedExtensions(descriptor, dictionary)
    _AddSlots(descriptor, dictionary)

    superclass = super(GeneratedProtocolMessageType, cls)
    new_class = superclass.__new__(cls, name, bases, dictionary)
    return new_class