Python protorpc.messages.EnumField() Examples

The following are 19 code examples of protorpc.messages.EnumField(). 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: descriptor_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testDefault_EnumField(self):
    class MyEnum(messages.Enum):

      VAL = 1

    module_name = test_util.get_module_name(MyEnum)
    field = messages.EnumField(MyEnum, 10, default=MyEnum.VAL)
    field.name = 'a_field'

    expected = descriptor.FieldDescriptor()
    expected.name = 'a_field'
    expected.number = 10
    expected.label = descriptor.FieldDescriptor.Label.OPTIONAL
    expected.variant = messages.EnumField.DEFAULT_VARIANT
    expected.type_name = '%s.MyEnum' % module_name
    expected.default_value = '1'

    described = descriptor.describe_field(field)
    self.assertEquals(expected, described) 
Example #2
Source File: messages_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testEnumField_WrongType(self):
    """Test that forward referencing the wrong type raises an error."""
    global AMessage
    try:
      class AMessage(messages.Message):
        pass

      class AnotherMessage(messages.Message):

        a_field = messages.EnumField('AMessage', 1)

      self.assertRaises(messages.FieldDefinitionError,
                        getattr,
                        AnotherMessage.field_by_name('a_field'),
                        'type')
    finally:
      del AMessage 
Example #3
Source File: definition_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testDefineField_Enum(self):
    """Test defining an enum field."""
    field_descriptor = descriptor.FieldDescriptor()

    field_descriptor.name = 'a_field'
    field_descriptor.number = 1
    field_descriptor.variant = descriptor.FieldDescriptor.Variant.ENUM
    field_descriptor.type_name = 'something.yet.to.be.Defined'
    field_descriptor.label = descriptor.FieldDescriptor.Label.REPEATED

    field = definition.define_field(field_descriptor)

    # Name will not be set from the original descriptor.
    self.assertFalse(hasattr(field, 'name'))

    self.assertTrue(isinstance(field, messages.EnumField))
    self.assertEquals(1, field.number)
    self.assertEquals(descriptor.FieldDescriptor.Variant.ENUM, field.variant)
    self.assertFalse(field.required)
    self.assertTrue(field.repeated)
    self.assertRaisesWithRegexpMatch(messages.DefinitionNotFoundError,
                                     'Could not find definition for '
                                     'something.yet.to.be.Defined',
                                     getattr, field, 'type') 
Example #4
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testDefaultFields_Enum(self):
    """Test the default for enum fields."""
    class Symbol(messages.Enum):

      ALPHA = 1
      BETA = 2
      GAMMA = 3

    field = messages.EnumField(Symbol, 1, default=Symbol.ALPHA)

    self.assertEquals(Symbol.ALPHA, field.default) 
Example #5
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testEnumField_ForwardReference(self):
    """Test the construction of forward reference enum fields."""
    global MyMessage
    global ForwardEnum
    global ForwardMessage
    try:
      class MyMessage(messages.Message):

        forward = messages.EnumField('ForwardEnum', 1)
        nested = messages.EnumField('ForwardMessage.NestedEnum', 2)
        inner = messages.EnumField('Inner', 3)

        class Inner(messages.Enum):
          pass

      class ForwardEnum(messages.Enum):
        pass

      class ForwardMessage(messages.Message):

        class NestedEnum(messages.Enum):
          pass

      self.assertEquals(ForwardEnum,
                        MyMessage.field_by_name('forward').type)

      self.assertEquals(ForwardMessage.NestedEnum,
                        MyMessage.field_by_name('nested').type)

      self.assertEquals(MyMessage.Inner,
                        MyMessage.field_by_name('inner').type)
    finally:
      try:
        del MyMessage
        del ForwardEnum
        del ForwardMessage
      except:
        pass 
Example #6
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testEnumField(self):
    """Test the construction of enum fields."""
    self.assertRaises(messages.FieldDefinitionError,
                      messages.EnumField,
                      str,
                      10)

    self.assertRaises(messages.FieldDefinitionError,
                      messages.EnumField,
                      messages.Enum,
                      10)

    class Color(messages.Enum):
      RED = 1
      GREEN = 2
      BLUE = 3

    field = messages.EnumField(Color, 10)
    self.assertEquals(Color, field.type)

    class Another(messages.Enum):
      VALUE = 1

    self.assertRaises(messages.InvalidDefaultError,
                      messages.EnumField,
                      Color,
                      10,
                      default=Another.VALUE) 
Example #7
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testDefaultFields_EnumInvalidDelayedResolution(self):
    """Test that enum fields raise errors upon delayed resolution error."""
    field = messages.EnumField('protorpc.descriptor.FieldDescriptor.Label',
                               1,
                               default=200)

    self.assertRaisesWithRegexpMatch(TypeError,
                                     'No such value for 200 in Enum Label',
                                     getattr,
                                     field,
                                     'default') 
Example #8
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testDefaultFields_EnumOkIfTypeKnown(self):
    """Test that enum fields accept valid default values when type is known."""
    field = messages.EnumField(descriptor.FieldDescriptor.Label,
                               1,
                               default='REPEATED')

    self.assertEquals(descriptor.FieldDescriptor.Label.REPEATED, field.default) 
Example #9
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testDefaultFields_EnumIntDelayedResolution(self):
    """Test that enum fields resolve default integers."""
    field = messages.EnumField('protorpc.descriptor.FieldDescriptor.Label',
                               1,
                               default=2)

    self.assertEquals(descriptor.FieldDescriptor.Label.REQUIRED, field.default) 
Example #10
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testDefaultFields_EnumStringDelayedResolution(self):
    """Test that enum fields resolve default strings."""
    field = messages.EnumField('protorpc.descriptor.FieldDescriptor.Label',
                               1,
                               default='OPTIONAL')

    self.assertEquals(descriptor.FieldDescriptor.Label.OPTIONAL, field.default) 
Example #11
Source File: msgprop_test.py    From datastore-ndb-python with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    super(MsgPropTests, self).setUp()
    global Greeting

    class Greeting(messages.Message):
      text = messages.StringField(1, required=True)
      when = messages.IntegerField(2)
      color = messages.EnumField(Color, 3) 
Example #12
Source File: msgprop.py    From python-compat-runtime with Apache License 2.0 4 votes vote down vote up
def _make_model_class(message_type, indexed_fields, **props):
  """Construct a Model subclass corresponding to a Message subclass.

  Args:
    message_type: A Message subclass.
    indexed_fields: A list of dotted and undotted field names.
    **props: Additional properties with which to seed the class.

  Returns:
    A Model subclass whose properties correspond to those fields of
    message_type whose field name is listed in indexed_fields, plus
    the properties specified by the **props arguments.  For dotted
    field names, a StructuredProperty is generated using a Model
    subclass created by a recursive call.

  Raises:
    Whatever _analyze_indexed_fields() raises.
    ValueError if a field name conflicts with a name in **props.
    ValueError if a field name is not valid field of message_type.
    ValueError if an undotted field name designates a MessageField.
  """
  analyzed = _analyze_indexed_fields(indexed_fields)
  for field_name, sub_fields in analyzed.iteritems():
    if field_name in props:
      raise ValueError('field name %s is reserved' % field_name)
    try:
      field = message_type.field_by_name(field_name)
    except KeyError:
      raise ValueError('Message type %s has no field named %s' %
                       (message_type.__name__, field_name))
    if isinstance(field, messages.MessageField):
      if not sub_fields:
        raise ValueError(
            'MessageField %s cannot be indexed, only sub-fields' % field_name)
      sub_model_class = _make_model_class(field.type, sub_fields)
      prop = model.StructuredProperty(sub_model_class, field_name,
                                      repeated=field.repeated)
    else:
      if sub_fields is not None:
        raise ValueError(
            'Unstructured field %s cannot have indexed sub-fields' % field_name)
      if isinstance(field, messages.EnumField):
        prop = EnumProperty(field.type, field_name, repeated=field.repeated)
      elif isinstance(field, messages.BytesField):
        prop = model.BlobProperty(field_name,
                                  repeated=field.repeated, indexed=True)
      else:
        # IntegerField, FloatField, BooleanField, StringField.
        prop = model.GenericProperty(field_name, repeated=field.repeated)
    props[field_name] = prop
  return model.MetaModel('_%s__Model' % message_type.__name__,
                         (model.Model,), props) 
Example #13
Source File: discovery.py    From luci-py with Apache License 2.0 4 votes vote down vote up
def _get_type_format(field):
  """Returns the schema type and format for the given message type.

  Args:
    field: The protorpc.messages.Field to get schema type and format for.

  Returns:
    (type, format) for use in the "schemas" section of a discovery document.
  """
  if isinstance(field, messages.BooleanField):
    return ('boolean', None)

  if isinstance(field, messages.BytesField):
    return ('string', 'byte')

  if isinstance(field, message_types.DateTimeField):
    return ('string', 'date-time')

  if isinstance(field, messages.EnumField):
    return ('string', None)

  if isinstance(field, messages.FloatField):
    if field.variant == messages.Variant.DOUBLE:
      return ('number', 'double')
    return ('number', 'float')

  if isinstance(field, messages.IntegerField):
    if field.variant in (messages.Variant.INT32, messages.Variant.SINT32):
      return ('integer', 'int32')

    if field.variant in (messages.Variant.INT64, messages.Variant.SINT64):
      # If the type requires int64 or uint64, specify string or JavaScript will
      # convert them to 32-bit.
      return ('string', 'int64')

    if field.variant == messages.Variant.UINT32:
      return ('integer', 'uint32')

    if field.variant == messages.Variant.UINT64:
      return ('string', 'uint64')

    # Despite the warning about JavaScript, Endpoints v2's discovery document
    # generator uses integer, int64 as the default here. Follow their choice.
    return ('integer', 'int64')

  if isinstance(field, messages.StringField):
    return ('string', None)

  return (None, None) 
Example #14
Source File: discovery.py    From luci-py with Apache License 2.0 4 votes vote down vote up
def _get_type_format(field):
  """Returns the schema type and format for the given message type.

  Args:
    field: The protorpc.messages.Field to get schema type and format for.

  Returns:
    (type, format) for use in the "schemas" section of a discovery document.
  """
  if isinstance(field, messages.BooleanField):
    return ('boolean', None)

  if isinstance(field, messages.BytesField):
    return ('string', 'byte')

  if isinstance(field, message_types.DateTimeField):
    return ('string', 'date-time')

  if isinstance(field, messages.EnumField):
    return ('string', None)

  if isinstance(field, messages.FloatField):
    if field.variant == messages.Variant.DOUBLE:
      return ('number', 'double')
    return ('number', 'float')

  if isinstance(field, messages.IntegerField):
    if field.variant in (messages.Variant.INT32, messages.Variant.SINT32):
      return ('integer', 'int32')

    if field.variant in (messages.Variant.INT64, messages.Variant.SINT64):
      # If the type requires int64 or uint64, specify string or JavaScript will
      # convert them to 32-bit.
      return ('string', 'int64')

    if field.variant == messages.Variant.UINT32:
      return ('integer', 'uint32')

    if field.variant == messages.Variant.UINT64:
      return ('string', 'uint64')

    # Despite the warning about JavaScript, Endpoints v2's discovery document
    # generator uses integer, int64 as the default here. Follow their choice.
    return ('integer', 'int64')

  if isinstance(field, messages.StringField):
    return ('string', None)

  return (None, None) 
Example #15
Source File: discovery.py    From luci-py with Apache License 2.0 4 votes vote down vote up
def _get_type_format(field):
  """Returns the schema type and format for the given message type.

  Args:
    field: The protorpc.messages.Field to get schema type and format for.

  Returns:
    (type, format) for use in the "schemas" section of a discovery document.
  """
  if isinstance(field, messages.BooleanField):
    return ('boolean', None)

  if isinstance(field, messages.BytesField):
    return ('string', 'byte')

  if isinstance(field, message_types.DateTimeField):
    return ('string', 'date-time')

  if isinstance(field, messages.EnumField):
    return ('string', None)

  if isinstance(field, messages.FloatField):
    if field.variant == messages.Variant.DOUBLE:
      return ('number', 'double')
    return ('number', 'float')

  if isinstance(field, messages.IntegerField):
    if field.variant in (messages.Variant.INT32, messages.Variant.SINT32):
      return ('integer', 'int32')

    if field.variant in (messages.Variant.INT64, messages.Variant.SINT64):
      # If the type requires int64 or uint64, specify string or JavaScript will
      # convert them to 32-bit.
      return ('string', 'int64')

    if field.variant == messages.Variant.UINT32:
      return ('integer', 'uint32')

    if field.variant == messages.Variant.UINT64:
      return ('string', 'uint64')

    # Despite the warning about JavaScript, Endpoints v2's discovery document
    # generator uses integer, int64 as the default here. Follow their choice.
    return ('integer', 'int64')

  if isinstance(field, messages.StringField):
    return ('string', None)

  return (None, None) 
Example #16
Source File: discovery.py    From luci-py with Apache License 2.0 4 votes vote down vote up
def _get_type_format(field):
  """Returns the schema type and format for the given message type.

  Args:
    field: The protorpc.messages.Field to get schema type and format for.

  Returns:
    (type, format) for use in the "schemas" section of a discovery document.
  """
  if isinstance(field, messages.BooleanField):
    return ('boolean', None)

  if isinstance(field, messages.BytesField):
    return ('string', 'byte')

  if isinstance(field, message_types.DateTimeField):
    return ('string', 'date-time')

  if isinstance(field, messages.EnumField):
    return ('string', None)

  if isinstance(field, messages.FloatField):
    if field.variant == messages.Variant.DOUBLE:
      return ('number', 'double')
    return ('number', 'float')

  if isinstance(field, messages.IntegerField):
    if field.variant in (messages.Variant.INT32, messages.Variant.SINT32):
      return ('integer', 'int32')

    if field.variant in (messages.Variant.INT64, messages.Variant.SINT64):
      # If the type requires int64 or uint64, specify string or JavaScript will
      # convert them to 32-bit.
      return ('string', 'int64')

    if field.variant == messages.Variant.UINT32:
      return ('integer', 'uint32')

    if field.variant == messages.Variant.UINT64:
      return ('string', 'uint64')

    # Despite the warning about JavaScript, Endpoints v2's discovery document
    # generator uses integer, int64 as the default here. Follow their choice.
    return ('integer', 'int64')

  if isinstance(field, messages.StringField):
    return ('string', None)

  return (None, None) 
Example #17
Source File: discovery.py    From luci-py with Apache License 2.0 4 votes vote down vote up
def _get_type_format(field):
  """Returns the schema type and format for the given message type.

  Args:
    field: The protorpc.messages.Field to get schema type and format for.

  Returns:
    (type, format) for use in the "schemas" section of a discovery document.
  """
  if isinstance(field, messages.BooleanField):
    return ('boolean', None)

  if isinstance(field, messages.BytesField):
    return ('string', 'byte')

  if isinstance(field, message_types.DateTimeField):
    return ('string', 'date-time')

  if isinstance(field, messages.EnumField):
    return ('string', None)

  if isinstance(field, messages.FloatField):
    if field.variant == messages.Variant.DOUBLE:
      return ('number', 'double')
    return ('number', 'float')

  if isinstance(field, messages.IntegerField):
    if field.variant in (messages.Variant.INT32, messages.Variant.SINT32):
      return ('integer', 'int32')

    if field.variant in (messages.Variant.INT64, messages.Variant.SINT64):
      # If the type requires int64 or uint64, specify string or JavaScript will
      # convert them to 32-bit.
      return ('string', 'int64')

    if field.variant == messages.Variant.UINT32:
      return ('integer', 'uint32')

    if field.variant == messages.Variant.UINT64:
      return ('string', 'uint64')

    # Despite the warning about JavaScript, Endpoints v2's discovery document
    # generator uses integer, int64 as the default here. Follow their choice.
    return ('integer', 'int64')

  if isinstance(field, messages.StringField):
    return ('string', None)

  return (None, None) 
Example #18
Source File: messages_test.py    From protorpc with Apache License 2.0 4 votes vote down vote up
def testEquality(self):
    """Test message class equality."""
    # Comparison against enums must work.
    class MyEnum(messages.Enum):
      val1 = 1
      val2 = 2

    # Comparisons against nested messages must work.
    class AnotherMessage(messages.Message):
      string = messages.StringField(1)

    class MyMessage(messages.Message):
      field1 = messages.IntegerField(1)
      field2 = messages.EnumField(MyEnum, 2)
      field3 = messages.MessageField(AnotherMessage, 3)

    message1 = MyMessage()

    self.assertNotEquals('hi', message1)
    self.assertNotEquals(AnotherMessage(), message1)
    self.assertEquals(message1, message1)

    message2 = MyMessage()

    self.assertEquals(message1, message2)

    message1.field1 = 10
    self.assertNotEquals(message1, message2)

    message2.field1 = 20
    self.assertNotEquals(message1, message2)

    message2.field1 = 10
    self.assertEquals(message1, message2)

    message1.field2 = MyEnum.val1
    self.assertNotEquals(message1, message2)

    message2.field2 = MyEnum.val2
    self.assertNotEquals(message1, message2)

    message2.field2 = MyEnum.val1
    self.assertEquals(message1, message2)

    message1.field3 = AnotherMessage()
    message1.field3.string = u'value1'
    self.assertNotEquals(message1, message2)

    message2.field3 = AnotherMessage()
    message2.field3.string = u'value2'
    self.assertNotEquals(message1, message2)

    message2.field3.string = u'value1'
    self.assertEquals(message1, message2) 
Example #19
Source File: msgprop.py    From datastore-ndb-python with Apache License 2.0 4 votes vote down vote up
def _make_model_class(message_type, indexed_fields, **props):
  """Construct a Model subclass corresponding to a Message subclass.

  Args:
    message_type: A Message subclass.
    indexed_fields: A list of dotted and undotted field names.
    **props: Additional properties with which to seed the class.

  Returns:
    A Model subclass whose properties correspond to those fields of
    message_type whose field name is listed in indexed_fields, plus
    the properties specified by the **props arguments.  For dotted
    field names, a StructuredProperty is generated using a Model
    subclass created by a recursive call.

  Raises:
    Whatever _analyze_indexed_fields() raises.
    ValueError if a field name conflicts with a name in **props.
    ValueError if a field name is not valid field of message_type.
    ValueError if an undotted field name designates a MessageField.
  """
  analyzed = _analyze_indexed_fields(indexed_fields)
  for field_name, sub_fields in analyzed.iteritems():
    if field_name in props:
      raise ValueError('field name %s is reserved' % field_name)
    try:
      field = message_type.field_by_name(field_name)
    except KeyError:
      raise ValueError('Message type %s has no field named %s' %
                       (message_type.__name__, field_name))
    if isinstance(field, messages.MessageField):
      if not sub_fields:
        raise ValueError(
            'MessageField %s cannot be indexed, only sub-fields' % field_name)
      sub_model_class = _make_model_class(field.type, sub_fields)
      prop = model.StructuredProperty(sub_model_class, field_name,
                                      repeated=field.repeated)
    else:
      if sub_fields is not None:
        raise ValueError(
            'Unstructured field %s cannot have indexed sub-fields' % field_name)
      if isinstance(field, messages.EnumField):
        prop = EnumProperty(field.type, field_name, repeated=field.repeated)
      elif isinstance(field, messages.BytesField):
        prop = model.BlobProperty(field_name,
                                  repeated=field.repeated, indexed=True)
      else:
        # IntegerField, FloatField, BooleanField, StringField.
        prop = model.GenericProperty(field_name, repeated=field.repeated)
    props[field_name] = prop
  return model.MetaModel('_%s__Model' % message_type.__name__,
                         (model.Model,), props)