Python protorpc.messages.Message() Examples

The following are 30 code examples of protorpc.messages.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 protorpc.messages , or try the search function .
Example #1
Source File: msgprop_test.py    From datastore-ndb-python with Apache License 2.0 6 votes vote down vote up
def testErrors(self):
    class Storage(model.Model):
      greet = msgprop.MessageProperty(Greeting, indexed_fields=['text'])

    # Call MessageProperty(x) where x is not a Message class.
    self.assertRaises(TypeError, msgprop.MessageProperty, Storage)
    self.assertRaises(TypeError, msgprop.MessageProperty, 42)
    self.assertRaises(TypeError, msgprop.MessageProperty, None)

    # Call MessageProperty(Greeting, indexed_fields=x) where x
    # includes invalid field names.
    self.assertRaises(ValueError, msgprop.MessageProperty,
                      Greeting, indexed_fields=['text', 'nope'])
    self.assertRaises(TypeError, msgprop.MessageProperty,
                      Greeting, indexed_fields=['text', 42])
    self.assertRaises(TypeError, msgprop.MessageProperty,
                      Greeting, indexed_fields=['text', None])
    self.assertRaises(ValueError, msgprop.MessageProperty,
                      Greeting, indexed_fields=['text', 'text'])  # Duplicate.

    # Set a MessageProperty value to a non-Message instance.
    self.assertRaises(TypeError, Storage, greet=42) 
Example #2
Source File: msgprop.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def _from_base_type(self, ent):
    """Convert a Model instance (entity) to a Message value."""
    if ent._projection:
      # Projection query result.  Reconstitute the message from the fields.
      return _projected_entity_to_message(ent, self._message_type)

    blob = ent.blob_
    if blob is not None:
      protocol = self._protocol_impl
    else:
      # Perhaps it was written using a different protocol.
      protocol = None
      for name in _protocols_registry.names:
        key = '__%s__' % name
        if key in ent._values:
          blob = ent._values[key]
          if isinstance(blob, model._BaseValue):
            blob = blob.b_val
          protocol = _protocols_registry.lookup_by_name(name)
          break
    if blob is None or protocol is None:
      return None  # This will reveal the underlying dummy model.
    msg = protocol.decode_message(self._message_type, blob)
    return msg 
Example #3
Source File: msgprop.py    From datastore-ndb-python with Apache License 2.0 6 votes vote down vote up
def _message_to_entity(msg, modelclass):
  """Recursive helper for _to_base_type() to convert a message to an entity.

  Args:
    msg: A Message instance.
    modelclass: A Model subclass.

  Returns:
    An instance of modelclass.
  """
  ent = modelclass()
  for prop_name, prop in modelclass._properties.iteritems():
    if prop._code_name == 'blob_':  # TODO: Devise a cleaner test.
      continue  # That's taken care of later.
    value = getattr(msg, prop_name)
    if value is not None and isinstance(prop, model.StructuredProperty):
      if prop._repeated:
        value = [_message_to_entity(v, prop._modelclass) for v in value]
      else:
        value = _message_to_entity(value, prop._modelclass)
    setattr(ent, prop_name, value)
  return ent 
Example #4
Source File: msgprop.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def _message_to_entity(msg, modelclass):
  """Recursive helper for _to_base_type() to convert a message to an entity.

  Args:
    msg: A Message instance.
    modelclass: A Model subclass.

  Returns:
    An instance of modelclass.
  """
  ent = modelclass()
  for prop_name, prop in modelclass._properties.iteritems():
    if prop._code_name == 'blob_':  # TODO: Devise a cleaner test.
      continue  # That's taken care of later.
    value = getattr(msg, prop_name)
    if value is not None and isinstance(prop, model.StructuredProperty):
      if prop._repeated:
        value = [_message_to_entity(v, prop._modelclass) for v in value]
      else:
        value = _message_to_entity(value, prop._modelclass)
    setattr(ent, prop_name, value)
  return ent 
Example #5
Source File: definition_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testDefineMessage(self):
    """Test defining Message class from descriptor."""

    class AMessage(messages.Message):
      class NestedEnum(messages.Enum):
        pass

      field1 = messages.IntegerField(1)
      field2 = messages.StringField(2)

    message_descriptor = descriptor.describe_message(AMessage)

    message_class = definition.define_message(message_descriptor, '__main__')

    self.assertEquals('AMessage', message_class.__name__)
    self.assertEquals('__main__', message_class.__module__)

    self.assertEquals(message_descriptor,
                      descriptor.describe_message(message_class)) 
Example #6
Source File: msgprop_test.py    From datastore-ndb-python with Apache License 2.0 6 votes vote down vote up
def testRepeatedNestedMessageField(self):
    class Outer(messages.Message):
      greeting = messages.MessageField(Greeting, 1)
      extra = messages.IntegerField(2)

    class Store(model.Model):
      outers = msgprop.MessageProperty(Outer, repeated=True,
                                       indexed_fields=['greeting.text'])
    gr1 = Greeting(text='abc', when=123)
    gr2 = Greeting(text='def', when=456)
    outer1 = Outer(greeting=gr1, extra=1)
    outer2 = Outer(greeting=gr2, extra=2)
    store1 = Store(outers=[outer1])
    store1.put()
    store2 = Store(outers=[outer2])
    store2.put()
    store3 = Store(outers=[outer1, outer2])
    store3.put()
    res = Store.query(Store.outers.greeting.text == 'abc').fetch()
    self.assertEqual(res, [store1, store3]) 
Example #7
Source File: msgprop_test.py    From datastore-ndb-python with Apache License 2.0 6 votes vote down vote up
def testNestedRepeatedMessageField(self):
    class Outer(messages.Message):
      greetings = messages.MessageField(Greeting, 1, repeated=True)
      extra = messages.IntegerField(2)

    class Store(model.Model):
      outer = msgprop.MessageProperty(Outer, indexed_fields=['greetings.text',
                                                             'extra'])
    gr1 = Greeting(text='abc', when=123)
    gr2 = Greeting(text='def', when=456)
    outer1 = Outer(greetings=[gr1], extra=1)
    outer2 = Outer(greetings=[gr2], extra=2)
    outer3 = Outer(greetings=[gr1, gr2], extra=3)
    store1 = Store(outer=outer1)
    store1.put()
    store2 = Store(outer=outer2)
    store2.put()
    store3 = Store(outer=outer3)
    store3.put()
    res = Store.query(Store.outer.greetings.text == 'abc').fetch()
    self.assertEqual(res, [store1, store3]) 
Example #8
Source File: msgprop_test.py    From datastore-ndb-python with Apache License 2.0 6 votes vote down vote up
def testNestedFieldErrors(self):
    class Outer(messages.Message):
      greetings = messages.MessageField(Greeting, 1, repeated=True)
      extra = messages.IntegerField(2)
    # Parent/child conflicts.
    self.assertRaises(ValueError, msgprop.MessageProperty,
                      Outer, indexed_fields=['greetings.text', 'greetings'])
    self.assertRaises(ValueError, msgprop.MessageProperty,
                      Outer, indexed_fields=['greetings', 'greetings.text'])
    # Duplicate inner field.
    self.assertRaises(ValueError, msgprop.MessageProperty,
                      Outer, indexed_fields=['greetings.text',
                                             'greetings.text'])
    # Can't index MessageField.
    self.assertRaises(ValueError, msgprop.MessageProperty,
                      Outer, indexed_fields=['greetings'])
    # Can't specify subfields for non-MessageField.
    self.assertRaises(ValueError, msgprop.MessageProperty,
                      Outer, indexed_fields=['extra.foobar'])
    # Non-existent subfield.
    self.assertRaises(ValueError, msgprop.MessageProperty,
                      Outer, indexed_fields=['greetings.foobar']) 
Example #9
Source File: definition_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testDefineMessageFieldsOnly(self):
    """Test definition a message with only fields."""

    class AMessage(messages.Message):

      field1 = messages.IntegerField(1)
      field2 = messages.StringField(2)

    message_descriptor = descriptor.describe_message(AMessage)

    message_class = definition.define_message(message_descriptor, '__main__')

    self.assertEquals('AMessage', message_class.__name__)
    self.assertEquals('__main__', message_class.__module__)

    self.assertEquals(message_descriptor,
                      descriptor.describe_message(message_class)) 
Example #10
Source File: msgprop_test.py    From datastore-ndb-python with Apache License 2.0 6 votes vote down vote up
def testProjectionQueries(self):
    class Wrapper(messages.Message):
      greet = messages.MessageField(Greeting, 1)

    class Storage(model.Model):
      wrap = msgprop.MessageProperty(Wrapper, indexed_fields=['greet.text',
                                                              'greet.when'])
    gr1 = Greeting(text='abc', when=123)
    wr1 = Wrapper(greet=gr1)
    st1 = Storage(wrap=wr1)
    st1.put()
    res1 = Storage.query().get(projection=['wrap.greet.text',
                                           Storage.wrap.greet.when])
    self.assertNotEqual(res1, st1)
    self.assertEqual(res1.wrap, st1.wrap)
    res2 = Storage.query().get(projection=['wrap.greet.text'])
    self.assertEqual(res2.wrap, Wrapper(greet=Greeting(text='abc'))) 
Example #11
Source File: msgprop_test.py    From datastore-ndb-python with Apache License 2.0 6 votes vote down vote up
def testProjectionQueriesRepeatedField(self):
    class Wrapper(messages.Message):
      greets = messages.MessageField(Greeting, 1, repeated=True)

    class Storage(model.Model):
      wrap = msgprop.MessageProperty(Wrapper, indexed_fields=['greets.text',
                                                              'greets.when'])
    gr1 = Greeting(text='abc', when=123)
    wr1 = Wrapper(greets=[gr1])
    st1 = Storage(wrap=wr1)
    st1.put()
    res1 = Storage.query().get(projection=['wrap.greets.text',
                                           Storage.wrap.greets.when])
    self.assertNotEqual(res1, st1)
    self.assertEqual(res1.wrap, st1.wrap)
    res2 = Storage.query().get(projection=['wrap.greets.text'])
    self.assertEqual(res2.wrap, Wrapper(greets=[Greeting(text='abc')])) 
Example #12
Source File: definition_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testDefineMessageEnumOnly(self):
    """Test definition a message with only enums."""

    class AMessage(messages.Message):
      class NestedEnum(messages.Enum):
        pass

    message_descriptor = descriptor.describe_message(AMessage)

    message_class = definition.define_message(message_descriptor, '__main__')

    self.assertEquals('AMessage', message_class.__name__)
    self.assertEquals('__main__', message_class.__module__)

    self.assertEquals(message_descriptor,
                      descriptor.describe_message(message_class)) 
Example #13
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def resource_method_b(self, _):
    """A method belonging to a sub-resource."""
    return Message() 
Example #14
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def get_method(self, _):
    """An HTTP GET method."""
    return Message() 
Example #15
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def resource_method_c(self, _):
    """A method belonging to a sub-resource."""
    return Message() 
Example #16
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def post_method(self, _):
    """An HTTP POST method."""
    return Message() 
Example #17
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def get_method(self, _):
    """An HTTP GET method."""
    return Message() 
Example #18
Source File: remote_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testBadRequestType(self):
    """Test bad request types used in remote definition."""

    for request_type in (None, 1020, messages.Message, str):

      def declare():
        class BadService(object):

          @remote.method(request_type, SimpleResponse)
          def remote_method(self, request):
            pass

      self.assertRaises(TypeError, declare) 
Example #19
Source File: remote_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testBadResponseType(self):
    """Test bad response types used in remote definition."""

    for response_type in (None, 1020, messages.Message, str):

      def declare():
        class BadService(object):

          @remote.method(SimpleRequest, response_type)
          def remote_method(self, request):
            pass

      self.assertRaises(TypeError, declare) 
Example #20
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testDefinitionName_Nested(self):
    """Test nested Enum names."""
    class MyMessage(messages.Message):

      class NestedEnum(messages.Enum):

        pass

      class NestedMessage(messages.Message):

        class NestedEnum(messages.Enum):

          pass

    module_name = test_util.get_module_name(EnumTest)
    self.assertEquals('%s.MyMessage.NestedEnum' % module_name,
                      MyMessage.NestedEnum.definition_name())
    self.assertEquals('%s.MyMessage' % module_name,
                      MyMessage.NestedEnum.outer_definition_name())
    self.assertEquals(module_name,
                      MyMessage.NestedEnum.definition_package())

    self.assertEquals('%s.MyMessage.NestedMessage.NestedEnum' % module_name,
                      MyMessage.NestedMessage.NestedEnum.definition_name())
    self.assertEquals(
      '%s.MyMessage.NestedMessage' % module_name,
      MyMessage.NestedMessage.NestedEnum.outer_definition_name())
    self.assertEquals(module_name,
                      MyMessage.NestedMessage.NestedEnum.definition_package()) 
Example #21
Source File: definition_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testDefineMessageEmpty(self):
    """Test definition a message with no fields or enums."""

    class AMessage(messages.Message):
      pass

    message_descriptor = descriptor.describe_message(AMessage)

    message_class = definition.define_message(message_descriptor, '__main__')

    self.assertEquals('AMessage', message_class.__name__)
    self.assertEquals('__main__', message_class.__module__)

    self.assertEquals(message_descriptor,
                      descriptor.describe_message(message_class)) 
Example #22
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def resource_method_a(self, _):
    """A method belonging to a resource."""
    return Message() 
Example #23
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def path_parameter_method(self, _):
    """An HTTP POST method supporting path parameters."""
    return Message() 
Example #24
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def query_string_method(self, _):
    """An HTTP GET method supporting query strings."""
    return Message() 
Example #25
Source File: msgprop.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def __init__(self, message_type, name=None,
               indexed_fields=None, protocol=None, **kwds):
    """Constructor.

    Args:
      message_tyoe: A subclass of protorpc.messages.Message.
      name: Optional datastore name (defaults to the property name).
      indexed_fields: Optional list of dotted and undotted field names.
      protocol: Optional protocol name default 'protobuf'.

    Additional keywords arguments specify the same options as
    supported by StructuredProperty, except 'indexed'.
    """
    if not (isinstance(message_type, type) and
            issubclass(message_type, messages.Message)):
      raise TypeError('MessageProperty argument must be a Message subclass')
    self._message_type = message_type
    if indexed_fields is not None:
      # TODO: Check they are all strings naming fields.
      self._indexed_fields = tuple(indexed_fields)
    # NOTE: Otherwise the class default i.e. (), prevails.
    if protocol is None:
      protocol = _default_protocol
    self._protocol = protocol
    self._protocol_impl = _protocols_registry.lookup_by_name(protocol)
    blob_prop = model.BlobProperty('__%s__' % self._protocol)
    # TODO: Solve this without reserving 'blob_'.
    message_class = _make_model_class(message_type, self._indexed_fields,
                                      blob_=blob_prop)
    super(MessageProperty, self).__init__(message_class, name, **kwds) 
Example #26
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def post_method(self, _):
    """An HTTP POST method."""
    return Message() 
Example #27
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def post_method(self, _):
    """An HTTP POST method."""
    return Message() 
Example #28
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def resource_method_b(self, _):
    """A method belonging to a sub-resource."""
    return Message() 
Example #29
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def resource_method_a(self, _):
    """A method belonging to a resource."""
    return Message() 
Example #30
Source File: discovery_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def path_parameter_method(self, _):
    """An HTTP POST method supporting path parameters."""
    return Message()