OLD | NEW |
1 #! /usr/bin/env python | 1 #! /usr/bin/env python |
2 # -*- coding: utf-8 -*- | 2 # -*- coding: utf-8 -*- |
3 # | 3 # |
4 # Protocol Buffers - Google's data interchange format | 4 # Protocol Buffers - Google's data interchange format |
5 # Copyright 2008 Google Inc. All rights reserved. | 5 # Copyright 2008 Google Inc. All rights reserved. |
6 # https://developers.google.com/protocol-buffers/ | 6 # https://developers.google.com/protocol-buffers/ |
7 # | 7 # |
8 # Redistribution and use in source and binary forms, with or without | 8 # Redistribution and use in source and binary forms, with or without |
9 # modification, are permitted provided that the following conditions are | 9 # modification, are permitted provided that the following conditions are |
10 # met: | 10 # met: |
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
53 from google.protobuf import descriptor | 53 from google.protobuf import descriptor |
54 from google.protobuf import message | 54 from google.protobuf import message |
55 from google.protobuf import reflection | 55 from google.protobuf import reflection |
56 from google.protobuf import text_format | 56 from google.protobuf import text_format |
57 from google.protobuf.internal import api_implementation | 57 from google.protobuf.internal import api_implementation |
58 from google.protobuf.internal import more_extensions_pb2 | 58 from google.protobuf.internal import more_extensions_pb2 |
59 from google.protobuf.internal import more_messages_pb2 | 59 from google.protobuf.internal import more_messages_pb2 |
60 from google.protobuf.internal import message_set_extensions_pb2 | 60 from google.protobuf.internal import message_set_extensions_pb2 |
61 from google.protobuf.internal import wire_format | 61 from google.protobuf.internal import wire_format |
62 from google.protobuf.internal import test_util | 62 from google.protobuf.internal import test_util |
| 63 from google.protobuf.internal import testing_refleaks |
63 from google.protobuf.internal import decoder | 64 from google.protobuf.internal import decoder |
64 | 65 |
65 | 66 |
| 67 BaseTestCase = testing_refleaks.BaseTestCase |
| 68 |
| 69 |
66 class _MiniDecoder(object): | 70 class _MiniDecoder(object): |
67 """Decodes a stream of values from a string. | 71 """Decodes a stream of values from a string. |
68 | 72 |
69 Once upon a time we actually had a class called decoder.Decoder. Then we | 73 Once upon a time we actually had a class called decoder.Decoder. Then we |
70 got rid of it during a redesign that made decoding much, much faster overall. | 74 got rid of it during a redesign that made decoding much, much faster overall. |
71 But a couple tests in this file used it to check that the serialized form of | 75 But a couple tests in this file used it to check that the serialized form of |
72 a message was correct. So, this class implements just the methods that were | 76 a message was correct. So, this class implements just the methods that were |
73 used by said tests, so that we don't have to rewrite the tests. | 77 used by said tests, so that we don't have to rewrite the tests. |
74 """ | 78 """ |
75 | 79 |
(...skipping 12 matching lines...) Expand all Loading... |
88 | 92 |
89 def ReadSInt64(self): | 93 def ReadSInt64(self): |
90 return wire_format.ZigZagDecode(self.ReadVarint()) | 94 return wire_format.ZigZagDecode(self.ReadVarint()) |
91 | 95 |
92 ReadSInt32 = ReadSInt64 | 96 ReadSInt32 = ReadSInt64 |
93 | 97 |
94 def ReadFieldNumberAndWireType(self): | 98 def ReadFieldNumberAndWireType(self): |
95 return wire_format.UnpackTag(self.ReadVarint()) | 99 return wire_format.UnpackTag(self.ReadVarint()) |
96 | 100 |
97 def ReadFloat(self): | 101 def ReadFloat(self): |
98 result = struct.unpack("<f", self._bytes[self._pos:self._pos+4])[0] | 102 result = struct.unpack('<f', self._bytes[self._pos:self._pos+4])[0] |
99 self._pos += 4 | 103 self._pos += 4 |
100 return result | 104 return result |
101 | 105 |
102 def ReadDouble(self): | 106 def ReadDouble(self): |
103 result = struct.unpack("<d", self._bytes[self._pos:self._pos+8])[0] | 107 result = struct.unpack('<d', self._bytes[self._pos:self._pos+8])[0] |
104 self._pos += 8 | 108 self._pos += 8 |
105 return result | 109 return result |
106 | 110 |
107 def EndOfStream(self): | 111 def EndOfStream(self): |
108 return self._pos == len(self._bytes) | 112 return self._pos == len(self._bytes) |
109 | 113 |
110 | 114 |
111 class ReflectionTest(unittest.TestCase): | 115 class ReflectionTest(BaseTestCase): |
112 | 116 |
113 def assertListsEqual(self, values, others): | 117 def assertListsEqual(self, values, others): |
114 self.assertEqual(len(values), len(others)) | 118 self.assertEqual(len(values), len(others)) |
115 for i in range(len(values)): | 119 for i in range(len(values)): |
116 self.assertEqual(values[i], others[i]) | 120 self.assertEqual(values[i], others[i]) |
117 | 121 |
118 def testScalarConstructor(self): | 122 def testScalarConstructor(self): |
119 # Constructor with only scalar types should succeed. | 123 # Constructor with only scalar types should succeed. |
120 proto = unittest_pb2.TestAllTypes( | 124 proto = unittest_pb2.TestAllTypes( |
121 optional_int32=24, | 125 optional_int32=24, |
(...skipping 488 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
610 # proto.nonexistent_field = 23 should fail as well. | 614 # proto.nonexistent_field = 23 should fail as well. |
611 self.assertRaises(AttributeError, setattr, proto, 'nonexistent_field', 23) | 615 self.assertRaises(AttributeError, setattr, proto, 'nonexistent_field', 23) |
612 | 616 |
613 def testSingleScalarTypeSafety(self): | 617 def testSingleScalarTypeSafety(self): |
614 proto = unittest_pb2.TestAllTypes() | 618 proto = unittest_pb2.TestAllTypes() |
615 self.assertRaises(TypeError, setattr, proto, 'optional_int32', 1.1) | 619 self.assertRaises(TypeError, setattr, proto, 'optional_int32', 1.1) |
616 self.assertRaises(TypeError, setattr, proto, 'optional_int32', 'foo') | 620 self.assertRaises(TypeError, setattr, proto, 'optional_int32', 'foo') |
617 self.assertRaises(TypeError, setattr, proto, 'optional_string', 10) | 621 self.assertRaises(TypeError, setattr, proto, 'optional_string', 10) |
618 self.assertRaises(TypeError, setattr, proto, 'optional_bytes', 10) | 622 self.assertRaises(TypeError, setattr, proto, 'optional_bytes', 10) |
619 | 623 |
620 def testIntegerTypes(self): | 624 def assertIntegerTypes(self, integer_fn): |
| 625 """Verifies setting of scalar integers. |
| 626 |
| 627 Args: |
| 628 integer_fn: A function to wrap the integers that will be assigned. |
| 629 """ |
621 def TestGetAndDeserialize(field_name, value, expected_type): | 630 def TestGetAndDeserialize(field_name, value, expected_type): |
622 proto = unittest_pb2.TestAllTypes() | 631 proto = unittest_pb2.TestAllTypes() |
| 632 value = integer_fn(value) |
623 setattr(proto, field_name, value) | 633 setattr(proto, field_name, value) |
624 self.assertIsInstance(getattr(proto, field_name), expected_type) | 634 self.assertIsInstance(getattr(proto, field_name), expected_type) |
625 proto2 = unittest_pb2.TestAllTypes() | 635 proto2 = unittest_pb2.TestAllTypes() |
626 proto2.ParseFromString(proto.SerializeToString()) | 636 proto2.ParseFromString(proto.SerializeToString()) |
627 self.assertIsInstance(getattr(proto2, field_name), expected_type) | 637 self.assertIsInstance(getattr(proto2, field_name), expected_type) |
628 | 638 |
629 TestGetAndDeserialize('optional_int32', 1, int) | 639 TestGetAndDeserialize('optional_int32', 1, int) |
630 TestGetAndDeserialize('optional_int32', 1 << 30, int) | 640 TestGetAndDeserialize('optional_int32', 1 << 30, int) |
631 TestGetAndDeserialize('optional_uint32', 1 << 30, int) | 641 TestGetAndDeserialize('optional_uint32', 1 << 30, int) |
632 try: | 642 try: |
633 integer_64 = long | 643 integer_64 = long |
634 except NameError: # Python3 | 644 except NameError: # Python3 |
635 integer_64 = int | 645 integer_64 = int |
636 if struct.calcsize('L') == 4: | 646 if struct.calcsize('L') == 4: |
637 # Python only has signed ints, so 32-bit python can't fit an uint32 | 647 # Python only has signed ints, so 32-bit python can't fit an uint32 |
638 # in an int. | 648 # in an int. |
639 TestGetAndDeserialize('optional_uint32', 1 << 31, long) | 649 TestGetAndDeserialize('optional_uint32', 1 << 31, integer_64) |
640 else: | 650 else: |
641 # 64-bit python can fit uint32 inside an int | 651 # 64-bit python can fit uint32 inside an int |
642 TestGetAndDeserialize('optional_uint32', 1 << 31, int) | 652 TestGetAndDeserialize('optional_uint32', 1 << 31, int) |
643 TestGetAndDeserialize('optional_int64', 1 << 30, integer_64) | 653 TestGetAndDeserialize('optional_int64', 1 << 30, integer_64) |
644 TestGetAndDeserialize('optional_int64', 1 << 60, integer_64) | 654 TestGetAndDeserialize('optional_int64', 1 << 60, integer_64) |
645 TestGetAndDeserialize('optional_uint64', 1 << 30, integer_64) | 655 TestGetAndDeserialize('optional_uint64', 1 << 30, integer_64) |
646 TestGetAndDeserialize('optional_uint64', 1 << 60, integer_64) | 656 TestGetAndDeserialize('optional_uint64', 1 << 60, integer_64) |
647 | 657 |
648 def testSingleScalarBoundsChecking(self): | 658 def testIntegerTypes(self): |
| 659 self.assertIntegerTypes(lambda x: x) |
| 660 |
| 661 def testNonStandardIntegerTypes(self): |
| 662 self.assertIntegerTypes(test_util.NonStandardInteger) |
| 663 |
| 664 def testIllegalValuesForIntegers(self): |
| 665 pb = unittest_pb2.TestAllTypes() |
| 666 |
| 667 # Strings are illegal, even when the represent an integer. |
| 668 with self.assertRaises(TypeError): |
| 669 pb.optional_uint64 = '2' |
| 670 |
| 671 # The exact error should propagate with a poorly written custom integer. |
| 672 with self.assertRaisesRegexp(RuntimeError, 'my_error'): |
| 673 pb.optional_uint64 = test_util.NonStandardInteger(5, 'my_error') |
| 674 |
| 675 def assetIntegerBoundsChecking(self, integer_fn): |
| 676 """Verifies bounds checking for scalar integer fields. |
| 677 |
| 678 Args: |
| 679 integer_fn: A function to wrap the integers that will be assigned. |
| 680 """ |
649 def TestMinAndMaxIntegers(field_name, expected_min, expected_max): | 681 def TestMinAndMaxIntegers(field_name, expected_min, expected_max): |
650 pb = unittest_pb2.TestAllTypes() | 682 pb = unittest_pb2.TestAllTypes() |
| 683 expected_min = integer_fn(expected_min) |
| 684 expected_max = integer_fn(expected_max) |
651 setattr(pb, field_name, expected_min) | 685 setattr(pb, field_name, expected_min) |
652 self.assertEqual(expected_min, getattr(pb, field_name)) | 686 self.assertEqual(expected_min, getattr(pb, field_name)) |
653 setattr(pb, field_name, expected_max) | 687 setattr(pb, field_name, expected_max) |
654 self.assertEqual(expected_max, getattr(pb, field_name)) | 688 self.assertEqual(expected_max, getattr(pb, field_name)) |
655 self.assertRaises(ValueError, setattr, pb, field_name, expected_min - 1) | 689 self.assertRaises(ValueError, setattr, pb, field_name, expected_min - 1) |
656 self.assertRaises(ValueError, setattr, pb, field_name, expected_max + 1) | 690 self.assertRaises(ValueError, setattr, pb, field_name, expected_max + 1) |
657 | 691 |
658 TestMinAndMaxIntegers('optional_int32', -(1 << 31), (1 << 31) - 1) | 692 TestMinAndMaxIntegers('optional_int32', -(1 << 31), (1 << 31) - 1) |
659 TestMinAndMaxIntegers('optional_uint32', 0, 0xffffffff) | 693 TestMinAndMaxIntegers('optional_uint32', 0, 0xffffffff) |
660 TestMinAndMaxIntegers('optional_int64', -(1 << 63), (1 << 63) - 1) | 694 TestMinAndMaxIntegers('optional_int64', -(1 << 63), (1 << 63) - 1) |
661 TestMinAndMaxIntegers('optional_uint64', 0, 0xffffffffffffffff) | 695 TestMinAndMaxIntegers('optional_uint64', 0, 0xffffffffffffffff) |
| 696 # A bit of white-box testing since -1 is an int and not a long in C++ and |
| 697 # so goes down a different path. |
| 698 pb = unittest_pb2.TestAllTypes() |
| 699 with self.assertRaises(ValueError): |
| 700 pb.optional_uint64 = integer_fn(-(1 << 63)) |
662 | 701 |
663 pb = unittest_pb2.TestAllTypes() | 702 pb = unittest_pb2.TestAllTypes() |
664 pb.optional_nested_enum = 1 | 703 pb.optional_nested_enum = integer_fn(1) |
665 self.assertEqual(1, pb.optional_nested_enum) | 704 self.assertEqual(1, pb.optional_nested_enum) |
666 | 705 |
| 706 def testSingleScalarBoundsChecking(self): |
| 707 self.assetIntegerBoundsChecking(lambda x: x) |
| 708 |
| 709 def testNonStandardSingleScalarBoundsChecking(self): |
| 710 self.assetIntegerBoundsChecking(test_util.NonStandardInteger) |
| 711 |
667 def testRepeatedScalarTypeSafety(self): | 712 def testRepeatedScalarTypeSafety(self): |
668 proto = unittest_pb2.TestAllTypes() | 713 proto = unittest_pb2.TestAllTypes() |
669 self.assertRaises(TypeError, proto.repeated_int32.append, 1.1) | 714 self.assertRaises(TypeError, proto.repeated_int32.append, 1.1) |
670 self.assertRaises(TypeError, proto.repeated_int32.append, 'foo') | 715 self.assertRaises(TypeError, proto.repeated_int32.append, 'foo') |
671 self.assertRaises(TypeError, proto.repeated_string, 10) | 716 self.assertRaises(TypeError, proto.repeated_string, 10) |
672 self.assertRaises(TypeError, proto.repeated_bytes, 10) | 717 self.assertRaises(TypeError, proto.repeated_bytes, 10) |
673 | 718 |
674 proto.repeated_int32.append(10) | 719 proto.repeated_int32.append(10) |
675 proto.repeated_int32[0] = 23 | 720 proto.repeated_int32[0] = 23 |
676 self.assertRaises(IndexError, proto.repeated_int32.__setitem__, 500, 23) | 721 self.assertRaises(IndexError, proto.repeated_int32.__setitem__, 500, 23) |
(...skipping 288 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
965 | 1010 |
966 # Test clearing. | 1011 # Test clearing. |
967 proto.ClearField('repeated_nested_message') | 1012 proto.ClearField('repeated_nested_message') |
968 self.assertTrue(not proto.repeated_nested_message) | 1013 self.assertTrue(not proto.repeated_nested_message) |
969 self.assertEqual(0, len(proto.repeated_nested_message)) | 1014 self.assertEqual(0, len(proto.repeated_nested_message)) |
970 | 1015 |
971 # Test constructing an element while adding it. | 1016 # Test constructing an element while adding it. |
972 proto.repeated_nested_message.add(bb=23) | 1017 proto.repeated_nested_message.add(bb=23) |
973 self.assertEqual(1, len(proto.repeated_nested_message)) | 1018 self.assertEqual(1, len(proto.repeated_nested_message)) |
974 self.assertEqual(23, proto.repeated_nested_message[0].bb) | 1019 self.assertEqual(23, proto.repeated_nested_message[0].bb) |
| 1020 self.assertRaises(TypeError, proto.repeated_nested_message.add, 23) |
975 | 1021 |
976 def testRepeatedCompositeRemove(self): | 1022 def testRepeatedCompositeRemove(self): |
977 proto = unittest_pb2.TestAllTypes() | 1023 proto = unittest_pb2.TestAllTypes() |
978 | 1024 |
979 self.assertEqual(0, len(proto.repeated_nested_message)) | 1025 self.assertEqual(0, len(proto.repeated_nested_message)) |
980 m0 = proto.repeated_nested_message.add() | 1026 m0 = proto.repeated_nested_message.add() |
981 # Need to set some differentiating variable so m0 != m1 != m2: | 1027 # Need to set some differentiating variable so m0 != m1 != m2: |
982 m0.bb = len(proto.repeated_nested_message) | 1028 m0.bb = len(proto.repeated_nested_message) |
983 m1 = proto.repeated_nested_message.add() | 1029 m1 = proto.repeated_nested_message.add() |
984 m1.bb = len(proto.repeated_nested_message) | 1030 m1.bb = len(proto.repeated_nested_message) |
(...skipping 190 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1175 self.assertEqual(0, required.a) | 1221 self.assertEqual(0, required.a) |
1176 self.assertTrue(not extendee_proto.HasExtension(extension)) | 1222 self.assertTrue(not extendee_proto.HasExtension(extension)) |
1177 required.a = 23 | 1223 required.a = 23 |
1178 self.assertEqual(23, extendee_proto.Extensions[extension].a) | 1224 self.assertEqual(23, extendee_proto.Extensions[extension].a) |
1179 self.assertTrue(extendee_proto.HasExtension(extension)) | 1225 self.assertTrue(extendee_proto.HasExtension(extension)) |
1180 extendee_proto.ClearExtension(extension) | 1226 extendee_proto.ClearExtension(extension) |
1181 self.assertTrue(required is not extendee_proto.Extensions[extension]) | 1227 self.assertTrue(required is not extendee_proto.Extensions[extension]) |
1182 self.assertTrue(not extendee_proto.HasExtension(extension)) | 1228 self.assertTrue(not extendee_proto.HasExtension(extension)) |
1183 | 1229 |
1184 def testRegisteredExtensions(self): | 1230 def testRegisteredExtensions(self): |
1185 self.assertTrue('protobuf_unittest.optional_int32_extension' in | 1231 pool = unittest_pb2.DESCRIPTOR.pool |
1186 unittest_pb2.TestAllExtensions._extensions_by_name) | 1232 self.assertTrue( |
1187 self.assertTrue(1 in unittest_pb2.TestAllExtensions._extensions_by_number) | 1233 pool.FindExtensionByNumber( |
| 1234 unittest_pb2.TestAllExtensions.DESCRIPTOR, 1)) |
| 1235 self.assertIs( |
| 1236 pool.FindExtensionByName( |
| 1237 'protobuf_unittest.optional_int32_extension').containing_type, |
| 1238 unittest_pb2.TestAllExtensions.DESCRIPTOR) |
1188 # Make sure extensions haven't been registered into types that shouldn't | 1239 # Make sure extensions haven't been registered into types that shouldn't |
1189 # have any. | 1240 # have any. |
1190 self.assertEqual(0, len(unittest_pb2.TestAllTypes._extensions_by_name)) | 1241 self.assertEqual(0, len( |
| 1242 pool.FindAllExtensions(unittest_pb2.TestAllTypes.DESCRIPTOR))) |
1191 | 1243 |
1192 # If message A directly contains message B, and | 1244 # If message A directly contains message B, and |
1193 # a.HasField('b') is currently False, then mutating any | 1245 # a.HasField('b') is currently False, then mutating any |
1194 # extension in B should change a.HasField('b') to True | 1246 # extension in B should change a.HasField('b') to True |
1195 # (and so on up the object tree). | 1247 # (and so on up the object tree). |
1196 def testHasBitsForAncestorsOfExtendedMessage(self): | 1248 def testHasBitsForAncestorsOfExtendedMessage(self): |
1197 # Optional scalar extension. | 1249 # Optional scalar extension. |
1198 toplevel = more_extensions_pb2.TopLevelMessage() | 1250 toplevel = more_extensions_pb2.TopLevelMessage() |
1199 self.assertTrue(not toplevel.HasField('submessage')) | 1251 self.assertTrue(not toplevel.HasField('submessage')) |
1200 self.assertEqual(0, toplevel.submessage.Extensions[ | 1252 self.assertEqual(0, toplevel.submessage.Extensions[ |
(...skipping 343 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1544 self.assertTrue(foreign is not proto.optional_foreign_message) | 1596 self.assertTrue(foreign is not proto.optional_foreign_message) |
1545 self.assertEqual(5, nested.bb) | 1597 self.assertEqual(5, nested.bb) |
1546 self.assertEqual(6, foreign.c) | 1598 self.assertEqual(6, foreign.c) |
1547 nested.bb = 15 | 1599 nested.bb = 15 |
1548 foreign.c = 16 | 1600 foreign.c = 16 |
1549 self.assertFalse(proto.HasField('optional_nested_message')) | 1601 self.assertFalse(proto.HasField('optional_nested_message')) |
1550 self.assertEqual(0, proto.optional_nested_message.bb) | 1602 self.assertEqual(0, proto.optional_nested_message.bb) |
1551 self.assertFalse(proto.HasField('optional_foreign_message')) | 1603 self.assertFalse(proto.HasField('optional_foreign_message')) |
1552 self.assertEqual(0, proto.optional_foreign_message.c) | 1604 self.assertEqual(0, proto.optional_foreign_message.c) |
1553 | 1605 |
| 1606 def testDisconnectingInOneof(self): |
| 1607 m = unittest_pb2.TestOneof2() # This message has two messages in a oneof. |
| 1608 m.foo_message.qux_int = 5 |
| 1609 sub_message = m.foo_message |
| 1610 # Accessing another message's field does not clear the first one |
| 1611 self.assertEqual(m.foo_lazy_message.qux_int, 0) |
| 1612 self.assertEqual(m.foo_message.qux_int, 5) |
| 1613 # But mutating another message in the oneof detaches the first one. |
| 1614 m.foo_lazy_message.qux_int = 6 |
| 1615 self.assertEqual(m.foo_message.qux_int, 0) |
| 1616 # The reference we got above was detached and is still valid. |
| 1617 self.assertEqual(sub_message.qux_int, 5) |
| 1618 sub_message.qux_int = 7 |
| 1619 |
1554 def testOneOf(self): | 1620 def testOneOf(self): |
1555 proto = unittest_pb2.TestAllTypes() | 1621 proto = unittest_pb2.TestAllTypes() |
1556 proto.oneof_uint32 = 10 | 1622 proto.oneof_uint32 = 10 |
1557 proto.oneof_nested_message.bb = 11 | 1623 proto.oneof_nested_message.bb = 11 |
1558 self.assertEqual(11, proto.oneof_nested_message.bb) | 1624 self.assertEqual(11, proto.oneof_nested_message.bb) |
1559 self.assertFalse(proto.HasField('oneof_uint32')) | 1625 self.assertFalse(proto.HasField('oneof_uint32')) |
1560 nested = proto.oneof_nested_message | 1626 nested = proto.oneof_nested_message |
1561 proto.oneof_string = 'abc' | 1627 proto.oneof_string = 'abc' |
1562 self.assertEqual('abc', proto.oneof_string) | 1628 self.assertEqual('abc', proto.oneof_string) |
1563 self.assertEqual(11, nested.bb) | 1629 self.assertEqual(11, nested.bb) |
(...skipping 238 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1802 from google.protobuf.internal import import_test_package | 1868 from google.protobuf.internal import import_test_package |
1803 # pylint: enable=g-import-not-at-top | 1869 # pylint: enable=g-import-not-at-top |
1804 msg = import_test_package.myproto.Outer() | 1870 msg = import_test_package.myproto.Outer() |
1805 # Just check the default value. | 1871 # Just check the default value. |
1806 self.assertEqual(57, msg.inner.value) | 1872 self.assertEqual(57, msg.inner.value) |
1807 | 1873 |
1808 # Since we had so many tests for protocol buffer equality, we broke these out | 1874 # Since we had so many tests for protocol buffer equality, we broke these out |
1809 # into separate TestCase classes. | 1875 # into separate TestCase classes. |
1810 | 1876 |
1811 | 1877 |
1812 class TestAllTypesEqualityTest(unittest.TestCase): | 1878 class TestAllTypesEqualityTest(BaseTestCase): |
1813 | 1879 |
1814 def setUp(self): | 1880 def setUp(self): |
1815 self.first_proto = unittest_pb2.TestAllTypes() | 1881 self.first_proto = unittest_pb2.TestAllTypes() |
1816 self.second_proto = unittest_pb2.TestAllTypes() | 1882 self.second_proto = unittest_pb2.TestAllTypes() |
1817 | 1883 |
1818 def testNotHashable(self): | 1884 def testNotHashable(self): |
1819 self.assertRaises(TypeError, hash, self.first_proto) | 1885 self.assertRaises(TypeError, hash, self.first_proto) |
1820 | 1886 |
1821 def testSelfEquality(self): | 1887 def testSelfEquality(self): |
1822 self.assertEqual(self.first_proto, self.first_proto) | 1888 self.assertEqual(self.first_proto, self.first_proto) |
1823 | 1889 |
1824 def testEmptyProtosEqual(self): | 1890 def testEmptyProtosEqual(self): |
1825 self.assertEqual(self.first_proto, self.second_proto) | 1891 self.assertEqual(self.first_proto, self.second_proto) |
1826 | 1892 |
1827 | 1893 |
1828 class FullProtosEqualityTest(unittest.TestCase): | 1894 class FullProtosEqualityTest(BaseTestCase): |
1829 | 1895 |
1830 """Equality tests using completely-full protos as a starting point.""" | 1896 """Equality tests using completely-full protos as a starting point.""" |
1831 | 1897 |
1832 def setUp(self): | 1898 def setUp(self): |
1833 self.first_proto = unittest_pb2.TestAllTypes() | 1899 self.first_proto = unittest_pb2.TestAllTypes() |
1834 self.second_proto = unittest_pb2.TestAllTypes() | 1900 self.second_proto = unittest_pb2.TestAllTypes() |
1835 test_util.SetAllFields(self.first_proto) | 1901 test_util.SetAllFields(self.first_proto) |
1836 test_util.SetAllFields(self.second_proto) | 1902 test_util.SetAllFields(self.second_proto) |
1837 | 1903 |
1838 def testNotHashable(self): | 1904 def testNotHashable(self): |
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1904 # Ensure that we test "has" bits as well as value for | 1970 # Ensure that we test "has" bits as well as value for |
1905 # nonrepeated composite field. | 1971 # nonrepeated composite field. |
1906 self.first_proto.ClearField('optional_nested_message') | 1972 self.first_proto.ClearField('optional_nested_message') |
1907 self.second_proto.optional_nested_message.ClearField('bb') | 1973 self.second_proto.optional_nested_message.ClearField('bb') |
1908 self.assertNotEqual(self.first_proto, self.second_proto) | 1974 self.assertNotEqual(self.first_proto, self.second_proto) |
1909 self.first_proto.optional_nested_message.bb = 0 | 1975 self.first_proto.optional_nested_message.bb = 0 |
1910 self.first_proto.optional_nested_message.ClearField('bb') | 1976 self.first_proto.optional_nested_message.ClearField('bb') |
1911 self.assertEqual(self.first_proto, self.second_proto) | 1977 self.assertEqual(self.first_proto, self.second_proto) |
1912 | 1978 |
1913 | 1979 |
1914 class ExtensionEqualityTest(unittest.TestCase): | 1980 class ExtensionEqualityTest(BaseTestCase): |
1915 | 1981 |
1916 def testExtensionEquality(self): | 1982 def testExtensionEquality(self): |
1917 first_proto = unittest_pb2.TestAllExtensions() | 1983 first_proto = unittest_pb2.TestAllExtensions() |
1918 second_proto = unittest_pb2.TestAllExtensions() | 1984 second_proto = unittest_pb2.TestAllExtensions() |
1919 self.assertEqual(first_proto, second_proto) | 1985 self.assertEqual(first_proto, second_proto) |
1920 test_util.SetAllExtensions(first_proto) | 1986 test_util.SetAllExtensions(first_proto) |
1921 self.assertNotEqual(first_proto, second_proto) | 1987 self.assertNotEqual(first_proto, second_proto) |
1922 test_util.SetAllExtensions(second_proto) | 1988 test_util.SetAllExtensions(second_proto) |
1923 self.assertEqual(first_proto, second_proto) | 1989 self.assertEqual(first_proto, second_proto) |
1924 | 1990 |
(...skipping 12 matching lines...) Expand all Loading... |
1937 | 2003 |
1938 # Ensure that differences in cached values | 2004 # Ensure that differences in cached values |
1939 # don't matter if "has" bits are both false. | 2005 # don't matter if "has" bits are both false. |
1940 first_proto = unittest_pb2.TestAllExtensions() | 2006 first_proto = unittest_pb2.TestAllExtensions() |
1941 second_proto = unittest_pb2.TestAllExtensions() | 2007 second_proto = unittest_pb2.TestAllExtensions() |
1942 self.assertEqual( | 2008 self.assertEqual( |
1943 0, first_proto.Extensions[unittest_pb2.optional_int32_extension]) | 2009 0, first_proto.Extensions[unittest_pb2.optional_int32_extension]) |
1944 self.assertEqual(first_proto, second_proto) | 2010 self.assertEqual(first_proto, second_proto) |
1945 | 2011 |
1946 | 2012 |
1947 class MutualRecursionEqualityTest(unittest.TestCase): | 2013 class MutualRecursionEqualityTest(BaseTestCase): |
1948 | 2014 |
1949 def testEqualityWithMutualRecursion(self): | 2015 def testEqualityWithMutualRecursion(self): |
1950 first_proto = unittest_pb2.TestMutualRecursionA() | 2016 first_proto = unittest_pb2.TestMutualRecursionA() |
1951 second_proto = unittest_pb2.TestMutualRecursionA() | 2017 second_proto = unittest_pb2.TestMutualRecursionA() |
1952 self.assertEqual(first_proto, second_proto) | 2018 self.assertEqual(first_proto, second_proto) |
1953 first_proto.bb.a.bb.optional_int32 = 23 | 2019 first_proto.bb.a.bb.optional_int32 = 23 |
1954 self.assertNotEqual(first_proto, second_proto) | 2020 self.assertNotEqual(first_proto, second_proto) |
1955 second_proto.bb.a.bb.optional_int32 = 23 | 2021 second_proto.bb.a.bb.optional_int32 = 23 |
1956 self.assertEqual(first_proto, second_proto) | 2022 self.assertEqual(first_proto, second_proto) |
1957 | 2023 |
1958 | 2024 |
1959 class ByteSizeTest(unittest.TestCase): | 2025 class ByteSizeTest(BaseTestCase): |
1960 | 2026 |
1961 def setUp(self): | 2027 def setUp(self): |
1962 self.proto = unittest_pb2.TestAllTypes() | 2028 self.proto = unittest_pb2.TestAllTypes() |
1963 self.extended_proto = more_extensions_pb2.ExtendedMessage() | 2029 self.extended_proto = more_extensions_pb2.ExtendedMessage() |
1964 self.packed_proto = unittest_pb2.TestPackedTypes() | 2030 self.packed_proto = unittest_pb2.TestPackedTypes() |
1965 self.packed_extended_proto = unittest_pb2.TestPackedExtensions() | 2031 self.packed_extended_proto = unittest_pb2.TestPackedExtensions() |
1966 | 2032 |
1967 def Size(self): | 2033 def Size(self): |
1968 return self.proto.ByteSize() | 2034 return self.proto.ByteSize() |
1969 | 2035 |
(...skipping 275 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2245 # * Handling of unrecognized tags ("uninterpreted_bytes"). | 2311 # * Handling of unrecognized tags ("uninterpreted_bytes"). |
2246 # * Handling of MessageSets. | 2312 # * Handling of MessageSets. |
2247 # * Consistent ordering of tags in the wire format, | 2313 # * Consistent ordering of tags in the wire format, |
2248 # including ordering between extensions and non-extension | 2314 # including ordering between extensions and non-extension |
2249 # fields. | 2315 # fields. |
2250 # * Consistent serialization of negative numbers, especially | 2316 # * Consistent serialization of negative numbers, especially |
2251 # negative int32s. | 2317 # negative int32s. |
2252 # * Handling of empty submessages (with and without "has" | 2318 # * Handling of empty submessages (with and without "has" |
2253 # bits set). | 2319 # bits set). |
2254 | 2320 |
2255 class SerializationTest(unittest.TestCase): | 2321 class SerializationTest(BaseTestCase): |
2256 | 2322 |
2257 def testSerializeEmtpyMessage(self): | 2323 def testSerializeEmtpyMessage(self): |
2258 first_proto = unittest_pb2.TestAllTypes() | 2324 first_proto = unittest_pb2.TestAllTypes() |
2259 second_proto = unittest_pb2.TestAllTypes() | 2325 second_proto = unittest_pb2.TestAllTypes() |
2260 serialized = first_proto.SerializeToString() | 2326 serialized = first_proto.SerializeToString() |
2261 self.assertEqual(first_proto.ByteSize(), len(serialized)) | 2327 self.assertEqual(first_proto.ByteSize(), len(serialized)) |
2262 self.assertEqual( | 2328 self.assertEqual( |
2263 len(serialized), | 2329 len(serialized), |
2264 second_proto.MergeFromString(serialized)) | 2330 second_proto.MergeFromString(serialized)) |
2265 self.assertEqual(first_proto, second_proto) | 2331 self.assertEqual(first_proto, second_proto) |
(...skipping 540 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2806 self.assertEqual(1, proto.optional_message.c) | 2872 self.assertEqual(1, proto.optional_message.c) |
2807 | 2873 |
2808 def testInitRepeatedKwargs(self): | 2874 def testInitRepeatedKwargs(self): |
2809 proto = unittest_pb2.TestAllTypes(repeated_int32=[1, 2, 3]) | 2875 proto = unittest_pb2.TestAllTypes(repeated_int32=[1, 2, 3]) |
2810 self.assertTrue(proto.IsInitialized()) | 2876 self.assertTrue(proto.IsInitialized()) |
2811 self.assertEqual(1, proto.repeated_int32[0]) | 2877 self.assertEqual(1, proto.repeated_int32[0]) |
2812 self.assertEqual(2, proto.repeated_int32[1]) | 2878 self.assertEqual(2, proto.repeated_int32[1]) |
2813 self.assertEqual(3, proto.repeated_int32[2]) | 2879 self.assertEqual(3, proto.repeated_int32[2]) |
2814 | 2880 |
2815 | 2881 |
2816 class OptionsTest(unittest.TestCase): | 2882 class OptionsTest(BaseTestCase): |
2817 | 2883 |
2818 def testMessageOptions(self): | 2884 def testMessageOptions(self): |
2819 proto = message_set_extensions_pb2.TestMessageSet() | 2885 proto = message_set_extensions_pb2.TestMessageSet() |
2820 self.assertEqual(True, | 2886 self.assertEqual(True, |
2821 proto.DESCRIPTOR.GetOptions().message_set_wire_format) | 2887 proto.DESCRIPTOR.GetOptions().message_set_wire_format) |
2822 proto = unittest_pb2.TestAllTypes() | 2888 proto = unittest_pb2.TestAllTypes() |
2823 self.assertEqual(False, | 2889 self.assertEqual(False, |
2824 proto.DESCRIPTOR.GetOptions().message_set_wire_format) | 2890 proto.DESCRIPTOR.GetOptions().message_set_wire_format) |
2825 | 2891 |
2826 def testPackedOptions(self): | 2892 def testPackedOptions(self): |
2827 proto = unittest_pb2.TestAllTypes() | 2893 proto = unittest_pb2.TestAllTypes() |
2828 proto.optional_int32 = 1 | 2894 proto.optional_int32 = 1 |
2829 proto.optional_double = 3.0 | 2895 proto.optional_double = 3.0 |
2830 for field_descriptor, _ in proto.ListFields(): | 2896 for field_descriptor, _ in proto.ListFields(): |
2831 self.assertEqual(False, field_descriptor.GetOptions().packed) | 2897 self.assertEqual(False, field_descriptor.GetOptions().packed) |
2832 | 2898 |
2833 proto = unittest_pb2.TestPackedTypes() | 2899 proto = unittest_pb2.TestPackedTypes() |
2834 proto.packed_int32.append(1) | 2900 proto.packed_int32.append(1) |
2835 proto.packed_double.append(3.0) | 2901 proto.packed_double.append(3.0) |
2836 for field_descriptor, _ in proto.ListFields(): | 2902 for field_descriptor, _ in proto.ListFields(): |
2837 self.assertEqual(True, field_descriptor.GetOptions().packed) | 2903 self.assertEqual(True, field_descriptor.GetOptions().packed) |
2838 self.assertEqual(descriptor.FieldDescriptor.LABEL_REPEATED, | 2904 self.assertEqual(descriptor.FieldDescriptor.LABEL_REPEATED, |
2839 field_descriptor.label) | 2905 field_descriptor.label) |
2840 | 2906 |
2841 | 2907 |
2842 | 2908 |
2843 class ClassAPITest(unittest.TestCase): | 2909 class ClassAPITest(BaseTestCase): |
2844 | 2910 |
2845 @unittest.skipIf( | 2911 @unittest.skipIf( |
2846 api_implementation.Type() == 'cpp' and api_implementation.Version() == 2, | 2912 api_implementation.Type() == 'cpp' and api_implementation.Version() == 2, |
2847 'C++ implementation requires a call to MakeDescriptor()') | 2913 'C++ implementation requires a call to MakeDescriptor()') |
2848 def testMakeClassWithNestedDescriptor(self): | 2914 def testMakeClassWithNestedDescriptor(self): |
2849 leaf_desc = descriptor.Descriptor('leaf', 'package.parent.child.leaf', '', | 2915 leaf_desc = descriptor.Descriptor('leaf', 'package.parent.child.leaf', '', |
2850 containing_type=None, fields=[], | 2916 containing_type=None, fields=[], |
2851 nested_types=[], enum_types=[], | 2917 nested_types=[], enum_types=[], |
2852 extensions=[]) | 2918 extensions=[]) |
2853 child_desc = descriptor.Descriptor('child', 'package.parent.child', '', | 2919 child_desc = descriptor.Descriptor('child', 'package.parent.child', '', |
(...skipping 62 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2916 ' label: LABEL_OPTIONAL' | 2982 ' label: LABEL_OPTIONAL' |
2917 ' type: TYPE_UINT32' | 2983 ' type: TYPE_UINT32' |
2918 ' }' | 2984 ' }' |
2919 ' }' | 2985 ' }' |
2920 ' }' | 2986 ' }' |
2921 '}') | 2987 '}') |
2922 file_descriptor = descriptor_pb2.FileDescriptorProto() | 2988 file_descriptor = descriptor_pb2.FileDescriptorProto() |
2923 text_format.Merge(file_descriptor_str, file_descriptor) | 2989 text_format.Merge(file_descriptor_str, file_descriptor) |
2924 return file_descriptor.SerializeToString() | 2990 return file_descriptor.SerializeToString() |
2925 | 2991 |
| 2992 @testing_refleaks.SkipReferenceLeakChecker('MakeDescriptor is not repeatable') |
| 2993 # This test can only run once; the second time, it raises errors about |
| 2994 # conflicting message descriptors. |
2926 def testParsingFlatClassWithExplicitClassDeclaration(self): | 2995 def testParsingFlatClassWithExplicitClassDeclaration(self): |
2927 """Test that the generated class can parse a flat message.""" | 2996 """Test that the generated class can parse a flat message.""" |
2928 # TODO(xiaofeng): This test fails with cpp implemetnation in the call | 2997 # TODO(xiaofeng): This test fails with cpp implemetnation in the call |
2929 # of six.with_metaclass(). The other two callsites of with_metaclass | 2998 # of six.with_metaclass(). The other two callsites of with_metaclass |
2930 # in this file are both excluded from cpp test, so it might be expected | 2999 # in this file are both excluded from cpp test, so it might be expected |
2931 # to fail. Need someone more familiar with the python code to take a | 3000 # to fail. Need someone more familiar with the python code to take a |
2932 # look at this. | 3001 # look at this. |
2933 if api_implementation.Type() != 'python': | 3002 if api_implementation.Type() != 'python': |
2934 return | 3003 return |
2935 file_descriptor = descriptor_pb2.FileDescriptorProto() | 3004 file_descriptor = descriptor_pb2.FileDescriptorProto() |
2936 file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A')) | 3005 file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A')) |
2937 msg_descriptor = descriptor.MakeDescriptor( | 3006 msg_descriptor = descriptor.MakeDescriptor( |
2938 file_descriptor.message_type[0]) | 3007 file_descriptor.message_type[0]) |
2939 | 3008 |
2940 class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageTyp
e, message.Message)): | 3009 class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageTyp
e, message.Message)): |
2941 DESCRIPTOR = msg_descriptor | 3010 DESCRIPTOR = msg_descriptor |
2942 msg = MessageClass() | 3011 msg = MessageClass() |
2943 msg_str = ( | 3012 msg_str = ( |
2944 'flat: 0 ' | 3013 'flat: 0 ' |
2945 'flat: 1 ' | 3014 'flat: 1 ' |
2946 'flat: 2 ') | 3015 'flat: 2 ') |
2947 text_format.Merge(msg_str, msg) | 3016 text_format.Merge(msg_str, msg) |
2948 self.assertEqual(msg.flat, [0, 1, 2]) | 3017 self.assertEqual(msg.flat, [0, 1, 2]) |
2949 | 3018 |
| 3019 @testing_refleaks.SkipReferenceLeakChecker('MakeDescriptor is not repeatable') |
2950 def testParsingFlatClass(self): | 3020 def testParsingFlatClass(self): |
2951 """Test that the generated class can parse a flat message.""" | 3021 """Test that the generated class can parse a flat message.""" |
2952 file_descriptor = descriptor_pb2.FileDescriptorProto() | 3022 file_descriptor = descriptor_pb2.FileDescriptorProto() |
2953 file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('B')) | 3023 file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('B')) |
2954 msg_descriptor = descriptor.MakeDescriptor( | 3024 msg_descriptor = descriptor.MakeDescriptor( |
2955 file_descriptor.message_type[0]) | 3025 file_descriptor.message_type[0]) |
2956 msg_class = reflection.MakeClass(msg_descriptor) | 3026 msg_class = reflection.MakeClass(msg_descriptor) |
2957 msg = msg_class() | 3027 msg = msg_class() |
2958 msg_str = ( | 3028 msg_str = ( |
2959 'flat: 0 ' | 3029 'flat: 0 ' |
2960 'flat: 1 ' | 3030 'flat: 1 ' |
2961 'flat: 2 ') | 3031 'flat: 2 ') |
2962 text_format.Merge(msg_str, msg) | 3032 text_format.Merge(msg_str, msg) |
2963 self.assertEqual(msg.flat, [0, 1, 2]) | 3033 self.assertEqual(msg.flat, [0, 1, 2]) |
2964 | 3034 |
| 3035 @testing_refleaks.SkipReferenceLeakChecker('MakeDescriptor is not repeatable') |
2965 def testParsingNestedClass(self): | 3036 def testParsingNestedClass(self): |
2966 """Test that the generated class can parse a nested message.""" | 3037 """Test that the generated class can parse a nested message.""" |
2967 file_descriptor = descriptor_pb2.FileDescriptorProto() | 3038 file_descriptor = descriptor_pb2.FileDescriptorProto() |
2968 file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('C')) | 3039 file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('C')) |
2969 msg_descriptor = descriptor.MakeDescriptor( | 3040 msg_descriptor = descriptor.MakeDescriptor( |
2970 file_descriptor.message_type[0]) | 3041 file_descriptor.message_type[0]) |
2971 msg_class = reflection.MakeClass(msg_descriptor) | 3042 msg_class = reflection.MakeClass(msg_descriptor) |
2972 msg = msg_class() | 3043 msg = msg_class() |
2973 msg_str = ( | 3044 msg_str = ( |
2974 'bar {' | 3045 'bar {' |
2975 ' baz {' | 3046 ' baz {' |
2976 ' deep: 4' | 3047 ' deep: 4' |
2977 ' }' | 3048 ' }' |
2978 '}') | 3049 '}') |
2979 text_format.Merge(msg_str, msg) | 3050 text_format.Merge(msg_str, msg) |
2980 self.assertEqual(msg.bar.baz.deep, 4) | 3051 self.assertEqual(msg.bar.baz.deep, 4) |
2981 | 3052 |
2982 if __name__ == '__main__': | 3053 if __name__ == '__main__': |
2983 unittest.main() | 3054 unittest.main() |
OLD | NEW |