Python protorpc.messages.IntegerField() Examples

The following are 30 code examples of protorpc.messages.IntegerField(). 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(self):
    for field_class, default, expected_default in (
        (messages.IntegerField, 200, '200'),
        (messages.FloatField, 1.5, '1.5'),
        (messages.FloatField, 1e6, '1000000.0'),
        (messages.BooleanField, True, 'true'),
        (messages.BooleanField, False, 'false'),
        (messages.BytesField, 'ab\xF1', 'ab\\xf1'),
        (messages.StringField, RUSSIA, RUSSIA),
        ):
      field = field_class(10, default=default)
      field.name = u'a_field'

      expected = descriptor.FieldDescriptor()
      expected.name = u'a_field'
      expected.number = 10
      expected.label = descriptor.FieldDescriptor.Label.OPTIONAL
      expected.variant = field_class.DEFAULT_VARIANT
      expected.default_value = expected_default

      described = descriptor.describe_field(field)
      described.check_initialized()
      self.assertEquals(expected, described) 
Example #2
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 #3
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 #4
Source File: definition_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testDefineField_Default_Invalid(self):
    """Test defining a default value that is not valid."""
    field_descriptor = descriptor.FieldDescriptor()

    field_descriptor.name = 'a_field'
    field_descriptor.number = 1
    field_descriptor.variant = descriptor.FieldDescriptor.Variant.INT64
    field_descriptor.default_value = u'Test'

    # Verify that the string is passed to the Constructor.
    mock = mox.Mox()
    mock.StubOutWithMock(messages.IntegerField, '__init__')
    messages.IntegerField.__init__(
        default=u'Test',
        number=1,
        variant=messages.Variant.INT64
        ).AndRaise(messages.InvalidDefaultError)

    mock.ReplayAll()
    self.assertRaises(messages.InvalidDefaultError,
                      definition.define_field, field_descriptor)
    mock.VerifyAll()

    mock.ResetAll()
    mock.UnsetStubs() 
Example #5
Source File: definition_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testDefineField_Default_Int(self):
    """Test defining a default value for an int."""
    field_descriptor = descriptor.FieldDescriptor()

    field_descriptor.name = 'a_field'
    field_descriptor.number = 1
    field_descriptor.variant = descriptor.FieldDescriptor.Variant.INT64
    field_descriptor.default_value = u'34'

    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.IntegerField))
    self.assertEquals(1, field.number)
    self.assertEquals(descriptor.FieldDescriptor.Variant.INT64, field.variant)
    self.assertFalse(field.required)
    self.assertFalse(field.repeated)
    self.assertEqual(field.default, 34) 
Example #6
Source File: definition_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testDefineField_Optional(self):
    """Test defining an optional field instance from a method descriptor."""
    field_descriptor = descriptor.FieldDescriptor()

    field_descriptor.name = 'a_field'
    field_descriptor.number = 1
    field_descriptor.variant = descriptor.FieldDescriptor.Variant.INT32
    field_descriptor.label = descriptor.FieldDescriptor.Label.OPTIONAL

    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.IntegerField))
    self.assertEquals(1, field.number)
    self.assertEquals(descriptor.FieldDescriptor.Variant.INT32, field.variant)
    self.assertFalse(field.required)
    self.assertFalse(field.repeated) 
Example #7
Source File: messages_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testValidate_Repeated(self):
    """Tests validation of repeated fields."""
    class SimpleMessage(messages.Message):
      repeated = messages.IntegerField(1, repeated=True)

    simple_message = SimpleMessage()

    # Check valid values.
    for valid_value in [], [10], [10, 20], (), (10,), (10, 20):
      simple_message.repeated = valid_value
      simple_message.check_initialized()

    # Check cleared.
    simple_message.repeated = []
    simple_message.check_initialized()

    # Check invalid values.
    for invalid_value in 10, ['10', '20'], [None], (None,):
      self.assertRaises(messages.ValidationError,
                        setattr, simple_message, 'repeated', invalid_value) 
Example #8
Source File: messages_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testDefaultFields_Single(self):
    """Test default field is correct type (single)."""
    defaults = {messages.IntegerField: 10,
                messages.FloatField: 1.5,
                messages.BooleanField: False,
                messages.BytesField: b'abc',
                messages.StringField: u'abc',
               }

    def action(field_class):
      field_class(1, default=defaults[field_class])
    self.ActionOnAllFieldClasses(action)

    # Run defaults test again checking for str/unicode compatiblity.
    defaults[messages.StringField] = 'abc'
    self.ActionOnAllFieldClasses(action) 
Example #9
Source File: descriptor_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testLabel(self):
    for repeated, required, expected_label in (
        (True, False, descriptor.FieldDescriptor.Label.REPEATED),
        (False, True, descriptor.FieldDescriptor.Label.REQUIRED),
        (False, False, descriptor.FieldDescriptor.Label.OPTIONAL)):
      field = messages.IntegerField(10, required=required, repeated=repeated)
      field.name = 'a_field'

      expected = descriptor.FieldDescriptor()
      expected.name = 'a_field'
      expected.number = 10
      expected.label = expected_label
      expected.variant = descriptor.FieldDescriptor.Variant.INT64

      described = descriptor.describe_field(field)
      described.check_initialized()
      self.assertEquals(expected, described) 
Example #10
Source File: messages_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testEqualityWithUnknowns(self):
    """Test message class equality with unknown fields."""

    class MyMessage(messages.Message):
      field1 = messages.IntegerField(1)

    message1 = MyMessage()
    message2 = MyMessage()
    self.assertEquals(message1, message2)
    message1.set_unrecognized_field('unknown1', 'value1',
                                    messages.Variant.STRING)
    self.assertEquals(message1, message2)

    message1.set_unrecognized_field('unknown2', ['asdf', 3],
                                    messages.Variant.STRING)
    message1.set_unrecognized_field('unknown3', 4.7,
                                    messages.Variant.DOUBLE)
    self.assertEquals(message1, message2) 
Example #11
Source File: protourlencode_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testParameterPrefix(self):
    """Test using the 'prefix' parameter to encode_message."""
    class MyMessage(messages.Message):
      number = messages.IntegerField(1)
      names = messages.StringField(2, repeated=True)

    message = MyMessage()
    message.number = 10
    message.names = [u'Fred', u'Lisa']

    encoded_message = protourlencode.encode_message(message, prefix='prefix-')
    self.assertEquals({'prefix-number': ['10'],
                       'prefix-names-0': ['Fred'],
                       'prefix-names-1': ['Lisa'],
                      },
                      cgi.parse_qs(encoded_message))

    self.assertEquals(message, protourlencode.decode_message(MyMessage,
                                                             encoded_message,
                                                             prefix='prefix-')) 
Example #12
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 #13
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 #14
Source File: msgprop_test.py    From datastore-ndb-python with Apache License 2.0 6 votes vote down vote up
def testNestedMessageField(self):
    class Inner(messages.Message):
      count = messages.IntegerField(1)
      greet = messages.MessageField(Greeting, 2)

    class Outer(messages.Message):
      inner = messages.MessageField(Inner, 1)
      extra = messages.StringField(2)

    class Store(model.Model):
      outer = msgprop.MessageProperty(Outer,
                                      indexed_fields=['inner.greet.text'])
    greet = Greeting(text='abc', when=123)
    inner = Inner(count=42, greet=greet)
    outer = Outer(inner=inner)
    st = Store(outer=outer)
    st.put()
    res = Store.query(Store.outer.inner.greet.text == 'abc').fetch()
    self.assertEqual(res, [st]) 
Example #15
Source File: protourlencode_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testProtourlencodeUnrecognizedField(self):
    """Test that unrecognized fields are saved and can be accessed."""

    class MyMessage(messages.Message):
      number = messages.IntegerField(1)

    decoded = protourlencode.decode_message(MyMessage,
                                            self.unexpected_tag_message)
    self.assertEquals(1, len(decoded.all_unrecognized_fields()))
    self.assertEquals('unexpected', decoded.all_unrecognized_fields()[0])
    # Unknown values set to a list of however many values had that name.
    self.assertEquals((['whatever'], messages.Variant.STRING),
                      decoded.get_unrecognized_field_info('unexpected'))

    repeated_unknown = urllib.urlencode([('repeated', 400),
                                         ('repeated', 'test'),
                                         ('repeated', '123.456')])
    decoded2 = protourlencode.decode_message(MyMessage, repeated_unknown)
    self.assertEquals((['400', 'test', '123.456'], messages.Variant.STRING),
                      decoded2.get_unrecognized_field_info('repeated')) 
Example #16
Source File: messages_test.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def testIsInitializedNestedField(self):
    """Tests is_initialized for nested fields."""
    class SimpleMessage(messages.Message):
      required = messages.IntegerField(1, required=True)

    class NestedMessage(messages.Message):
      simple = messages.MessageField(SimpleMessage, 1)

    simple_message = SimpleMessage()
    self.assertFalse(simple_message.is_initialized())
    nested_message = NestedMessage(simple=simple_message)
    self.assertFalse(nested_message.is_initialized())

    simple_message.required = 10

    self.assertTrue(simple_message.is_initialized())
    self.assertTrue(nested_message.is_initialized()) 
Example #17
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testStrictAssignment(self):
    """Tests that cannot assign to unknown or non-reserved attributes."""
    class SimpleMessage(messages.Message):
      field = messages.IntegerField(1)

    simple_message = SimpleMessage()
    self.assertRaises(AttributeError,
                      setattr,
                      simple_message,
                      'does_not_exist',
                      10) 
Example #18
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testValidate_Required(self):
    """Tests validation of required fields."""
    class SimpleMessage(messages.Message):
      required = messages.IntegerField(1, required=True)

    simple_message = SimpleMessage()
    self.assertRaises(messages.ValidationError,
                      simple_message.check_initialized)
    simple_message.required = 10
    simple_message.check_initialized() 
Example #19
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testIsInitialized(self):
    """Tests is_initialized."""
    class SimpleMessage(messages.Message):
      required = messages.IntegerField(1, required=True)

    simple_message = SimpleMessage()
    self.assertFalse(simple_message.is_initialized())

    simple_message.required = 10

    self.assertTrue(simple_message.is_initialized()) 
Example #20
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testListAssignmentDoesNotCopy(self):
    class SimpleMessage(messages.Message):
      repeated = messages.IntegerField(1, repeated=True)

    message = SimpleMessage()
    original = message.repeated
    message.repeated = []
    self.assertFalse(original is message.repeated) 
Example #21
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testMessageFieldValidate_Initialized(self):
    """Test validation on message field."""
    class MyMessage(messages.Message):
      field1 = messages.IntegerField(1, required=True)

    field = messages.MessageField(MyMessage, 10)

    # Will validate messages where is_initialized() is False.
    message = MyMessage()
    field.validate(message)
    message.field1 = 20
    field.validate(message) 
Example #22
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testSameNumbers(self):
    """Test that cannot assign two fields with same numbers."""

    def action():
      class BadMessage(messages.Message):
        f1 = messages.IntegerField(1)
        f2 = messages.IntegerField(1)
    self.assertRaises(messages.DuplicateNumberError,
                      action) 
Example #23
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def CreateMessageClass(self):
    """Creates a simple message class with 3 fields.

    Fields are defined in alphabetical order but with conflicting numeric
    order.
    """
    class ComplexMessage(messages.Message):
      a3 = messages.IntegerField(3)
      b1 = messages.StringField(1)
      c2 = messages.StringField(2)

    return ComplexMessage 
Example #24
Source File: protobuf_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testUnrecognizedFieldWrongFormat(self):
    """Test that unrecognized fields in the wrong format are skipped."""

    class SimpleMessage(messages.Message):
      value = messages.IntegerField(1)

    message = SimpleMessage(value=3)
    message.set_unrecognized_field('from_json', 'test', messages.Variant.STRING)

    encoded = protobuf.encode_message(message)
    expected = (
        chr((1 << protobuf._WIRE_TYPE_BITS) | protobuf._Encoder.NUMERIC) +
        chr(3))
    self.assertEquals(encoded, expected) 
Example #25
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testInitializeNestedFieldFromDict(self):
    """Tests initializing nested fields from dict."""
    class SimpleMessage(messages.Message):
      required = messages.IntegerField(1, required=True)

    class NestedMessage(messages.Message):
      simple = messages.MessageField(SimpleMessage, 1)

    class RepeatedMessage(messages.Message):
      simple = messages.MessageField(SimpleMessage, 1, repeated=True)

    nested_message1 = NestedMessage(simple={'required': 10})
    self.assertTrue(nested_message1.is_initialized())
    self.assertTrue(nested_message1.simple.is_initialized())

    nested_message2 = NestedMessage()
    nested_message2.simple = {'required': 10}
    self.assertTrue(nested_message2.is_initialized())
    self.assertTrue(nested_message2.simple.is_initialized())

    repeated_values = [{}, {'required': 10}, SimpleMessage(required=20)]

    repeated_message1 = RepeatedMessage(simple=repeated_values)
    self.assertEquals(3, len(repeated_message1.simple))
    self.assertFalse(repeated_message1.is_initialized())

    repeated_message1.simple[0].required = 0
    self.assertTrue(repeated_message1.is_initialized())

    repeated_message2 = RepeatedMessage()
    repeated_message2.simple = repeated_values
    self.assertEquals(3, len(repeated_message2.simple))
    self.assertFalse(repeated_message2.is_initialized())

    repeated_message2.simple[0].required = 0
    self.assertTrue(repeated_message2.is_initialized()) 
Example #26
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testUnrecognizedFieldInvalidVariant(self):
    class MyMessage(messages.Message):
      field1 = messages.IntegerField(1)

    message1 = MyMessage()
    self.assertRaises(TypeError, message1.set_unrecognized_field, 'unknown4',
                      {'unhandled': 'type'}, None)
    self.assertRaises(TypeError, message1.set_unrecognized_field, 'unknown4',
                      {'unhandled': 'type'}, 123) 
Example #27
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testRepr(self):
    """Test represtation of Message object."""
    class MyMessage(messages.Message):
      integer_value = messages.IntegerField(1)
      string_value = messages.StringField(2)
      unassigned = messages.StringField(3)
      unassigned_with_default = messages.StringField(4, default=u'a default')

    my_message = MyMessage()
    my_message.integer_value = 42
    my_message.string_value = u'A string'

    pat = re.compile(r"<MyMessage\n integer_value: 42\n"
                      " string_value: [u]?'A string'>")
    self.assertTrue(pat.match(repr(my_message)) is not None) 
Example #28
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testConstructorKwargs(self):
    """Test kwargs via constructor."""
    class SomeMessage(messages.Message):
      name = messages.StringField(1)
      number = messages.IntegerField(2)

    expected = SomeMessage()
    expected.name = 'my name'
    expected.number = 200
    self.assertEquals(expected, SomeMessage(name='my name', number=200)) 
Example #29
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testCompareAutoInitializedRepeatedFields(self):
    class SomeMessage(messages.Message):
      repeated = messages.IntegerField(1, repeated=True)

    message1 = SomeMessage(repeated=[])
    message2 = SomeMessage()
    self.assertEquals(message1, message2) 
Example #30
Source File: messages_test.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def testPickle(self):
    """Testing pickling and unpickling of Message instances."""
    global MyEnum
    global AnotherMessage
    global MyMessage

    class MyEnum(messages.Enum):
      val1 = 1
      val2 = 2

    class AnotherMessage(messages.Message):
      string = messages.StringField(1, repeated=True)

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

    message = MyMessage(field1=1, field2=MyEnum.val2,
                        field3=AnotherMessage(string=['a', 'b', 'c']))
    message.set_unrecognized_field('exists', 'value', messages.Variant.STRING)
    message.set_unrecognized_field('repeated', ['list', 0, ('test',)],
                                   messages.Variant.STRING)
    unpickled = pickle.loads(pickle.dumps(message))
    self.assertEquals(message, unpickled)
    self.assertTrue(AnotherMessage.string is unpickled.field3.string.field)
    self.assertTrue('exists' in message.all_unrecognized_fields())
    self.assertEquals(('value', messages.Variant.STRING),
                      message.get_unrecognized_field_info('exists'))
    self.assertEquals((['list', 0, ('test',)], messages.Variant.STRING),
                      message.get_unrecognized_field_info('repeated'))